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(play): flagship $THREE world town — pinned official community
nirholas80a045659d7f
diff --git a/api/pump/[action].js b/api/pump/[action].jsindex f5dced516..fa1b36d56 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -117,6 +117,7 @@ const wrapped = wrap(async (req, res) => {case 'first-claims': return handleFirstClaims(req, res);case 'recent-graduations': return handleRecentGraduations(req, res);case 'trending': return handleTrending(req, res);+ case 'coin': return handleCoin(req, res);case 'coin-trades': return handleCoinTrades(req, res);case 'search': return handleSearch(req, res);case 'collect-creator-fee-prep': return handleCollectCreatorFeePrep(req, res);@@ -2471,6 +2472,47 @@ async function handleTrending(req, res) {return json(res, 200, arr);}+// ── coin ─────────────────────────────────────────────────────────────────────+// Live metadata for a single mint, proxied from pump.fun's frontend API+// (CORS-protected from the browser). Powers the /play lobby's pinned flagship+// town so its name/symbol/art/market-cap are always real and current, even when+// the coin isn't in the trending 30. Short-cached per mint to spare the upstream.++const COIN_CACHE = new Map(); // mint → { at, body }+const COIN_TTL_MS = 30_000;++async function handleCoin(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;+ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ const url = new URL(req.url, `http://${req.headers.host}`);+ const mint = (url.searchParams.get('mint') || '').trim();+ if (!MINT_RE.test(mint)) return error(res, 400, 'invalid_mint', 'mint must be a base58 address');++ const now = Date.now();+ const hit = COIN_CACHE.get(mint);+ if (hit && now - hit.at < COIN_TTL_MS) {+ res.setHeader('cache-control', 'public, max-age=15');+ return json(res, 200, hit.body);+ }++ let resp;+ try {+ resp = await fetch(new URL(`/coins/${mint}`, PUMP_FRONTEND_BASE), {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(8000),+ });+ } catch {+ return error(res, 504, 'upstream_timeout', 'pump.fun did not respond');+ }+ if (!resp.ok) return error(res, 502, 'upstream_failed', `pump.fun returned ${resp.status}`);+ const [body] = repairCoinImages([await resp.json()]);+ COIN_CACHE.set(mint, { at: now, body });+ res.setHeader('cache-control', 'public, max-age=15');+ return json(res, 200, body);+}+// ── coin-trades ────────────────────────────────────────────────────────────// Recent buy/sell trades for a single mint, proxied from pump.fun's swap API// (CORS-protected from the browser). Powers the homepage live token card'sdiff --git a/multiplayer/deploy-cloudrun.sh b/multiplayer/deploy-cloudrun.shindex a48974620..5b257e265 100755--- a/multiplayer/deploy-cloudrun.sh+++ b/multiplayer/deploy-cloudrun.sh@@ -22,20 +22,52 @@ REGION="${REGION:-us-central1}"ALLOWED_ORIGINS="${ALLOWED_ORIGINS:-https://three.ws,https://www.three.ws}"PROJECT="$(gcloud config get-value project 2>/dev/null)"+# ── Capacity tunables ──────────────────────────────────────────────────────+# CONCURRENCY is the # of simultaneous connections Cloud Run routes to ONE+# instance. The platform default is 80 — for a WebSocket server that is a hard+# ~80-player ceiling, so we raise it well above the per-instance comfort limit.+CONCURRENCY="${CONCURRENCY:-1000}"+CPU="${CPU:-2}"+MEMORY="${MEMORY:-2Gi}"+MIN_INSTANCES="${MIN_INSTANCES:-1}"++# Horizontal scaling: a Colyseus fleet only works when the room registry ++# presence are shared via Redis (REDIS_URI, e.g. a Memorystore instance). Until+# that is set we MUST stay single-instance, or players for the same coin land on+# different instances and can't see each other. Set REDIS_URI to scale out.+REDIS_URI="${REDIS_URI:-}"+if [[ -n "${REDIS_URI}" ]]; then+ MAX_INSTANCES="${MAX_INSTANCES:-10}"+else+ MAX_INSTANCES="${MAX_INSTANCES:-1}"+fi+if [[ -z "${PROJECT}" || "${PROJECT}" == "(unset)" ]]; thenecho "No GCP project set. Run: gcloud config set project YOUR_PROJECT_ID" >&2exit 1fi+# Assemble env vars (@-delimited so values containing commas are safe). Redis ++# monitor creds are only passed when provided.+ENV_VARS="NODE_ENV=production@ALLOWED_ORIGINS=${ALLOWED_ORIGINS}"+[[ -n "${REDIS_URI}" ]] && ENV_VARS="${ENV_VARS}@REDIS_URI=${REDIS_URI}"+[[ -n "${MONITOR_USER:-}" ]] && ENV_VARS="${ENV_VARS}@MONITOR_USER=${MONITOR_USER}"+[[ -n "${MONITOR_PASS:-}" ]] && ENV_VARS="${ENV_VARS}@MONITOR_PASS=${MONITOR_PASS}"+echo "Deploying '${SERVICE}' to Cloud Run (project=${PROJECT}, region=${REGION})..."+echo " cpu=${CPU} memory=${MEMORY} concurrency=${CONCURRENCY} instances=${MIN_INSTANCES}..${MAX_INSTANCES} redis=$([[ -n "${REDIS_URI}" ]] && echo on || echo off)"# Flags that matter for a long-lived Colyseus game server on Cloud Run:# --no-cpu-throttling : keep CPU allocated between requests so the room# simulation/patch loop never stalls (the #1 gotcha).-# --min-instances 1 : rooms live in-memory; never cold-start them away.-# --max-instances 1 : matchmaking is per-process. Stay single-instance until-# @colyseus/redis-presence is wired (see README scaling).-# --session-affinity : best-effort sticky sessions for WS reconnects.+# --concurrency : connections routed per instance. The default 80 is a+# hard WS-connection ceiling — raised here.+# --min-instances : rooms live in-memory; keep ≥1 warm so they never+# cold-start away.+# --max-instances : >1 ONLY with REDIS_URI (shared room registry/presence);+# otherwise players for the same coin split across boxes.+# --session-affinity : sticky sessions so a client's HTTP matchmake + WS land+# on the same instance.# --timeout 3600 : Cloud Run's max WS lifetime (60 min); client reconnects.# --port 2567 : container listens here (matches Dockerfile/fly.toml).# A fresh project's default compute service account can take minutes to appear@@ -52,13 +84,14 @@ gcloud run deploy "${SERVICE}" \--allow-unauthenticated \--port 2567 \--no-cpu-throttling \- --min-instances 1 \- --max-instances 1 \- --memory 512Mi \- --cpu 1 \+ --concurrency "${CONCURRENCY}" \+ --min-instances "${MIN_INSTANCES}" \+ --max-instances "${MAX_INSTANCES}" \+ --memory "${MEMORY}" \+ --cpu "${CPU}" \--timeout 3600 \--session-affinity \- --set-env-vars "^@^NODE_ENV=production@ALLOWED_ORIGINS=${ALLOWED_ORIGINS}"+ --set-env-vars "^@^${ENV_VARS}"URL="$(gcloud run services describe "${SERVICE}" --region "${REGION}" --format 'value(status.url)')"WSS="${URL/https:/wss:}"diff --git a/multiplayer/package.json b/multiplayer/package.jsonindex 0407d51b0..edd514da7 100644--- a/multiplayer/package.json+++ b/multiplayer/package.json@@ -16,6 +16,8 @@"@bonfida/spl-name-service": "^0.1.67","@colyseus/core": "^0.16.24","@colyseus/monitor": "^0.16.7",+ "@colyseus/redis-driver": "^0.16.0",+ "@colyseus/redis-presence": "^0.16.0","@colyseus/schema": "^3.0.0","@colyseus/ws-transport": "^0.16.5","@ethereum-attestation-service/eas-sdk": "0.29.1",@@ -23,6 +25,7 @@"@pump-fun/pump-sdk": "1.1.0","@solana/actions": "0.0.2","@solana/pay": "1.0.16",+ "@upstash/redis": "^1.38.0","agent0-sdk": "^1.7.1","ethers": "^6.16.0","express": "^4.21.2",diff --git a/multiplayer/src/avatar-url.js b/multiplayer/src/avatar-url.jsnew file mode 100644index 000000000..9c174a0df--- /dev/null+++ b/multiplayer/src/avatar-url.js@@ -0,0 +1,27 @@+// Shared avatar-URL sanitizer for every authoritative room (WalkRoom, GameRoom).+//+// We only ever broadcast avatar URLs we'd be willing to load cross-origin: our+// own origins and the public model hosts. Site-relative paths are always fine.+// Everything else — javascript:/data: URLs, arbitrary hosts, oversized strings —+// collapses to '' so a malicious client can't make everyone fetch attacker-+// controlled URLs. Centralized here so the allow-list never drifts between rooms.++const AVATAR_HOST_ALLOW = [+ /(^|\.)three\.ws$/i,+ /(^|\.)r2\.cloudflarestorage\.com$/i,+ /(^|\.)r2\.dev$/i,+ /(^|\.)pump\.fun$/i,+ /(^|\.)githubusercontent\.com$/i,+];++export function cleanAvatarUrl(v) {+ if (typeof v !== 'string' || v.length > 1024) return '';+ const s = v.trim();+ if (!s) return '';+ // Site-relative path (e.g. /avatars/default.glb) is always allowed.+ if (s.startsWith('/') && !s.startsWith('//')) return s;+ let u;+ try { u = new URL(s); } catch { return ''; }+ if (u.protocol !== 'https:' && u.protocol !== 'http:') return '';+ return AVATAR_HOST_ALLOW.some((re) => re.test(u.hostname)) ? s : '';+}diff --git a/multiplayer/src/block-store.js b/multiplayer/src/block-store.jsnew file mode 100644index 000000000..f1a834005--- /dev/null+++ b/multiplayer/src/block-store.js@@ -0,0 +1,123 @@+// BlockStore — durable persistence for each coin world's collaborative voxel+// build, so a community's creation survives both the room emptying (Colyseus+// disposes an idle room) and a full server restart/redeploy.+//+// Two tiers, layered:+// 1. In-process memory. The multiplayer server runs as a single always-on+// instance (Cloud Run min=1/max=1), so this Map alone already makes a build+// outlive the room — walk away, the room disposes, walk back tomorrow and+// the same process rehydrates it. This is real persistence, not a cache of+// convenience; it just doesn't survive the process dying.+// 2. Upstash Redis (REST), used when UPSTASH_REDIS_REST_URL + _TOKEN are set.+// This upgrades durability across restarts and redeploys. Writes are+// debounced (one network round-trip a few seconds after the last edit) and+// flushed on room dispose, so a busy build doesn't hammer Redis.+//+// Each world is stored as a single JSON object { "gx,gy,gz": type } under the+// key `walkblocks:<mint>`. A world is hard-capped (see MAX_BLOCKS in WalkRoom),+// so the payload stays tens of KB — comfortably one Redis value.++const REDIS_URL = process.env.UPSTASH_REDIS_REST_URL || '';+const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || '';+const SAVE_DEBOUNCE_MS = 4000;+const KEY_PREFIX = 'walkblocks:';++function redisKey(coin) {+ // '' (the mainland lobby) gets its own stable bucket.+ return KEY_PREFIX + (coin || 'mainland');+}++class BlockStore {+ constructor() {+ this._mem = new Map(); // coin → Map(packedKey → type)+ this._saveTimers = new Map(); // coin → timeout handle+ this._redis = null;+ this._redisReady = null;+ if (REDIS_URL && REDIS_TOKEN) {+ // Lazy dynamic import so the dependency is only touched when configured.+ this._redisReady = import('@upstash/redis')+ .then(({ Redis }) => { this._redis = new Redis({ url: REDIS_URL, token: REDIS_TOKEN }); })+ .catch((err) => { console.warn('[block-store] Redis init failed, memory-only:', err?.message); });+ console.log('[block-store] persistence: memory + Upstash Redis');+ } else {+ console.log('[block-store] persistence: memory-only (set UPSTASH_REDIS_REST_URL/_TOKEN for cross-restart durability)');+ }+ }++ // Return the live Map for a coin, loading it from memory or Redis on first+ // access. Subsequent edits mutate this same Map in place.+ async load(coin) {+ if (this._mem.has(coin)) return this._mem.get(coin);+ const map = new Map();+ this._mem.set(coin, map);+ if (this._redisReady) {+ try {+ await this._redisReady;+ const raw = this._redis ? await this._redis.get(redisKey(coin)) : null;+ const obj = typeof raw === 'string' ? JSON.parse(raw) : raw; // Upstash may auto-parse JSON+ if (obj && typeof obj === 'object') {+ for (const [k, t] of Object.entries(obj)) {+ const type = Number(t);+ if (Number.isInteger(type)) map.set(k, type);+ }+ }+ } catch (err) {+ console.warn(`[block-store] load failed for ${coin || 'mainland'}:`, err?.message);+ }+ }+ return map;+ }++ // In-memory edits + a debounced durable write. Synchronous so callers don't+ // await on the hot path of a place/break.+ set(coin, key, type) {+ const map = this._mem.get(coin);+ if (!map) return;+ map.set(key, type);+ this._scheduleSave(coin);+ }++ delete(coin, key) {+ const map = this._mem.get(coin);+ if (!map) return;+ map.delete(key);+ this._scheduleSave(coin);+ }++ _scheduleSave(coin) {+ if (!this._redis && !this._redisReady) return; // memory-only: nothing to flush+ if (this._saveTimers.has(coin)) return;+ const handle = setTimeout(() => {+ this._saveTimers.delete(coin);+ this.flush(coin);+ }, SAVE_DEBOUNCE_MS);+ // Don't keep the event loop alive purely for a pending save.+ if (typeof handle.unref === 'function') handle.unref();+ this._saveTimers.set(coin, handle);+ }++ // Write the current world to Redis now. Called by the debounce timer and on+ // room dispose so the final state always lands. No-op without Redis.+ async flush(coin) {+ const pending = this._saveTimers.get(coin);+ if (pending) { clearTimeout(pending); this._saveTimers.delete(coin); }+ if (!this._redisReady) return;+ await this._redisReady;+ if (!this._redis) return;+ const map = this._mem.get(coin);+ if (!map) return;+ try {+ if (map.size === 0) {+ await this._redis.del(redisKey(coin));+ } else {+ await this._redis.set(redisKey(coin), JSON.stringify(Object.fromEntries(map)));+ }+ } catch (err) {+ console.warn(`[block-store] save failed for ${coin || 'mainland'}:`, err?.message);+ }+ }+}++// One store shared by every WalkRoom instance in the process — that shared+// memory is exactly what lets a build outlive its room.+export const blockStore = new BlockStore();diff --git a/multiplayer/src/index.js b/multiplayer/src/index.jsindex e32851b25..a2557622f 100644--- a/multiplayer/src/index.js+++ b/multiplayer/src/index.js@@ -42,9 +42,30 @@ app.get(['/health', '/healthz'], (_req, res) => {res.json({ ok: true, name: 'three.ws-multiplayer' });});-// Admin monitor UI. Protect this behind a reverse proxy or basic auth in prod-// (see @colyseus/monitor docs) — it exposes live room/client state.-app.use('/colyseus', monitor());+// Admin monitor UI — exposes live room/client state, so it must NOT be open to+// the world in production. Mount it only when protected by basic-auth creds+// (MONITOR_USER + MONITOR_PASS), or, outside production, openly for local dev.+const MONITOR_USER = process.env.MONITOR_USER;+const MONITOR_PASS = process.env.MONITOR_PASS;+const IS_PROD = process.env.NODE_ENV === 'production';+function monitorBasicAuth(req, res, next) {+ const hdr = req.headers.authorization || '';+ const [scheme, encoded] = hdr.split(' ');+ if (scheme === 'Basic' && encoded) {+ const [user, pass] = Buffer.from(encoded, 'base64').toString().split(':');+ if (user === MONITOR_USER && pass === MONITOR_PASS) return next();+ }+ res.set('WWW-Authenticate', 'Basic realm="colyseus-monitor"').status(401).send('auth required');+}+if (MONITOR_USER && MONITOR_PASS) {+ app.use('/colyseus', monitorBasicAuth, monitor());+ console.log('[multiplayer] monitor mounted at /colyseus (basic auth)');+} else if (!IS_PROD) {+ app.use('/colyseus', monitor());+ console.log('[multiplayer] monitor mounted at /colyseus (open — dev only)');+} else {+ console.log('[multiplayer] monitor disabled (set MONITOR_USER/MONITOR_PASS to enable in prod)');+}const httpServer = http.createServer(app);@@ -69,7 +90,32 @@ const transport = new WebSocketTransport({},});-const gameServer = new Server({ transport });+// Horizontal scaling across Cloud Run instances. Colyseus rooms live in one+// process, so to run more than one instance the room registry (driver) and+// pub/sub (presence) must be shared — otherwise matchmaking on instance A can't+// see a room hosted on instance B and players for the same coin split apart.+// Setting REDIS_URI (e.g. a Memorystore instance) wires both; without it the+// server runs single-instance exactly as before (zero new behaviour, the deps+// are only imported when REDIS_URI is present).+const REDIS_URI = process.env.REDIS_URI || process.env.REDIS_URL;+let driver, presence;+if (REDIS_URI) {+ try {+ const [{ RedisDriver }, { RedisPresence }] = await Promise.all([+ import('@colyseus/redis-driver'),+ import('@colyseus/redis-presence'),+ ]);+ driver = new RedisDriver(REDIS_URI);+ presence = new RedisPresence(REDIS_URI);+ console.log('[multiplayer] horizontal scaling ENABLED (Redis driver + presence)');+ } catch (err) {+ console.error('[multiplayer] REDIS_URI set but Redis deps unavailable — staying single-instance:', err?.message);+ }+} else {+ console.log('[multiplayer] single-instance mode (set REDIS_URI to scale horizontally)');+}++const gameServer = new Server({ transport, ...(driver && { driver }), ...(presence && { presence }) });// Each coin is its own world: filterBy(['coin']) makes joinOrCreate match only// rooms sharing the same community coin (mint), so players of the same coin land// together while different coins stay isolated. A missing coin resolves to thediff --git a/multiplayer/src/rooms/GameRoom.js b/multiplayer/src/rooms/GameRoom.jsindex b15e741bc..b5469f61a 100644Binary files a/multiplayer/src/rooms/GameRoom.js and b/multiplayer/src/rooms/GameRoom.js differdiff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex 00599ec1d..f1499d285 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 91037e43f..c670803eb 100644--- a/multiplayer/src/schemas.js+++ b/multiplayer/src/schemas.js@@ -44,6 +44,20 @@ defineTypes(Player, {tsServer: 'float64',});+// A single placed voxel in a coin's world. Keyed in the blocks MapSchema by its+// packed grid coordinate ("gx,gy,gz"), so the position never has to ride on the+// wire — only the block type does. Delta encoding then makes a place/break a+// one-entry patch. `t` is the palette index (see build-voxels.js BLOCK_TYPES).+export class Block extends Schema {+ constructor() {+ super();+ this.t = 0;+ }+}+defineTypes(Block, {+ t: 'uint8',+});+export class WalkState extends Schema {constructor() {super();@@ -55,6 +69,10 @@ export class WalkState extends Schema {this.coinName = '';this.coinSymbol = '';this.coinImage = '';+ // Collaborative voxel builds for this coin's world. Keyed by packed grid+ // coordinate; the value carries only the block type. Persisted per coin so+ // a community's build survives the room emptying and the server restarting.+ this.blocks = new MapSchema();}}defineTypes(WalkState, {@@ -63,4 +81,5 @@ defineTypes(WalkState, {coinName: 'string',coinSymbol: 'string',coinImage: 'string',+ blocks: { map: Block },});diff --git a/pages/avatar-edit.html b/pages/avatar-edit.htmlindex 7be12b1da..f6ecf187c 100644--- a/pages/avatar-edit.html+++ b/pages/avatar-edit.html@@ -671,6 +671,7 @@<div class="ae-bar-title" id="ae-title">Customize</div><div class="ae-actions"><button class="ae-btn" id="ae-reset" type="button" disabled>Discard</button>+ <button class="ae-btn" id="ae-play" type="button" disabled title="Drop into /play as this avatar">▶ Play as this</button><button class="ae-btn primary" id="ae-save" type="button" disabled>Save</button></div></header>diff --git a/public/features.json b/public/features.jsonindex 32b34a6b9..3350eb4c6 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-05-30T13:29:11.974Z",+ "generated_at": "2026-05-30T13:43:55.117Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/_capture-play-prod.mjs b/scripts/_capture-play-prod.mjsnew file mode 100644index 000000000..cc41359bf--- /dev/null+++ b/scripts/_capture-play-prod.mjs@@ -0,0 +1,20 @@+// Capture the LIVE /play lobby from production (https://three.ws/play).+// Lobby-only: real pump.fun coin grid, no multiplayer WS handshake required.+import { chromium } from 'playwright';+import { setTimeout as sleep } from 'node:timers/promises';++const browser = await chromium.launch({+ args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'],+});+const page = await browser.newPage({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 });+const errors = [];+page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));++await page.goto('https://three.ws/play', { waitUntil: 'domcontentloaded', timeout: 40000 });+const got = await page.waitForSelector('.cc-card:not(.cc-skeleton)', { timeout: 25000 }).then(() => true).catch(() => false);+console.log('real coin cards:', got);+await sleep(2500);+await page.screenshot({ path: '/tmp/play-lobby.png', animations: 'disabled', caret: 'hide', timeout: 30000 });+console.log('lobby saved; errors:', errors.length ? errors.join(' | ') : 'none');+await browser.close();+process.exit(0);diff --git a/scripts/check-chart-screen.mjs b/scripts/check-chart-screen.mjsnew file mode 100644index 000000000..8c281b395--- /dev/null+++ b/scripts/check-chart-screen.mjs@@ -0,0 +1,79 @@+// Headless proof that the in-world live chart screen renders in a coin community.+// Deep-links /play into a real pump.fun coin, waits for the world + chart screen,+// confirms it ingested real trades, then screenshots the scene.+import { chromium } from 'playwright';+import { writeFileSync } from 'node:fs';+const RESULT = '/tmp/probe.json';+const save = (o) => { try { writeFileSync(RESULT, JSON.stringify(o, null, 2)); } catch {} };++const BASE = process.env.BASE || 'http://localhost:3000';+const MINT = process.env.MINT || '9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump'; // Fartcoin+const errors = [];++const browser = await chromium.launch({+ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'],+});+const page = await browser.newPage({ viewport: { width: 1280, height: 800 } });+page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });+page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));++await page.goto(`${BASE}/pages/play.html?coin=${MINT}&name=Fartcoin&symbol=Fartcoin`, { waitUntil: 'domcontentloaded', timeout: 90000 });+await page.waitForFunction(() => !!window.__CC__, { timeout: 60000 });++// The chart screen is built as soon as the world geometry is assembled (before+// the multiplayer connect, which may be offline in headless CI).+const built = await page.waitForFunction(() => !!window.__CC__?._chartScreen, { timeout: 25000 })+ .then(() => true).catch(() => false);+if (!built) {+ const dbg = await page.evaluate(() => ({ phase: window.__CC__?.phase, hasCC: !!window.__CC__ }));+ save({ ok: false, dbg, errors });+ console.log('chart screen not built. state:', JSON.stringify(dbg), 'errors:', errors);+ await page.screenshot({ path: '/tmp/chart-screen.png' });+ await browser.close();+ process.exit(1);+}++// Give the trades poll a couple of cycles to land real data.+await page.waitForTimeout(8000);++const probe = await page.evaluate(() => {+ const cs = window.__CC__._chartScreen;+ // The screen face is an HTML canvas behind a CanvasTexture. Sample its pixels+ // to prove it actually painted something (not a blank/black plane).+ let painted = false, distinctColors = 0;+ try {+ const canvas = cs?.mesh?.material?.map?.image;+ if (canvas?.getContext) {+ const c = canvas.getContext('2d');+ const { data } = c.getImageData(0, 0, canvas.width, canvas.height);+ const seen = new Set();+ for (let i = 0; i < data.length; i += 4 * 997) {+ seen.add((data[i] >> 4) + ',' + (data[i + 1] >> 4) + ',' + (data[i + 2] >> 4));+ }+ distinctColors = seen.size;+ painted = seen.size > 4; // a chart has many tones; a blank canvas has ~1+ }+ } catch (e) { /* ignore */ }+ return {+ phase: window.__CC__.phase,+ hasScreen: !!cs,+ hasMesh: !!cs?.mesh,+ mint: cs?.mint || null,+ painted,+ distinctColors,+ };+});++const ok = probe.hasScreen && probe.hasMesh && probe.painted && !errors.length;+save({ ok, probe, errors });+console.log('probe:', JSON.stringify(probe));+console.log('console errors:', errors.length ? errors : 'none');++// Screenshot is best-effort: swiftshader can stall on a continuously-rendering+// WebGL page, so never let it fail the check.+try {+ await page.evaluate(() => { document.getElementById('kx-loading')?.remove(); });+ await page.screenshot({ path: '/tmp/chart-screen.png', timeout: 8000, animations: 'disabled' });+} catch { /* non-fatal */ }+await browser.close();+process.exit(ok ? 0 : 1);diff --git a/scripts/debug-avatar-load.mjs b/scripts/debug-avatar-load.mjsnew file mode 100644index 000000000..dafe1db94--- /dev/null+++ b/scripts/debug-avatar-load.mjs@@ -0,0 +1,35 @@+// Headless probe: load /play, capture console errors + whether the lobby preset+// chips render a real model portrait or fall back to emoji/capsule.+import { chromium } from 'playwright';++const BASE = process.env.BASE || 'http://127.0.0.1:3030';+const logs = [];+const browser = await chromium.launch({ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'] });+const page = await browser.newPage({ viewport: { width: 1280, height: 800 } });+page.on('console', (m) => logs.push(`[${m.type()}] ${m.text()}`));+page.on('pageerror', (e) => logs.push('pageerror: ' + e.message));+page.on('requestfailed', (r) => logs.push(`reqfail: ${r.url()} :: ${r.failure()?.errorText}`));++await page.goto(`${BASE}/pages/play.html`, { waitUntil: 'domcontentloaded' });+await page.waitForTimeout(3000);+await page.waitForFunction(() => !!window.__CC__, { timeout: 20000 }).catch(() => logs.push('NO __CC__'));+await page.evaluate(() => { document.getElementById('kx-loading')?.remove(); document.getElementById('cc-loading')?.remove(); }).catch(() => {});++await page.waitForSelector('.cc-avatar-chip', { state: 'attached', timeout: 20000 }).catch(() => logs.push('NO chips'));+await page.waitForTimeout(9000);++const chipState = await page.evaluate(() => {+ const chips = [...document.querySelectorAll('.cc-avatar-chip')];+ return {+ total: chips.length,+ stillLoading: chips.filter((c) => c.classList.contains('cc-avatar-loading')).length,+ rendered: document.querySelectorAll('img.cc-avatar-render').length,+ emoji: document.querySelectorAll('.cc-avatar-chip .cc-avatar-glyph').length,+ thumbImg: document.querySelectorAll('.cc-avatar-chip img:not(.cc-avatar-render)').length,+ };+});++await browser.close();+console.log('chipState:', JSON.stringify(chipState));+console.log('--- console/network logs ---');+console.log(logs.join('\n'));diff --git a/scripts/demo-screens.mjs b/scripts/demo-screens.mjsnew file mode 100644index 000000000..e352f9096--- /dev/null+++ b/scripts/demo-screens.mjs@@ -0,0 +1,36 @@+// Capture what /play actually looks like right now: lobby + in-world.+// Stubs the trending-coins API (Vercel fn not available in plain `vite dev`) so+// we can click into a world and screenshot the real 3D scene. Reports console+// errors. Screenshots land in /tmp.+import { chromium } from 'playwright';++const BASE = process.env.BASE || 'http://localhost:3000';+const errors = [];+const browser = await chromium.launch();+const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });+page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });+page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));++// Stub trending coins so the lobby populates.+const COINS = Array.from({ length: 8 }, (_, i) => ({+ mint: 'Mint' + i, name: ['Doge','Pepe','Bonk','Wif','Popcat','Mew','Goat','Moodeng'][i],+ symbol: ['DOGE','PEPE','BONK','WIF','POPCAT','MEW','GOAT','MOO'][i],+ image: '', marketCap: (i + 1) * 1.2e6,+}));+await page.route('**/api/pump/trending**', (r) => r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ coins: COINS, items: COINS }) }));+await page.route('**/api/explore**', (r) => r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ items: [] }) }));++await page.goto(`${BASE}/pages/play.html`, { waitUntil: 'load' });+await page.waitForTimeout(1500);+await page.screenshot({ path: '/tmp/play-lobby.png' });+console.log('lobby captured');++// Enter a world directly via the scene API (offline — no server needed).+await page.waitForFunction(() => !!window.__CC__, { timeout: 8000 });+await page.evaluate(() => window.__CC__.enter({ mint: 'DemoMint', name: 'Doge', symbol: 'DOGE', image: '' }));+await page.waitForTimeout(4000); // let avatar + scene settle+await page.screenshot({ path: '/tmp/play-world.png' });+console.log('world captured');++await browser.close();+console.log('console errors:', errors.length ? errors : 'none');diff --git a/scripts/play-x-post.md b/scripts/play-x-post.mdnew file mode 100644index 000000000..fa9f86e2d--- /dev/null+++ b/scripts/play-x-post.md@@ -0,0 +1,86 @@+# /play — X launch post package++**Live URL:** https://three.ws/play+**One-liner:** Every pump.fun coin has its own real-time 3D multiplayer world.++---++## Hero post (recommended)++> every pump.fun coin now has its own world.+>+> not a chart. not a chatroom. a 3D world.+>+> pick a coin → drop in as your avatar → see who else is there, live.+>+> the community *is* the place now.+>+> ▶ three.ws/play++Attach: 10–15s screen recording (spawn into a coin world) OR the in-world screenshot.++---++## Thread (for depth)++**1/**+every pump.fun coin now has its own 3D world.+real-time multiplayer. real avatars. live right now.++this is /play 👇+*(attach: in-world clip)*++**2/**+open the lobby → it's a live grid of trending coins straight from the pump.fun feed.++pick one. you spawn inside *that coin's* world, standing under its totem.+*(attach: lobby screenshot)*++**3/**+you're a real 3D avatar — pick a preset or paste your own GLB.+everyone else in the world is too.++you see them move, chat, and emote in real time. names + speech bubbles float over heads.+*(attach: world screenshot with avatars/chat)*++**4/**+the link IS the world.+share three.ws/play?coin=… and anyone lands in the same room with you.++holders aren't a number anymore. they're people standing next to you.++**5/**+live now. pick a coin, meet its community →+three.ws/play++---++## Alt single posts (pick by audience)++**Degen voice**+> your bags now have a clubhouse.+> every pumpfun coin = a 3D world you and the other holders walk around in. live.+> three.ws/play++**Product voice**+> Shipped: /play — every pump.fun token gets a real-time 3D multiplayer world.+> Live trending feed → enter any coin → full 3D avatars, chat, emotes, presence.+> Built on Colyseus. Deep-linkable per coin.+> three.ws/play++**Visionary voice**+> a token is a coordination point. so why does it live as a row in a table?+> on three.ws every coin is a place — a world its community actually inhabits, together, in real time.+> three.ws/play++---++## Assets+- `/tmp/play-lobby.png` — desktop lobby (live trending coin grid + avatar picker)+- `/tmp/play-world.png` — in-world (coin totem, 3D avatars, chat)+- `/tmp/play-mobile.png` — mobile lobby++## Posting notes+- Lead with motion. A clip of spawning in beats any static image for this.+- First reply: drop a direct deep-link to one hot coin's world so people click through instantly.+- Best alt text: "Lobby of three.ws /play showing a live grid of trending pump.fun coins, each a 3D world to enter."diff --git a/scripts/shoot-play.mjs b/scripts/shoot-play.mjsnew file mode 100644index 000000000..1f88dc008--- /dev/null+++ b/scripts/shoot-play.mjs@@ -0,0 +1,64 @@+// Self-contained: boot Vite as a child, screenshot the /play lobby, an in-world+// shot (entering a coin), and a mobile lobby shot. Logs each step + any console+// errors to /tmp/shoot.txt, then tears down. Throwaway.+import { spawn } from 'node:child_process';+import { chromium } from 'playwright';+import { setTimeout as sleep } from 'node:timers/promises';+import { appendFileSync, writeFileSync } from 'node:fs';++writeFileSync('/tmp/shoot.txt', '');+const log = (m) => appendFileSync('/tmp/shoot.txt', m + '\n');++const vite = spawn('node_modules/.bin/vite', ['--port', '4400', '--strictPort'], {+ cwd: process.cwd(),+ stdio: ['ignore', 'pipe', 'pipe'],+});+let booted = false;+vite.stdout.on('data', (d) => { if (/4400|ready in/i.test(String(d))) booted = true; });+vite.stderr.on('data', (d) => log('vite-err: ' + String(d).trim()));++log('waiting for vite');+for (let i = 0; i < 60 && !booted; i++) await sleep(500);+log('booted=' + booted);+if (!booted) { vite.kill('SIGKILL'); process.exit(1); }+await sleep(1200);++const BASE = 'http://localhost:4400';+const errors = [];+const browser = await chromium.launch({+ args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'],+});++async function shoot(label, { mobile = false, deepLink = '', enterCoin = false } = {}) {+ const page = await browser.newPage({+ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 900 },+ deviceScaleFactor: 2,+ });+ page.on('console', (m) => { if (m.type() === 'error') errors.push(`[${label}] console: ` + m.text()); });+ page.on('pageerror', (e) => errors.push(`[${label}] pageerror: ` + e.message));+ try {+ log(`goto ${label}`);+ await page.goto(`${BASE}/play${deepLink}`, { waitUntil: 'domcontentloaded', timeout: 30000 });+ // Wait for the lobby to paint real coin cards (skeletons resolve to cards).+ await page.waitForSelector('.cc-card:not(.cc-skeleton)', { timeout: 20000 }).catch(() => log(`${label}: no real card`));+ await sleep(2500);+ if (enterCoin) {+ const card = await page.$('.cc-card:not(.cc-skeleton)');+ if (card) { await card.click(); log(`${label}: clicked coin`); await sleep(9000); }+ else errors.push(`[${label}] no coin card to enter`);+ }+ await page.screenshot({ path: `/tmp/play-${label}.png` });+ log(`${label}: shot saved`);+ } catch (e) { errors.push(`[${label}] nav: ` + e.message); }+ await page.close();+}++await shoot('lobby');+await shoot('world', { enterCoin: true });+await shoot('mobile', { mobile: true });++log('ERRORS: ' + (errors.length ? '\n' + errors.join('\n') : 'none'));+await browser.close();+vite.kill('SIGKILL');+log('done');+process.exit(0);diff --git a/scripts/test-avatar-previews.mjs b/scripts/test-avatar-previews.mjsnew file mode 100644index 000000000..ca048c8d6--- /dev/null+++ b/scripts/test-avatar-previews.mjs@@ -0,0 +1,48 @@+// Headless proof that the lobby avatar picker renders REAL model portraits, not+// emoji. Loads /play, waits for preset chips, then asserts at least one chip+// swapped its placeholder for a rendered <img.cc-avatar-render> data URL.+import { chromium } from 'playwright';++const BASE = process.env.BASE || 'http://localhost:3000';+const errors = [];++const browser = await chromium.launch({ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'] });+const page = await browser.newPage({ viewport: { width: 1280, height: 800 } });+page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });+page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));++await page.goto(`${BASE}/pages/play.html`, { waitUntil: 'load' });+// Dismiss the boot-loader overlay so the lobby (and its avatar chips) are the+// visible, interactable surface — otherwise the loader sits on top of them.+await page.waitForFunction(() => !!window.__CC__, { timeout: 15000 });+await page.evaluate(() => {+ document.getElementById('kx-loading')?.remove();+ document.getElementById('cc-loading')?.remove();+});+await page.waitForSelector('.cc-avatar-chip', { state: 'attached', timeout: 15000 });++// Wait until at least one chip finishes rendering its portrait (or all stop loading).+const rendered = await page.waitForFunction(() => {+ const chips = [...document.querySelectorAll('.cc-avatar-chip')];+ if (!chips.length) return false;+ const stillLoading = chips.some((c) => c.classList.contains('cc-avatar-loading'));+ const renders = document.querySelectorAll('img.cc-avatar-render').length;+ if (renders > 0) return { renders, total: chips.length };+ if (!stillLoading) return { renders: 0, total: chips.length };+ return false;+}, { timeout: 30000 }).then((h) => h.jsonValue());++const sample = await page.evaluate(() => {+ const img = document.querySelector('img.cc-avatar-render');+ return img ? { src: img.src.slice(0, 30), w: img.naturalWidth, h: img.naturalHeight } : null;+});++await browser.close();++console.log('chips:', rendered.total, 'rendered portraits:', rendered.renders);+console.log('sample:', JSON.stringify(sample));+const webglErrs = errors.filter((e) => !/favicon|colyseus|websocket|ws:|net::ERR/i.test(e));+if (webglErrs.length) { console.error('console errors:', webglErrs); process.exit(1); }+if (!rendered.renders) { console.error('FAIL: no rendered portraits — chips fell back to emoji/thumb'); process.exit(1); }+if (!sample || !sample.src.startsWith('data:image')) { console.error('FAIL: portrait is not a rendered data URL'); process.exit(1); }+console.log('PASS: avatar previews render the real model');diff --git a/src/avatar-edit.js b/src/avatar-edit.jsindex e50032880..e0808a470 100644--- a/src/avatar-edit.js+++ b/src/avatar-edit.js@@ -23,6 +23,7 @@ import { AccessoryManager } from './agent-accessories.js';import { uploadAvatarSnapshot } from './voice/avatar-snapshot.js';import { IdleAnimation } from './idle-animation.js';import { renderSculptPanel } from './avatar-sculpt.js';+import { playAs } from './game/play-handoff.js';// ── Routing ────────────────────────────────────────────────────────────@@ -124,6 +125,9 @@ async function init() {$('ae-title').textContent = `Customize · ${avatar.name}`;$('ae-back').href = `/avatars/${encodeURIComponent(avatar.id)}`;+ // This avatar already has a baked GLB, so it's playable right now — light up+ // the handoff into /play.+ $('ae-play').disabled = false;currentAppearance = normalizeAppearance(avatar.appearance);workingAppearance = clone(currentAppearance);@@ -624,6 +628,26 @@ async function applyAccessory(tab, presetId) {// ── Header / status ────────────────────────────────────────────────────function bindHeader() {+ // Jump into /play as this avatar. If there are unsaved appearance edits, bake+ // them first so the world shows the look the user actually sees here, then hand+ // off the canonical avatar id (peers resolve it to the freshly-baked GLB).+ $('ae-play').addEventListener('click', async () => {+ $('ae-play').disabled = true;+ try {+ if (!$('ae-save').disabled) {+ setStatus('spin', 'Saving your look before you play…');+ await saveAppearance();+ renderChips();+ renderActivePanel();+ updateDirtyState();+ }+ setStatus('spin', 'Entering /play…');+ await playAs({ id: avatar.id, name: avatar.name, dest: '/play' });+ } catch (err) {+ setStatus('err', err.message);+ $('ae-play').disabled = false;+ }+ });$('ae-save').addEventListener('click', async () => {$('ae-save').disabled = true;$('ae-reset').disabled = true;diff --git a/src/game/avatar-rig.js b/src/game/avatar-rig.jsindex efcc86657..c3f6fa123 100644--- a/src/game/avatar-rig.js+++ b/src/game/avatar-rig.js@@ -14,6 +14,7 @@ import {import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';import { AnimationManager } from '../animation-manager.js';+import { GUEST_SENTINEL, resolveGuestAvatar } from './play-handoff.js';export const AVATAR_DEFAULT = '/avatars/default.glb';export const MANIFEST_URL = '/animations/manifest.json';@@ -66,6 +67,10 @@ export function getLocomotionDefs() {export async function resolveAvatarUrl(input) {const v = (input || '').trim();if (!v) return AVATAR_DEFAULT;+ // A just-created avatar staged locally (create → play handoff). Resolves to a+ // blob: URL for instant self-preview; the scene uploads it in the background+ // and swaps in a public URL so peers can load it too.+ if (v === GUEST_SENTINEL) return (await resolveGuestAvatar()) || AVATAR_DEFAULT;if (/^https?:\/\//i.test(v) || v.startsWith('/')) return v;try {const r = await fetch(`/api/avatars/${encodeURIComponent(v)}`, { headers: { accept: 'application/json' } });@@ -74,9 +79,30 @@ export async function resolveAvatarUrl(input) {return AVATAR_DEFAULT;}+// Plausible human heights in metres. Name labels and chat bubbles anchor to+// this value, so it must stay near the *visible* top of the avatar.+const MIN_AVATAR_HEIGHT_M = 0.5;+const MAX_AVATAR_HEIGHT_M = 2.4;+const FALLBACK_AVATAR_HEIGHT_M = 1.7;++// Derive the head-anchor height from a model's bounding box. Box3.setFromObject+// reads each skinned mesh's *rest-pose* geometry AABB — which for many rigged+// GLBs/VRMs bears no relation to the posed, visible silhouette (stray helper+// geometry, a scaled skeleton root, or bind-pose vertices flung far from origin+// can report tens of metres while the avatar renders at normal size). An+// unbounded height pushes the chat bubble past the camera's far plane, so the+// frustum cull in _updateLabels hides it and the bubble never appears above the+// head. Clamp to a human range so a mis-measured model still anchors sanely.+function headAnchorHeight(box) {+ const raw = box.max.y - box.min.y;+ if (!Number.isFinite(raw)) return FALLBACK_AVATAR_HEIGHT_M;+ return Math.min(MAX_AVATAR_HEIGHT_M, Math.max(MIN_AVATAR_HEIGHT_M, raw));+}+// Load a GLB avatar into a rig + wire an AnimationManager (idle/walk/emotes).-// Returns { height }. On failure, drops in a capsule stand-in so the player is-// never invisible.+// Returns { height, fallback }. On failure, drops in a capsule stand-in so the+// player is never invisible, and flags `fallback: true` so callers can tell the+// user their model didn't load instead of silently swapping it.export async function buildAvatar(rig, url, anim) {try {const gltf = await _gltf.loadAsync(url);@@ -87,7 +113,7 @@ export async function buildAvatar(rig, url, anim) {rig.add(model);anim.attach(model);if (_animDefs?.length) { anim.setAnimationDefs(_animDefs); await anim.loadAll(); await anim.crossfadeTo(CLIP_IDLE, 0); }- return { height: Math.max(0.5, box.max.y - box.min.y) };+ return { height: headAnchorHeight(box), fallback: false };} catch (err) {console.warn('[avatar-rig] avatar load failed, using stand-in:', url, err?.message);const body = new Mesh(new CapsuleGeometry(0.32, 0.7, 4, 10), new MeshStandardMaterial({ color: 0x8aa6d8 }));@@ -95,7 +121,7 @@ export async function buildAvatar(rig, url, anim) {const head = new Mesh(new SphereGeometry(0.28, 14, 10), new MeshStandardMaterial({ color: 0xf1c9a5 }));head.position.y = 1.55; head.castShadow = true;rig.add(body, head);- return { height: 1.7 };+ return { height: 1.7, fallback: true };}}diff --git a/src/game/boot-avatar.js b/src/game/boot-avatar.jsindex 735346a07..807d4b8f6 100644--- a/src/game/boot-avatar.js+++ b/src/game/boot-avatar.js@@ -23,7 +23,9 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { AnimationManager } from '../animation-manager.js';import {AVATAR_DEFAULT, loadManifest, getLocomotionDefs, CLIP_IDLE,+ resolveAvatarUrl, dracoLoader,} from './avatar-rig.js';+import { getPlayAvatar } from './play-handoff.js';const REDUCED_MOTION = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;const TURN_SPEED = 0.5; // radians/sec — a slow, premium turntable@@ -62,7 +64,16 @@ function boot() {window.addEventListener('resize', sizeToBox, { passive: true });- new GLTFLoader().loadAsync(AVATAR_DEFAULT).then(async (gltf) => {+ // Preview the avatar the player has actually chosen (persisted in cc-avatar by+ // the lobby / a create→play handoff), not a generic default — so the first+ // character they see while the scene loads is *theirs*. DRACO is wired in+ // because most avatar GLBs are compressed. Falls back to the default on any+ // resolve/load failure so a broken pick never wedges the loader.+ const loader = new GLTFLoader();+ loader.setDRACOLoader(dracoLoader);+ resolveAvatarUrl(getPlayAvatar())+ .then((chosen) => loader.loadAsync(chosen).catch(() => loader.loadAsync(AVATAR_DEFAULT)))+ .then(async (gltf) => {if (!alive) return;model = gltf.scene;model.traverse((n) => { if (n.isMesh) { n.frustumCulled = false; n.castShadow = false; } });diff --git a/src/game/build-voxels.js b/src/game/build-voxels.jsnew file mode 100644index 000000000..fda6bf19d--- /dev/null+++ b/src/game/build-voxels.js@@ -0,0 +1,387 @@+// Collaborative voxel building for Coin Communities — the Minecraft layer.+//+// Every /play world is a shared, persistent place; this module lets the people+// in it BUILD that place. Players place and break 1.5m blocks on a grid; the+// server (WalkRoom) is authoritative and persists the result per coin, so a+// community's creation is there when they come back and there for everyone who+// drops in. Two coins never share a build — it rides on the same per-mint room+// isolation the avatars and chat already use.+//+// This file owns three things, kept deliberately separate from the scene:+// 1. The block palette (BLOCK_TYPES) + grid maths, shared with the server's+// validation (the caps here MUST mirror WalkRoom's).+// 2. VoxelWorld — instanced rendering of the whole build (one InstancedMesh+// per block type so a few thousand blocks stay a handful of draw calls),+// plus raycasting (what cell is the player aiming at?) and a ghost cursor.+// 3. createBuildHud — the self-contained build HUD (hotbar, mode toggle), so+// the build UI never has to thread through the rest of the chrome.++import {+ Object3D, Vector3, Color, BoxGeometry, EdgesGeometry,+ InstancedMesh, LineSegments, LineBasicMaterial, Mesh,+ MeshStandardMaterial, MeshBasicMaterial, DynamicDrawUsage, Group,+} from 'three';++// Metres per grid cell. Sized so a stack of three reads as "wall height" next to+// a ~1.7m avatar — substantial to build with, without thousands of tiny cubes.+export const BLOCK = 1.5;+// Build bounds — a circular area on the plaza and a height ceiling, in cells.+// These mirror WalkRoom's MAX_GRID_XZ / MAX_GRID_Y exactly; the server rejects+// anything outside them, so keeping them in sync keeps the client honest.+export const MAX_GRID_XZ = 30;+export const MAX_GRID_Y = 24;+export const MAX_BLOCKS = 6000;++// The palette. Index === the wire type the server validates against, so order is+// load-bearing — never reorder, only append (and bump BLOCK_TYPE_COUNT server+// side). `swatch` is the hotbar colour; `emissive`/`opacity`/`metalness` tune the+// in-world material so gold glints, neon glows, and glass reads as glass.+export const BLOCK_TYPES = [+ { name: 'Stone', color: 0x9aa0a8, swatch: '#9aa0a8', roughness: 0.95 },+ { name: 'Grass', color: 0x5cb24f, swatch: '#5cb24f', roughness: 1 },+ { name: 'Dirt', color: 0x8a5a36, swatch: '#8a5a36', roughness: 1 },+ { name: 'Wood', color: 0xb07f43, swatch: '#b07f43', roughness: 0.85 },+ { name: 'Brick', color: 0xb5483a, swatch: '#b5483a', roughness: 0.9 },+ { name: 'Snow', color: 0xeef3f8, swatch: '#eef3f8', roughness: 0.8 },+ { name: 'Glass', color: 0xbfe6ff, swatch: '#bfe6ff', roughness: 0.1, opacity: 0.4, metalness: 0.1 },+ { name: 'Obsidian', color: 0x15171d, swatch: '#15171d', roughness: 0.4, metalness: 0.3 },+ { name: 'Gold', color: 0xffce5c, swatch: '#ffce5c', roughness: 0.3, metalness: 0.7, emissive: 0x3a2e00, emissiveIntensity: 0.35 },+ { name: 'Neon', color: 0x2af0e0, swatch: '#2af0e0', roughness: 0.3, emissive: 0x2af0e0, emissiveIntensity: 0.85 },+];+export const BLOCK_TYPE_COUNT = BLOCK_TYPES.length;++const _dummy = new Object3D();++export function keyOf(gx, gy, gz) { return `${gx},${gy},${gz}`; }+export function parseKey(key) { const p = key.split(','); return [+p[0], +p[1], +p[2]]; }++// Centre of a grid cell in world space. y is offset by half a block so gy=0 sits+// flush on the ground plane (its base at y=0, top at y=BLOCK).+export function cellToWorld(gx, gy, gz, target = new Vector3()) {+ return target.set(gx * BLOCK, gy * BLOCK + BLOCK / 2, gz * BLOCK);+}++// Is a cell inside the legal build volume? Mirrors the server's _cellKey checks.+export function cellInBounds(gx, gy, gz) {+ if (!Number.isInteger(gx) || !Number.isInteger(gy) || !Number.isInteger(gz)) return false;+ if (gy < 0 || gy >= MAX_GRID_Y) return false;+ return Math.hypot(gx, gz) <= MAX_GRID_XZ;+}++function makeMaterial(def) {+ const opts = {+ color: def.color,+ roughness: def.roughness ?? 0.9,+ metalness: def.metalness ?? 0,+ };+ if (def.emissive !== undefined) { opts.emissive = def.emissive; opts.emissiveIntensity = def.emissiveIntensity ?? 0.4; }+ if (def.opacity !== undefined) { opts.transparent = true; opts.opacity = def.opacity; }+ return new MeshStandardMaterial(opts);+}++// One InstancedMesh per block type, grown in powers of two as the build expands.+// Instance index ↔ key is kept in `keys[]`; removal swap-pops the last instance+// into the freed slot and reports the moved key so the owner can fix its index.+class TypeBatch {+ constructor(scene, geometry, material, type) {+ this.scene = scene;+ this.geometry = geometry;+ this.material = material;+ this.type = type;+ this.keys = [];+ this.capacity = 0;+ this.mesh = null;+ }++ _alloc(cap) {+ const m = new InstancedMesh(this.geometry, this.material, cap);+ m.castShadow = true;+ m.receiveShadow = true;+ m.frustumCulled = false; // a build can sprawl past the avatar-fit bounds+ m.instanceMatrix.setUsage(DynamicDrawUsage);+ m.userData.voxelType = this.type; // raycast hit → which palette batch+ m.count = this.keys.length;+ return m;+ }++ _ensure(n) {+ if (this.mesh && n <= this.capacity) return;+ const cap = Math.max(64, 1 << Math.ceil(Math.log2(Math.max(1, n))));+ const next = this._alloc(cap);+ this.capacity = cap;+ if (this.mesh) { this.scene.remove(this.mesh); this.mesh.dispose(); }+ this.mesh = next;+ this.scene.add(this.mesh);+ this._writeAll();+ }++ _writeOne(i) {+ const [gx, gy, gz] = parseKey(this.keys[i]);+ cellToWorld(gx, gy, gz, _dummy.position);+ _dummy.rotation.set(0, 0, 0);+ _dummy.scale.setScalar(1);+ _dummy.updateMatrix();+ this.mesh.setMatrixAt(i, _dummy.matrix);+ }++ _writeAll() {+ for (let i = 0; i < this.keys.length; i++) this._writeOne(i);+ this.mesh.count = this.keys.length;+ this.mesh.instanceMatrix.needsUpdate = true;+ }++ add(key) {+ const i = this.keys.length;+ this.keys.push(key);+ this._ensure(this.keys.length); // may rewrite all; cheap at human pace+ this._writeOne(i);+ this.mesh.count = this.keys.length;+ this.mesh.instanceMatrix.needsUpdate = true;+ return i;+ }++ // Remove instance i. Returns the key swapped into slot i (or null if i was+ // last), so the VoxelWorld index can be repaired in O(1).+ removeAt(i) {+ const last = this.keys.length - 1;+ let moved = null;+ if (i !== last) {+ this.keys[i] = this.keys[last];+ this._writeOne(i);+ moved = this.keys[i];+ }+ this.keys.pop();+ this.mesh.count = this.keys.length;+ this.mesh.instanceMatrix.needsUpdate = true;+ return moved;+ }++ dispose() {+ if (this.mesh) { this.scene.remove(this.mesh); this.mesh.dispose(); this.mesh = null; }+ this.material.dispose();+ }+}++export class VoxelWorld {+ constructor(scene) {+ this.scene = scene;+ this.geometry = new BoxGeometry(BLOCK, BLOCK, BLOCK);+ this.batches = BLOCK_TYPES.map((def, i) => new TypeBatch(scene, this.geometry, makeMaterial(def), i));+ this.index = new Map(); // key → { type, i }+ this._meshes = []; // refreshed lazily for raycasting+ this._buildGhost();+ }++ get count() { return this.index.size; }++ hasBlock(key) { return this.index.has(key); }++ // Add or repaint a block. Idempotent for an unchanged (key,type).+ setBlock(gx, gy, gz, type) {+ if (type < 0 || type >= this.batches.length) return;+ const key = keyOf(gx, gy, gz);+ const cur = this.index.get(key);+ if (cur) {+ if (cur.type === type) return;+ this._removeKey(key); // repaint = remove from old batch, add to new+ }+ const i = this.batches[type].add(key);+ this.index.set(key, { type, i });+ }++ removeBlock(gx, gy, gz) { this._removeKey(keyOf(gx, gy, gz)); }++ _removeKey(key) {+ const entry = this.index.get(key);+ if (!entry) return;+ const moved = this.batches[entry.type].removeAt(entry.i);+ this.index.delete(key);+ // The swap-popped block now lives at the freed slot — fix its stored index.+ if (moved) {+ const m = this.index.get(moved);+ if (m) m.i = entry.i;+ }+ }++ clear() {+ for (const b of this.batches) { while (b.keys.length) b.removeAt(b.keys.length - 1); }+ this.index.clear();+ }++ // What cell is the camera ray aiming at? Returns the hit block's cell (for+ // breaking), the adjacent empty cell along the hit face (for placing), and+ // whether that placement cell is in bounds. Falls back to the ground plane so+ // the very first block has somewhere to land.+ raycast(raycaster) {+ this._meshes.length = 0;+ for (const b of this.batches) if (b.mesh && b.mesh.count > 0) this._meshes.push(b.mesh);+ const hits = raycaster.intersectObjects(this._meshes, false);+ const blockHit = hits.find((h) => h.instanceId != null);++ // Ground-plane (y=0) intersection, computed analytically so we don't need a+ // raycastable floor object competing with the real plaza mesh.+ const ground = this._groundCell(raycaster);++ if (blockHit && (!ground || blockHit.distance <= ground.distance)) {+ const batch = this.batches[blockHit.object.userData.voxelType];+ const key = batch?.keys[blockHit.instanceId];+ if (key) {+ const [gx, gy, gz] = parseKey(key);+ const n = blockHit.face?.normal || { x: 0, y: 1, z: 0 };+ const place = [gx + Math.round(n.x), gy + Math.round(n.y), gz + Math.round(n.z)];+ return {+ hit: 'block',+ cell: [gx, gy, gz],+ placeCell: place,+ placeValid: cellInBounds(place[0], place[1], place[2]) && !this.index.has(keyOf(...place)),+ };+ }+ }+ if (ground) {+ return {+ hit: 'ground',+ cell: null,+ placeCell: ground.cell,+ placeValid: cellInBounds(...ground.cell) && !this.index.has(keyOf(...ground.cell)),+ };+ }+ return null;+ }++ _groundCell(raycaster) {+ const { origin, direction } = raycaster.ray;+ if (direction.y >= -1e-4) return null; // looking up / parallel — no floor hit+ const t = -origin.y / direction.y;+ if (t <= 0) return null;+ const px = origin.x + direction.x * t;+ const pz = origin.z + direction.z * t;+ const gx = Math.round(px / BLOCK);+ const gz = Math.round(pz / BLOCK);+ return { cell: [gx, 0, gz], distance: t * direction.length() };+ }++ // --- Ghost cursor ------------------------------------------------------+ _buildGhost() {+ const g = new Group();+ g.visible = false;+ // Slightly inflated so the wireframe rides just outside whatever it marks.+ const box = new BoxGeometry(BLOCK * 1.02, BLOCK * 1.02, BLOCK * 1.02);+ this._ghostFill = new Mesh(box, new MeshBasicMaterial({ transparent: true, opacity: 0.16, depthWrite: false }));+ this._ghostEdges = new LineSegments(new EdgesGeometry(box), new LineBasicMaterial({ transparent: true, opacity: 0.9 }));+ g.add(this._ghostFill, this._ghostEdges);+ this.scene.add(g);+ this._ghost = g;+ this._ghostColor = new Color();+ }++ // Show the cursor at a cell, tinted by intent: green = will place, red = will+ // break, amber = blocked (out of bounds / occupied).+ showGhost(cell, kind) {+ if (!cell) { this.hideGhost(); return; }+ cellToWorld(cell[0], cell[1], cell[2], this._ghost.position);+ const hex = kind === 'remove' ? 0xff5a5a : kind === 'blocked' ? 0xffb648 : 0x66ff8c;+ this._ghostColor.setHex(hex);+ this._ghostFill.material.color.copy(this._ghostColor);+ this._ghostEdges.material.color.copy(this._ghostColor);+ this._ghost.visible = true;+ }++ hideGhost() { if (this._ghost) this._ghost.visible = false; }++ dispose() {+ this.hideGhost();+ this.scene.remove(this._ghost);+ this._ghostFill.geometry.dispose(); this._ghostFill.material.dispose();+ this._ghostEdges.geometry.dispose(); this._ghostEdges.material.dispose();+ for (const b of this.batches) b.dispose();+ this.geometry.dispose();+ this.index.clear();+ }+}++// --- Build HUD -------------------------------------------------------------+// A self-contained DOM control: a hotbar of the palette (1–0 / click to pick), a+// place/break mode toggle, and an enable toggle. Returned controller lets the+// scene drive selection from keys and reflect connection state. Kept here so the+// build feature owns its own chrome end-to-end.+export function createBuildHud({ onToggle, onPick, onModeChange }) {+ const el = (tag, props = {}, kids = []) => {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(props)) {+ if (k === 'class') n.className = v;+ else if (k === 'text') n.textContent = v;+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);+ else if (v != null && v !== false) n.setAttribute(k, v === true ? '' : v);+ }+ for (const kid of [].concat(kids)) if (kid != null) n.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);+ return n;+ };++ let active = false;+ let mode = 'place';++ const toggleBtn = el('button', {+ class: 'cc-build-toggle', type: 'button', title: 'Build mode (B)', 'aria-pressed': 'false',+ onclick: () => setActive(!active),+ }, [el('span', { class: 'cc-build-toggle-ico', text: '⛏' }), el('span', { class: 'cc-build-toggle-text', text: 'Build' })]);++ const slots = BLOCK_TYPES.map((def, i) => {+ const slot = el('button', {+ class: 'cc-build-slot' + (i === 0 ? ' cc-on' : ''), type: 'button',+ title: `${def.name} (${(i + 1) % 10})`, 'aria-label': def.name,+ onclick: () => pick(i),+ }, [+ el('span', { class: 'cc-build-swatch', style: `background:${def.swatch}` }),+ el('span', { class: 'cc-build-key', text: String((i + 1) % 10) }),+ ]);+ return slot;+ });+ const hotbar = el('div', { class: 'cc-build-hotbar', role: 'toolbar', 'aria-label': 'Block palette' }, slots);++ const modeBtn = el('button', {+ class: 'cc-build-mode', type: 'button', title: 'Toggle place / break (right-click also breaks)',+ onclick: () => setMode(mode === 'place' ? 'remove' : 'place'),+ }, [el('span', { class: 'cc-build-mode-ico', text: '▦' }), el('span', { class: 'cc-build-mode-text', text: 'Place' })]);++ const hint = el('div', { class: 'cc-build-hint', text: 'Tap to place · right-click to break · 1–0 pick block' });++ const panel = el('div', { class: 'cc-build-panel', hidden: true }, [modeBtn, hotbar, hint]);+ const root = el('div', { id: 'cc-build', class: 'cc-build' }, [toggleBtn, panel]);+ document.body.appendChild(root);++ function pick(i) {+ for (let k = 0; k < slots.length; k++) slots[k].classList.toggle('cc-on', k === i);+ onPick?.(i);+ }+ function setMode(m) {+ mode = m;+ modeBtn.classList.toggle('cc-removing', m === 'remove');+ modeBtn.querySelector('.cc-build-mode-text').textContent = m === 'remove' ? 'Break' : 'Place';+ modeBtn.querySelector('.cc-build-mode-ico').textContent = m === 'remove' ? '✖' : '▦';+ onModeChange?.(m);+ }+ function setActive(v) {+ active = v;+ root.classList.toggle('cc-build-on', v);+ toggleBtn.classList.toggle('cc-on', v);+ toggleBtn.setAttribute('aria-pressed', String(v));+ panel.hidden = !v;+ onToggle?.(v);+ }++ return {+ root,+ get active() { return active; },+ get mode() { return mode; },+ setActive,+ setMode,+ select: pick,+ // Disable the whole control when there's no live connection to build into.+ setEnabled(enabled, reason) {+ toggleBtn.disabled = !enabled;+ toggleBtn.title = enabled ? 'Build mode (B)' : (reason || 'Building needs a live connection');+ if (!enabled && active) setActive(false);+ },+ dispose() { root.remove(); },+ };+}diff --git a/src/game/chart-screen.js b/src/game/chart-screen.jsindex 1d7762b70..a71d59a0c 100644--- a/src/game/chart-screen.js+++ b/src/game/chart-screen.js@@ -171,6 +171,7 @@ export function createChartScreen(scene, coin, opts = {}) {let points = []; // [{ ts, price }] ascending by tslet recent = []; // newest-first trades for the ticker/flowlet status = 'loading'; // loading | live | empty | error+ let firstFill = true; // suppress the reactor on the initial backlog polllet lastErr = 0;let pollTimer = null;let destroyed = false;@@ -178,24 +179,25 @@ export function createChartScreen(scene, coin, opts = {}) {let t = 0; // elapsed seconds (ticker scroll + pulse)function ingest(trades) {- let added = 0;+ const fresh = []; // trades new this batch — emitted so the world can reactfor (const tr of trades) {if (!tr.tx || seen.has(tr.tx)) continue;seen.add(tr.tx);- added++;const ts = tr.timestamp ? Date.parse(tr.timestamp) : Date.now();const price = tr.price_usd != null ? Number(tr.price_usd) : null;if (price > 0 && isFinite(price)) points.push({ ts, price });- recent.push({+ const rec = {tx: tr.tx,ts,isBuy: tr.is_buy === true,sol: Number(tr.sol_amount) || 0,usd: tr.usd_amount != null ? Number(tr.usd_amount) : null,trader: tr.user || '',- });+ };+ recent.push(rec);+ fresh.push(rec);}- if (!added) return;+ if (!fresh.length) return;points.sort((a, b) => a.ts - b.ts);if (points.length > MAX_POINTS) points = points.slice(-MAX_POINTS);recent.sort((a, b) => b.ts - a.ts);@@ -205,6 +207,15 @@ export function createChartScreen(scene, coin, opts = {}) {// we need to keep recognising.if (seen.size > 800) seen = new Set(recent.map((r) => r.tx));status = points.length ? 'live' : (recent.length ? 'live' : 'empty');+ // Hand the freshly-landed trades (newest first) + derived metrics to whoever+ // wants to drive the world off the live tape. The first poll is the backlog+ // the feed already holds, not live activity — emitting it would set off+ // fireworks for a 100-trade history dump the instant a player walks in, so we+ // swallow that initial burst and only react to trades that land while here.+ if (opts.onTrades && !firstFill) {+ const batch = fresh.slice().sort((a, b) => b.ts - a.ts);+ try { opts.onTrades(batch, metrics()); } catch { /* reactor is non-critical */ }+ }}async function fetchTrades() {@@ -214,6 +225,11 @@ export function createChartScreen(scene, coin, opts = {}) {const data = await r.json();const trades = Array.isArray(data?.trades) ? data.trades : [];ingest(trades);+ // After the first successful poll, everything it carried is treated as+ // backlog; from here on, trades are live and drive the world. Cleared+ // here (not in ingest) so an empty-on-entry coin still reacts to its+ // genuine first trade on a later poll.+ firstFill = false;if (status === 'loading') status = trades.length ? 'live' : 'empty';} catch {lastErr = Date.now();@@ -479,6 +495,7 @@ export function createChartScreen(scene, coin, opts = {}) {group,mesh: panel,mint: coin.mint,+ getMetrics: metrics,update(dt) {if (destroyed) return;t += dt;diff --git a/src/game/coin-buy.js b/src/game/coin-buy.jsnew file mode 100644index 000000000..d6a71db16--- /dev/null+++ b/src/game/coin-buy.js@@ -0,0 +1,338 @@+// Native pump.fun buy — the in-world "ape this coin" flow for /play.+//+// Every /play world IS a pump.fun coin, so the most natural action in that+// world is buying it. This is a REAL on-chain buy, not a redirect: the+// three.ws server builds the unsigned transaction (handling both the bonding+// curve and the post-graduation AMM via @pump-fun/pump-sdk), the player's+// Solana wallet signs it, and we broadcast through our same-origin RPC proxy.+//+// Loaded as its own lazy chunk (dynamic import on first Buy click) so the heavy+// Solana/pump SDKs never weigh down the main /play bundle. The read-only quote+// SDK and @solana/web3.js are themselves imported on demand inside here, so the+// modal opens instantly and prices in the background.++import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';++const WSOL = 'So11111111111111111111111111111111111111112';+const NETWORK = 'mainnet';+const SOL_PRESETS = [0.1, 0.5, 1];+const SLIPPAGE_PRESETS = [100, 300, 500]; // bps — 1% / 3% / 5%+const DEFAULT_SLIPPAGE_BPS = 300;+const PUMP_DECIMALS = 6; // pump.fun mints are always 6 decimals++let _open = null; // the live modal controller, so a second click reuses it++function el(tag, props = {}, kids = []) {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(props)) {+ if (k === 'class') n.className = v;+ else if (k === 'text') n.textContent = v;+ else if (k === 'html') n.innerHTML = v;+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);+ else if (v !== null && v !== undefined && v !== false) n.setAttribute(k, v === true ? '' : v);+ }+ for (const kid of [].concat(kids)) if (kid != null && kid !== false) n.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);+ return n;+}++const fmtTokens = (raw) => {+ const n = Number(raw) / 10 ** PUMP_DECIMALS;+ if (!isFinite(n) || n <= 0) return null;+ if (n >= 1e9) return (n / 1e9).toFixed(2) + 'B';+ if (n >= 1e6) return (n / 1e6).toFixed(2) + 'M';+ if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';+ return n.toLocaleString(undefined, { maximumFractionDigits: 2 });+};++function shortAddr(a) {+ return a ? `${a.slice(0, 4)}…${a.slice(-4)}` : '';+}++/**+ * Open the buy modal for a coin. Idempotent — a second call refocuses the+ * existing modal instead of stacking.+ * @param {{mint:string, name?:string, symbol?:string, image?:string}} coin+ */+export function openBuyModal(coin) {+ if (!coin?.mint) return;+ if (_open) { _open.focus(); return; }+ _open = new BuyModal(coin);+}++class BuyModal {+ constructor(coin) {+ this.coin = coin;+ this.sym = coin.symbol ? '$' + coin.symbol.toUpperCase() : 'this coin';+ this.amount = SOL_PRESETS[0];+ this.slippageBps = DEFAULT_SLIPPAGE_BPS;+ this.busy = false;+ this._quoteSeq = 0;+ this._build();+ this._refreshWallet();+ this._quote();+ }++ // --------------------------------------------------------------- view+ _build() {+ this.amountInput = el('input', {+ type: 'number', min: '0', step: '0.05', inputmode: 'decimal',+ class: 'cc-buy-amount', value: String(this.amount), 'aria-label': 'Amount in SOL',+ oninput: () => { this.amount = Math.max(0, Number(this.amountInput.value) || 0); this._syncPresets(); this._quote(); this._syncCta(); },+ });++ this.presetRow = el('div', { class: 'cc-buy-presets' },+ SOL_PRESETS.map((v) => el('button', {+ class: 'cc-buy-preset' + (v === this.amount ? ' cc-on' : ''), text: v + ' SOL', type: 'button',+ onclick: () => { this.amount = v; this.amountInput.value = String(v); this._syncPresets(); this._quote(); this._syncCta(); },+ })));++ this.quoteLine = el('div', { class: 'cc-buy-quote', role: 'status', 'aria-live': 'polite' }, 'Fetching price…');++ this.slipRow = el('div', { class: 'cc-buy-slip' }, [+ el('span', { class: 'cc-buy-slip-label', text: 'Max slippage' }),+ ...SLIPPAGE_PRESETS.map((bps) => el('button', {+ class: 'cc-buy-slip-btn' + (bps === this.slippageBps ? ' cc-on' : ''), type: 'button',+ text: (bps / 100) + '%',+ onclick: () => { this.slippageBps = bps; for (const b of this.slipRow.querySelectorAll('.cc-buy-slip-btn')) b.classList.toggle('cc-on', b.textContent === (bps / 100) + '%'); this._quote(); },+ })),+ ]);++ this.walletLine = el('div', { class: 'cc-buy-wallet' });++ this.cta = el('button', { class: 'cc-buy-cta', type: 'button', onclick: () => this._onCta() });+ this.ctaLabel = 'buy';++ this.statusLine = el('div', { class: 'cc-buy-status', role: 'status', 'aria-live': 'polite', hidden: true });++ const pumpLink = el('a', {+ class: 'cc-buy-pumplink', href: `https://pump.fun/coin/${this.coin.mint}`,+ target: '_blank', rel: 'noopener noreferrer',+ text: 'Or trade on pump.fun ↗',+ });++ const head = el('div', { class: 'cc-buy-head' }, [+ this.coin.image ? el('img', { class: 'cc-buy-img', src: this.coin.image, alt: '' }) : el('div', { class: 'cc-buy-img cc-buy-img-ph', text: '◎' }),+ el('div', { class: 'cc-buy-titles' }, [+ el('div', { class: 'cc-buy-name', text: this.coin.name || 'Buy coin' }),+ el('div', { class: 'cc-buy-sym', text: this.coin.symbol ? '$' + this.coin.symbol.toUpperCase() : this.coin.mint.slice(0, 8) + '…' }),+ ]),+ el('button', { class: 'cc-buy-x', type: 'button', 'aria-label': 'Close', text: '✕', onclick: () => this.close() }),+ ]);++ this.card = el('div', { class: 'cc-buy-card', role: 'dialog', 'aria-modal': 'true', 'aria-label': `Buy ${this.coin.name || 'coin'}` }, [+ head,+ el('label', { class: 'cc-buy-field' }, [+ el('span', { class: 'cc-buy-field-label', text: 'You pay' }),+ el('div', { class: 'cc-buy-amount-wrap' }, [this.amountInput, el('span', { class: 'cc-buy-unit', text: 'SOL' })]),+ ]),+ this.presetRow,+ this.quoteLine,+ this.slipRow,+ this.walletLine,+ this.cta,+ this.statusLine,+ pumpLink,+ ]);++ this.overlay = el('div', { class: 'cc-buy-overlay', onpointerdown: (e) => { if (e.target === this.overlay) this.close(); } }, [this.card]);+ // Keep the game from swallowing typing/keys while the modal is up.+ this.card.addEventListener('keydown', (e) => {+ if (e.key === 'Escape') this.close();+ e.stopPropagation();+ });+ document.body.appendChild(this.overlay);+ requestAnimationFrame(() => this.overlay.classList.add('cc-on'));+ this._syncCta();+ setTimeout(() => this.amountInput.focus(), 30);+ }++ focus() { this.amountInput?.focus(); }++ close() {+ this.overlay.classList.remove('cc-on');+ setTimeout(() => this.overlay.remove(), 180);+ if (_open === this) _open = null;+ }++ _syncPresets() {+ for (const b of this.presetRow.children) b.classList.toggle('cc-on', b.textContent === this.amount + ' SOL');+ }++ // --------------------------------------------------------------- wallet+ _refreshWallet() {+ const w = detectSolanaWallet();+ const addr = w?.publicKey?.toString?.();+ if (!w) {+ this.walletLine.textContent = '';+ this.walletLine.append(el('span', { class: 'cc-buy-wallet-off', text: 'No Solana wallet detected' }));+ this._wallet = null;+ } else if (addr) {+ this.walletLine.textContent = '';+ this.walletLine.append(+ el('span', { class: 'cc-buy-wallet-dot' }),+ el('span', { text: `Wallet ${shortAddr(addr)}` }),+ );+ this._wallet = w;+ } else {+ this.walletLine.textContent = '';+ this.walletLine.append(el('span', { text: 'Wallet not connected' }));+ this._wallet = w;+ }+ this._syncCta();+ }++ _syncCta() {+ const w = detectSolanaWallet();+ const connected = !!w?.publicKey;+ if (this.busy) { this.cta.disabled = true; return; }+ if (!w) { this.cta.textContent = 'Get Phantom to buy'; this.ctaLabel = 'install'; this.cta.disabled = false; return; }+ if (!connected) { this.cta.textContent = 'Connect wallet'; this.ctaLabel = 'connect'; this.cta.disabled = false; return; }+ this.ctaLabel = 'buy';+ this.cta.textContent = this.amount > 0 ? `Buy ${this.amount} SOL of ${this.sym}` : 'Enter an amount';+ this.cta.disabled = !(this.amount > 0);+ }++ // --------------------------------------------------------------- quote+ async _quote() {+ if (!(this.amount > 0)) { this.quoteLine.textContent = ''; return; }+ const seq = ++this._quoteSeq;+ this.quoteLine.classList.remove('cc-buy-quote-warn');+ this.quoteLine.textContent = 'Fetching price…';+ const lamports = Math.floor(this.amount * 1e9);+ try {+ const { quoteSwap } = await import('../pump/pump-swap-quote.js');+ const q = await quoteSwap({ inputMint: WSOL, outputMint: this.coin.mint, amountIn: lamports, slippageBps: this.slippageBps });+ if (seq !== this._quoteSeq) return;+ const tokens = fmtTokens(q.amountOut);+ const impact = (q.priceImpactBps / 100);+ this.quoteLine.textContent = '';+ this.quoteLine.append(+ el('span', { class: 'cc-buy-quote-out', text: tokens ? `≈ ${tokens} ${this.coin.symbol ? '$' + this.coin.symbol.toUpperCase() : 'tokens'}` : 'Quoted at market' }),+ el('span', { class: 'cc-buy-quote-impact' + (impact >= 5 ? ' cc-buy-quote-warn' : ''), text: ` · ${impact < 0.01 ? '<0.01' : impact.toFixed(2)}% impact` }),+ );+ } catch (err) {+ if (seq !== this._quoteSeq) return;+ // No AMM pool yet → the coin is still on the bonding curve. The buy still+ // works (the server prices it on-curve); we just can't pre-quote the exact+ // token amount. Say so honestly instead of pretending.+ this.quoteLine.classList.add('cc-buy-quote-warn');+ this.quoteLine.textContent = `Still on the bonding curve — priced at buy. You'll receive ${this.sym} for ${this.amount} SOL.`;+ }+ }++ // --------------------------------------------------------------- actions+ async _onCta() {+ if (this.busy) return;+ const w = detectSolanaWallet();+ if (!w) { window.open('https://phantom.app/', '_blank', 'noopener'); return; }+ if (!w.publicKey) {+ this._setStatus('Approve the connection in your wallet…', '');+ try { await w.connect(); } catch { this._setStatus('Wallet connection cancelled.', 'err'); return; }+ this._refreshWallet();+ this._setStatus('', '', true);+ return; // let the user review, then click Buy+ }+ this._buy();+ }++ async _buy() {+ if (!(this.amount > 0)) return;+ this.busy = true; this._syncCta();+ const wallet = detectSolanaWallet();+ const walletAddress = wallet.publicKey.toString();+ try {+ this._setStatus('Building your transaction…', '');+ const prep = await this._fetchJson('/api/pump/buy-prep', {+ mint: this.coin.mint, network: NETWORK, sol: this.amount,+ slippage_bps: this.slippageBps, wallet_address: walletAddress,+ });++ this._setStatus('Approve the purchase in your wallet…', '');+ const { VersionedTransaction, Connection } = await import('@solana/web3.js');+ const tx = VersionedTransaction.deserialize(+ Uint8Array.from(atob(prep.tx_base64), (c) => c.charCodeAt(0)),+ );+ const signed = await wallet.signTransaction(tx);++ this._setStatus('Submitting on-chain…', '');+ const conn = new Connection(SOLANA_RPC[NETWORK], 'confirmed');+ const sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false, maxRetries: 3 });++ const url = solanaTxExplorerUrl(NETWORK, sig);+ this._setStatusNode(el('span', {}, ['Submitted — ', el('a', { href: url, target: '_blank', rel: 'noopener', text: 'view ↗' }), ' · confirming…']), 'ok');++ const latest = await conn.getLatestBlockhash('confirmed');+ try {+ await conn.confirmTransaction({ signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, 'confirmed');+ } catch { /* landed but slow to confirm — the explorer link is the source of truth */ }++ // Best-effort server tracking; the buy already settled on-chain, so a+ // failure here must never read as a failed purchase.+ this._fetchJson('/api/pump/buy-confirm', {+ mint: this.coin.mint, network: NETWORK, tx_signature: sig,+ wallet_address: walletAddress, sol: this.amount, route: prep.route, slippage_bps: this.slippageBps,+ }).catch(() => {});++ this.cta.textContent = `Bought ${this.sym} ✓`;+ this._setStatusNode(el('span', {}, [`Bought ${this.sym}. `, el('a', { href: url, target: '_blank', rel: 'noopener', text: 'View on Solscan ↗' })]), 'ok');+ this.busy = false;+ this.cta.disabled = true;+ setTimeout(() => this._refreshWallet(), 1500);+ } catch (err) {+ this.busy = false; this._syncCta();+ if (err.status === 401) {+ this._setStatusNode(el('span', {}, [+ 'Sign in to three.ws to trade. ',+ el('button', { class: 'cc-buy-link', type: 'button', text: 'Sign in', onclick: () => this._signInAndRetry() }),+ ]), 'err');+ return;+ }+ const msg = err.message || 'Purchase failed.';+ // User rejection in the wallet isn't an error worth shouting about.+ const friendly = /reject|denied|cancell?ed|user/i.test(msg) ? 'Cancelled in wallet.' : msg;+ this._setStatus(friendly, 'err');+ }+ }++ async _signInAndRetry() {+ this._setStatus('Opening sign-in…', '');+ try {+ const { signInWithWallet } = await import('../wallet-auth.js');+ await signInWithWallet();+ this._setStatus('Signed in — retrying…', 'ok');+ this._buy();+ } catch (err) {+ this._setStatus(err?.message || 'Sign-in failed.', 'err');+ }+ }++ // POST helper that surfaces the HTTP status on the thrown error so callers can+ // branch on 401 (needs sign-in) vs. other failures.+ async _fetchJson(path, body) {+ const res = await fetch(path, {+ method: 'POST', credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ const e = new Error(data.error_description || data.error || `request failed (${res.status})`);+ e.status = res.status;+ throw e;+ }+ if (path.includes('buy-prep') && !data.tx_base64) throw new Error('server did not return a transaction');+ return data;+ }++ _setStatus(text, kind, hide) {+ this.statusLine.hidden = !!hide || !text;+ this.statusLine.textContent = text || '';+ this.statusLine.setAttribute('data-kind', kind || '');+ }+ _setStatusNode(node, kind) {+ this.statusLine.hidden = false;+ this.statusLine.textContent = '';+ this.statusLine.setAttribute('data-kind', kind || '');+ this.statusLine.appendChild(node);+ }+}diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.jsindex 919ea6cb1..5f5eeb33b 100644--- a/src/game/coincommunities-ui.js+++ b/src/game/coincommunities-ui.js@@ -43,6 +43,7 @@ export class CommunityUI {constructor(h) {this.h = h;this.coins = [];+ this.featured = null; // pinned official town (e.g. the $THREE flagship)this.searchResults = []; // live pump.fun search hits beyond the trending gridthis.searching = false;this._searchSeq = 0; // guards against out-of-order async search responses@@ -57,6 +58,16 @@ export class CommunityUI {this.searchInput = el('input', { type: 'text', placeholder: 'Search any pump.fun coin…', oninput: () => this._onSearchInput() });this.grid = el('div', { class: 'cc-grid' });+ // Your display name — the label peers see above your avatar and in chat.+ // Persisted so it sticks across sessions; broadcast live if changed in-world.+ this.nameInput = el('input', {+ type: 'text', maxlength: '24', class: 'cc-name-input', id: 'cc-name-input',+ placeholder: 'Pick a name', 'aria-label': 'Your display name',+ value: localStorage.getItem('cc-name') || '',+ onchange: () => this._commitName(),+ onkeydown: (e) => { if (e.key === 'Enter') { this._commitName(); this.nameInput.blur(); } e.stopPropagation(); },+ });+this.presetRow = el('div', { class: 'cc-avatar-presets' });this.customInput = el('input', {type: 'text',@@ -76,6 +87,18 @@ export class CommunityUI {el('span', { class: 'cc-upload-text', text: 'Upload .glb' }),this.uploadFile,]);++ // Browse the full avatar library (your own + the public gallery) with live+ // 3D previews, instead of pasting a URL. Reuses the platform-wide+ // AvatarGalleryPicker, lazy-loaded so the lobby bundle stays lean.+ this.galleryBtn = el('button', {+ type: 'button', class: 'cc-gallery-btn',+ title: 'Browse your avatars and the public gallery',+ onclick: () => this._openGallery(),+ }, [+ el('span', { class: 'cc-gallery-ico', text: '🖼' }),+ el('span', { class: 'cc-gallery-text', text: 'Browse gallery' }),+ ]);this.uploadStatus = el('div', { class: 'cc-upload-status', role: 'status', 'aria-live': 'polite', hidden: true });this.lobby = el('div', { id: 'cc-lobby' }, [@@ -95,9 +118,13 @@ export class CommunityUI {]),]),this.avatarBar = el('div', { class: 'cc-avatar-bar' }, [- el('div', { class: 'cc-avatar-label', html: 'Your avatar<small>Pick one, paste a URL, or drop your own .glb</small>' }),+ el('div', { class: 'cc-name-row' }, [+ 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>' }),this.presetRow,- el('div', { class: 'cc-avatar-custom' }, [this.customInput, this.uploadBtn]),+ el('div', { class: 'cc-avatar-custom' }, [this.customInput, this.galleryBtn, this.uploadBtn]),this.uploadStatus,el('div', { class: 'cc-avatar-dropmsg', text: 'Drop .glb to use as your avatar' }),]),@@ -176,6 +203,53 @@ export class CommunityUI {this._setAvatar(url, 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.+ async _openGallery() {+ this.galleryBtn.classList.add('cc-busy');+ try {+ const { openAvatarPicker } = await import('../avatar-gallery-picker.js');+ const selected = await openAvatarPicker({+ source: 'both',+ showModes: false,+ title: 'Choose your avatar',+ ctaLabel: 'Use this avatar',+ selectedId: this._galleryChip?._avatarId || '',+ });+ if (selected) this._adoptGalleryAvatar(selected);+ } catch (err) {+ console.warn('[coincommunities] gallery picker failed:', err?.message);+ } finally {+ this.galleryBtn.classList.remove('cc-busy');+ }+ }++ // Surface a gallery pick as its own selected chip and make it the active+ // avatar. Stores the canonical avatar id when available (so the picker can+ // pre-select it next time); the scene resolves it to a loadable URL before+ // broadcasting to peers.+ _adoptGalleryAvatar(a) {+ const value = a.id || a.model_url;+ if (!value) return;+ if (this._galleryChip?.isConnected) this._galleryChip.remove();+ const chip = el('button', {+ class: 'cc-avatar-chip cc-avatar-loading cc-avatar-gallery',+ title: a.name || 'Your avatar', 'aria-label': a.name || 'Your avatar',+ onclick: () => this._setAvatar(value, false),+ }, [+ a.thumbnail_url+ ? el('img', { src: a.thumbnail_url, alt: a.name || 'Avatar', loading: 'lazy' })+ : el('span', { class: 'cc-avatar-glyph', text: '🧑' }),+ ]);+ chip._url = value;+ chip._avatarId = a.id || '';+ this._galleryChip = chip;+ this.presetRow.insertBefore(chip, this.presetRow.firstChild);+ this._renderChipPreview(chip, { url: a.model_url || value, label: a.name || 'Your avatar' });+ this._setAvatar(value, false);+ }+async _renderPresets() {// Default + a few real three.ws community avatars (best-effort fetch).const presets = [{ label: 'Default', url: DEFAULT_AVATAR, icon: '🧍' }];@@ -236,6 +310,9 @@ export class CommunityUI {setCoinsLoading() {this.grid.textContent = '';+ // Keep the pinned official town visible while the live grid loads, so the+ // flagship never blinks out behind the skeletons.+ if (this.featured) this.grid.appendChild(this._coinCard(this.featured, true));for (let i = 0; i < 8; i++) {this.grid.appendChild(el('div', { class: 'cc-card cc-skeleton' }, [el('div', { class: 'cc-card-img' }),@@ -246,6 +323,9 @@ export class CommunityUI {setCoins(list) { this.coins = list || []; this._renderGrid(); }+ /** Pin an official town (e.g. the $THREE flagship) to the top of the lobby. */+ setFeatured(coin) { this.featured = coin && coin.mint ? coin : null; this._renderGrid(); }+setCoinsError(retry) {this.grid.textContent = '';this.grid.appendChild(el('div', { class: 'cc-state' }, [@@ -293,15 +373,19 @@ export class CommunityUI {const q = this.searchInput.value.trim().toLowerCase();const matches = (c) =>!q || (c.name || '').toLowerCase().includes(q) || (c.symbol || '').toLowerCase().includes(q) || (c.mint || '').toLowerCase().includes(q);+ // The pinned official town leads the grid when it matches the current query,+ // and is excluded from the regular list so it never appears twice.+ const featured = this.featured && matches(this.featured) ? this.featured : null;// Trending matches first, then live search hits not already on screen —// deduped by mint so a coin never appears twice.- const list = this.coins.filter(matches);+ const list = this.coins.filter((c) => matches(c) && c.mint !== this.featured?.mint);const seen = new Set(list.map((c) => c.mint));+ if (this.featured) seen.add(this.featured.mint);for (const c of this.searchResults) {if (c.mint && !seen.has(c.mint)) { seen.add(c.mint); list.push(c); }}this.grid.textContent = '';- if (!list.length) {+ if (!featured && !list.length) {if (this.searching) { this._renderSearching(); return; }this.grid.appendChild(el('div', { class: 'cc-state' }, [el('span', { class: 'cc-state-ico', text: '🪙' }),@@ -309,29 +393,40 @@ export class CommunityUI {]));return;}- for (const c of list) {- const mc = fmtMc(c.marketCap);- const card = el('div', { class: 'cc-card', onclick: () => this.h.onEnter(c) }, [- el('div', { class: 'cc-card-img', style: c.image ? `background-image:url("${c.image}")` : '' }, [- el('span', { class: 'cc-card-live' }, [el('span', { class: 'cc-dot' }), document.createTextNode('LIVE')]),- ]),- el('div', { class: 'cc-card-body' }, [- el('div', { class: 'cc-card-name', text: c.name || 'Unnamed coin' }),- el('div', { class: 'cc-card-meta' }, [- el('span', { class: 'cc-card-sym', text: c.symbol ? '$' + c.symbol : '' }),- mc ? el('span', { text: mc + ' mcap' }) : null,- ]),- el('div', { class: 'cc-card-cta', text: 'Enter community →' }),- ]),- ]);- this.grid.appendChild(card);- }+ if (featured) this.grid.appendChild(this._coinCard(featured, true));+ for (const c of list) this.grid.appendChild(this._coinCard(c, false));// Searching beyond the trending grid while results are already showing.if (this.searching) this.grid.appendChild(el('div', { class: 'cc-search-more' }, [el('span', { class: 'cc-spinner' }), document.createTextNode('Searching all of pump.fun…'),]));}+ // Build one lobby card. The featured (official) town gets a distinct frame, an+ // OFFICIAL badge, and a "home town" call to action so it reads as the flagship.+ _coinCard(c, featured) {+ const mc = fmtMc(c.marketCap);+ const liveBadge = featured+ ? el('span', { class: 'cc-card-official', title: 'Official three.ws town' }, [+ el('span', { class: 'cc-card-official-ico', text: '◇' }),+ document.createTextNode('OFFICIAL'),+ ])+ : el('span', { class: 'cc-card-live' }, [el('span', { class: 'cc-dot' }), document.createTextNode('LIVE')]);+ return el('div', {+ class: 'cc-card' + (featured ? ' cc-card-featured' : ''),+ onclick: () => this.h.onEnter(c),+ }, [+ el('div', { class: 'cc-card-img', style: c.image ? `background-image:url("${c.image}")` : '' }, [liveBadge]),+ el('div', { class: 'cc-card-body' }, [+ el('div', { class: 'cc-card-name', text: c.name || 'Unnamed coin' }),+ el('div', { class: 'cc-card-meta' }, [+ el('span', { class: 'cc-card-sym', text: c.symbol ? '$' + c.symbol : '' }),+ mc ? el('span', { text: mc + ' mcap' }) : null,+ ]),+ el('div', { class: 'cc-card-cta', text: featured ? 'Enter home town →' : 'Enter community →' }),+ ]),+ ]);+ }+_renderSearching() {this.grid.appendChild(el('div', { class: 'cc-state' }, [el('span', { class: 'cc-spinner cc-spinner-lg' }),@@ -345,6 +440,13 @@ export class CommunityUI {this.coinName = el('div', { class: 'cc-coin-name', text: '' });this.coinSym = el('span', { class: 'cc-coin-sym', text: '' });this.onlineCount = el('span', { text: '1 online' });+ // Buy this coin from inside its own world — the most natural action in a+ // pump.fun community. Opens the native on-chain buy modal (lazy chunk).+ this.buyBtnLabel = el('span', { class: 'cc-buy-btn-text', text: 'Buy' });+ this.buyBtn = el('button', {+ class: 'cc-buy-btn', type: 'button', title: 'Buy this coin',+ onclick: () => this.h.onBuy?.(),+ }, [el('span', { class: 'cc-buy-btn-ico', text: '⚡' }), this.buyBtnLabel]);const banner = el('div', { class: 'cc-coin-banner' }, [this.coinImg,el('div', { class: 'cc-coin-info' }, [@@ -354,6 +456,7 @@ export class CommunityUI {el('span', { class: 'cc-online' }, [el('span', { class: 'cc-dot' }), this.onlineCount]),]),]),+ this.buyBtn,]);const leave = el('button', { class: 'cc-leave', onclick: () => this.h.onLeave() }, [@@ -361,10 +464,11 @@ export class CommunityUI {]);this.statusText = el('span', { text: 'connecting…' });+ this.pingText = el('span', { class: 'cc-ping', hidden: true });this.statusPill = el('div', {id: 'cc-status', 'data-state': 'connecting',onclick: () => { if (['offline', 'failed'].includes(this.statusPill.getAttribute('data-state'))) this.h.onRetry?.(); },- }, [el('span', { class: 'cc-dot' }), this.statusText]);+ }, [el('span', { class: 'cc-dot' }), this.statusText, this.pingText]);this.chatLog = el('div', { class: 'cc-chat-log' });this.chatInput = el('input', {@@ -431,11 +535,13 @@ export class CommunityUI {this.hud.hidden = false;this.coinName.textContent = coin.name || 'Community';this.coinSym.textContent = coin.symbol ? '$' + coin.symbol : '';+ this.buyBtnLabel.textContent = coin.symbol ? 'Buy $' + coin.symbol.toUpperCase() : 'Buy';if (coin.image) { this.coinImg.src = coin.image; this.coinImg.style.display = ''; }else this.coinImg.style.display = 'none';this.chatLog.textContent = '';this._unread = 0;this.chatUnread.hidden = true;+ this.pingText.hidden = true;}showLobby() {@@ -448,10 +554,48 @@ export class CommunityUI {const labels = { connecting: 'connecting…', online: 'connected', offline: 'reconnecting…', failed: 'offline — retry', idle: 'idle' };this.statusPill.setAttribute('data-state', state);this.statusText.textContent = labels[state] || state;+ // The latency readout is only meaningful while the link is live.+ if (state !== 'online') this.pingText.hidden = true;+ }++ // Show the live round-trip latency next to the status dot. Colour-coded so a+ // glance reads as healthy (green), okay (amber), or laggy (red).+ setPing(ms) {+ if (this.statusPill.getAttribute('data-state') !== 'online') return;+ this.pingText.hidden = false;+ this.pingText.textContent = `${ms}ms`;+ this.pingText.setAttribute('data-grade', ms < 90 ? 'good' : ms < 200 ? 'ok' : 'bad');}setOnline(n) { this.onlineCount.textContent = `${n} online`; }+ /** Persist the typed display name and, if connected, broadcast it live. */+ _commitName() {+ const name = this.nameInput.value.trim().slice(0, 24);+ if (name) localStorage.setItem('cc-name', name);+ this.h.onRename?.(name);+ }++ /** The chosen display name, or '' to let the caller fall back to a guest id. */+ getName() { return this.nameInput.value.trim().slice(0, 24); }++ /** Reflect a name assigned elsewhere (e.g. a generated guest id) in the field. */+ setName(name) { if (name) this.nameInput.value = name; }++ // Transient bottom-center toast for one-off notices (avatar fell back to a+ // stand-in, etc.). Self-dismisses; a new toast replaces the previous one.+ toast(msg, kind = '') {+ if (!this._toast) {+ this._toast = el('div', { id: 'cc-toast', role: 'status', 'aria-live': 'polite' });+ document.body.appendChild(this._toast);+ }+ clearTimeout(this._toastTimer);+ this._toast.textContent = msg;+ this._toast.setAttribute('data-kind', kind);+ this._toast.classList.add('cc-on');+ this._toastTimer = setTimeout(() => this._toast.classList.remove('cc-on'), 4200);+ }+addChat({ name, text, mine }) {const t = new Date();const stamp = `${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}`;diff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssindex b079a80b9..658d88ac8 100644--- a/src/game/coincommunities.css+++ b/src/game/coincommunities.css@@ -179,16 +179,15 @@ html, body {width: 50px; height: 50px; border-radius: var(--cc-radius); overflow: hidden;border: 1px solid var(--cc-edge); background: var(--cc-bg2);cursor: pointer; padding: 0; display: grid; place-items: center; font-size: 22px;- filter: grayscale(1) contrast(1.05);- transition: border-color 0.12s ease, transform 0.08s ease, filter 0.15s ease;+ transition: border-color 0.12s ease, transform 0.08s ease;}.cc-avatar-chip img { width: 100%; height: 100%; object-fit: cover; }/* Rendered avatar portraits frame head-to-chest, so contain + anchor to top andsit on the panel surface rather than being cropped like a photo thumbnail. */.cc-avatar-chip img.cc-avatar-render { object-fit: contain; object-position: center top; background: var(--cc-bg2); }.cc-avatar-glyph { font-size: 22px; line-height: 1; }-.cc-avatar-chip:hover { transform: translateY(-2px); border-color: var(--cc-edge-hi); filter: grayscale(0.4) contrast(1.05); }-.cc-avatar-chip.cc-on { border-color: #fff; box-shadow: 0 0 0 1px #fff, var(--cc-glow); filter: grayscale(0); }+.cc-avatar-chip:hover { transform: translateY(-2px); border-color: var(--cc-edge-hi); }+.cc-avatar-chip.cc-on { border-color: #fff; box-shadow: 0 0 0 1px #fff, var(--cc-glow); }/* Loading shimmer while the model renders to a portrait. */.cc-avatar-chip.cc-avatar-loading { position: relative; }.cc-avatar-chip.cc-avatar-loading::after {@@ -249,7 +248,22 @@ html, body {@keyframes cc-status-blink { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }@media (prefers-reduced-motion: reduce) { .cc-upload-status[data-state="working"]::before { animation: none; } }-.cc-avatar-chip.cc-avatar-upload.cc-on { border-color: #fff; }+.cc-avatar-chip.cc-avatar-upload.cc-on,+.cc-avatar-chip.cc-avatar-gallery.cc-on { border-color: #fff; }++/* browse-gallery button — mirrors the upload button so the avatar bar reads as+ one set of equal-weight actions */+.cc-gallery-btn {+ display: inline-flex; align-items: center; gap: 7px; flex: none; cursor: pointer; user-select: none;+ background: var(--cc-bg2); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm);+ padding: 9px 14px; color: var(--cc-text); font-size: 13px; font-weight: 600; white-space: nowrap;+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.1s ease;+}+.cc-gallery-btn:hover { border-color: var(--cc-edge-hi); background: var(--cc-bg3); }+.cc-gallery-btn:active { transform: translateY(1px); }+.cc-gallery-btn:focus-visible { border-color: var(--cc-edge-hi); box-shadow: 0 0 0 1px var(--cc-edge-hi); outline: none; }+.cc-gallery-ico { font-size: 13px; line-height: 1; }+.cc-gallery-btn.cc-busy { pointer-events: none; opacity: 0.65; }/* coin grid */.cc-section-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.18em; color: var(--cc-faint); margin: 10px 2px 14px; }@@ -261,8 +275,8 @@ html, body {display: flex; flex-direction: column;}.cc-card:hover { transform: translateY(-3px); border-color: var(--cc-edge-hi); box-shadow: var(--cc-shadow); }-.cc-card-img { aspect-ratio: 16/10; background: var(--cc-bg2) center/cover no-repeat; position: relative; filter: grayscale(1) contrast(1.05); transition: filter 0.25s ease; }-.cc-card:hover .cc-card-img { filter: grayscale(0.15) contrast(1.05); }+.cc-card-img { aspect-ratio: 16/10; background: var(--cc-bg2) center/cover no-repeat; position: relative; filter: saturate(0.96) contrast(1.03); transition: filter 0.25s ease; }+.cc-card:hover .cc-card-img { filter: saturate(1.12) contrast(1.05); }.cc-card-img::after { content: ""; position: absolute; inset: 0; background: linear-gradient(180deg, transparent 45%, rgba(6, 6, 7, 0.92)); }.cc-card-live {position: absolute; top: 9px; left: 9px; z-index: 1;@@ -284,6 +298,42 @@ html, body {}.cc-card:hover .cc-card-cta { opacity: 1; transform: translateY(0); }.cc-card-cta:hover { filter: brightness(0.92); }++/* Featured / official town — the pinned flagship. Spans the full first row as a+ hero: art on the left, identity on the right, with a bright persistent frame+ so it reads as the front door rather than just another card. */+.cc-card-featured {+ grid-column: 1 / -1;+ flex-direction: row;+ border-color: var(--cc-edge-hi);+ box-shadow: 0 0 0 1px var(--cc-edge-hi), var(--cc-shadow), 0 0 30px rgba(255, 255, 255, 0.06);+}+.cc-card-featured::before {+ content: ""; position: absolute; inset: 0; pointer-events: none; z-index: 2;+ border-radius: inherit;+ background: linear-gradient(115deg, rgba(255, 255, 255, 0.06), transparent 38%);+}+.cc-card-featured .cc-card-img { aspect-ratio: auto; flex: 0 0 38%; min-height: 168px; }+.cc-card-featured .cc-card-img::after { background: linear-gradient(90deg, transparent 55%, rgba(6, 6, 7, 0.92)); }+.cc-card-featured .cc-card-body { flex: 1; justify-content: center; padding: 20px 22px; gap: 6px; }+.cc-card-featured .cc-card-name { font-size: 22px; white-space: normal; }+.cc-card-featured .cc-card-meta { font-size: 13px; }+.cc-card-featured .cc-card-cta { opacity: 1; transform: none; align-self: flex-start; padding: 10px 22px; margin-top: 16px; }+.cc-card-official {+ position: absolute; top: 9px; left: 9px; z-index: 1;+ display: inline-flex; align-items: center; gap: 6px;+ background: #fff; color: var(--cc-ink); border-radius: var(--cc-radius-sm);+ padding: 3px 9px; font-size: 10px; font-weight: 800; letter-spacing: 0.14em; text-transform: uppercase;+ box-shadow: var(--cc-glow);+}+.cc-card-official-ico { font-size: 11px; line-height: 1; }+@media (max-width: 560px) {+ .cc-card-featured { flex-direction: column; }+ .cc-card-featured .cc-card-img { flex-basis: auto; aspect-ratio: 16/10; width: 100%; }+ .cc-card-featured .cc-card-img::after { background: linear-gradient(180deg, transparent 45%, rgba(6, 6, 7, 0.92)); }+ .cc-card-featured .cc-card-name { font-size: 19px; }+}+.cc-skeleton { pointer-events: none; }.cc-skeleton .cc-card-img, .cc-skeleton .cc-card-name, .cc-skeleton .cc-card-meta {background: linear-gradient(90deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.04));@@ -325,7 +375,7 @@ html, body {border-radius: var(--cc-radius); padding: 10px 16px 10px 11px; box-shadow: var(--cc-shadow);backdrop-filter: blur(10px); max-width: 70vw;}-.cc-coin-img { width: 40px; height: 40px; border-radius: var(--cc-radius-sm); object-fit: cover; background: var(--cc-bg2); flex: none; filter: grayscale(1) contrast(1.05); }+.cc-coin-img { width: 40px; height: 40px; border-radius: var(--cc-radius-sm); object-fit: cover; background: var(--cc-bg2); flex: none; filter: saturate(1.04) contrast(1.03); }.cc-coin-info { min-width: 0; }.cc-coin-name { font-weight: 800; font-size: 15px; letter-spacing: 0.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }.cc-coin-sub { display: flex; align-items: center; gap: 9px; color: var(--cc-dim); font-size: 12px; margin-top: 2px; font-variant-numeric: tabular-nums; }@@ -544,3 +594,386 @@ html, body {.cc-adventure span { display: flex; flex-direction: column; font-weight: 700; font-size: 13px; line-height: 1.2; letter-spacing: 0.02em; }.cc-adventure small { font-weight: 500; font-size: 11px; color: var(--cc-dim); }@media (max-width: 640px) { .cc-adventure small { display: none; } }++/* ── Buy this coin ──────────────────────────────────────────────────────────+ The native on-chain buy. In a pump.fun world the loudest action is "ape it",+ so the CTA is the only solid-white element on screen. */++.cc-buy-btn {+ flex: none; display: inline-flex; align-items: center; gap: 7px;+ margin-left: 4px; padding: 9px 15px;+ background: var(--cc-accent); color: var(--cc-ink);+ border: 1px solid var(--cc-accent); border-radius: var(--cc-radius);+ font-weight: 800; font-size: 12px; letter-spacing: 0.04em; text-transform: uppercase;+ cursor: pointer; box-shadow: var(--cc-glow);+ transition: transform 0.12s ease, box-shadow 0.12s ease, background 0.12s ease;+}+.cc-buy-btn:hover { transform: translateY(-1px); box-shadow: 0 0 22px rgba(255, 255, 255, 0.55); }+.cc-buy-btn:active { transform: translateY(1px); }+.cc-buy-btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }+.cc-buy-btn-ico { font-size: 13px; line-height: 1; }+.cc-buy-btn-text { white-space: nowrap; max-width: 42vw; overflow: hidden; text-overflow: ellipsis; }++/* Live latency readout in the status pill. */+.cc-ping {+ font-variant-numeric: tabular-nums; padding-left: 8px; margin-left: 2px;+ border-left: 1px solid var(--cc-edge); color: var(--cc-dim);+}+.cc-ping[data-grade="good"] { color: var(--cc-text); }+.cc-ping[data-grade="ok"] { color: #d8c08a; }+.cc-ping[data-grade="bad"] { color: #d88a8a; }++/* Name field in the lobby avatar bar. */+.cc-name-row { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }+.cc-name-label {+ color: var(--cc-dim); font-size: 12px; letter-spacing: 0.18em;+ text-transform: uppercase; flex: none;+}+.cc-name-input {+ flex: 1; min-width: 0; max-width: 280px;+ background: var(--cc-bg2); border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius); padding: 10px 13px;+ color: var(--cc-text); font-size: 14px; font-weight: 600; outline: none;+ transition: border-color 0.12s ease;+}+.cc-name-input::placeholder { color: var(--cc-dim); font-weight: 400; }+.cc-name-input:focus { border-color: var(--cc-edge-hi); }++/* Transient toast (avatar fell back, buy panel unavailable, …). */+#cc-toast {+ position: fixed; left: 50%; bottom: 96px; transform: translate(-50%, 12px);+ max-width: min(440px, 86vw); padding: 11px 16px;+ background: var(--cc-panel-solid); border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius); box-shadow: var(--cc-shadow); backdrop-filter: blur(10px);+ color: var(--cc-text); font-size: 13px; line-height: 1.4; text-align: center;+ opacity: 0; pointer-events: none; z-index: 60;+ transition: opacity 0.18s ease, transform 0.18s ease;+}+#cc-toast.cc-on { opacity: 1; transform: translate(-50%, 0); }+#cc-toast[data-kind="warn"] { border-color: rgba(216, 192, 138, 0.5); }++/* ── Native buy modal ───────────────────────────────────────────────────── */+.cc-buy-overlay {+ position: fixed; inset: 0; z-index: 80;+ display: flex; align-items: center; justify-content: center; padding: 20px;+ background: rgba(4, 4, 6, 0.66); backdrop-filter: blur(6px);+ opacity: 0; transition: opacity 0.18s ease;+}+.cc-buy-overlay.cc-on { opacity: 1; }+.cc-buy-card {+ width: 100%; max-width: 380px;+ background: var(--cc-panel-solid); border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius); box-shadow: var(--cc-shadow);+ padding: 18px; transform: translateY(10px) scale(0.99);+ transition: transform 0.18s ease;+}+.cc-buy-overlay.cc-on .cc-buy-card { transform: translateY(0) scale(1); }+.cc-buy-head { display: flex; align-items: center; gap: 11px; margin-bottom: 16px; }+.cc-buy-img {+ width: 40px; height: 40px; border-radius: var(--cc-radius-sm); object-fit: cover;+ background: var(--cc-bg2); flex: none;+}+.cc-buy-img-ph { display: flex; align-items: center; justify-content: center; color: var(--cc-faint); font-size: 22px; }+.cc-buy-titles { flex: 1; min-width: 0; }+.cc-buy-name { font-weight: 800; font-size: 15px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.cc-buy-sym { color: var(--cc-dim); font-size: 12px; margin-top: 2px; }+.cc-buy-x {+ flex: none; width: 28px; height: 28px; border-radius: var(--cc-radius-sm);+ background: none; border: 1px solid var(--cc-edge); color: var(--cc-dim);+ cursor: pointer; font-size: 13px; line-height: 1; transition: border-color 0.12s ease, color 0.12s ease;+}+.cc-buy-x:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }++.cc-buy-field { display: block; }+.cc-buy-field-label { display: block; color: var(--cc-dim); font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; margin-bottom: 7px; }+.cc-buy-amount-wrap {+ display: flex; align-items: center; gap: 8px;+ background: var(--cc-bg2); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);+ padding: 12px 14px; transition: border-color 0.12s ease;+}+.cc-buy-amount-wrap:focus-within { border-color: var(--cc-edge-hi); }+.cc-buy-amount {+ flex: 1; min-width: 0; background: none; border: none; outline: none;+ color: var(--cc-text); font-size: 22px; font-weight: 800; font-variant-numeric: tabular-nums;+}+.cc-buy-amount::-webkit-outer-spin-button, .cc-buy-amount::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }+.cc-buy-amount { -moz-appearance: textfield; }+.cc-buy-unit { color: var(--cc-dim); font-weight: 700; font-size: 14px; letter-spacing: 0.04em; }++.cc-buy-presets { display: flex; gap: 7px; margin-top: 9px; }+.cc-buy-preset {+ flex: 1; padding: 8px 0; background: var(--cc-bg2); border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius); color: var(--cc-dim); font-size: 12px; font-weight: 700;+ cursor: pointer; transition: border-color 0.12s ease, color 0.12s ease, background 0.12s ease;+}+.cc-buy-preset:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }+.cc-buy-preset.cc-on { background: rgba(255, 255, 255, 0.08); border-color: var(--cc-edge-hi); color: var(--cc-text); }++.cc-buy-quote {+ margin-top: 13px; min-height: 18px; font-size: 13px; color: var(--cc-text);+ font-variant-numeric: tabular-nums; line-height: 1.4;+}+.cc-buy-quote-out { font-weight: 700; }+.cc-buy-quote-impact { color: var(--cc-dim); }+.cc-buy-quote-warn { color: #d8c08a; }+.cc-buy-quote.cc-buy-quote-warn { font-size: 12px; }++.cc-buy-slip { display: flex; align-items: center; gap: 7px; margin-top: 14px; }+.cc-buy-slip-label { color: var(--cc-dim); font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; margin-right: auto; }+.cc-buy-slip-btn {+ padding: 5px 10px; background: var(--cc-bg2); border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius-sm); color: var(--cc-dim); font-size: 12px; font-weight: 600;+ font-variant-numeric: tabular-nums; cursor: pointer; transition: border-color 0.12s ease, color 0.12s ease;+}+.cc-buy-slip-btn:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }+.cc-buy-slip-btn.cc-on { border-color: var(--cc-edge-hi); color: var(--cc-text); background: rgba(255, 255, 255, 0.06); }++.cc-buy-wallet {+ display: flex; align-items: center; gap: 7px; margin-top: 15px;+ color: var(--cc-dim); font-size: 12px; font-variant-numeric: tabular-nums;+}+.cc-buy-wallet-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--cc-live); box-shadow: var(--cc-glow); flex: none; }+.cc-buy-wallet-off { color: var(--cc-faint); }++.cc-buy-cta {+ width: 100%; margin-top: 14px; padding: 14px;+ background: var(--cc-accent); color: var(--cc-ink);+ border: 1px solid var(--cc-accent); border-radius: var(--cc-radius);+ font-weight: 800; font-size: 14px; letter-spacing: 0.03em; cursor: pointer;+ box-shadow: var(--cc-glow); transition: transform 0.12s ease, box-shadow 0.12s ease, opacity 0.12s ease;+}+.cc-buy-cta:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 0 22px rgba(255, 255, 255, 0.55); }+.cc-buy-cta:active:not(:disabled) { transform: translateY(1px); }+.cc-buy-cta:disabled { opacity: 0.45; cursor: default; box-shadow: none; }+.cc-buy-cta:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }++.cc-buy-status {+ margin-top: 12px; font-size: 12.5px; line-height: 1.45; text-align: center;+ color: var(--cc-dim); word-break: break-word;+}+.cc-buy-status[data-kind="ok"] { color: var(--cc-text); }+.cc-buy-status[data-kind="err"] { color: #d88a8a; }+.cc-buy-status a { color: inherit; text-decoration: underline; }+.cc-buy-link { background: none; border: none; padding: 0; color: var(--cc-text); text-decoration: underline; cursor: pointer; font: inherit; }++.cc-buy-pumplink {+ display: block; margin-top: 14px; text-align: center;+ color: var(--cc-dim); font-size: 12px; text-decoration: none;+ transition: color 0.12s ease;+}+.cc-buy-pumplink:hover { color: var(--cc-text); }++@media (max-width: 640px) {+ .cc-buy-btn-text { display: none; }+ .cc-buy-btn { padding: 9px 12px; }+ .cc-name-input { max-width: none; }+}++/* ───────────────────────── Build mode (voxel) ───────────────────────── */+/* The collaborative building HUD is its own <body> child (outside #cc-hud),+ so it carries its own layering. A top-centre cluster: a toggle pill, and a+ panel (mode switch + palette hotbar + hint) that drops in when build is on.+ Top-centre keeps it clear of the joystick (bottom-left), emotes/hint+ (bottom-centre), chat (right), and the banner/status (top corners). */+#cc-build {+ position: fixed;+ top: 14px;+ left: 50%;+ transform: translateX(-50%);+ z-index: 6;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 8px;+ pointer-events: none;+ font: 13px/1.3 system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;+ color: #fff;+}+#cc-build button {+ pointer-events: auto;+}++.cc-build-toggle {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ padding: 8px 14px;+ border-radius: 999px;+ border: 1px solid rgba(255, 255, 255, 0.14);+ background: rgba(12, 14, 20, 0.72);+ -webkit-backdrop-filter: blur(10px);+ backdrop-filter: blur(10px);+ color: #e9eaee;+ font-weight: 600;+ letter-spacing: 0.01em;+ cursor: pointer;+ transition:+ background 0.15s,+ border-color 0.15s,+ color 0.15s,+ transform 0.1s,+ opacity 0.15s;+}+.cc-build-toggle:hover {+ background: rgba(22, 25, 33, 0.85);+ border-color: rgba(255, 255, 255, 0.26);+}+.cc-build-toggle:active {+ transform: translateY(1px);+}+.cc-build-toggle:focus-visible {+ outline: 2px solid #66ff8c;+ outline-offset: 2px;+}+.cc-build-toggle.cc-on {+ background: #f4f5f7;+ color: #0c0e14;+ border-color: #f4f5f7;+}+.cc-build-toggle:disabled {+ opacity: 0.4;+ cursor: not-allowed;+}+.cc-build-toggle-ico {+ font-size: 15px;+ line-height: 1;+}++.cc-build-panel {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 8px;+ padding: 10px;+ border-radius: 14px;+ border: 1px solid rgba(255, 255, 255, 0.12);+ background: rgba(10, 12, 18, 0.74);+ -webkit-backdrop-filter: blur(14px);+ backdrop-filter: blur(14px);+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);+ animation: cc-build-in 0.16s ease;+}+.cc-build-panel[hidden] {+ display: none;+}+@keyframes cc-build-in {+ from {+ opacity: 0;+ transform: translateY(-6px);+ }+ to {+ opacity: 1;+ transform: none;+ }+}++.cc-build-hotbar {+ display: flex;+ gap: 6px;+}+.cc-build-slot {+ position: relative;+ width: 44px;+ height: 44px;+ padding: 0;+ border-radius: 10px;+ border: 1px solid rgba(255, 255, 255, 0.14);+ background: rgba(255, 255, 255, 0.04);+ cursor: pointer;+ overflow: hidden;+ transition:+ border-color 0.12s,+ transform 0.1s,+ box-shadow 0.12s;+}+.cc-build-slot:hover {+ border-color: rgba(255, 255, 255, 0.4);+ transform: translateY(-1px);+}+.cc-build-slot:focus-visible {+ outline: 2px solid #66ff8c;+ outline-offset: 2px;+}+.cc-build-slot.cc-on {+ border-color: #ffffff;+ box-shadow:+ 0 0 0 2px rgba(255, 255, 255, 0.5),+ 0 4px 14px rgba(0, 0, 0, 0.35);+ transform: translateY(-2px);+}+.cc-build-swatch {+ position: absolute;+ inset: 5px;+ border-radius: 6px;+ box-shadow:+ inset 0 0 0 1px rgba(0, 0, 0, 0.25),+ inset 0 6px 10px rgba(255, 255, 255, 0.18);+}+.cc-build-key {+ position: absolute;+ right: 3px;+ bottom: 2px;+ font-size: 10px;+ font-weight: 700;+ color: #fff;+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.9);+ pointer-events: none;+}++.cc-build-mode {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 6px 12px;+ border-radius: 999px;+ border: 1px solid rgba(255, 255, 255, 0.16);+ background: rgba(102, 255, 140, 0.14);+ color: #c9ffd8;+ font-weight: 600;+ cursor: pointer;+ transition:+ background 0.14s,+ color 0.14s,+ border-color 0.14s;+}+.cc-build-mode:hover {+ border-color: rgba(255, 255, 255, 0.3);+}+.cc-build-mode:focus-visible {+ outline: 2px solid #66ff8c;+ outline-offset: 2px;+}+.cc-build-mode.cc-removing {+ background: rgba(255, 90, 90, 0.16);+ color: #ffd2d2;+}+.cc-build-mode-ico {+ font-size: 13px;+}++.cc-build-hint {+ font-size: 11px;+ color: rgba(255, 255, 255, 0.55);+ text-align: center;+ letter-spacing: 0.01em;+}++@media (pointer: coarse) {+ .cc-build-hint {+ display: none;+ }+ .cc-build-slot {+ width: 40px;+ height: 40px;+ }+}+@media (max-width: 560px) {+ #cc-build {+ top: 8px;+ }+ .cc-build-hotbar {+ flex-wrap: wrap;+ max-width: 264px;+ justify-content: center;+ }+}diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 30fc97f64..4fc6b0f80 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -24,11 +24,15 @@ import { CommunityNet } from './community-net.js';import { CommunityUI } from './coincommunities-ui.js';import { createWorldEnvironment } from './world-env.js';import { createChartScreen } from './chart-screen.js';+import { MarketReactor } from './market-reactor.js';+import { VoxelWorld, createBuildHud, parseKey } from './build-voxels.js';import { normalizeGatewayURL } from '../ipfs.js';import {loadManifest, getEmoteDefs, resolveAvatarUrl, buildAvatar, playEmoteClip,CLIP_IDLE, CLIP_WALK,} from './avatar-rig.js';+import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';+import { HOME_TOWN, isHomeTown } from './home-town.js';const WORLD_RADIUS = 58; // a touch inside the server's 60m clampconst MOVE_SPEED = 4.2;@@ -40,6 +44,7 @@ const REMOTE_LERP = 0.18;const JOY_DEADZONE = 0.12; // swallow tiny stick grazes so the avatar doesn't driftconst TRENDING_URL = '/api/pump/trending?limit=30';const SEARCH_URL = '/api/pump/search';+const COIN_URL = '/api/pump/coin';// Normalize a raw pump.fun coin (trending feed or search results — both share// the same upstream shape) into the compact record the lobby/world consume.@@ -168,10 +173,30 @@ export class CoinCommunities {onEmote: (n) => this._emote(n),onSearch: (q) => this._searchCoins(q),onRetry: () => this.net?.retry(),- onAvatarChange: (url) => { this.net?.setAvatar(url); },+ // Resolve the picked value (avatar id, gallery pick, URL) to a loadable,+ // host-whitelisted URL before broadcasting, so a mid-session avatar swap+ // actually reaches peers (the server rejects bare ids / blob: URLs).+ onAvatarChange: (val) => {+ if (!this.net || val === GUEST_SENTINEL) return;+ resolveAvatarUrl(val).then((u) => this.net?.setAvatar(u));+ },+ onRename: (name) => this._rename(name),+ onBuy: () => this._openBuy(),});+ // Collaborative building HUD (hotbar + place/break toggle). Hidden until the+ // player is in a world and connected — there's nowhere to build otherwise.+ this.buildType = 0;+ this.buildHud = createBuildHud({+ onToggle: (on) => this._onBuildToggle(on),+ onPick: (i) => { this.buildType = i; },+ onModeChange: () => this._refreshGhost(),+ });+ this.buildHud.root.hidden = true;+ this.buildHud.setEnabled(false);+this._hideBootLoader();+ this._loadHomeTown();this._loadCoins();this._bindInput();@@ -213,6 +238,23 @@ export class CoinCommunities {}}+ // The flagship $THREE town is always pinned to the top of the lobby, even when+ // it isn't trending — it's the platform's front door. Show the static identity+ // instantly so the card never flashes empty, then refresh name/art/market-cap+ // live from pump.fun so the pin is real, not a hardcoded snapshot.+ async _loadHomeTown() {+ this.ui.setFeatured({ ...HOME_TOWN, official: true });+ try {+ const r = await fetch(`${COIN_URL}?mint=${HOME_TOWN.mint}`, { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error('HTTP ' + r.status);+ const [coin] = mapCoins([await r.json()]);+ if (coin?.mint) this.ui.setFeatured({ ...HOME_TOWN, ...coin, official: true });+ } catch (err) {+ // Non-fatal: the static pin from above stands in until next load.+ console.warn('[coincommunities] home town refresh failed:', err?.message);+ }+ }+// Live search across ALL of pump.fun (not just the trending grid) so any// coin can be turned into a world. Returns mapped coins; throws on failure// so the UI can distinguish "no matches" from "search unavailable".@@ -268,21 +310,21 @@ export class CoinCommunities {this._screenPulse.material.opacity = 0.35 + 0.35 * (0.5 + 0.5 * Math.sin(this._screenT * 2.4));}this._chartScreen?.update(dt);+ this._reactor?.update(dt);}// Central coin totem — the community's banner in 3D._buildTotem(coin) {const g = new Group();const pillar = new Mesh(new CylinderGeometry(1.1, 1.4, 6, 24),- new MeshStandardMaterial({ color: 0x2a2a30, roughness: 0.7, metalness: 0.1 }));+ new MeshStandardMaterial({ color: 0x3a4a72, roughness: 0.6, metalness: 0.2 }));pillar.position.y = 3; pillar.castShadow = true; pillar.receiveShadow = true;g.add(pillar);- // Floating coin disc with the token image — polished chrome that catches the- // moonlight key, slowly turning. Monochrome: the only colour is the light it- // reflects (and the token art on its faces).+ // Floating coin disc with the token image — a warm gold coin that catches the+ // sun key, slowly turning. The token art rides on its faces.const spin = new Group(); spin.position.y = 7.5;const disc = new Mesh(new CylinderGeometry(2.2, 2.2, 0.3, 40),- new MeshStandardMaterial({ color: 0xd8d8de, roughness: 0.22, metalness: 0.95, emissive: 0x202024, emissiveIntensity: 0.25 }));+ new MeshStandardMaterial({ color: 0xffce5c, roughness: 0.35, metalness: 0.7, emissive: 0x3a2e00, emissiveIntensity: 0.3 }));disc.rotation.x = Math.PI / 2; disc.castShadow = true;spin.add(disc);this._totemDisc = disc;@@ -313,7 +355,7 @@ export class CoinCommunities {x.textAlign = 'center'; x.fillStyle = '#fff';x.font = '800 50px Inter, system-ui, sans-serif';x.fillText(name.slice(0, 18).toUpperCase(), 256, 56);- x.font = 'bold 32px Inter, system-ui, sans-serif'; x.fillStyle = 'rgba(255,255,255,0.6)';+ x.font = 'bold 32px Inter, system-ui, sans-serif'; x.fillStyle = '#5fc8ff';x.fillText(sym, 256, 100);const tex = new CanvasTexture(c); tex.colorSpace = SRGBColorSpace;const m = new Mesh(new PlaneGeometry(6, 1.5), new MeshBasicMaterial({ map: tex, transparent: true, side: DoubleSide }));@@ -460,6 +502,18 @@ export class CoinCommunities {async enter(coin) {if (this.phase !== 'lobby') return;this.phase = 'loading';+ // A bare deep link (/play?coin=<home mint>) carries no name/art; backfill the+ // flagship town's identity so its totem, jumbotron, and HUD are never blank.+ if (isHomeTown(coin.mint)) {+ coin = {+ ...coin,+ name: coin.name || HOME_TOWN.name,+ symbol: coin.symbol || HOME_TOWN.symbol,+ image: coin.image || HOME_TOWN.image,+ biome: HOME_TOWN.biome,+ official: true,+ };+ }this.coin = coin;this.ui.enterWorld(coin);// Reflect the community in the URL so it can be shared / refreshed into.@@ -473,35 +527,98 @@ export class CoinCommunities {await loadManifest();this.ui.setEmotes(getEmoteDefs().map((d) => ({ name: d.name, icon: d.icon || '🙂', label: d.label })));+ // Re-theme the environment for this specific community: a distinct biome,+ // palette, and flora derived deterministically from the coin's mint, so+ // every community has its own recognisable world.+ this.env?.dispose();+ // The flagship town pins its signature biome; every other coin draws its+ // look from the mint seed.+ const biomeOverride = isHomeTown(coin.mint) ? (coin.biome || HOME_TOWN.biome) : undefined;+ this.env = createWorldEnvironment(this.scene, this.renderer, WORLD_RADIUS, { mint: coin.mint, biome: biomeOverride });+ this.ui.toast(`${coin.symbol ? '$' + coin.symbol : coin.name || 'Community'} — ${this.env.biome.label}`, 'info');+// Build the coin's world + local avatar.this._buildTotem(coin);this._buildScreen(coin);+ // The market reactor turns the live trade tape into world behaviour: buys+ // ripple green and kick the boundary ring, sells ripple red, volume spins+ // the totem, the rolling % drives the weather, and whales detonate a beam+ // of light with a shower of coins. It's fed by the chart screen's onTrades.+ this._reactor = new MarketReactor({+ scene: this.scene,+ env: this.env,+ totem: this._coinSpin,+ totemPos: [0, 0, -12],+ onWhale: (tr) => {+ const usd = formatUsd(tr.usd);+ const who = tr.isBuy ? 'bought' : 'sold';+ this.ui.toast(`🐋 Whale ${who}${usd ? ' ' + usd : ''} of ${coin.symbol ? '$' + coin.symbol : coin.name || 'this coin'}`, 'info');+ },+ });// Live trading terminal facing the spawn from past the totem: the coin's// price chart, % change, volume, buy/sell flow, and a ticker of real// on-chain trades — a second screen players can walk up to and tap to open- // the coin on pump.fun. Identity jumbotron behind, market chart ahead.- this._chartScreen = createChartScreen(this.scene, coin, { position: [0, 0, -30], width: 18 });+ // the coin on pump.fun. Identity jumbotron behind, market chart ahead. Its+ // freshly-landed trades feed the reactor so the world reacts to the tape.+ this._chartScreen = createChartScreen(this.scene, coin, {+ position: [0, 0, -30], width: 18,+ onTrades: (trades, metrics) => this._reactor?.ingestTrades(trades, metrics),+ });this.localRig = new Group();this.localRig.position.copy(this.localPos);this.scene.add(this.localRig);this.localAnim = new AnimationManager();const avatarInput = this.ui.getAvatar();const url = await resolveAvatarUrl(avatarInput);- const { height: localHeight } = await buildAvatar(this.localRig, url, this.localAnim);+ const { height: localHeight, fallback: avatarFallback } = await buildAvatar(this.localRig, url, this.localAnim);this.localHeight = localHeight;+ // Don't silently swap a broken model for the stand-in — tell the player so+ // they know to pick another avatar.+ if (avatarFallback && avatarInput !== GUEST_SENTINEL) {+ this.ui.toast('Couldn’t load that avatar — using a stand-in. Try another in the lobby.', 'warn');+ }- // Connect to this coin's room.- const name = localStorage.getItem('cc-name') || ('guest-' + Math.random().toString(36).slice(2, 6));+ // Connect to this coin's room. A locally-staged guest avatar (just created,+ // not yet uploaded) can't be loaded by peers, so we join without one and+ // upload in the background — then broadcast the public URL so everyone sees+ // it. Otherwise broadcast a loadable URL/path directly.+ const isGuest = avatarInput === GUEST_SENTINEL;+ const netAvatar = isGuest+ ? ''+ : (/^https?:\/\//i.test(avatarInput) || avatarInput.startsWith('/') ? avatarInput : url);+ // Prefer the name the player typed in the lobby; only mint a guest id when+ // they left it blank, and reflect that id back into the field so it's theirs.+ let name = this.ui.getName();+ if (!name) {+ name = localStorage.getItem('cc-name') || ('guest-' + Math.random().toString(36).slice(2, 6));+ this.ui.setName(name);+ }localStorage.setItem('cc-name', name);+ // Fresh voxel build layer for this coin. The server is authoritative: it+ // streams the persisted build in on join and every live edit after, so the+ // geometry is driven entirely by these block events (local clicks only send).+ this.voxels = new VoxelWorld(this.scene);+this.net = new CommunityNet({- name, avatar: /^https?:\/\//i.test(avatarInput) || avatarInput.startsWith('/') ? avatarInput : url,+ name, avatar: netAvatar,coin: { mint: coin.mint, name: coin.name, symbol: coin.symbol, image: coin.image },});- this.net.on('status', ({ status }) => { this.ui.setStatus(status); this._updateOnline(); });+ if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));+ this.net.on('status', ({ status }) => {+ this.ui.setStatus(status);+ this._updateOnline();+ // Only offer building while there's a live link to build into.+ this.buildHud.setEnabled(status === 'online', 'Building needs a live connection');+ });this.net.on('add', (p, id) => this._onAdd(p, id));this.net.on('change', (p, id) => this._onChange(p, id));this.net.on('remove', (id) => this._onRemove(id));this.net.on('chat', (m) => this._onChat(m));+ this.net.on('ping', (ms) => this.ui.setPing(ms));+ this.net.on('blockAdd', (key, t) => { const [x, y, z] = parseKey(key); this.voxels?.setBlock(x, y, z, t); });+ this.net.on('blockChange', (key, t) => { const [x, y, z] = parseKey(key); this.voxels?.setBlock(x, y, z, t); });+ 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.phase = 'world';this._initJoystick();@@ -519,6 +636,11 @@ export class CoinCommunities {this._screenArt = null; this._screenPulse = null;}if (this._chartScreen) { this._chartScreen.dispose(); this._chartScreen = null; }+ if (this._reactor) { this._reactor.dispose(); this._reactor = null; }+ if (this.voxels) { this.voxels.dispose(); this.voxels = null; }+ this.buildHud.setActive(false);+ this.buildHud.setEnabled(false);+ this.buildHud.root.hidden = true;if (this.localRig) { this.scene.remove(this.localRig); this.localRig = null; }if (this._nipple) { this._nipple.destroy(); this._nipple = null; }this.phase = 'lobby';@@ -551,11 +673,50 @@ export class CoinCommunities {const mine = m.id === this.net.sessionId;this.ui.addChat({ name: m.name, text: m.text, mine });if (mine) this._sayLocal(m.text);- else this.remotes.get(m.id)?.say(m.text);+ else { this.remotes.get(m.id)?.say(m.text); this._bumpTabUnread(); }}_sendChat(text) { this.net?.sendChat(text); }_emote(name) { this.net?.sendEmote(name); playEmoteClip(this.localAnim, name, this.motion); }+ // Surface unread chat in the tab title when the page is backgrounded, so a+ // new message pulls the user back. Cleared the moment they refocus the tab.+ _bumpTabUnread() {+ if (!document.hidden) return;+ this._tabUnread = (this._tabUnread || 0) + 1;+ if (!this._baseTitle) this._baseTitle = document.title;+ document.title = `(${this._tabUnread}) ${this._baseTitle}`;+ if (!this._tabFocusBound) {+ this._tabFocusBound = true;+ const clear = () => {+ if (document.hidden) return;+ this._tabUnread = 0;+ if (this._baseTitle) document.title = this._baseTitle;+ };+ document.addEventListener('visibilitychange', clear);+ window.addEventListener('focus', clear);+ }+ }++ // Live rename: persist and broadcast so peers' nameplates update instantly.+ _rename(name) {+ const clean = (name || '').trim().slice(0, 24);+ if (clean) localStorage.setItem('cc-name', clean);+ if (this.net && clean) this.net.rename(clean);+ }++ // Open the native on-chain buy for the current coin. Lazy-loaded so the+ // Solana/pump SDKs never weigh down the main /play bundle.+ async _openBuy() {+ if (!this.coin?.mint) return;+ try {+ const { openBuyModal } = await import('./coin-buy.js');+ openBuyModal(this.coin);+ } catch (err) {+ console.warn('[coincommunities] buy modal failed to load:', err?.message);+ this.ui.toast('Couldn’t open the buy panel. Trade on pump.fun instead.', 'warn');+ }+ }+_sayLocal(text) {if (this._localBubble) this._localBubble.remove();this._localBubble = document.createElement('div');@@ -572,28 +733,54 @@ export class CoinCommunities {if (this.ui.chatFocused) return;if (e.key === 'Enter' && this.phase === 'world') { e.preventDefault(); this.ui.focusChat(); return; }if (e.code === 'Space') { e.preventDefault(); this._jump(); return; } // don't scroll the page- this.keys.add(e.key.toLowerCase());+ const k = e.key.toLowerCase();+ if (this.phase === 'world') {+ // B toggles build mode; while it's on, 1–0 pick the active block.+ if (k === 'b') {+ e.preventDefault();+ if (this.net?.status === 'online' || this.buildHud.active) this.buildHud.setActive(!this.buildHud.active);+ return;+ }+ if (this.buildHud.active && k.length === 1 && k >= '0' && k <= '9') {+ e.preventDefault();+ this.buildHud.select(k === '0' ? 9 : Number(k) - 1);+ return;+ }+ }+ this.keys.add(k);});window.addEventListener('keyup', (e) => this.keys.delete(e.key.toLowerCase()));this.canvas.addEventListener('pointerdown', (e) => {this._dragging = true; this._lastPtr = { x: e.clientX, y: e.clientY };this._downPtr = { x: e.clientX, y: e.clientY };+ // Touch has no hover, so seed the ghost on press so the first tap aims true.+ if (this.phase === 'world' && this.buildHud.active && e.button !== 2) this._updateGhost(e.clientX, e.clientY);});window.addEventListener('pointerup', () => { this._dragging = false; });- // A tap (negligible drag) on the live chart screen opens the coin on pump.fun.+ // A tap (negligible drag) builds in build mode, otherwise opens the coin on+ // pump.fun when it lands on the live chart screen.this.canvas.addEventListener('pointerup', (e) => {if (!this._downPtr) return;const moved = Math.hypot(e.clientX - this._downPtr.x, e.clientY - this._downPtr.y);this._downPtr = null;- if (moved < 6 && this._raycastScreen(e.clientX, e.clientY)) this._chartScreen.openExternal();+ if (moved >= 6 || e.button === 2) return; // a look-drag, or a right-click (handled by contextmenu)+ if (this.phase === 'world' && this.buildHud.active) { this._buildAt(e.clientX, e.clientY, false); return; }+ if (this._raycastScreen(e.clientX, e.clientY)) this._chartScreen.openExternal();+ });+ // Right-click always breaks the targeted block while building.+ this.canvas.addEventListener('contextmenu', (e) => {+ if (this.phase === 'world' && this.buildHud.active) { e.preventDefault(); this._buildAt(e.clientX, e.clientY, true); }});window.addEventListener('pointermove', (e) => {if (!this._dragging) {- // Hover cursor over the clickable screen (throttled).+ // Throttled hover: drive the build ghost while building, else the+ // pointer cursor over the clickable chart screen.const now = performance.now();- if (this.phase === 'world' && this._chartScreen && now - (this._hoverAt || 0) > 80) {+ if (this.phase === 'world' && now - (this._hoverAt || 0) > 40) {this._hoverAt = now;- this.canvas.style.cursor = this._raycastScreen(e.clientX, e.clientY) ? 'pointer' : '';+ this._lastHover = { x: e.clientX, y: e.clientY };+ if (this.buildHud.active) this._updateGhost(e.clientX, e.clientY);+ else if (this._chartScreen) this.canvas.style.cursor = this._raycastScreen(e.clientX, e.clientY) ? 'pointer' : '';}return;}@@ -608,10 +795,9 @@ export class CoinCommunities {}, { passive: false });}- // Cast a ray from a screen-space point into the world and report whether it- // hits the live chart screen's face — powers tap-to-open and the hover cursor.- _raycastScreen(clientX, clientY) {- if (!this._chartScreen?.mesh) return false;+ // Build a camera ray through a screen-space point (shared by the chart-screen+ // hit test and the voxel targeting).+ _pointerRay(clientX, clientY) {this._raycaster = this._raycaster || new Raycaster();this._ndc = this._ndc || new Vector2();const rect = this.canvas.getBoundingClientRect();@@ -620,7 +806,59 @@ export class CoinCommunities {-((clientY - rect.top) / rect.height) * 2 + 1,);this._raycaster.setFromCamera(this._ndc, this.camera);- return this._raycaster.intersectObject(this._chartScreen.mesh, false).length > 0;+ return this._raycaster;+ }++ // Cast a ray from a screen-space point into the world and report whether it+ // hits the live chart screen's face — powers tap-to-open and the hover cursor.+ _raycastScreen(clientX, clientY) {+ if (!this._chartScreen?.mesh) return false;+ return this._pointerRay(clientX, clientY).intersectObject(this._chartScreen.mesh, false).length > 0;+ }++ // ---------------------------------------------------------------- building+ // Place or break a block under the pointer. Server-authoritative: we only send+ // the intent, and the block appears/disappears when the server echoes its+ // blocks state back (see the blockAdd/blockRemove wiring in enter()).+ _buildAt(clientX, clientY, forceRemove) {+ if (!this.voxels || this.net?.status !== 'online') return;+ const target = this.voxels.raycast(this._pointerRay(clientX, clientY));+ if (!target) return;+ if (forceRemove || this.buildHud.mode === 'remove') {+ if (target.hit === 'block' && target.cell) this.net.sendRemove(target.cell[0], target.cell[1], target.cell[2]);+ } else if (target.placeValid) {+ this.net.sendPlace(target.placeCell[0], target.placeCell[1], target.placeCell[2], this.buildType);+ } else if (target.placeCell) {+ // Aimed somewhere illegal (out of bounds / occupied) — flash the cursor.+ this.voxels.showGhost(target.placeCell, 'blocked');+ return;+ }+ this._updateGhost(clientX, clientY);+ }++ // Move the ghost cursor to whatever the pointer aims at, tinted by intent+ // (green place / red break / amber blocked).+ _updateGhost(clientX, clientY) {+ if (!this.voxels) return;+ const target = this.voxels.raycast(this._pointerRay(clientX, clientY));+ if (!target) { this.voxels.hideGhost(); return; }+ if (this.buildHud.mode === 'remove') {+ if (target.hit === 'block') this.voxels.showGhost(target.cell, 'remove');+ else this.voxels.hideGhost();+ } else {+ this.voxels.showGhost(target.placeCell, target.placeValid ? 'place' : 'blocked');+ }+ }++ // Re-evaluate the ghost after a mode flip, without waiting for pointer motion.+ _refreshGhost() {+ if (this.buildHud.active && this._lastHover) this._updateGhost(this._lastHover.x, this._lastHover.y);+ }++ _onBuildToggle(on) {+ if (!on) { this.voxels?.hideGhost(); this.canvas.style.cursor = ''; return; }+ this.ui.toast('Build mode — tap to place, right-click to break, 1–0 pick a block', 'info');+ if (this._lastHover) this._updateGhost(this._lastHover.x, this._lastHover.y);}_initJoystick() {diff --git a/src/game/community-net.js b/src/game/community-net.jsindex 5205ad9d6..bf938fc25 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -71,7 +71,13 @@ 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+ ping: new Set(), // (ms) — smoothed round-trip latency to the server+ blockAdd: new Set(), // (key, type) — a voxel appeared (placed or restored)+ blockChange: new Set(), // (key, type) — a voxel was repainted+ blockRemove: new Set(), // (key) — a voxel was broken};+ this.ping = null; // smoothed RTT in ms, null until the first echo+ this._pingSentAt = 0; // perf-clock stamp of the last move awaiting an echothis._lastSent = null;this._lastSentAt = 0;this._reconnectTimer = null;@@ -121,10 +127,33 @@ export class CommunityNet {const $ = getStateCallbacks(this.room);$(this.room.state).players.onAdd((player, id) => {this._emit('add', player, id);- $(player).onChange(() => this._emit('change', player, id));+ $(player).onChange(() => {+ // The server echoes our own authoritative state back after each+ // move; the gap from send → echo is a real network+server RTT.+ if (id === this.sessionId && this._pingSentAt) {+ const rtt = performance.now() - this._pingSentAt;+ this._pingSentAt = 0;+ if (rtt > 0 && rtt < 5000) {+ this.ping = this.ping == null ? rtt : this.ping * 0.7 + rtt * 0.3;+ this._emit('ping', Math.round(this.ping));+ }+ }+ this._emit('change', player, id);+ });});$(this.room.state).players.onRemove((_p, id) => this._emit('remove', id));+ // Voxel builds: the server is authoritative for every block, so the+ // world's geometry is driven entirely by these state callbacks — local+ // place/break clicks only *send*; the block appears when the server+ // echoes it back, keeping every client's build identical. onAdd fires+ // for the full persisted build at join time and for each new placement.+ $(this.room.state).blocks.onAdd((block, key) => {+ this._emit('blockAdd', key, block.t);+ $(block).onChange(() => this._emit('blockChange', key, block.t));+ });+ $(this.room.state).blocks.onRemove((_b, key) => this._emit('blockRemove', key));+this.room.onLeave((code) => {this._setStatus('offline');if (!this._destroyed && code !== 1000) this._scheduleReconnect();@@ -178,10 +207,18 @@ export class CommunityNet {this.room.send('move', { x: state.x, y: state.y, z: state.z, yaw: state.yaw, motion: state.motion });this._lastSent = { ...state };this._lastSentAt = now;+ // Stamp this move for RTT measurement unless one is already awaiting its+ // echo, so each sample pairs a single send with its first state echo.+ if (!this._pingSentAt) this._pingSentAt = now;}sendEmote(name) { this.room?.send('emote', { name }); }sendChat(text) { this.room?.send('chat', { text }); }+ // Place/break a voxel at an integer grid cell. Server-authoritative: these only+ // request the edit; the block is added/removed locally when the server patches+ // state.blocks (see the onAdd/onRemove wiring above).+ 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 }); }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/game-net.js b/src/game/game-net.jsindex 56c09042c..edc6f5bd8 100644--- a/src/game/game-net.js+++ b/src/game/game-net.js@@ -43,6 +43,7 @@ function defaultServerUrl() {export class GameNet {constructor(opts = {}) {this.name = opts.name || 'guest';+ this.avatar = opts.avatar || ''; // loadable GLB/VRM URL or path; '' = defaultthis.url = opts.url || defaultServerUrl();this.client = null;this.room = null;@@ -93,7 +94,7 @@ export class GameNet {this._setStatus('connecting');try {this.client = new Client(this.url);- this.room = await this.client.joinOrCreate(ROOM_NAME, { name: this.name });+ this.room = await this.client.joinOrCreate(ROOM_NAME, { name: this.name, avatar: this.avatar });this.sessionId = this.room.sessionId;this.room.onMessage('realm', (layout) => this._emit('realm', layout));@@ -149,6 +150,7 @@ export class GameNet {// ----- intents ---------------------------------------------------------step(tx, ty, yaw) { this.room?.send('step', { tx, ty, yaw }); }+ setAvatar(url) { this.avatar = url; this.room?.send('setAvatar', { avatar: url }); }gather(id) { this.room?.send('gather', { id }); }attack(id) { this.room?.send('attack', { id }); }invMove(from, to) { this.room?.send('invMove', { from, to }); }diff --git a/src/game/home-town.js b/src/game/home-town.jsnew file mode 100644index 000000000..2aeb4482e--- /dev/null+++ b/src/game/home-town.js@@ -0,0 +1,27 @@+// The flagship town — three.ws's own $THREE community.+//+// Every pump.fun coin gets a 3D world on demand, but the platform's home token+// deserves a permanent, curated home: a town that is always pinned to the top+// of the /play lobby (even when it isn't trending), badged as official, and+// dressed in a fixed signature biome instead of the seed-lottery one. This is+// the front door of the metaverse — the world a first-time visitor should land+// in. Keeping its identity in one module means the lobby card, the deep link,+// and the world dressing all agree on a single source of truth.+//+// `image` is a sensible static fallback (the token's IPFS art); the lobby+// refreshes name/symbol/art/market-cap live from /api/pump/coin so the pinned+// card is never stale. `biome` forces the world archetype — see world-env.js.++export const HOME_TOWN = {+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ name: 'three.ws',+ symbol: 'three',+ image: 'https://ipfs.io/ipfs/bafybeihe22b5sxr3ihnxt7pregfieyteqvubqhik3j3y4bbx243xlqjw3q',+ // The signature look for the home town: the Neon Expanse, whose cyan/magenta+ // neon over deep indigo matches the platform's monochrome-with-accent brand.+ biome: 'alien',+ official: true,+};++/** True when a mint is the flagship $THREE town. */+export const isHomeTown = (mint) => !!mint && mint === HOME_TOWN.mint;diff --git a/src/game/iso-game.js b/src/game/iso-game.jsindex 37811fca1..c33e5768f 100644--- a/src/game/iso-game.js+++ b/src/game/iso-game.js@@ -31,6 +31,7 @@ import { GameNet } from './game-net.js';import {loadManifest, resolveAvatarUrl, buildAvatar, newAnim, CLIP_IDLE, CLIP_WALK,} from './avatar-rig.js';+import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';const TILE = 1.0; // world units per tileconst STEP_INTERVAL_MS = 165; // walk cadence — one authoritative step per tile@@ -118,6 +119,9 @@ class GamePlayerView {this.motion = player.motion;this.anim.crossfadeTo(this.motion === 'walk' ? CLIP_WALK : CLIP_IDLE, 0.16);}+ // Peers' avatars are server-authoritative (the local player owns its own+ // look). setAvatar self-guards, so this is a no-op until a peer changes.+ if (!this.isLocal) this.setAvatar(player.cosmetic || '');// Mark when the server says we moved so the loop can settle us to idle on// arrival without waiting for a separate motion patch.if (moved) this._movedAt = performance.now();@@ -340,13 +344,22 @@ export class IsoGame {if (this.phase === 'world' || this.phase === 'connecting') return;this.phase = 'connecting';this._setHudPhase('connecting');- // Reuse the avatar the player already picked on /play (persisted there).- // Cross-player avatar sync needs a networked field on GamePlayer; until- // then this at least keeps your own look consistent across both scenes.+ // Reuse the avatar the player picked on /play (persisted in cc-avatar) and+ // network it through GamePlayer.cosmetic so peers render it too — both+ // scenes now share one look. A locally-staged guest avatar resolves to a+ // blob for our own view and uploads in the background; once it has a public+ // URL we broadcast it.this.avatarPref = localStorage.getItem('cc-avatar') || '';+ const isGuest = this.avatarPref === GUEST_SENTINEL;+ this.localAvatarUrl = await resolveAvatarUrl(this.avatarPref);+ const netAvatar = isGuest+ ? ''+ : (/^https?:\/\//i.test(this.avatarPref) || this.avatarPref.startsWith('/')+ ? this.avatarPref : this.localAvatarUrl);await loadManifest();- this.net = new GameNet({ name });+ this.net = new GameNet({ name, avatar: netAvatar });+ if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));this.net.on('status', ({ status, error }) => this._onStatus(status, error));this.net.on('realm', (layout) => this._buildRealm(layout));this.net.on('notice', (n) => this._toast(n));@@ -386,7 +399,9 @@ export class IsoGame {if (this.players.has(id)) { this.players.get(id).apply(p); return; }const isLocal = id === this.myId;const view = new GamePlayerView(this.scene, (tx, ty) => this._tileToWorld(tx, ty), p, isLocal);- if (isLocal && this.avatarPref) view.setAvatar(this.avatarPref);+ // The local player renders its own resolved avatar immediately (covers a+ // guest blob the server hasn't received the public URL for yet).+ if (isLocal && this.localAvatarUrl) view.setAvatar(this.localAvatarUrl);this.players.set(id, view);this._updateOnline();}diff --git a/src/game/market-reactor.js b/src/game/market-reactor.jsnew file mode 100644index 000000000..0c5084596--- /dev/null+++ b/src/game/market-reactor.js@@ -0,0 +1,213 @@+// Market Reactor — turns a coin's live on-chain tape into world behaviour.+//+// The /play world already streams real pump.fun trades onto the chart screen+// (chart-screen.js). On its own that data dead-ends on a panel. The reactor+// pipes the same feed into the *environment* so the arena physically responds+// to the market: every buy ripples green across the plaza and kicks the+// boundary ring, every sell ripples red, sustained volume spins the coin totem+// faster, the rolling % change drives the weather between storm and euphoria,+// and a whale-sized trade detonates a beam of light over the totem with a+// shower of coins. The coin's price becomes the room's pulse.+//+// All effects are pooled/capped and self-dispose, so a busy room stays cheap.+// The reactor owns one FX group it adds to the scene and tears down on dispose;+// the slow "weather" lives on the environment (env.setMood / env.flashRing).++import {+ Group, Mesh, MeshBasicMaterial,+ RingGeometry, CylinderGeometry,+ AdditiveBlending, DoubleSide,+} from 'three';++// Trade colours mirror the chart screen so the world and the panel speak the+// same visual language (up = green, down = red, the coin itself = gold).+const COL_BUY = 0x5fd08a;+const COL_SELL = 0xe06c75;+const COL_GOLD = 0xffce5c;++// A trade at/above this USD size is a "whale" — it earns the full spectacle+// (beam + shockwave + confetti) rather than just a ripple. Memecoin-scaled.+const WHALE_USD = 750;++// Caps so a frantic room can never accumulate unbounded meshes.+const MAX_RIPPLES = 16;+const MAX_CONFETTI = 80;++export class MarketReactor {+ /**+ * @param {object} o+ * @param {THREE.Scene} o.scene scene to mount the FX group into+ * @param {object} o.env world environment (flashRing, setMood)+ * @param {THREE.Object3D} [o.totem] the spinning coin group — gets a heat boost+ * @param {[number,number,number]} [o.totemPos] world origin of the totem for FX+ * @param {(trade:object)=>void} [o.onWhale] called when a whale trade lands+ */+ constructor({ scene, env, totem = null, totemPos = [0, 0, -12], onWhale = null }) {+ this.scene = scene;+ this.env = env;+ this.totem = totem;+ this.origin = totemPos;+ this.onWhale = onWhale;++ this.fx = new Group();+ scene.add(this.fx);++ // Shared geometry — every ripple/shockwave reuses these; only per-effect+ // materials are cloned (so each can fade independently) and disposed.+ this._ringGeo = new RingGeometry(0.92, 1, 56);+ this._coinGeo = new CylinderGeometry(0.17, 0.17, 0.04, 14);+ this._beamGeo = new CylinderGeometry(2.4, 2.4, 1, 28, 1, true);++ this._ripples = []; // { mesh, mat, age, life, maxScale, fade }+ this._confetti = []; // { mesh, mat, vx, vy, vz, spin, age, life }+ this._beams = []; // { mesh, mat, age, life, peak }++ this._heat = 0; // 0..1 trade-velocity energy; decays each frame+ }++ // Feed a batch of freshly-landed trades + the chart's derived metrics. Drives+ // the immediate reactions (flash/ripple/whale) and the slow mood.+ ingestTrades(trades, metrics) {+ // Weather first: rolling % change → storm (−) … euphoria (+). ±35% maps to+ // the extremes, so an ordinary chart sits near neutral.+ const pct = metrics && typeof metrics.pct === 'number' ? metrics.pct : 0;+ this.env?.setMood?.(pct / 35);++ if (!Array.isArray(trades)) return;+ for (const tr of trades) {+ const usd = Number(tr.usd) || 0;+ const buy = tr.isBuy === true;+ const color = buy ? COL_BUY : COL_SELL;++ // Bigger trades hit harder — both the ring flash and the spent heat.+ const weight = usd > 0 ? Math.min(1, usd / 600) : 0.12;+ this.env?.flashRing?.(color, 0.18 + weight * 0.7);+ this._heat = Math.min(1, this._heat + 0.05 + weight * 0.4);++ if (usd >= WHALE_USD) {+ this._spawnWhale(buy);+ try { this.onWhale?.(tr); } catch { /* toast is non-critical */ }+ } else {+ this._spawnRipple(color, 0.45 + weight * 0.2, 22 + weight * 8);+ }+ }+ }++ // A flat ring that expands outward across the plaza from the totem and fades.+ _spawnRipple(color, fade, maxScale) {+ if (this._ripples.length >= MAX_RIPPLES) this._retire(this._ripples.shift());+ const mat = new MeshBasicMaterial({+ color, transparent: true, opacity: fade,+ side: DoubleSide, depthWrite: false,+ });+ const mesh = new Mesh(this._ringGeo, mat);+ mesh.rotation.x = -Math.PI / 2;+ mesh.position.set(this.origin[0], 0.05, this.origin[2]);+ mesh.scale.setScalar(1);+ this.fx.add(mesh);+ this._ripples.push({ mesh, mat, age: 0, life: 1.5, maxScale, fade });+ }++ // The whale spectacle: a column of light over the totem, a bright shockwave+ // at its base, and (on a buy) a burst of coins raining off the top.+ _spawnWhale(buy) {+ const color = buy ? COL_GOLD : COL_SELL;++ const beamMat = new MeshBasicMaterial({+ color, transparent: true, opacity: 0,+ side: DoubleSide, depthWrite: false, blending: AdditiveBlending,+ });+ const beam = new Mesh(this._beamGeo, beamMat);+ beam.scale.set(1, 46, 1);+ beam.position.set(this.origin[0], 23, this.origin[2]);+ this.fx.add(beam);+ this._beams.push({ mesh: beam, mat: beamMat, age: 0, life: 2.4, peak: 0.42 });++ this._spawnRipple(color, 0.7, 44); // hard, wide shockwave at the base++ if (buy) {+ const n = 22;+ for (let i = 0; i < n; i++) {+ if (this._confetti.length >= MAX_CONFETTI) break;+ const mat = new MeshBasicMaterial({ color: COL_GOLD, transparent: true, opacity: 1 });+ const mesh = new Mesh(this._coinGeo, mat);+ mesh.position.set(this.origin[0], 9.5, this.origin[2]);+ // A cone of upward velocity so coins fountain off the totem crown.+ const ang = (i / n) * Math.PI * 2;+ const spread = 2.2 + (i % 3) * 0.6;+ mesh.rotation.set(ang, ang * 1.3, 0);+ this.fx.add(mesh);+ this._confetti.push({+ mesh, mat,+ vx: Math.cos(ang) * spread,+ vy: 6.5 + (i % 5) * 0.7,+ vz: Math.sin(ang) * spread,+ spin: 6 + (i % 4) * 2,+ age: 0, life: 2.4,+ });+ }+ }+ }++ update(dt) {+ // Heat bleeds off; while it lasts it spins the totem above its idle drift.+ this._heat = Math.max(0, this._heat - dt * 0.4);+ if (this.totem && this._heat > 0) this.totem.rotation.y += dt * this._heat * 3.2;++ // Ripples: ease outward (fast then settling) and fade to nothing.+ for (let i = this._ripples.length - 1; i >= 0; i--) {+ const r = this._ripples[i];+ r.age += dt;+ const k = Math.min(1, r.age / r.life);+ const ease = 1 - (1 - k) * (1 - k); // ease-out+ r.mesh.scale.setScalar(1 + ease * r.maxScale);+ r.mat.opacity = r.fade * (1 - k);+ if (k >= 1) { this._retire(r); this._ripples.splice(i, 1); }+ }++ // Beams: fade in, hold, fade out over their life.+ for (let i = this._beams.length - 1; i >= 0; i--) {+ const b = this._beams[i];+ b.age += dt;+ const k = Math.min(1, b.age / b.life);+ const env = k < 0.12 ? k / 0.12 : (1 - (k - 0.12) / 0.88);+ b.mat.opacity = Math.max(0, env) * b.peak;+ if (k >= 1) { this._retire(b); this._beams.splice(i, 1); }+ }++ // Confetti: ballistic arc under gravity, spin, fade on the way down.+ for (let i = this._confetti.length - 1; i >= 0; i--) {+ const c = this._confetti[i];+ c.age += dt;+ c.vy -= 14 * dt;+ c.mesh.position.x += c.vx * dt;+ c.mesh.position.y += c.vy * dt;+ c.mesh.position.z += c.vz * dt;+ c.mesh.rotation.x += c.spin * dt;+ c.mesh.rotation.z += c.spin * 0.6 * dt;+ const k = Math.min(1, c.age / c.life);+ c.mat.opacity = k > 0.6 ? 1 - (k - 0.6) / 0.4 : 1;+ if (k >= 1 || c.mesh.position.y < 0.05) { this._retire(c); this._confetti.splice(i, 1); }+ }+ }++ // Pull one effect off the scene and free its cloned material.+ _retire(e) {+ if (!e) return;+ this.fx.remove(e.mesh);+ e.mat?.dispose?.();+ }++ dispose() {+ this.scene.remove(this.fx);+ for (const r of this._ripples) r.mat?.dispose?.();+ for (const c of this._confetti) c.mat?.dispose?.();+ for (const b of this._beams) b.mat?.dispose?.();+ this._ripples = []; this._confetti = []; this._beams = [];+ this._ringGeo.dispose();+ this._coinGeo.dispose();+ this._beamGeo.dispose();+ // Reset the weather so a reused environment doesn't inherit our mood.+ this.env?.setMood?.(0);+ }+}diff --git a/src/game/play-handoff.js b/src/game/play-handoff.jsnew file mode 100644index 000000000..e65710132--- /dev/null+++ b/src/game/play-handoff.js@@ -0,0 +1,135 @@+// Avatar handoff between the creation surfaces and the live worlds (/play, /game).+//+// One localStorage key — `cc-avatar` — is the contract that ties the platform's+// avatar tools to its multiplayer scenes. The lobby avatar bar, the boot loader,+// the social walkaround (coincommunities.js) and the isometric RPG (iso-game.js)+// all read it. This module is the single writer used by every "use this avatar"+// affordance, so the value stored is always something the scenes can resolve:+//+// • a three.ws avatar id — canonical identity, resolved via /api/avatars/:id+// • a public GLB/VRM URL or path+// • GUEST_SENTINEL — a just-created avatar not yet uploaded, staged+// in IndexedDB by guest-avatar.js+//+// Scenes resolve all three through resolveAvatarUrl() in avatar-rig.js. A guest+// avatar shows to its creator instantly from the local blob; the scene then+// uploads it in the background (uploadPendingGuestAvatar) and swaps in the public+// URL so peers see it too — no upload round-trip before the world appears.++import { stage, load, peek } from '../guest-avatar.js';++export const CC_AVATAR_KEY = 'cc-avatar';+export const CC_NAME_KEY = 'cc-name';+export const GUEST_SENTINEL = 'guest:pending';++// One object URL per staged blob, cached so repeated resolves (local rig + boot+// loader + thumbnail) share it and we only revoke when the staged avatar changes.+let _guest = { id: null, url: null };++export function getPlayAvatar() {+ try { return localStorage.getItem(CC_AVATAR_KEY) || ''; } catch { return ''; }+}++// Persist the avatar every world reads. Prefer a canonical id; fall back to a+// loadable URL/path or the guest sentinel. Returns the stored value.+export function setPlayAvatar(value) {+ const v = (value || '').trim();+ try { localStorage.setItem(CC_AVATAR_KEY, v); } catch { /* storage disabled */ }+ return v;+}++export function setPlayName(name) {+ const v = (name || '').trim().slice(0, 24);+ if (!v) return '';+ try { localStorage.setItem(CC_NAME_KEY, v); } catch { /* ignore */ }+ return v;+}++/**+ * Adopt an avatar and (optionally) jump into a world. The single entry point for+ * every "Play as this" / "Use in /play" button across the creation surfaces.+ *+ * @param {object} opts+ * @param {string} [opts.id] three.ws avatar id (preferred — stable identity)+ * @param {string} [opts.url] public GLB/VRM URL (used when no id is available)+ * @param {Blob} [opts.blob] a freshly-created GLB not yet uploaded+ * @param {string} [opts.name] player display name to carry in+ * @param {string} [opts.source] provenance label when staging a blob+ * @param {'/play'|'/game'|null} [opts.dest='/play'] where to navigate; null = stay+ * @param {object} [opts.coin] optional { mint, name, symbol, image } deep-link+ * @returns {Promise<string>} the value stored in cc-avatar+ */+export async function playAs(opts = {}) {+ const { id, url, blob, name, dest = '/play', coin } = opts;+ let value;+ if (blob instanceof Blob) {+ await stage(blob, { source: opts.source || 'three-ws-studio', name: name || 'My avatar' });+ value = GUEST_SENTINEL;+ } else {+ value = (id || url || '').trim();+ }+ if (!value) throw new Error('playAs requires an id, url, or blob');+ setPlayAvatar(value);+ if (name) setPlayName(name);++ if (dest) {+ const q = new URLSearchParams();+ if (coin?.mint) {+ q.set('coin', coin.mint);+ if (coin.name) q.set('name', coin.name);+ if (coin.symbol) q.set('symbol', coin.symbol);+ if (coin.image) q.set('image', coin.image);+ }+ const qs = q.toString();+ location.href = dest + (qs ? '?' + qs : '');+ }+ return value;+}++// Resolve the guest sentinel to a local object URL for instant self-preview.+// Returns null when nothing is staged. Cached per staged blob; the previous URL+// is revoked only when the staged avatar actually changes, so a loader mid-fetch+// is never pulled out from under.+export async function resolveGuestAvatar() {+ const ptr = peek();+ if (!ptr) return null;+ if (_guest.id === ptr.id && _guest.url) return _guest.url;+ const rec = await load();+ if (!rec?.blob) return null;+ if (_guest.url) { try { URL.revokeObjectURL(_guest.url); } catch { /* ignore */ } }+ _guest = { id: rec.id, url: URL.createObjectURL(rec.blob) };+ return _guest.url;+}++export function hasPendingGuestAvatar() {+ return getPlayAvatar() === GUEST_SENTINEL && !!peek();+}++/**+ * Upload a staged guest avatar so every peer can fetch it, then promote+ * cc-avatar from the local sentinel to the real public URL. Safe to call when+ * nothing is staged (returns null). The local staging is intentionally kept so a+ * refresh still self-previews instantly; the public URL now in cc-avatar wins for+ * the network.+ *+ * @param {(publicUrl: string) => void} [onPublished] called once the URL is live+ * @returns {Promise<string|null>} the public URL, or null if there was nothing to upload+ */+export async function uploadPendingGuestAvatar(onPublished) {+ if (getPlayAvatar() !== GUEST_SENTINEL) return null;+ const rec = await load();+ if (!rec?.blob) return null;+ try {+ const { uploadGlb } = await import('./avatar-upload.js');+ const file = new File([rec.blob], `${(rec.name || 'avatar').replace(/[^\w.-]+/g, '-')}.glb`, {+ type: 'model/gltf-binary',+ });+ const publicUrl = await uploadGlb(file);+ setPlayAvatar(publicUrl);+ onPublished?.(publicUrl);+ return publicUrl;+ } catch (err) {+ console.warn('[play-handoff] guest avatar upload failed; staying local-only:', err?.message);+ return null;+ }+}diff --git a/src/game/world-env.js b/src/game/world-env.jsindex 555143ded..a8abd8ca8 100644--- a/src/game/world-env.js+++ b/src/game/world-env.js@@ -1,16 +1,19 @@-// World environment — a sleek, nocturnal arena that flows straight out of the-// monochrome lobby. Where the old build was a bright green meadow (which broke-// the brand the moment a player dropped in), this is the same design language as-// the lobby: near-black ground, a fine technical hairline grid, a thin glowing-// boundary ring, a dark silhouette treeline melting into fog, and a single cool-// "moonlight" key so the white avatars and their long shadows are the only thing-// that reads as light. Colour is expressed only as light. Self-contained: the-// scene file creates it once and ticks update(dt).+// World environment — a distinct, living biome for every coin community.//-// Everything decorative sits OUTSIDE the playRadius circle so it frames the-// space without ever blocking a player. Geometry is low-poly and shared/cloned,-// so the whole environment is cheap enough to run alongside the avatars and-// their shadows.+// The lobby/landing stays monochrome by design, but the moment a player drops+// into a world it should feel alive AND feel like *this* community's place.+// Two coins should never share a skin. We hash the coin's mint into a stable+// seed, pick one of several biome archetypes from it (meadow, desert, tundra,+// volcanic, alien, tropical), then jitter that biome's palette and scatter its+// vegetation from the same seed — so a given coin always renders the same world,+// and a thousand coins render a thousand recognisably different ones.+//+// Colour does the heavy lifting here — the monochrome restraint is the lobby's+// job, not the world's. Everything decorative sits OUTSIDE the playRadius circle+// so it frames the space without ever blocking a player. Geometry is low-poly+// and shared/cloned, so the whole environment is cheap enough to run alongside+// the avatars and their shadows. The scene file creates it once per community+// and ticks update(dt).import {Color, Fog, Group, Vector3, MathUtils, DoubleSide, SRGBColorSpace,@@ -20,67 +23,237 @@ import {GridHelper, CanvasTexture,} from 'three';-// Palette — monochrome nocturne. Pure greyscale; the only "warm" point is the-// cool moonlight key. Matches the lobby tokens (--cc-bg #060607 … hairlines).-const C_SKY_TOP = '#070709';-const C_SKY_HORIZON = '#26262c'; // also the fog colour, so ground melts into the seam-const C_GROUND = 0x0c0c0e; // field beyond the arena-const C_PLAZA = 0x141417; // the mown play circle reads a touch lighter-const C_GRID = 0x6f6f78; // faint technical hairline grid-const C_RING = 0xffffff; // glowing boundary hairline (light = the only colour)-const C_HILL = 0x131316;-const C_TRUNK = 0x101012;-const C_LEAF_A = 0x16161a;-const C_LEAF_B = 0x1d1d22;--// A seeded LCG so the treeline/hill layout is identical on every load (stable-// demos, no first-frame reshuffle) without touching Math.random.+// FNV-1a hash → a stable 32-bit seed from a coin mint (or any string). Identical+// input always yields the identical world; no Math.random in the layout path.+export function seedFromString(str) {+ let h = 2166136261 >>> 0;+ const s = String(str || 'three-ws');+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ return h >>> 0;+}++// A seeded LCG so a community's treeline/hill/prop layout is identical on every+// load (stable demos, no first-frame reshuffle) without touching Math.random.function rng(seed) {let s = seed >>> 0;return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 0xffffffff; };}-// A vertical gradient backdrop (near-black overhead → dim grey at the horizon),-// rendered as the scene background so it's immune to fog and never rotates with-// the orbit camera — a clean studio sky behind the arena.-function gradientSky() {+// --- Biome archetypes ------------------------------------------------------+// Each entry is a complete mood: graded sky, atmospheric fog, a key/fill light+// rig, ground + plaza + accent palette, and which flora the band outside the+// arena is planted with. The mint's seed picks one of these, then a per-coin+// hue jitter (below) shifts it so two coins in the same biome still read apart.+const BIOMES = [+ {+ id: 'meadow', label: 'Verdant Meadow',+ sky: ['#2f6fd0', '#7fb4ec', '#eaf2ff'], fog: '#cfe0f4', fogNear: 90, fogFar: 340,+ hemi: [0xbfd8ff, 0x4a6b3a, 0.75], ambient: 0.25,+ sun: { color: 0xfff2d0, intensity: 2.1, elevation: 48, azimuth: 135 },+ ground: 0x4f9d5b, plaza: 0xcdb892, grid: 0x8f7f5e, ring: 0x4ea8ff,+ hill: 0x6f9f86, trunk: 0x6b4a2f, leafA: 0x3f8a49, leafB: 0x57ab60,+ flora: 'conifer', density: 46,+ },+ {+ id: 'desert', label: 'Dune Sea',+ sky: ['#3b7bc4', '#c9a86a', '#f6e6c4'], fog: '#ead8b0', fogNear: 80, fogFar: 320,+ hemi: [0xffe7bf, 0xb98a4a, 0.85], ambient: 0.3,+ sun: { color: 0xffe1a8, intensity: 2.4, elevation: 58, azimuth: 110 },+ ground: 0xd9b878, plaza: 0xc9a25e, grid: 0xa07c44, ring: 0xff9a3c,+ hill: 0xcaa569, trunk: 0x3f7a44, leafA: 0x4f9a52, leafB: 0x5fae5a,+ flora: 'cactus', density: 26,+ },+ {+ id: 'tundra', label: 'Frostfields',+ sky: ['#5b7fb0', '#bcd3ea', '#f2f7fb'], fog: '#dfeaf4', fogNear: 70, fogFar: 300,+ hemi: [0xdfeeff, 0x9fb0c2, 0.8], ambient: 0.35,+ sun: { color: 0xeaf2ff, intensity: 1.9, elevation: 32, azimuth: 150 },+ ground: 0xe7eef5, plaza: 0xcfd9e2, grid: 0x9fb0bf, ring: 0x7fd4ff,+ hill: 0xc9d6e2, trunk: 0x4a3f33, leafA: 0xdfe9f2, leafB: 0xcdd9e6,+ flora: 'snowpine', density: 40,+ },+ {+ id: 'volcanic', label: 'Ashen Caldera',+ sky: ['#3a1f2a', '#7a3322', '#d65a2e'], fog: '#5a2a22', fogNear: 60, fogFar: 280,+ hemi: [0xff8a5a, 0x2a1410, 0.55], ambient: 0.22,+ sun: { color: 0xff7a3a, intensity: 1.7, elevation: 22, azimuth: 200 },+ ground: 0x2a2424, plaza: 0x3a2e2c, grid: 0x6a3a2a, ring: 0xff5a2a,+ hill: 0x352828, trunk: 0x241c18, leafA: 0x140e0c, leafB: 0x1c1410,+ flora: 'deadtree', density: 34,+ },+ {+ id: 'alien', label: 'Neon Expanse',+ sky: ['#1a0f3a', '#5a2a8a', '#c25ad6'], fog: '#3a1f6a', fogNear: 70, fogFar: 320,+ hemi: [0xc59aff, 0x2a1a5a, 0.7], ambient: 0.28,+ sun: { color: 0xc8a0ff, intensity: 1.8, elevation: 40, azimuth: 160 },+ ground: 0x3a2a6a, plaza: 0x2e2456, grid: 0x6a4ab0, ring: 0x2af0e0,+ hill: 0x4a3a8a, trunk: 0x6a4ab0, leafA: 0x2af0e0, leafB: 0xff5ad0,+ flora: 'crystal', density: 30,+ },+ {+ id: 'tropical', label: 'Lagoon Shore',+ sky: ['#1f9fd0', '#7fdce8', '#eafbff'], fog: '#cdeef4', fogNear: 90, fogFar: 340,+ hemi: [0xcdf4ff, 0x3a8a7a, 0.8], ambient: 0.3,+ sun: { color: 0xfff4d8, intensity: 2.2, elevation: 52, azimuth: 120 },+ ground: 0x2fb89a, plaza: 0xe6d8a8, grid: 0xb8a878, ring: 0x2ad0ff,+ hill: 0x3fae9a, trunk: 0x7a5a36, leafA: 0x3f9a54, leafB: 0x5fbf66,+ flora: 'palm', density: 30,+ },+];++// Map any seed to a biome. Exposed so the UI can name the world the player is in.+export function biomeForSeed(seed) {+ return BIOMES[(seed >>> 3) % BIOMES.length];+}++// Look up a biome by its archetype id (e.g. a curated world that pins its look+// instead of drawing it from the mint seed). Returns null for an unknown id so+// the caller can fall back to the seeded pick.+export function biomeById(id) {+ return BIOMES.find((b) => b.id === id) || null;+}++// A vertical gradient backdrop, rendered as the scene background so it's immune+// to fog and never rotates with the orbit camera — a clean graded sky per biome.+function gradientSky(top, mid, horizon) {const c = document.createElement('canvas');c.width = 4; c.height = 256;const x = c.getContext('2d');const g = x.createLinearGradient(0, 0, 0, 256);- g.addColorStop(0, C_SKY_TOP);- g.addColorStop(0.62, '#101015');- g.addColorStop(1, C_SKY_HORIZON);+ g.addColorStop(0, top);+ g.addColorStop(0.55, mid);+ g.addColorStop(1, horizon);x.fillStyle = g; x.fillRect(0, 0, 4, 256);const tex = new CanvasTexture(c);tex.colorSpace = SRGBColorSpace;return tex;}-export function createWorldEnvironment(scene, renderer, playRadius = 58) {+// Per-coin hue jitter: nudge a base hex around the colour wheel + lightness so+// two communities sharing a biome still feel distinct. Natural biomes get a+// gentle shift; the accent ring gets a wider one so it clearly differs per coin.+function jitter(hex, rand, hueAmt = 0.06, litAmt = 0.06) {+ return new Color(hex).offsetHSL((rand() - 0.5) * 2 * hueAmt, 0, (rand() - 0.5) * 2 * litAmt);+}++// --- Flora builders --------------------------------------------------------+// Each returns a Group positioned at origin; the caller scatters/scales it. They+// share geometry/material passed in so a whole treeline is a handful of buffers.++function makeConifer(g, mats, rand, snow = false) {+ const trunk = new Mesh(g.trunk, mats.trunk);+ trunk.position.y = 1.2; trunk.castShadow = true;+ const tree = new Group(); tree.add(trunk);+ const tiers = rand() > 0.5 ? 3 : 2;+ for (let t = 0; t < tiers; t++) {+ const leaf = new Mesh(g.leaf, rand() > 0.5 ? mats.leafA : mats.leafB);+ leaf.position.y = 2.6 + t * 1.4;+ leaf.scale.setScalar(1 - t * 0.22);+ leaf.castShadow = true;+ tree.add(leaf);+ }+ if (snow) tree.scale.y *= 1.05;+ return tree;+}++function makeCactus(g, mats, rand) {+ const cactus = new Group();+ const body = new Mesh(g.cactus, mats.leafA);+ body.position.y = 1.6; body.castShadow = true;+ cactus.add(body);+ const arms = rand() > 0.4 ? 2 : 1;+ for (let i = 0; i < arms; i++) {+ const arm = new Mesh(g.cactusArm, rand() > 0.5 ? mats.leafA : mats.leafB);+ const side = i === 0 ? 1 : -1;+ arm.position.set(side * 0.62, 1.6 + rand() * 0.7, 0);+ arm.rotation.z = side * 0.5;+ arm.castShadow = true;+ cactus.add(arm);+ }+ return cactus;+}++function makeDeadtree(g, mats, rand) {+ const tree = new Group();+ const trunk = new Mesh(g.deadTrunk, mats.trunk);+ trunk.position.y = 1.7; trunk.castShadow = true;+ tree.add(trunk);+ const branches = 2 + Math.floor(rand() * 3);+ for (let i = 0; i < branches; i++) {+ const b = new Mesh(g.branch, mats.trunk);+ b.position.y = 1.8 + rand() * 1.4;+ b.rotation.z = (rand() - 0.5) * 1.6;+ b.rotation.y = rand() * Math.PI * 2;+ b.castShadow = true;+ tree.add(b);+ }+ return tree;+}++function makeCrystal(g, mats, rand) {+ const cluster = new Group();+ const shards = 1 + Math.floor(rand() * 3);+ for (let i = 0; i < shards; i++) {+ const shard = new Mesh(g.crystal, rand() > 0.5 ? mats.leafA : mats.leafB);+ const h = 2.4 + rand() * 3.4;+ shard.scale.set(0.5 + rand() * 0.5, h, 0.5 + rand() * 0.5);+ shard.position.set((rand() - 0.5) * 1.6, h * 0.5, (rand() - 0.5) * 1.6);+ shard.rotation.y = rand() * Math.PI;+ shard.castShadow = true;+ cluster.add(shard);+ }+ return cluster;+}++function makePalm(g, mats, rand) {+ const palm = new Group();+ const lean = (rand() - 0.5) * 0.4;+ const trunk = new Mesh(g.palmTrunk, mats.trunk);+ trunk.position.y = 2.6; trunk.rotation.z = lean; trunk.castShadow = true;+ palm.add(trunk);+ const crown = new Group();+ crown.position.set(Math.sin(lean) * -5.2, 5.2, 0);+ const fronds = 6 + Math.floor(rand() * 3);+ for (let i = 0; i < fronds; i++) {+ const frond = new Mesh(g.frond, rand() > 0.5 ? mats.leafA : mats.leafB);+ frond.rotation.y = (i / fronds) * Math.PI * 2;+ frond.rotation.z = 0.9;+ frond.position.y = 0.1;+ frond.castShadow = true;+ crown.add(frond);+ }+ palm.add(crown);+ return palm;+}++export function createWorldEnvironment(scene, renderer, playRadius = 58, opts = {}) {+ const seed = (typeof opts.seed === 'number' ? opts.seed : seedFromString(opts.mint)) >>> 0;+ // A curated world can pin its archetype by id; everyone else draws theirs from+ // the mint seed. The per-coin palette jitter below still runs off the seed, so+ // even a pinned biome keeps a touch of this coin's own colour.+ const biome = (opts.biome && biomeById(opts.biome)) || biomeForSeed(seed);const root = new Group();scene.add(root);- const rand = rng(0x3d3d3d);+ const rand = rng(seed || 0x3d3d3d);const between = (a, b) => a + (b - a) * rand();+ const animators = [];// --- Sky + atmosphere --------------------------------------------------- scene.background = gradientSky();- // Dark fog tuned to the horizon so the ground edge, treeline, and hills all- // dissolve into the backdrop seam — no hard rim, attention stays on players.- scene.fog = new Fog(new Color(C_SKY_HORIZON), 70, 300);+ scene.background = gradientSky(biome.sky[0], biome.sky[1], biome.sky[2]);+ scene.fog = new Fog(new Color(biome.fog), biome.fogNear, biome.fogFar);// --- Lighting ----------------------------------------------------------- // One cool moonlight key (casts the long shadows), a faint cool sky/ground- // hemisphere, and a whisper of ambient so the dark geometry never crushes to- // pure black. The avatars are the brightest thing in frame, by design.- const hemi = new HemisphereLight(0x9fb0d8, 0x070709, 0.45);- root.add(hemi);- root.add(new AmbientLight(0xffffff, 0.12));+ // One key sun (casts the long shadows), a sky/ground hemisphere fill, and a+ // touch of ambient so shadowed geometry never goes muddy. All biome-tuned.+ root.add(new HemisphereLight(biome.hemi[0], biome.hemi[1], biome.hemi[2]));+ root.add(new AmbientLight(0xffffff, biome.ambient));const sun = new Vector3();- const elevation = 48, azimuth = 135;- sun.setFromSphericalCoords(1, MathUtils.degToRad(90 - elevation), MathUtils.degToRad(azimuth));- const sunLight = new DirectionalLight(0xdfe6ff, 2.2);+ sun.setFromSphericalCoords(1, MathUtils.degToRad(90 - biome.sun.elevation), MathUtils.degToRad(biome.sun.azimuth));+ const sunLight = new DirectionalLight(biome.sun.color, biome.sun.intensity);sunLight.position.copy(sun).multiplyScalar(120);sunLight.castShadow = true;sunLight.shadow.mapSize.set(2048, 2048);@@ -89,41 +262,43 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58) {sunLight.shadow.bias = -0.0004;root.add(sunLight, sunLight.target);+ // --- Palette (per-coin jitter over the biome base) ---------------------+ const cGround = jitter(biome.ground, rand);+ const cPlaza = jitter(biome.plaza, rand, 0.04, 0.04);+ const cHill = jitter(biome.hill, rand);+ const cRing = jitter(biome.ring, rand, 0.12, 0.04);+// --- Ground ------------------------------------------------------------- // Near-black field reaching into the fog, a slightly lighter mown play- // circle, a fine hairline grid for that technical lobby feel, and a single- // glowing white hairline tracing the arena boundary.const field = new Mesh(new CircleGeometry(400, 64),- new MeshStandardMaterial({ color: C_GROUND, roughness: 1, metalness: 0 }));+ new MeshStandardMaterial({ color: cGround, roughness: 1, metalness: 0 }));field.rotation.x = -Math.PI / 2; field.receiveShadow = true;root.add(field);const plaza = new Mesh(new CircleGeometry(playRadius, 64),- new MeshStandardMaterial({ color: C_PLAZA, roughness: 1, metalness: 0 }));+ new MeshStandardMaterial({ color: cPlaza, roughness: 1, metalness: 0 }));plaza.rotation.x = -Math.PI / 2; plaza.position.y = 0.01; plaza.receiveShadow = true;root.add(plaza);- // Technical hairline grid (echoes the lobby's faint background grid). Square,- // but the dark fog and the brighter plaza disc fade its reach so it reads as- // an intentional engineering grid rather than a hard sheet.- const grid = new GridHelper(playRadius * 2, 30, C_GRID, C_GRID);+ // Faint paving grid over the plaza — a sense of scale that the haze fades.+ const grid = new GridHelper(playRadius * 2, 30, biome.grid, biome.grid);grid.position.y = 0.02;grid.material.transparent = true;- grid.material.opacity = 0.14;+ grid.material.opacity = 0.18;grid.material.depthWrite = false;root.add(grid);- // Glowing boundary hairline — the one bright accent on the ground plane.+ // Glowing boundary hairline — the bright accent ring around the plaza, the+ // most per-coin-distinct colour in the scene.const ring = new Mesh(new RingGeometry(playRadius - 0.12, playRadius + 0.12, 128),- new MeshBasicMaterial({ color: C_RING, transparent: true, opacity: 0.32, side: DoubleSide }));+ new MeshBasicMaterial({ color: cRing, transparent: true, opacity: 0.55, side: DoubleSide }));ring.rotation.x = -Math.PI / 2; ring.position.y = 0.03;root.add(ring);// --- Distant hills ------------------------------------------------------ // A ring of broad, low mounds beyond the treeline gives the horizon depth as- // near-black silhouettes against the slightly lighter sky seam.+ // A ring of broad, low mounds beyond the flora gives the horizon depth,+ // hazing into the biome's sky seam.const hillGeo = new IcosahedronGeometry(1, 1);- const hillMat = new MeshStandardMaterial({ color: C_HILL, roughness: 1, metalness: 0, flatShading: true });+ const hillMat = new MeshStandardMaterial({ color: cHill, roughness: 1, metalness: 0, flatShading: true });for (let i = 0; i < 14; i++) {const ang = (i / 14) * Math.PI * 2 + between(-0.12, 0.12);const dist = between(150, 210);@@ -134,46 +309,101 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58) {root.add(h);}- // --- Treeline ----------------------------------------------------------- // Low-poly conifers scattered in a band just outside the play circle, kept as- // dark silhouettes so they frame the arena without colour. Shared geometry +- // two near-black leaf materials, cloned per tree (cheap at this count).- const trunkGeo = new CylinderGeometry(0.22, 0.34, 2.4, 6);- const trunkMat = new MeshStandardMaterial({ color: C_TRUNK, roughness: 1, metalness: 0 });- const leafGeo = new ConeGeometry(1.5, 3.2, 7);- const leafMatA = new MeshStandardMaterial({ color: C_LEAF_A, roughness: 1, metalness: 0, flatShading: true });- const leafMatB = new MeshStandardMaterial({ color: C_LEAF_B, roughness: 1, metalness: 0, flatShading: true });- const TREES = 46;- for (let i = 0; i < TREES; i++) {+ // --- Flora -------------------------------------------------------------+ // Shared geometry + materials; one builder per biome scatters them in a band+ // just outside the play circle. Two leaf tones per biome give natural variety.+ const cLeafA = jitter(biome.leafA, rand, 0.05, 0.05);+ const cLeafB = jitter(biome.leafB, rand, 0.05, 0.05);+ const neon = biome.flora === 'crystal';+ const mats = {+ trunk: new MeshStandardMaterial({ color: jitter(biome.trunk, rand, 0.03, 0.04), roughness: 1, metalness: 0 }),+ leafA: new MeshStandardMaterial({ color: cLeafA, roughness: neon ? 0.3 : 1, metalness: 0, flatShading: true, emissive: neon ? cLeafA : 0x000000, emissiveIntensity: neon ? 0.6 : 0 }),+ leafB: new MeshStandardMaterial({ color: cLeafB, roughness: neon ? 0.3 : 1, metalness: 0, flatShading: true, emissive: neon ? cLeafB : 0x000000, emissiveIntensity: neon ? 0.6 : 0 }),+ };+ const geo = {+ trunk: new CylinderGeometry(0.22, 0.34, 2.4, 6),+ leaf: new ConeGeometry(1.5, 3.2, 7),+ cactus: new CylinderGeometry(0.5, 0.6, 3.2, 8),+ cactusArm: new CylinderGeometry(0.26, 0.3, 1.6, 7),+ deadTrunk: new CylinderGeometry(0.18, 0.3, 3.4, 6),+ branch: new CylinderGeometry(0.08, 0.14, 1.6, 5),+ crystal: new ConeGeometry(0.6, 1, 5),+ palmTrunk: new CylinderGeometry(0.22, 0.36, 5.2, 7),+ frond: new ConeGeometry(0.5, 3.4, 4),+ };+ const builder = {+ conifer: makeConifer, snowpine: (g, m, r) => makeConifer(g, m, r, true),+ cactus: makeCactus, deadtree: makeDeadtree, crystal: makeCrystal, palm: makePalm,+ }[biome.flora] || makeConifer;++ const crystals = [];+ for (let i = 0; i < biome.density; i++) {const ang = rand() * Math.PI * 2;const dist = between(playRadius + 6, playRadius + 60);const s = between(0.8, 1.7);- const tree = new Group();- const trunk = new Mesh(trunkGeo, trunkMat);- trunk.position.y = 1.2; trunk.castShadow = true;- tree.add(trunk);- const tiers = rand() > 0.5 ? 3 : 2;- for (let t = 0; t < tiers; t++) {- const leaf = new Mesh(leafGeo, rand() > 0.5 ? leafMatA : leafMatB);- leaf.position.y = 2.6 + t * 1.4;- leaf.scale.setScalar(1 - t * 0.22);- leaf.castShadow = true;- tree.add(leaf);- }- tree.position.set(Math.cos(ang) * dist, 0, Math.sin(ang) * dist);- tree.scale.setScalar(s);- tree.rotation.y = rand() * Math.PI * 2;- root.add(tree);+ const plant = builder(geo, mats, rand);+ plant.position.set(Math.cos(ang) * dist, 0, Math.sin(ang) * dist);+ plant.scale.multiplyScalar(s);+ plant.rotation.y = rand() * Math.PI * 2;+ root.add(plant);+ if (neon) crystals.push(plant);+ }+ // Alien crystals breathe with a faint emissive shimmer — biome-specific life.+ if (crystals.length) {+ animators.push((t) => {+ const k = 0.45 + Math.sin(t * 0.8) * 0.25;+ mats.leafA.emissiveIntensity = 0.4 + k * 0.4;+ mats.leafB.emissiveIntensity = 0.4 + (1 - k) * 0.4;+ });}- // A slow breathing pulse on the boundary ring is the only motion — subtle,- // premium, and reduced-motion-safe (the amplitude is tiny). Tracked here so- // update() stays a one-liner.+ // --- Live-market reactivity --------------------------------------------+ // The boundary ring is the world's heartbeat: a slow breathing pulse is the+ // baseline, but a trade can kick it to a colour (green on a buy, red on a+ // sell) that decays back to the per-coin accent — so the arena visibly+ // flinches with the on-chain tape. The market-reactor drives flashRing().+ const baseRing = cRing.clone();+ const flashColor = new Color();+ let flash = 0; // 0..1, decays each frame+ animators.push((t, dt) => {+ flash = Math.max(0, flash - dt * 1.7); // ~0.6s to settle+ ring.material.opacity = 0.48 + Math.sin(t * 1.1) * 0.1 + flash * 0.5;+ ring.material.color.copy(baseRing).lerp(flashColor, flash);+ });++ // Mood is the slow weather: the rolling % change pushes the world between a+ // storm (fog closes in, the key dims) and euphoria (fog opens out, the sun+ // flares). We lerp toward the target so a jumpy feed reads as a tide, not a+ // strobe. Baselines are captured so every community settles back to its own.+ const baseFogNear = biome.fogNear, baseFogFar = biome.fogFar;+ const baseSun = biome.sun.intensity;+ let mood = 0, moodTarget = 0; // -1 storm … +1 euphoric+ animators.push((t, dt) => {+ mood += (moodTarget - mood) * Math.min(1, dt * 0.6);+ scene.fog.near = baseFogNear * (1 + mood * 0.18);+ scene.fog.far = baseFogFar * (1 + mood * 0.28);+ sunLight.intensity = baseSun * (1 + mood * 0.22);+ });+let t = 0;return {+ biome,+ seed,+ // Kick the boundary ring to a colour. strength 0..1 sets the flash+ // intensity; it decays back to the coin's accent within ~0.6s.+ flashRing(color, strength = 0.6) {+ const s = Math.max(0, Math.min(1, strength));+ if (s <= flash) return; // don't let a small trade stomp a bigger one mid-decay+ flash = s;+ flashColor.set(color);+ },+ // Set the weather target from a signed intensity (−1 storm … +1 euphoric).+ setMood(target) {+ moodTarget = Math.max(-1, Math.min(1, target || 0));+ },update(dt) {t += dt;- ring.material.opacity = 0.26 + Math.sin(t * 1.1) * 0.08;+ for (const a of animators) a(t, dt);},dispose() {scene.remove(root);@@ -183,8 +413,8 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58) {root.traverse((n) => {if (n.isMesh || n.isLine) {n.geometry?.dispose?.();- const mats = Array.isArray(n.material) ? n.material : [n.material];- for (const m of mats) m?.dispose?.();+ const ms = Array.isArray(n.material) ? n.material : [n.material];+ for (const m of ms) m?.dispose?.();}});},diff --git a/vite.config.js b/vite.config.jsindex 83ac6bae0..f82f2023b 100644--- a/vite.config.js+++ b/vite.config.js@@ -105,6 +105,16 @@ const appConfig = {// (ECONNREFUSED on a transient blip) bubbles up as an// uncaught exception and kills the dev server.if (!res || res.headersSent || res.writableEnded) return;+ // With ws:true, a failed WebSocket upgrade passes the raw+ // net.Socket here instead of an http ServerResponse. A socket+ // has no setHeader/statusCode, so calling them would itself+ // throw an uncaught exception and crash the dev server — which+ // is exactly the failure this handler exists to prevent. Just+ // close the socket and bail.+ if (typeof res.setHeader !== 'function') {+ res.destroy?.();+ return;+ }res.statusCode = 502;res.setHeader('content-type', 'application/json');res.end(JSON.stringify({