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): demo-ready Coin Communities — atmospheric world, joystick, boot avatar, avatar upload
nirholas25d72c9414fe
diff --git a/api/avatar/presign-glb.js b/api/avatar/presign-glb.jsnew file mode 100644index 000000000..a1e7f5870--- /dev/null+++ b/api/avatar/presign-glb.js@@ -0,0 +1,67 @@+// POST /api/avatar/presign-glb+//+// Returns a presigned PUT URL for uploading a self-contained .glb avatar to R2,+// plus the public URL it will be readable at after upload. Used by the /play+// lobby's "bring your own avatar" drop zone: the player drops a .glb, the client+// uploads it directly to storage, then broadcasts the resulting public URL to the+// room — so every peer (not just the uploader) renders the custom avatar.+//+// /play is anonymous, so a session is OPTIONAL. Authenticated users get a stable+// per-user key namespace; anonymous players upload under a shared `anon` prefix.+//+// Request body (JSON):+// filename string? — original filename (only the .glb extension matters)+// content_type string? — MIME type (default + only sensible value: model/gltf-binary)+// bytes number? — declared file size, rejected early if over the cap+//+// Response 200:+// {+// upload_url: string, // PUT the .glb here (expires in 5 min)+// public_url: string, // read from here after the PUT completes+// storage_key: string, // R2 key, for reference+// }++import { cors, error, json, wrap } from '../_lib/http.js';+import { getSessionUser } from '../_lib/auth.js';+import { presignUpload, publicUrl } from '../_lib/r2.js';+import { randomUUID } from 'crypto';++// 16 MB — generous for a single-mesh avatar, tight enough to keep the scene's+// per-peer download budget sane. Mirrored client-side in avatar-upload.js.+const MAX_GLB_BYTES = 16 * 1024 * 1024;++// glTF-binary is the only self-contained, single-file model format (a .gltf is+// JSON plus external .bin/texture refs, which a single PUT can't carry). Accept+// octet-stream too, since some browsers report .glb that way on drag-and-drop.+const ALLOWED_TYPES = new Set(['model/gltf-binary', 'application/octet-stream']);++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', `method ${req.method} not allowed`);++ let userId = 'anon';+ try {+ const session = await getSessionUser(req);+ if (session) userId = session.id ?? session.userId ?? 'anon';+ } catch { /* anonymous player — allowed */ }++ const body = req.body || {};+ const contentType = (body.content_type || 'model/gltf-binary').toLowerCase().trim();+ if (!ALLOWED_TYPES.has(contentType)) {+ return error(res, 415, 'unsupported_media_type', `content_type must be model/gltf-binary, got: ${contentType}`);+ }++ const bytes = Number(body.bytes);+ if (Number.isFinite(bytes) && bytes > MAX_GLB_BYTES) {+ return error(res, 413, 'payload_too_large', `glb is ${bytes} bytes; max is ${MAX_GLB_BYTES}`);+ }++ const key = `u/${userId}/avatar/${randomUUID()}.glb`;+ const uploadUrl = await presignUpload({ key, contentType });++ return json(res, 200, {+ upload_url: uploadUrl,+ public_url: publicUrl(key),+ storage_key: key,+ });+});diff --git a/pages/play.html b/pages/play.htmlindex 13f931f42..755726f25 100644--- a/pages/play.html+++ b/pages/play.html@@ -34,14 +34,21 @@<body><div id="kx-loading"><div class="kx-loading-card">+ <img class="kx-loading-logo" src="/three.svg" alt="three.ws" width="38" height="38" /><div class="kx-loading-mark">COIN COMMUNITIES</div>+ <div class="kx-boot-stage">+ <canvas id="kx-boot-avatar" aria-hidden="true"></canvas>+ <div class="kx-boot-fallback" aria-hidden="true"></div>+ </div><div class="kx-loading-sub">Joining the community…</div>- <div class="kx-spinner" role="status" aria-label="Loading"></div>+ <div class="kx-boot-bar" role="status" aria-label="Loading"><span></span></div></div></div><canvas id="kx-canvas"></canvas>+ <script type="module" src="/src/game/boot-avatar.js"></script><script type="module" src="/src/game/coincommunities.js"></script>+ <script type="module" src="/src/game/ambient-crowd.js"></script></body></html>diff --git a/public/features.json b/public/features.jsonindex 0004190b1..32b34a6b9 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-05-30T12:28:40.975Z",+ "generated_at": "2026-05-30T13:29:11.974Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/dev-keepalive.sh b/scripts/dev-keepalive.shnew file mode 100755index 000000000..26f7a3f11--- /dev/null+++ b/scripts/dev-keepalive.sh@@ -0,0 +1,13 @@+#!/usr/bin/env bash+# Keep the Vite dev server alive on a pinned port despite other workspace+# sessions issuing broad `pkill -f vite`. Whenever the server exits, restart it.+set -u+PORT="${1:-3007}"+cd "$(dirname "$0")/.."+while true; do+ echo "[keepalive] starting dev server on :$PORT ($(date '+%H:%M:%S'))"+ npm run dev -- --port "$PORT" --strictPort+ code=$?+ echo "[keepalive] dev exited (code $code); restarting in 2s"+ sleep 2+donediff --git a/scripts/test-ambient.mjs b/scripts/test-ambient.mjsnew file mode 100644index 000000000..952804ad7--- /dev/null+++ b/scripts/test-ambient.mjs@@ -0,0 +1,47 @@+// Headless proof the ambient crowd spawns, lives, and chatters in /play.+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));++// avoid lobby API dependency+await page.route('**/api/explore**', (r) => r.fulfill({ status: 200, contentType: 'application/json', body: '{"items":[]}' }));++await page.goto(`${BASE}/pages/play.html`, { waitUntil: 'load' });+await page.waitForFunction(() => !!window.__CC__, { timeout: 10000 });++// Drop into a world offline.+await page.evaluate(() => window.__CC__.enter({ mint: 'DemoMint', name: 'Doge', symbol: 'DOGE', image: '' }));++// Give the crowd time to attach, load avatars, walk, and chatter.+await page.waitForTimeout(7000);++const snap = await page.evaluate(() => {+ const labels = [...document.querySelectorAll('.cc-label')].map((n) => n.textContent);+ const chatMsgs = document.querySelectorAll('.cc-chat-log .cc-chat-msg').length;+ const online = document.querySelector('.cc-online span:last-child')?.textContent+ || [...document.querySelectorAll('span')].map(s=>s.textContent).find(t=>/online/.test(t||''));+ return { phase: window.__CC__.phase, labelCount: labels.length, labels, chatMsgs, online };+});++// Capture a frame of the living world.+await page.screenshot({ path: '/tmp/play-ambient.png' });+await browser.close();++console.log('phase :', snap.phase);+console.log('crowd labels :', snap.labelCount, snap.labels);+console.log('chat msgs :', snap.chatMsgs);+console.log('online text :', snap.online);+console.log('console errs :', errors.length ? errors : 'none');++let pass = true;+if (snap.phase !== 'world') { console.error('❌ did not reach world'); pass = false; }+if (snap.labelCount < 1) { console.error('❌ no ambient avatars spawned'); pass = false; }+if (errors.filter(e => !/Colyseus|WebSocket|connect failed|1006|game-server|run.app/i.test(e)).length) {+ console.error('❌ non-network console errors:', errors); pass = false;+}+console.log(pass ? '\n✅ AMBIENT CROWD LIVE — avatars present, screenshot at /tmp/play-ambient.png' : '\n❌ AMBIENT TEST FAILED');+process.exit(pass ? 0 : 1);diff --git a/src/animation-manager.js b/src/animation-manager.jsindex eb30610c2..8953476ba 100644--- a/src/animation-manager.js+++ b/src/animation-manager.js@@ -235,6 +235,15 @@ export class AnimationManager {try { this.onChange?.(name); } catch (e) { console.warn('[AnimationManager] onChange threw:', e); }}+ /**+ * Scale playback speed of the active clip. 1 = normal; >1 plays faster+ * (used to make a walk cycle read as a run).+ * @param {number} scale+ */+ setSpeed(scale) {+ this.currentAction?.setEffectiveTimeScale(scale);+ }+/** Stop all animations. */stopAll() {this.mixer?.stopAllAction();diff --git a/src/game/ambient-crowd.js b/src/game/ambient-crowd.jsnew file mode 100644index 000000000..0792c03c2--- /dev/null+++ b/src/game/ambient-crowd.js@@ -0,0 +1,226 @@+// Ambient crowd for /play — a living world without a server.+//+// Self-attaching: this module watches the live CoinCommunities scene+// (window.__CC__) and, while the player is inside a coin world, fills the plaza+// with decorative wandering avatars that stroll, idle, emote, and drop the+// occasional line into chat. So a solo demo never looks like an empty room — and+// the crowd tapers to nothing as real peers join, so the space is never padded+// with fakes once it's genuinely busy.+//+// Deliberately ZERO edits to coincommunities.js: it reads only the public+// scene/camera/ui and runs its own rAF. That keeps it collision-free while the+// rest of the scene is under active development.++import { Group, Vector3 } from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { Box3, Mesh, CapsuleGeometry, SphereGeometry, MeshStandardMaterial } from 'three';+import { AnimationManager } from '../animation-manager.js';++const AVATAR_DEFAULT = '/avatars/default.glb';+const MANIFEST_URL = '/animations/manifest.json';+const CLIP_IDLE = 'idle';+const CLIP_WALK = 'av-walk-feminine';+const WORLD_RADIUS = 54; // a touch inside the plaza edge+const AMBIENT_SPEED = 1.7; // gentle stroll, slower than the player+const AMBIENT_TARGET = 5; // strollers to keep around when you're alone++const NAMES = ['satoshi', 'anon', 'gm_ser', 'degenape', 'moonboy', 'pepe', 'wagmi', 'hodlqueen', 'vibes', 'chad', 'frfr', 'fomo', 'ngmi', 'based_dev', 'gigachad', '0xshill', 'florp'];+const LINES = ['gm ☀️', 'wen moon', 'lfg 🚀', 'wagmi', 'probably nothing', 'few understand', 'based', 'diamond hands 💎', 'ser…', 'this is the way', 'bullish af', 'vibes immaculate', 'we so back', 'iykyk', 'up only 📈'];++const _gltf = new GLTFLoader();+let _defs = null; // [idle, walk] animation defs+let _emotes = null; // a handful of emote defs++async function loadManifest() {+ if (_defs) return;+ let manifest = [];+ try {+ const r = await fetch(MANIFEST_URL, { cache: 'force-cache' });+ if (r.ok) manifest = await r.json();+ } catch { /* locomotion-only fallback below */ }+ const by = (n) => manifest.find((d) => d.name === n);+ _defs = [by(CLIP_IDLE), by(CLIP_WALK)].filter(Boolean);+ _emotes = manifest.filter((d) => d.name !== CLIP_IDLE && d.name !== CLIP_WALK).slice(0, 6);+}++// Load the default avatar into a rig + animation manager. Falls back to a simple+// stand-in so a wanderer is never invisible.+async function buildAvatar(rig, anim) {+ try {+ const gltf = await _gltf.loadAsync(AVATAR_DEFAULT);+ const model = gltf.scene;+ model.traverse((n) => { if (n.isMesh) { n.castShadow = true; n.receiveShadow = false; } });+ const box = new Box3().setFromObject(model);+ model.position.y -= box.min.y;+ rig.add(model);+ anim.attach(model);+ if (_defs?.length) { anim.setAnimationDefs(_defs); await anim.loadAll(); await anim.crossfadeTo(CLIP_IDLE, 0); }+ return Math.max(0.5, box.max.y - box.min.y);+ } catch {+ const body = new Mesh(new CapsuleGeometry(0.32, 0.7, 4, 10), new MeshStandardMaterial({ color: 0x9aa3ad }));+ body.position.y = 0.85; body.castShadow = true;+ const head = new Mesh(new SphereGeometry(0.28, 14, 10), new MeshStandardMaterial({ color: 0xc9cdd2 }));+ head.position.y = 1.55; head.castShadow = true;+ rig.add(body, head);+ return 1.7;+ }+}++async function playEmote(anim, motion) {+ if (!_emotes?.length) return;+ const def = _emotes[(Math.random() * _emotes.length) | 0];+ try {+ if (!anim.clips?.has?.(def.name)) await anim.loadAnimation(def.name, def.url, { loop: false });+ await anim.crossfadeTo(def.name, 0.15);+ setTimeout(() => anim.crossfadeTo(motion === 'walk' ? CLIP_WALK : CLIP_IDLE, 0.2), 2400);+ } catch { /* clip missing — ignore */ }+}++class Wanderer {+ constructor(scene, name) {+ this.name = name;+ this.rig = new Group();+ this.anim = new AnimationManager();+ this.height = 1.7;+ this.motion = 'idle';+ const a = Math.random() * Math.PI * 2, r = 5 + Math.random() * (WORLD_RADIUS * 0.7);+ this.rig.position.set(Math.cos(a) * r, 0, Math.sin(a) * r);+ this.yaw = Math.random() * Math.PI * 2; this.rig.rotation.y = this.yaw;+ scene.add(this.rig);+ this.scene = scene;++ this.label = document.createElement('div');+ this.label.className = 'cc-label';+ this.label.textContent = name;+ document.body.appendChild(this.label);++ this.bubble = null; this._bubbleTimer = null;+ this._dest = null;+ this._wait = 0.5 + Math.random() * 2.5;+ this._sayIn = 5 + Math.random() * 16;+ this._emoteIn = 9 + Math.random() * 22;++ buildAvatar(this.rig, this.anim).then((h) => { this.height = h; });+ }+ _setMotion(m) {+ if (m === this.motion) return;+ this.motion = m;+ this.anim.crossfadeTo(m === 'walk' ? CLIP_WALK : CLIP_IDLE, 0.2);+ }+ say(text, onChat) {+ if (this.bubble) this.bubble.remove();+ this.bubble = document.createElement('div');+ this.bubble.className = 'cc-bubble';+ this.bubble.textContent = text;+ document.body.appendChild(this.bubble);+ clearTimeout(this._bubbleTimer);+ this._bubbleTimer = setTimeout(() => { this.bubble?.remove(); this.bubble = null; }, 4500);+ onChat?.(this.name, text);+ }+ update(dt, onChat) {+ this._sayIn -= dt;+ if (this._sayIn <= 0) { this._sayIn = 12 + Math.random() * 26; this.say(LINES[(Math.random() * LINES.length) | 0], onChat); }+ this._emoteIn -= dt;+ if (this._emoteIn <= 0 && this.motion === 'idle') { this._emoteIn = 16 + Math.random() * 26; playEmote(this.anim, this.motion); }++ if (!this._dest) {+ this._wait -= dt;+ if (this._wait <= 0) {+ const a = Math.random() * Math.PI * 2, r = Math.random() * (WORLD_RADIUS * 0.8);+ this._dest = new Vector3(Math.cos(a) * r, 0, Math.sin(a) * r);+ this._setMotion('walk');+ }+ } else {+ const p = this.rig.position;+ const dx = this._dest.x - p.x, dz = this._dest.z - p.z;+ const dist = Math.hypot(dx, dz);+ if (dist < 0.45) { this._dest = null; this._wait = 1.5 + Math.random() * 4.5; this._setMotion('idle'); }+ else {+ const step = Math.min(dist, AMBIENT_SPEED * dt);+ p.x += (dx / dist) * step; p.z += (dz / dist) * step;+ const tYaw = Math.atan2(dx, dz);+ let d = tYaw - this.yaw;+ while (d > Math.PI) d -= Math.PI * 2;+ while (d < -Math.PI) d += Math.PI * 2;+ this.yaw += d * Math.min(1, dt * 6);+ this.rig.rotation.y = this.yaw;+ }+ }+ this.anim.update(dt);+ }+ dispose() {+ this.scene.remove(this.rig);+ this.label.remove();+ this.bubble?.remove();+ clearTimeout(this._bubbleTimer);+ }+}++class AmbientCrowd {+ constructor(cc) {+ this.cc = cc;+ this.list = [];+ this.active = false;+ this._names = [...NAMES];+ this._onChat = (n, t) => { try { this.cc.ui?.addChat?.({ name: n, text: t, mine: false }); } catch { /* ui not ready */ } };+ }+ _takeName() {+ if (!this._names.length) this._names = [...NAMES];+ const i = (Math.random() * this._names.length) | 0;+ return this._names.splice(i, 1)[0];+ }+ sync(realCount) {+ const want = Math.max(0, AMBIENT_TARGET - (realCount | 0));+ while (this.list.length < want) this.list.push(new Wanderer(this.cc.scene, this._takeName()));+ while (this.list.length > want) this.list.pop().dispose();+ // Reflect the livelier population in the HUD's online count.+ try { this.cc.ui?.setOnline?.((realCount | 0) + this.list.length + 1); } catch { /* ignore */ }+ }+ update(dt) {+ const cam = this.cc.camera;+ const W = window.innerWidth, H = window.innerHeight;+ const place = (node, pos, dy) => {+ const v = new Vector3(pos.x, pos.y + dy, pos.z).project(cam);+ if (v.z > 1 || v.z < -1) { node.style.display = 'none'; return; }+ node.style.display = '';+ node.style.transform = `translate(-50%, -100%) translate(${(v.x * 0.5 + 0.5) * W}px, ${(-v.y * 0.5 + 0.5) * H}px)`;+ };+ for (const w of this.list) {+ w.update(dt, this._onChat);+ place(w.label, w.rig.position, w.height + 0.2);+ if (w.bubble) place(w.bubble, w.rig.position, w.height + 0.7);+ }+ }+ clear() {+ for (const w of this.list) w.dispose();+ this.list = [];+ }+}++// ---- bootstrap: wait for the scene, then run an independent update loop ----+function attach() {+ const cc = window.__CC__;+ if (!cc || !cc.scene || !cc.camera) { setTimeout(attach, 300); return; }+ loadManifest();+ const crowd = new AmbientCrowd(cc);+ let last = performance.now();+ let realCount = -1;+ const tick = () => {+ requestAnimationFrame(tick);+ const now = performance.now();+ const dt = Math.min(0.05, (now - last) / 1000);+ last = now;+ if (cc.phase === 'world') {+ const rc = (cc.remotes?.size) | 0;+ if (!crowd.active) { crowd.active = true; realCount = -1; }+ if (rc !== realCount) { realCount = rc; crowd.sync(rc); }+ crowd.update(dt);+ } else if (crowd.active) {+ crowd.clear();+ crowd.active = false;+ }+ };+ requestAnimationFrame(tick);+}++attach();diff --git a/src/game/avatar-rig.js b/src/game/avatar-rig.jsindex 22c22c01d..efcc86657 100644--- a/src/game/avatar-rig.js+++ b/src/game/avatar-rig.js@@ -12,6 +12,7 @@ import {Group, Box3, Mesh, MeshStandardMaterial, CapsuleGeometry, SphereGeometry,} from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';import { AnimationManager } from '../animation-manager.js';export const AVATAR_DEFAULT = '/avatars/default.glb';@@ -19,7 +20,16 @@ export const MANIFEST_URL = '/animations/manifest.json';export const CLIP_IDLE = 'idle';export const CLIP_WALK = 'av-walk-feminine';+// A shared GLTF loader with Draco decompression wired in — many avatar GLBs+// (and most Sketchfab/pump.fun exports) are Draco-compressed, and without this+// they fail with "No DRACOLoader instance provided". Decoders are vendored at+// /three/draco/gltf/ (see scripts/copy-three-decoders.mjs).+const _draco = new DRACOLoader();+_draco.setDecoderPath('/three/draco/gltf/');const _gltf = new GLTFLoader();+_gltf.setDRACOLoader(_draco);+// Exported so other loaders (avatar-thumb) share one decoder module + cache.+export const dracoLoader = _draco;let _animDefs = null; // cached manifest defs (locomotion + emotes)let _emoteDefs = null;@@ -44,6 +54,13 @@ export function getEmoteDefs() {return _emoteDefs || [];}+// The locomotion clip defs (idle + walk) loaded by loadManifest(). Lets other+// modules (e.g. the thumbnail renderer) pose an avatar into idle instead of its+// raw T-pose bind pose without re-parsing the manifest.+export function getLocomotionDefs() {+ return (_animDefs || []).filter((d) => d.name === CLIP_IDLE || d.name === CLIP_WALK);+}+// Resolve an avatar input (GLB/VRM URL, site path, or three.ws avatar id) to a// loadable model URL. Falls back to the default avatar on anything unresolved.export async function resolveAvatarUrl(input) {diff --git a/src/game/avatar-thumb.js b/src/game/avatar-thumb.jsnew file mode 100644index 000000000..4eef06f05--- /dev/null+++ b/src/game/avatar-thumb.js@@ -0,0 +1,124 @@+// Avatar thumbnail renderer — turns a GLB/VRM avatar URL into a small framed+// PNG portrait so the lobby's avatar picker shows the *actual* model instead of+// a generic emoji. One shared offscreen WebGLRenderer snapshots each avatar in+// turn and caches the result by URL, so previewing N avatars costs a single+// WebGL context (not N live canvases) — consistent with the scene's WebGL+// context budget. Avatars natively face +Z (the scene rotates them to face the+// chase camera), so the portrait camera sits on +Z for a head-on front view.++import {+ Scene, PerspectiveCamera, WebGLRenderer, Group, Box3, Vector3,+ HemisphereLight, DirectionalLight, AmbientLight, SRGBColorSpace,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { AnimationManager } from '../animation-manager.js';+import { loadManifest, getLocomotionDefs, CLIP_IDLE, dracoLoader } from './avatar-rig.js';++const SIZE = 160; // square render target, downscaled by the chip's CSS box++// Share the rig's Draco-enabled loader so compressed avatar GLBs preview too.+const _loader = new GLTFLoader();+_loader.setDRACOLoader(dracoLoader);+const _cache = new Map(); // url -> Promise<string|null> (PNG data URL)+let _renderer = null;+let _scene = null;+let _camera = null;+let _failed = false; // WebGL unavailable — give up quietly after the first try++function ensureRenderer() {+ if (_renderer) return true;+ if (_failed) return false;+ try {+ _renderer = new WebGLRenderer({ alpha: true, antialias: true, preserveDrawingBuffer: true });+ _renderer.setPixelRatio(1);+ _renderer.setSize(SIZE, SIZE, false);+ _renderer.outputColorSpace = SRGBColorSpace;+ _scene = new Scene();+ _scene.add(new HemisphereLight(0xffffff, 0x404a5a, 1.15));+ const key = new DirectionalLight(0xffffff, 1.7);+ key.position.set(1.6, 2.4, 2.0);+ _scene.add(key, new AmbientLight(0xffffff, 0.45));+ _camera = new PerspectiveCamera(30, 1, 0.01, 100);+ return true;+ } catch (err) {+ console.warn('[avatar-thumb] WebGL unavailable, skipping previews:', err?.message);+ _failed = true;+ _renderer = null;+ return false;+ }+}++// Render `url` to a PNG portrait data URL. Cached per URL (including the null+// failure case) so repeated picker renders never re-load or re-render a model.+export function renderAvatarThumb(url) {+ if (!url) return Promise.resolve(null);+ if (_cache.has(url)) return _cache.get(url);+ const p = _snapshot(url).catch((err) => {+ console.warn('[avatar-thumb] preview failed:', url, err?.message);+ return null;+ });+ _cache.set(url, p);+ return p;+}++async function _snapshot(url) {+ if (!ensureRenderer()) return null;+ const gltf = await _loader.loadAsync(url);+ const model = gltf.scene;+ model.traverse((n) => { if (n.isMesh) n.frustumCulled = false; });+ _scene.add(model);++ // Settle the rig into idle so portraits read as a standing character, not a+ // stiff T-pose bind pose. Best-effort: a model with no skeleton or a missing+ // idle clip simply renders as-imported.+ let anim = null;+ try {+ await loadManifest();+ const idle = getLocomotionDefs().find((d) => d.name === CLIP_IDLE);+ if (idle) {+ anim = new AnimationManager();+ anim.attach(model);+ anim.setAnimationDefs([idle]);+ await anim.loadAll();+ await anim.crossfadeTo(CLIP_IDLE, 0);+ anim.update(0.6); // advance into the idle loop for a relaxed stance+ }+ } catch { /* render the bind pose */ }++ try {+ // Feet on the ground, centred on the vertical axis.+ const box = new Box3().setFromObject(model);+ const size = new Vector3(); box.getSize(size);+ const center = new Vector3(); box.getCenter(center);+ model.position.x -= center.x;+ model.position.z -= center.z;+ model.position.y -= box.min.y;++ // Portrait framing: aim at the head/shoulders and fill the frame with the+ // upper body, with a slight 3/4 turn for depth.+ const h = Math.max(0.2, size.y);+ const target = new Vector3(0, h * 0.84, 0);+ const frameH = h * 0.52;+ const fov = (_camera.fov * Math.PI) / 180;+ const dist = (frameH / 2) / Math.tan(fov / 2) * 1.12;+ _camera.position.set(dist * 0.22, target.y, dist);+ _camera.lookAt(target);+ _camera.updateProjectionMatrix();++ _renderer.render(_scene, _camera);+ return _renderer.domElement.toDataURL('image/png');+ } finally {+ anim?.dispose?.();+ _scene.remove(model);+ model.traverse((n) => {+ if (!n.isMesh) return;+ n.geometry?.dispose?.();+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ for (const m of mats) {+ if (!m) continue;+ for (const k in m) { const v = m[k]; if (v && v.isTexture) v.dispose(); }+ m.dispose?.();+ }+ });+ }+}diff --git a/src/game/avatar-upload.js b/src/game/avatar-upload.jsnew file mode 100644index 000000000..71776e8ce--- /dev/null+++ b/src/game/avatar-upload.js@@ -0,0 +1,104 @@+// Bring-your-own-avatar upload pipeline for the /play lobby.+//+// A dropped .glb is only useful to a multiplayer room if every peer can fetch it,+// so a local `blob:` URL won't do — it's valid only in the uploader's tab. This+// module validates the file is a real, renderable GLB, uploads it directly to R2+// via a short-lived presigned PUT (api/avatar/presign-glb), and returns the+// resulting PUBLIC url, which the scene then broadcasts like any other avatar URL.+//+// Validation runs fully client-side before a single byte is uploaded: parse the+// GLB, confirm it has a visible mesh and a measurable size. This rejects junk+// early and gives the picker a real reason string to show, rather than letting a+// broken model silently fall back to the capsule stand-in for everyone.++import { Box3, Vector3 } from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';++// Kept in sync with MAX_GLB_BYTES in api/avatar/presign-glb.js.+export const MAX_GLB_BYTES = 16 * 1024 * 1024;+export const MAX_GLB_MB = MAX_GLB_BYTES / (1024 * 1024);++const GLB_CONTENT_TYPE = 'model/gltf-binary';+const _loader = new GLTFLoader();++function disposeScene(scene) {+ scene.traverse((n) => {+ if (!n.isMesh) return;+ n.geometry?.dispose?.();+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ for (const m of mats) m?.dispose?.();+ });+}++// Validate that `file` is a usable .glb avatar. Throws Error(userFacingMessage)+// on rejection; resolves to { bytes, height } on success.+export async function validateGlb(file) {+ if (!file) throw new Error('No file selected.');+ if (!file.name.toLowerCase().endsWith('.glb')) {+ throw new Error('Only .glb files work — they bundle meshes and textures into one file. Export your model as GLB (not .gltf or .fbx).');+ }+ if (file.size < 64) throw new Error('That file is empty.');+ if (file.size > MAX_GLB_BYTES) {+ throw new Error(`That .glb is ${(file.size / (1024 * 1024)).toFixed(1)} MB — the limit is ${MAX_GLB_MB} MB. Decimate the mesh or shrink textures and try again.`);+ }++ let gltf;+ try {+ gltf = await _loader.parseAsync(await file.arrayBuffer(), '');+ } catch {+ throw new Error('That .glb could not be read as a 3D model — it may be corrupt or not actually a GLB.');+ }++ try {+ let hasMesh = false;+ gltf.scene.traverse((n) => { if (n.isMesh) hasMesh = true; });+ if (!hasMesh) throw new Error('That model has no visible geometry.');++ const size = new Vector3();+ new Box3().setFromObject(gltf.scene).getSize(size);+ const height = size.y;+ if (!Number.isFinite(height) || height <= 0) throw new Error('That model has no measurable size.');++ return { bytes: file.size, height };+ } finally {+ disposeScene(gltf.scene);+ }+}++// PUT the file to a presigned URL, reporting progress (0..1) along the way.+function putWithProgress(url, file, onProgress) {+ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open('PUT', url);+ // Must match the Content-Type the server signed, or R2 rejects the PUT.+ xhr.setRequestHeader('Content-Type', GLB_CONTENT_TYPE);+ xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress?.(e.loaded / e.total); };+ xhr.onload = () => (xhr.status >= 200 && xhr.status < 300+ ? resolve()+ : reject(new Error(`Upload was rejected by storage (${xhr.status}).`)));+ xhr.onerror = () => reject(new Error('Upload failed — check your connection and try again.'));+ xhr.send(file);+ });+}++// Upload a (validated) .glb and return its public URL. `onProgress(fraction)` is+// called during the transfer. Throws Error(userFacingMessage) on any failure.+export async function uploadGlb(file, onProgress) {+ let presign;+ try {+ const r = await fetch('/api/avatar/presign-glb', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ filename: file.name, content_type: GLB_CONTENT_TYPE, bytes: file.size }),+ });+ presign = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(presign?.message || `Could not prepare the upload (${r.status}).`);+ } catch (err) {+ throw new Error(err?.message || 'Could not reach the upload service.');+ }+ if (!presign?.upload_url || !presign?.public_url) throw new Error('Upload service returned an invalid response.');++ await putWithProgress(presign.upload_url, file, onProgress);+ return presign.public_url;+}diff --git a/src/game/boot-avatar.js b/src/game/boot-avatar.jsnew file mode 100644index 000000000..735346a07--- /dev/null+++ b/src/game/boot-avatar.js@@ -0,0 +1,159 @@+// Live 3D avatar for the /play boot loader.+//+// The boot loader (#kx-loading) covers the gap while the main scene bundle and+// avatar assets download. Instead of a bare spinner, we spin up a tiny WebGL+// canvas inside the loader card and render the real default avatar — loaded,+// posed into idle, and slowly turning under a soft key light — so the very+// first thing a player sees is a character, not a wait.+//+// Self-contained on purpose: this evaluates as soon as its module + Three.js+// chunk arrive (overlapping the main bundle's download), so the avatar is on+// screen as early as possible. It shares Three.js and the avatar-rig manifest+// with the scene, so the second GLB fetch is served from the browser cache.+//+// Hand-off: coincommunities.js awaits `window.__ccBootAvatar.ready` before it+// fades the loader out, then calls `dispose()`. `ready` ALWAYS resolves (even on+// WebGL/asset failure) so a missing avatar can never wedge the loader open.++import {+ Scene, PerspectiveCamera, WebGLRenderer, Box3, Vector3,+ HemisphereLight, DirectionalLight, AmbientLight, SRGBColorSpace,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { AnimationManager } from '../animation-manager.js';+import {+ AVATAR_DEFAULT, loadManifest, getLocomotionDefs, CLIP_IDLE,+} from './avatar-rig.js';++const REDUCED_MOTION = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;+const TURN_SPEED = 0.5; // radians/sec — a slow, premium turntable++function boot() {+ const canvas = document.getElementById('kx-boot-avatar');+ if (!canvas) return { ready: Promise.resolve(), dispose() {} };++ let renderer, scene, camera, anim, model, raf = 0, last = 0, yaw = -0.35, alive = true;+ let resolveReady;+ const ready = new Promise((res) => { resolveReady = res; });+ const done = () => { resolveReady?.(); resolveReady = null; };++ try {+ renderer = new WebGLRenderer({ canvas, alpha: true, antialias: true });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.outputColorSpace = SRGBColorSpace;+ sizeToBox();++ scene = new Scene();+ scene.add(new HemisphereLight(0xffffff, 0x202028, 1.1));+ const key = new DirectionalLight(0xffffff, 1.9);+ key.position.set(1.4, 2.6, 2.2);+ const rim = new DirectionalLight(0xbcd2ff, 0.7);+ rim.position.set(-1.8, 1.4, -2.0);+ scene.add(key, rim, new AmbientLight(0xffffff, 0.4));++ camera = new PerspectiveCamera(28, 1, 0.05, 100);+ } catch (err) {+ // No WebGL — reveal the static fallback mark and let the loader proceed.+ console.warn('[boot-avatar] WebGL unavailable:', err?.message);+ canvas.parentElement?.classList.add('kx-boot-noavatar');+ done();+ return { ready, dispose() {} };+ }++ window.addEventListener('resize', sizeToBox, { passive: true });++ new GLTFLoader().loadAsync(AVATAR_DEFAULT).then(async (gltf) => {+ if (!alive) return;+ model = gltf.scene;+ model.traverse((n) => { if (n.isMesh) { n.frustumCulled = false; n.castShadow = false; } });+ scene.add(model);++ // Feet on the ground, centred, framed from the chest up with a slight 3/4+ // turn — a portrait, not a full body lost in the small frame.+ const box = new Box3().setFromObject(model);+ const size = new Vector3(); box.getSize(size);+ const center = new Vector3(); box.getCenter(center);+ model.position.x -= center.x;+ model.position.z -= center.z;+ model.position.y -= box.min.y;++ const h = Math.max(0.4, size.y);+ const target = new Vector3(0, h * 0.82, 0);+ const frameH = h * 0.6;+ const fov = (camera.fov * Math.PI) / 180;+ const dist = (frameH / 2) / Math.tan(fov / 2) * 1.1;+ camera.position.set(0, target.y, dist);+ camera.lookAt(target);++ // Settle into idle so it reads as a standing character, not a T-pose.+ try {+ await loadManifest();+ const idle = getLocomotionDefs().find((d) => d.name === CLIP_IDLE);+ if (idle && alive) {+ anim = new AnimationManager();+ anim.attach(model);+ anim.setAnimationDefs([idle]);+ await anim.loadAll();+ await anim.crossfadeTo(CLIP_IDLE, 0);+ }+ } catch { /* render the bind pose */ }++ if (!alive) return;+ canvas.parentElement?.classList.add('kx-boot-ready');+ last = performance.now();+ loop(last, target);+ done();+ }).catch((err) => {+ console.warn('[boot-avatar] avatar load failed:', err?.message);+ canvas.parentElement?.classList.add('kx-boot-noavatar');+ done();+ });++ // Safety net: never hold the loader more than 6s waiting on the avatar.+ setTimeout(done, 6000);++ function loop(now, target) {+ if (!alive) return;+ raf = requestAnimationFrame((t) => loop(t, target));+ const dt = Math.min(0.05, (now - last) / 1000);+ last = now;+ if (!REDUCED_MOTION && model) {+ yaw += TURN_SPEED * dt;+ model.rotation.y = Math.sin(yaw) * 0.5 - 0.1; // gentle ease back and forth+ }+ anim?.update(dt);+ renderer.render(scene, camera);+ }++ function sizeToBox() {+ const r = canvas.getBoundingClientRect();+ const w = Math.max(1, r.width || canvas.clientWidth || 220);+ const h = Math.max(1, r.height || canvas.clientHeight || 280);+ renderer.setSize(w, h, false);+ if (camera) { camera.aspect = w / h; camera.updateProjectionMatrix(); }+ }++ function dispose() {+ alive = false;+ cancelAnimationFrame(raf);+ window.removeEventListener('resize', sizeToBox);+ try {+ anim?.dispose?.();+ model?.traverse((n) => {+ if (!n.isMesh) return;+ n.geometry?.dispose?.();+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ for (const m of mats) {+ if (!m) continue;+ for (const k in m) { const v = m[k]; if (v && v.isTexture) v.dispose(); }+ m.dispose?.();+ }+ });+ renderer.dispose();+ } catch { /* best-effort teardown */ }+ }++ return { ready, dispose };+}++window.__ccBootAvatar = boot();diff --git a/src/game/chart-screen.js b/src/game/chart-screen.jsnew file mode 100644index 000000000..1d7762b70--- /dev/null+++ b/src/game/chart-screen.js@@ -0,0 +1,504 @@+// Chart Screen — a live in-world trading terminal for a coin community.+//+// Each /play world IS a pump.fun coin, so the community deserves a real screen+// on the plaza showing that coin's live chart: a jumbotron mounted on posts,+// its face an HTML canvas painted with the price line, current price, market+// cap, buy/sell pressure, and a scrolling ticker of the latest on-chain trades.+// The canvas is wrapped in a CanvasTexture, so the 3D "screen" updates in place+// as new trades land — no DOM overlay, it's a physical object in the world you+// can walk up to and click (which opens the coin on pump.fun).+//+// Data is real: /api/pump/coin-trades (the same swap-API proxy the homepage live+// card uses). We poll, accumulate a growing price series across the session, and+// derive price / change / volume / flow from genuine trades. Loading, empty, and+// error states are all painted on the screen itself.++import {+ Group, Mesh, MeshBasicMaterial, MeshStandardMaterial,+ PlaneGeometry, CylinderGeometry, BoxGeometry,+ CanvasTexture, SRGBColorSpace, DoubleSide,+} from 'three';++const TRADES_URL = (mint, limit = 100) =>+ `/api/pump/coin-trades?mint=${encodeURIComponent(mint)}&limit=${limit}`;+const POLL_MS = 5000;+const REDRAW_MS = 100; // ~10fps: enough for a smooth ticker, cheap on the GPU+const MAX_POINTS = 220; // rolling price history kept across the session+const CW = 1280, CH = 720; // 16:9 canvas backing the screen++// Restrained palette — the /play client is monochrome, but a trading terminal+// earns a single directional accent (up green / down red) the way a real screen+// would. Everything else stays light-on-near-black to match the world's UI.+const COL = {+ bg0: '#0a0a0c', bg1: '#121216',+ grid: 'rgba(255,255,255,0.05)',+ text: '#f5f5f6', dim: '#8c8c92', faint: '#5a5a60',+ up: '#5fd08a', down: '#e06c75',+ line: '#f5f5f6',+};++// ── formatters ───────────────────────────────────────────────────────────────++// Memecoin prices span many orders of magnitude; render sub-cent values with the+// "0.0₍n₎digits" leading-zero notation (drawn with a real subscript on canvas).+function priceParts(v) {+ if (!isFinite(v) || v <= 0) return { whole: '—', sub: null, tail: '' };+ if (v >= 1) return { whole: '$' + v.toLocaleString('en-US', { maximumFractionDigits: 2 }), sub: null, tail: '' };+ if (v >= 0.001) return { whole: '$' + v.toFixed(5).replace(/0+$/, '').replace(/\.$/, '.0'), sub: null, tail: '' };+ const e = Math.floor(Math.log10(v)); // e.g. -7+ const zeros = -e - 1; // leading zeros after the decimal point+ const digits = String(Math.round(v / Math.pow(10, e - 2))).slice(0, 3); // 3 significant+ return { whole: '$0.0', sub: String(zeros), tail: digits };+}++function fmtCompactUsd(v) {+ const n = Number(v);+ if (!isFinite(n) || n <= 0) return '—';+ 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.toFixed(0);+}++function fmtSol(v) {+ const n = Number(v);+ if (!isFinite(n) || n === 0) return '0';+ if (n < 0.01) return n.toFixed(4);+ if (n < 1) return n.toFixed(3);+ return n.toFixed(2);+}++function shortAddr(a) {+ const s = String(a || '');+ return s.length > 9 ? `${s.slice(0, 4)}…${s.slice(-3)}` : s || '—';+}++function relTime(ms) {+ const s = Math.max(0, Math.round((Date.now() - ms) / 1000));+ if (s < 5) return 'now';+ if (s < 60) return s + 's';+ const m = Math.round(s / 60);+ if (m < 60) return m + 'm';+ const h = Math.round(m / 60);+ if (h < 24) return h + 'h';+ return Math.round(h / 24) + 'd';+}++function roundRect(ctx, x, y, w, h, r) {+ ctx.beginPath();+ ctx.moveTo(x + r, y);+ ctx.arcTo(x + w, y, x + w, y + h, r);+ ctx.arcTo(x + w, y + h, x, y + h, r);+ ctx.arcTo(x, y + h, x, y, r);+ ctx.arcTo(x, y, x + w, y, r);+ ctx.closePath();+}++// ── factory ──────────────────────────────────────────────────────────────────++/**+ * Build a live chart screen for one coin and add it to the scene.+ * @param {THREE.Scene} scene+ * @param {{mint:string,name:string,symbol:string,image:string,marketCap:number}} coin+ * @param {{position?:[number,number,number], rotationY?:number, width?:number}} [opts]+ * @returns {{group:THREE.Group, mesh:THREE.Mesh, update:Function, dispose:Function, openExternal:Function}}+ */+export function createChartScreen(scene, coin, opts = {}) {+ const position = opts.position || [0, 0, -26];+ const rotationY = opts.rotationY || 0;+ const width = opts.width || 18;+ const height = (width * CH) / CW;++ const group = new Group();+ group.position.set(position[0], position[1], position[2]);+ group.rotation.y = rotationY;++ const postH = 3.2;+ const cy = postH + height / 2; // screen vertical center++ // Two support posts + a crossbar read as a real jumbotron rig.+ const postMat = new MeshStandardMaterial({ color: 0x141417, roughness: 0.5, metalness: 0.6 });+ const postX = width / 2 - 0.7;+ for (const sx of [-postX, postX]) {+ const post = new Mesh(new CylinderGeometry(0.28, 0.34, postH + height, 16), postMat);+ post.position.set(sx, (postH + height) / 2, -0.15);+ post.castShadow = true;+ group.add(post);+ }+ const base = new Mesh(new BoxGeometry(width - 0.4, 0.4, 1.6), postMat);+ base.position.set(0, 0.2, -0.15); base.castShadow = true; base.receiveShadow = true;+ group.add(base);++ // Bezel behind the live face.+ const bezel = new Mesh(+ new BoxGeometry(width + 0.6, height + 0.6, 0.4),+ new MeshStandardMaterial({ color: 0x050506, roughness: 0.4, metalness: 0.7 }),+ );+ bezel.position.set(0, cy, -0.22);+ bezel.castShadow = true;+ group.add(bezel);++ // The live face: an HTML canvas → CanvasTexture → unlit plane (so it glows+ // like a screen rather than catching world light).+ const canvas = document.createElement('canvas');+ canvas.width = CW; canvas.height = CH;+ const ctx = canvas.getContext('2d');+ const tex = new CanvasTexture(canvas);+ tex.colorSpace = SRGBColorSpace;+ tex.anisotropy = 4;+ const panel = new Mesh(+ new PlaneGeometry(width, height),+ new MeshBasicMaterial({ map: tex, side: DoubleSide, toneMapped: false }),+ );+ panel.position.set(0, cy, 0.01);+ panel.userData.chartScreen = true; // raycast tag+ group.add(panel);++ scene.add(group);++ // Optional coin logo for the header (loaded async; header still renders without it).+ let logo = null;+ if (coin.image) {+ const im = new Image();+ im.crossOrigin = 'anonymous';+ im.referrerPolicy = 'no-referrer';+ im.onload = () => { logo = im; };+ im.src = coin.image;+ }++ // ── live state ──────────────────────────────────────────────────────────+ let seen = new Set(); // trade tx signatures already ingested+ let points = []; // [{ ts, price }] ascending by ts+ let recent = []; // newest-first trades for the ticker/flow+ let status = 'loading'; // loading | live | empty | error+ let lastErr = 0;+ let pollTimer = null;+ let destroyed = false;+ let acc = 0; // redraw accumulator+ let t = 0; // elapsed seconds (ticker scroll + pulse)++ function ingest(trades) {+ let added = 0;+ for (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({+ 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 || '',+ });+ }+ if (!added) 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);+ if (recent.length > 40) recent = recent.slice(0, 40);+ // Keep the dedup set from growing unbounded across a long session — the+ // upstream only ever returns the latest window, so the recent tx are all+ // 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');+ }++ async function fetchTrades() {+ try {+ const r = await fetch(TRADES_URL(coin.mint), { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error('HTTP ' + r.status);+ const data = await r.json();+ const trades = Array.isArray(data?.trades) ? data.trades : [];+ ingest(trades);+ if (status === 'loading') status = trades.length ? 'live' : 'empty';+ } catch {+ lastErr = Date.now();+ if (!points.length && !recent.length) status = 'error';+ }+ }++ function poll() {+ if (destroyed) return;+ clearTimeout(pollTimer);+ fetchTrades().finally(() => {+ if (destroyed) return;+ pollTimer = setTimeout(poll, POLL_MS);+ });+ }++ // ── derived metrics ───────────────────────────────────────────────────────+ function metrics() {+ const priced = points;+ const cur = priced.length ? priced[priced.length - 1].price : null;+ const first = priced.length ? priced[0].price : null;+ const pct = first && cur ? ((cur - first) / first) * 100 : null;+ let vol = 0, buys = 0, sells = 0;+ for (const r of recent) {+ if (r.usd) vol += r.usd;+ if (r.isBuy) buys++; else sells++;+ }+ const flow = buys + sells ? buys / (buys + sells) : 0.5;+ return { cur, pct, vol, buys, sells, flow };+ }++ // ── canvas rendering ──────────────────────────────────────────────────────+ function draw() {+ const m = metrics();+ const up = m.pct == null ? null : m.pct >= 0;+ const accent = up == null ? COL.line : up ? COL.up : COL.down;++ // Background — deep glass with a soft top sheen.+ const bg = ctx.createLinearGradient(0, 0, 0, CH);+ bg.addColorStop(0, COL.bg1); bg.addColorStop(1, COL.bg0);+ ctx.fillStyle = bg; ctx.fillRect(0, 0, CW, CH);++ // Header -----------------------------------------------------------------+ const padX = 48;+ let hx = padX;+ const headY = 64;+ // logo chip+ const chip = 56;+ ctx.save();+ roundRect(ctx, hx, headY - chip / 2, chip, chip, 10);+ ctx.fillStyle = '#1a1a1f'; ctx.fill();+ ctx.clip();+ if (logo) ctx.drawImage(logo, hx, headY - chip / 2, chip, chip);+ else {+ ctx.fillStyle = COL.dim;+ ctx.font = '700 22px Inter, system-ui, sans-serif';+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';+ ctx.fillText((coin.symbol || '?').slice(0, 3).toUpperCase(), hx + chip / 2, headY);+ }+ ctx.restore();+ hx += chip + 18;++ ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';+ ctx.fillStyle = COL.text;+ ctx.font = '800 34px Inter, system-ui, sans-serif';+ const nm = (coin.name || 'Community').toUpperCase();+ ctx.fillText(nm.length > 22 ? nm.slice(0, 21) + '…' : nm, hx, headY - 4);+ ctx.fillStyle = COL.dim;+ ctx.font = '600 20px Inter, system-ui, sans-serif';+ const sym = coin.symbol ? '$' + coin.symbol.toUpperCase() : '';+ ctx.fillText(`${sym}${sym ? ' · ' : ''}pump.fun`, hx, headY + 24);++ // live badge (top-right), pulsing+ const pulse = 0.55 + 0.45 * Math.sin(t * 4);+ const badgeW = 116, badgeH = 40, bx = CW - padX - badgeW, by = headY - badgeH / 2 - 6;+ roundRect(ctx, bx, by, badgeW, badgeH, 20);+ ctx.fillStyle = 'rgba(255,255,255,0.05)'; ctx.fill();+ ctx.strokeStyle = 'rgba(255,255,255,0.12)'; ctx.lineWidth = 1; ctx.stroke();+ ctx.beginPath();+ ctx.arc(bx + 26, by + badgeH / 2, 6, 0, Math.PI * 2);+ ctx.fillStyle = status === 'live' ? `rgba(95,208,138,${pulse})` : COL.faint;+ ctx.fill();+ ctx.fillStyle = COL.text;+ ctx.font = '700 18px Inter, system-ui, sans-serif';+ ctx.fillText(status === 'live' ? 'LIVE' : status === 'error' ? 'OFFLINE' : '···', bx + 44, by + 26);++ // "↗ pump.fun" affordance, bottom-right of header row+ ctx.fillStyle = COL.faint;+ ctx.font = '600 16px Inter, system-ui, sans-serif';+ ctx.textAlign = 'right';+ ctx.fillText('↗ tap to open on pump.fun', CW - padX, headY + 40);+ ctx.textAlign = 'left';++ // Price block ------------------------------------------------------------+ const priceY = 168;+ const pp = priceParts(m.cur);+ ctx.fillStyle = COL.text;+ ctx.font = '800 76px Inter, system-ui, sans-serif';+ ctx.textBaseline = 'alphabetic';+ let px = padX;+ ctx.fillText(pp.whole, px, priceY);+ px += ctx.measureText(pp.whole).width;+ if (pp.sub != null) {+ ctx.font = '800 44px Inter, system-ui, sans-serif';+ ctx.fillText(pp.sub, px + 4, priceY + 14);+ px += ctx.measureText(pp.sub).width + 8;+ ctx.font = '800 76px Inter, system-ui, sans-serif';+ ctx.fillText(pp.tail, px, priceY);+ }+ // change pill+ if (m.pct != null) {+ const lbl = `${up ? '▲' : '▼'} ${Math.abs(m.pct).toFixed(m.pct >= 100 ? 0 : 2)}%`;+ ctx.font = '800 30px Inter, system-ui, sans-serif';+ const w = ctx.measureText(lbl).width + 36;+ const pillX = padX, pillY = priceY + 22;+ roundRect(ctx, pillX, pillY, w, 46, 23);+ ctx.fillStyle = up ? 'rgba(95,208,138,0.14)' : 'rgba(224,108,117,0.14)';+ ctx.fill();+ ctx.fillStyle = accent;+ ctx.fillText(lbl, pillX + 18, pillY + 33);+ }+ // session-window note next to the pill+ ctx.fillStyle = COL.faint;+ ctx.font = '600 17px Inter, system-ui, sans-serif';+ ctx.fillText('live session · prices from on-chain swaps', padX + 230, priceY + 52);++ // Chart ------------------------------------------------------------------+ const cxL = padX, cxR = CW - padX;+ const cTop = 280, cBot = CH - 132;+ const cW = cxR - cxL, cH = cBot - cTop;++ // grid+ ctx.strokeStyle = COL.grid; ctx.lineWidth = 1;+ for (let i = 0; i <= 4; i++) {+ const gy = cTop + (cH * i) / 4;+ ctx.beginPath(); ctx.moveTo(cxL, gy); ctx.lineTo(cxR, gy); ctx.stroke();+ }++ if (points.length >= 2) {+ let lo = Infinity, hi = -Infinity;+ for (const p of points) { if (p.price < lo) lo = p.price; if (p.price > hi) hi = p.price; }+ if (hi === lo) { hi *= 1.0001; lo *= 0.9999; }+ const pad = (hi - lo) * 0.12;+ lo -= pad; hi += pad;+ const t0 = points[0].ts, t1 = points[points.length - 1].ts || t0 + 1;+ const span = Math.max(1, t1 - t0);+ const X = (ts) => cxL + (cW * (ts - t0)) / span;+ const Y = (pr) => cBot - (cH * (pr - lo)) / (hi - lo);++ // area fill+ ctx.beginPath();+ ctx.moveTo(X(points[0].ts), cBot);+ for (const p of points) ctx.lineTo(X(p.ts), Y(p.price));+ ctx.lineTo(X(points[points.length - 1].ts), cBot);+ ctx.closePath();+ const fill = ctx.createLinearGradient(0, cTop, 0, cBot);+ const rgb = up == null ? '245,245,246' : up ? '95,208,138' : '224,108,117';+ fill.addColorStop(0, `rgba(${rgb},0.28)`);+ fill.addColorStop(1, `rgba(${rgb},0.01)`);+ ctx.fillStyle = fill; ctx.fill();++ // line+ ctx.beginPath();+ points.forEach((p, i) => { const x = X(p.ts), y = Y(p.price); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); });+ ctx.strokeStyle = accent; ctx.lineWidth = 3; ctx.lineJoin = 'round';+ ctx.shadowColor = accent; ctx.shadowBlur = 14; ctx.stroke(); ctx.shadowBlur = 0;++ // leading dot, pulsing+ const lastP = points[points.length - 1];+ const lx = X(lastP.ts), ly = Y(lastP.price);+ ctx.beginPath(); ctx.arc(lx, ly, 9 + pulse * 3, 0, Math.PI * 2);+ ctx.fillStyle = `rgba(${rgb},${0.18 + pulse * 0.22})`; ctx.fill();+ ctx.beginPath(); ctx.arc(lx, ly, 5, 0, Math.PI * 2);+ ctx.fillStyle = accent; ctx.fill();++ // hi/lo labels+ ctx.fillStyle = COL.dim; ctx.font = '600 16px Inter, system-ui, sans-serif';+ ctx.textAlign = 'right';+ const hiP = priceParts(hi), loP = priceParts(lo);+ ctx.fillText(hiP.whole + (hiP.sub ? '·' + hiP.tail : ''), cxR - 6, cTop + 20);+ ctx.fillText(loP.whole + (loP.sub ? '·' + loP.tail : ''), cxR - 6, cBot - 8);+ ctx.textAlign = 'left';+ } else {+ ctx.fillStyle = COL.dim;+ ctx.font = '600 24px Inter, system-ui, sans-serif';+ ctx.textAlign = 'center';+ const msg = status === 'error' ? 'Live feed unavailable — retrying…'+ : status === 'empty' ? 'No recent trades yet — be the first to ape in.'+ : 'Loading on-chain trades…';+ ctx.fillText(msg, CW / 2, cTop + cH / 2);+ ctx.textAlign = 'left';+ }++ // Stat strip -------------------------------------------------------------+ const sY = cBot + 16, sH = 56;+ const stats = [+ ['MARKET CAP', fmtCompactUsd(coin.marketCap)],+ ['VOLUME (live)', fmtCompactUsd(m.vol)],+ ['TRADES', String(recent.length || 0)],+ ['FLOW', `${m.buys}B / ${m.sells}S`],+ ];+ const colW = (CW - padX * 2) / stats.length;+ stats.forEach(([k, v], i) => {+ const x = padX + colW * i;+ ctx.fillStyle = COL.faint; ctx.font = '700 15px Inter, system-ui, sans-serif';+ ctx.fillText(k, x, sY + 16);+ ctx.fillStyle = COL.text; ctx.font = '800 26px Inter, system-ui, sans-serif';+ ctx.fillText(v, x, sY + 44);+ if (i) {+ ctx.strokeStyle = COL.grid; ctx.beginPath();+ ctx.moveTo(x - 16, sY); ctx.lineTo(x - 16, sY + sH); ctx.stroke();+ }+ });++ // buy/sell pressure bar under the stat strip+ const barY = sY + sH + 6, barH = 6, barW = CW - padX * 2;+ roundRect(ctx, padX, barY, barW, barH, 3); ctx.fillStyle = 'rgba(224,108,117,0.5)'; ctx.fill();+ roundRect(ctx, padX, barY, barW * m.flow, barH, 3); ctx.fillStyle = COL.up; ctx.fill();++ // Ticker -----------------------------------------------------------------+ const tickY = CH - 30;+ ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fillRect(0, tickY - 26, CW, 56);+ ctx.save();+ ctx.beginPath(); ctx.rect(padX, tickY - 26, CW - padX * 2, 56); ctx.clip();+ if (recent.length) {+ const seg = recent.slice(0, 16).map((r) => {+ const side = r.isBuy ? 'BUY' : 'SELL';+ const usd = r.usd ? ' ' + fmtCompactUsd(r.usd) : '';+ return { r, txt: `${side} ${fmtSol(r.sol)} SOL${usd} · ${shortAddr(r.trader)} · ${relTime(r.ts)}` };+ });+ ctx.font = '700 18px Inter, system-ui, sans-serif';+ const gap = 64;+ const widths = seg.map((s) => ctx.measureText(s.txt).width + gap);+ const total = widths.reduce((a, b) => a + b, 0) || 1;+ let scroll = (t * 70) % total;+ let x = padX - scroll;+ // draw twice so it wraps seamlessly+ for (let pass = 0; pass < 2; pass++) {+ let xx = x + pass * total;+ seg.forEach((s, i) => {+ ctx.fillStyle = s.r.isBuy ? COL.up : COL.down;+ ctx.fillText(s.txt.split(' ')[0], xx, tickY);+ const lead = ctx.measureText(s.txt.split(' ')[0] + ' ').width;+ ctx.fillStyle = COL.dim;+ ctx.fillText(' ' + s.txt.split(' ').slice(1).join(' '), xx + lead - 8, tickY);+ xx += widths[i];+ });+ }+ } else {+ ctx.fillStyle = COL.faint; ctx.font = '600 17px Inter, system-ui, sans-serif';+ ctx.fillText('Awaiting live trades…', padX, tickY);+ }+ ctx.restore();++ tex.needsUpdate = true;+ }++ // first paint + go live+ draw();+ poll();++ return {+ group,+ mesh: panel,+ mint: coin.mint,+ update(dt) {+ if (destroyed) return;+ t += dt;+ acc += dt;+ if (acc >= REDRAW_MS / 1000) { acc = 0; draw(); }+ },+ openExternal() {+ window.open(`https://pump.fun/coin/${coin.mint}`, '_blank', 'noopener,noreferrer');+ },+ dispose() {+ destroyed = true;+ clearTimeout(pollTimer);+ scene.remove(group);+ group.traverse((n) => {+ if (n.isMesh) {+ n.geometry?.dispose?.();+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ for (const mm of mats) { mm?.map?.dispose?.(); mm?.dispose?.(); }+ }+ });+ },+ };+}diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.jsindex 98ca92260..919ea6cb1 100644--- a/src/game/coincommunities-ui.js+++ b/src/game/coincommunities-ui.js@@ -9,6 +9,10 @@// The 3D scene (coincommunities.js) owns WebGL + projected name labels; this// module owns the 2D chrome and calls back through the handlers passed in.+import { renderAvatarThumb } from './avatar-thumb.js';+import { resolveAvatarUrl } from './avatar-rig.js';+import { validateGlb, uploadGlb } from './avatar-upload.js';+function el(tag, props = {}, kids = []) {const n = document.createElement(tag);for (const [k, v] of Object.entries(props)) {@@ -39,6 +43,10 @@ export class CommunityUI {constructor(h) {this.h = h;this.coins = [];+ this.searchResults = []; // live pump.fun search hits beyond the trending grid+ this.searching = false;+ this._searchSeq = 0; // guards against out-of-order async search responses+ this._searchTimer = null;this.avatar = localStorage.getItem('cc-avatar') || DEFAULT_AVATAR;this._buildLobby();this._buildHud();@@ -46,7 +54,7 @@ export class CommunityUI {// ---------------------------------------------------------------- lobby_buildLobby() {- this.searchInput = el('input', { type: 'text', placeholder: 'Search coins…', oninput: () => this._renderGrid() });+ this.searchInput = el('input', { type: 'text', placeholder: 'Search any pump.fun coin…', oninput: () => this._onSearchInput() });this.grid = el('div', { class: 'cc-grid' });this.presetRow = el('div', { class: 'cc-avatar-presets' });@@ -57,11 +65,24 @@ export class CommunityUI {onchange: () => { this._setAvatar(this.customInput.value.trim() || DEFAULT_AVATAR, true); },});+ // Bring-your-own avatar: drop a .glb on the bar or pick one. It's validated,+ // uploaded to storage, then broadcast by its public URL so peers see it too.+ this.uploadFile = el('input', {+ type: 'file', accept: '.glb,model/gltf-binary', class: 'cc-upload-file',+ onchange: (e) => { const f = e.target.files?.[0]; if (f) this._handleGlbFile(f); e.target.value = ''; },+ });+ this.uploadBtn = el('label', { class: 'cc-upload-btn', title: 'Upload a .glb avatar from your device' }, [+ el('span', { class: 'cc-upload-ico', text: '⬆' }),+ el('span', { class: 'cc-upload-text', text: 'Upload .glb' }),+ this.uploadFile,+ ]);+ this.uploadStatus = el('div', { class: 'cc-upload-status', role: 'status', 'aria-live': 'polite', hidden: true });+this.lobby = el('div', { id: 'cc-lobby' }, [el('div', { class: 'cc-lobby-inner' }, [el('div', { class: 'cc-lobby-head' }, [el('div', { class: 'cc-brand' }, [- el('div', { class: 'cc-brand-logo', text: '🪙' }),+ el('a', { class: 'cc-brand-logo', href: '/', 'aria-label': 'three.ws home', title: 'three.ws', html: '<svg viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M11.013 1.011a16 16 0 0 0-3.96 1.39C2.79 4.531.213 8.757.012 13.564c-.16 3.933 1.31 7.62 4.117 10.357l.736.715-.16.46c-.084.249-.13.504-.138.761 0 1.358 1.448 2.218 2.638 1.567.535-.292.879-.748 1.043-1.384.084-.331.092-.462.07-.882-.02-.43-.04-.535-.18-.83-.246-.52-.567-.86-1.087-1.153l-.297-.167.106-.32c.18-.543.79-1.717 1.181-2.276 1.91-2.729 5.066-4.395 8.4-4.434l.43-.005.012-1.19c.006-.654.024-1.19.04-1.19s.252.197.526.438c.71.624 2.296 1.95 2.785 2.328.23.178.41.34.4.36-.01.02-.214.156-.453.303-.926.57-2.265 1.65-3.13 2.524l-.27.273.012 1.064.013 1.064.32.027c1.327.114 2.598.685 3.578 1.607.21.198.39.343.4.323.04-.073.276-1.327.346-1.84.296-2.169-.094-4.317-1.129-6.16l-.19-.34.246-.45c.811-1.485 1.291-3.063 1.456-4.776.04-.42.046-.488.111-.488.111 0 1.327.715 1.94 1.143 2.953 2.057 4.96 5.241 5.579 8.856.21 1.22.234 1.585.234 3.063 0 1.485-.024 1.844-.234 3.064-.811 4.736-4.06 8.732-8.51 10.474-1.04.407-2.504.78-3.578.91l-.32.04v2.395l.41-.046c2.014-.226 4.222-.93 5.98-1.91 4.84-2.688 8.058-7.464 8.696-12.897.105-.892.105-3.063 0-3.956-.638-5.433-3.856-10.21-8.697-12.898C24.083.99 21.875.285 19.86.06 19.322 0 19.27 0 15.752.006c-3.346.006-4.234.02-4.74.105Z"/></svg>' }),el('div', {}, [el('div', { class: 'cc-brand-title', text: 'Coin Communities' }),el('div', { class: 'cc-brand-sub', text: 'Every coin is a 3D world. Drop in and hang out.' }),@@ -73,10 +94,12 @@ export class CommunityUI {el('span', { html: 'Adventure mode<small>Gather · fight · level up</small>' }),]),]),- el('div', { class: 'cc-avatar-bar' }, [- el('div', { class: 'cc-avatar-label', html: 'Your avatar<small>Pick one, or bring your own / your agent</small>' }),+ 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>' }),this.presetRow,- el('div', { class: 'cc-avatar-custom' }, [this.customInput]),+ el('div', { class: 'cc-avatar-custom' }, [this.customInput, this.uploadBtn]),+ this.uploadStatus,+ el('div', { class: 'cc-avatar-dropmsg', text: 'Drop .glb to use as your avatar' }),]),el('p', { class: 'cc-section-title', text: 'Live communities' }),this.grid,@@ -84,10 +107,75 @@ export class CommunityUI {]);document.body.appendChild(this.lobby);+ this._wireGlbDrop();this._renderPresets();this.setCoinsLoading();}+ // Make the avatar bar a drop target for a local .glb. Only reacts to file+ // drags so a stray text/element drag never lights it up.+ _wireGlbDrop() {+ const bar = this.avatarBar;+ const hasFiles = (e) => [...(e.dataTransfer?.types || [])].includes('Files');+ const stop = (e) => { e.preventDefault(); e.stopPropagation(); };+ bar.addEventListener('dragenter', (e) => { stop(e); if (hasFiles(e)) bar.classList.add('cc-drag'); });+ bar.addEventListener('dragover', (e) => { stop(e); if (hasFiles(e)) { e.dataTransfer.dropEffect = 'copy'; bar.classList.add('cc-drag'); } });+ bar.addEventListener('dragleave', (e) => { stop(e); if (!bar.contains(e.relatedTarget)) bar.classList.remove('cc-drag'); });+ bar.addEventListener('drop', (e) => {+ stop(e);+ bar.classList.remove('cc-drag');+ const files = [...(e.dataTransfer?.files || [])];+ const glb = files.find((f) => f.name.toLowerCase().endsWith('.glb')) || files[0];+ if (glb) this._handleGlbFile(glb);+ });+ }++ // Validate → upload → adopt a dropped/selected .glb as the player's avatar.+ async _handleGlbFile(file) {+ if (this._uploading) return;+ this._uploading = true;+ this._setUploadState('working', 'Checking your model…');+ try {+ await validateGlb(file);+ this._setUploadState('working', 'Uploading… 0%');+ const url = await uploadGlb(file, (p) => this._setUploadState('working', `Uploading… ${Math.round(p * 100)}%`));+ this._addUploadedAvatar(url, file.name);+ this._setUploadState('done', `“${file.name}” is now your avatar.`);+ } catch (err) {+ this._setUploadState('error', err?.message || 'Upload failed.');+ } finally {+ this._uploading = false;+ }+ }++ _setUploadState(state, msg) {+ this.uploadStatus.hidden = false;+ this.uploadStatus.setAttribute('data-state', state);+ this.uploadStatus.textContent = msg;+ this.uploadBtn.classList.toggle('cc-busy', state === 'working');+ clearTimeout(this._uploadStatusTimer);+ if (state === 'done' || state === 'error') {+ const ttl = state === 'done' ? 4000 : 7000;+ this._uploadStatusTimer = setTimeout(() => { this.uploadStatus.hidden = true; }, ttl);+ }+ }++ // Surface the uploaded avatar as its own selected chip (replacing any prior+ // upload chip) and make it the active avatar.+ _addUploadedAvatar(url, name) {+ if (this._uploadChip?.isConnected) this._uploadChip.remove();+ const chip = el('button', {+ class: 'cc-avatar-chip cc-avatar-loading cc-avatar-upload',+ title: name || 'Your uploaded avatar', 'aria-label': name || 'Your uploaded avatar',+ onclick: () => this._setAvatar(url, false),+ }, [el('span', { class: 'cc-avatar-glyph', text: '🧑🎨' })]);+ chip._url = url;+ this._uploadChip = chip;+ this.presetRow.insertBefore(chip, this.presetRow.firstChild);+ this._renderChipPreview(chip, { url, label: name || 'Your avatar' });+ this._setAvatar(url, false);+ }+async _renderPresets() {// Default + a few real three.ws community avatars (best-effort fetch).const presets = [{ label: 'Default', url: DEFAULT_AVATAR, icon: '🧍' }];@@ -103,16 +191,39 @@ export class CommunityUI {this.presets = presets.slice(0, 7);this.presetRow.textContent = '';for (const p of this.presets) {+ // Start with the best instantly-available fallback (API thumbnail, else+ // emoji) so the chip is never empty, then render the real model and swap+ // it in. The chip carries a loading shimmer until a preview resolves.+ const fallback = p.thumb+ ? el('img', { src: p.thumb, alt: p.label, loading: 'lazy' })+ : el('span', { class: 'cc-avatar-glyph', text: p.icon || '🙂' });const chip = el('button', {- class: 'cc-avatar-chip' + (p.url === this.avatar ? ' cc-on' : ''),+ class: 'cc-avatar-chip cc-avatar-loading' + (p.url === this.avatar ? ' cc-on' : ''),title: p.label,+ 'aria-label': p.label,onclick: () => this._setAvatar(p.url, false),- }, p.thumb ? [el('img', { src: p.thumb, alt: p.label, loading: 'lazy' })] : [document.createTextNode(p.icon || '🙂')]);+ }, [fallback]);chip._url = p.url;this.presetRow.appendChild(chip);+ this._renderChipPreview(chip, p);}}+ // Render the real avatar model to a portrait and swap it into the chip,+ // replacing the placeholder. Leaves the fallback in place if rendering fails+ // (no WebGL, model load error) so the chip stays meaningful.+ async _renderChipPreview(chip, p) {+ let dataUrl = null;+ try {+ dataUrl = await renderAvatarThumb(await resolveAvatarUrl(p.url));+ } catch { /* keep fallback */ }+ if (!chip.isConnected) return;+ chip.classList.remove('cc-avatar-loading');+ if (!dataUrl) return;+ chip.textContent = '';+ chip.appendChild(el('img', { class: 'cc-avatar-render', src: dataUrl, alt: p.label }));+ }+_setAvatar(url, fromCustom) {this.avatar = url || DEFAULT_AVATAR;localStorage.setItem('cc-avatar', this.avatar);@@ -144,15 +255,57 @@ export class CommunityUI {]));}+ // Debounced live search: filter the loaded trending grid instantly for+ // snappy feedback, then query all of pump.fun so any coin (not just the+ // trending 30) becomes reachable as a world.+ _onSearchInput() {+ const q = this.searchInput.value.trim();+ clearTimeout(this._searchTimer);+ if (q.length < 2) {+ this.searchResults = [];+ this.searching = false;+ this._searchSeq++; // invalidate any in-flight search+ this._renderGrid();+ return;+ }+ this._renderGrid(); // instant local filter+ this._searchTimer = setTimeout(() => this._remoteSearch(q), 280);+ }++ async _remoteSearch(query) {+ if (!this.h.onSearch) return;+ const seq = ++this._searchSeq;+ this.searching = true;+ this._renderGrid();+ let results = [];+ try {+ results = (await this.h.onSearch(query)) || [];+ } catch (err) {+ console.warn('[coincommunities] search failed:', err?.message);+ }+ if (seq !== this._searchSeq) return; // a newer query superseded this one+ this.searchResults = results;+ this.searching = false;+ this._renderGrid();+ }+_renderGrid() {const q = this.searchInput.value.trim().toLowerCase();- const list = this.coins.filter((c) =>- !q || (c.name || '').toLowerCase().includes(q) || (c.symbol || '').toLowerCase().includes(q) || (c.mint || '').toLowerCase().includes(q));+ const matches = (c) =>+ !q || (c.name || '').toLowerCase().includes(q) || (c.symbol || '').toLowerCase().includes(q) || (c.mint || '').toLowerCase().includes(q);+ // 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 seen = new Set(list.map((c) => c.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 (this.searching) { this._renderSearching(); return; }this.grid.appendChild(el('div', { class: 'cc-state' }, [el('span', { class: 'cc-state-ico', text: '🪙' }),- el('div', { text: q ? 'No coins match your search.' : 'No communities yet — be the first in!' }),+ el('div', { text: q ? 'No coins match — try a different name, symbol, or mint.' : 'No communities yet — be the first in!' }),]));return;}@@ -173,6 +326,17 @@ export class CommunityUI {]);this.grid.appendChild(card);}+ // 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…'),+ ]));+ }++ _renderSearching() {+ this.grid.appendChild(el('div', { class: 'cc-state' }, [+ el('span', { class: 'cc-spinner cc-spinner-lg' }),+ el('div', { text: 'Searching all of pump.fun…' }),+ ]));}// ---------------------------------------------------------------- HUDdiff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssindex 1d9e25d5d..b079a80b9 100644--- a/src/game/coincommunities.css+++ b/src/game/coincommunities.css@@ -50,19 +50,74 @@ html, body {transition: opacity 0.5s ease;}#kx-loading.kx-hidden, #cc-loading.cc-hidden { opacity: 0; pointer-events: none; }-.kx-loading-card { text-align: center; }+.kx-loading-card { text-align: center; display: flex; flex-direction: column; align-items: center; }+.kx-loading-logo {+ width: 38px; height: 38px; opacity: 0; margin-bottom: 18px;+ filter: drop-shadow(0 0 14px rgba(255, 255, 255, 0.28));+ animation: kx-rise 0.7s ease 0.05s forwards;+}.kx-loading-mark {font-family: "Inter", system-ui, sans-serif; font-weight: 800;- font-size: clamp(28px, 6vw, 56px); letter-spacing: 0.28em; text-indent: 0.28em;+ font-size: clamp(26px, 5.4vw, 52px); letter-spacing: 0.28em; text-indent: 0.28em;color: #fff; text-transform: uppercase;-}-.kx-loading-sub { color: var(--cc-dim); margin-top: 10px; font-size: 12px; letter-spacing: 0.18em; text-transform: uppercase; }+ opacity: 0; animation: kx-rise 0.7s ease 0.14s forwards;+}+/* The 3D avatar turntable — the loader's hero. Falls back to a soft glyph mark+ if WebGL or the avatar asset is unavailable (.kx-boot-noavatar). */+.kx-boot-stage {+ position: relative; width: clamp(200px, 38vw, 264px); height: clamp(248px, 46vw, 320px);+ margin: 22px 0 14px; opacity: 0; animation: kx-rise 0.8s ease 0.24s forwards;+}+.kx-boot-stage::after {+ content: ""; position: absolute; left: 50%; bottom: 12%; transform: translateX(-50%);+ width: 56%; height: 26px; border-radius: 50%;+ background: radial-gradient(ellipse, rgba(0, 0, 0, 0.55), transparent 70%);+ filter: blur(2px); pointer-events: none;+}+#kx-boot-avatar {+ display: block; width: 100%; height: 100%; position: relative; z-index: 1;+ opacity: 0; transition: opacity 0.6s ease;+}+.kx-boot-stage.kx-boot-ready #kx-boot-avatar { opacity: 1; }+/* Fallback mark — hidden unless WebGL/asset load fails. */+.kx-boot-fallback {+ position: absolute; inset: 0; display: none; place-items: center;+ font-size: 76px; line-height: 1; color: rgba(255, 255, 255, 0.9);+}+.kx-boot-fallback::before { content: "🪙"; filter: drop-shadow(0 0 18px rgba(255, 255, 255, 0.25)); }+.kx-boot-stage.kx-boot-noavatar #kx-boot-avatar { display: none; }+.kx-boot-stage.kx-boot-noavatar .kx-boot-fallback { display: grid; animation: cc-float 3.4s ease-in-out infinite; }+.kx-loading-sub {+ color: var(--cc-dim); font-size: 12px; letter-spacing: 0.18em; text-transform: uppercase;+ opacity: 0; animation: kx-rise 0.7s ease 0.34s forwards;+}+/* Indeterminate progress sweep — a thin hairline that reads as "alive" without+ faking a percentage. */+.kx-boot-bar {+ position: relative; width: 132px; height: 2px; margin: 20px auto 0;+ background: rgba(255, 255, 255, 0.12); overflow: hidden; border-radius: 2px;+ opacity: 0; animation: kx-rise 0.7s ease 0.42s forwards;+}+.kx-boot-bar span {+ position: absolute; inset: 0 auto 0 0; width: 42%;+ background: linear-gradient(90deg, transparent, #fff, transparent);+ animation: kx-sweep 1.25s ease-in-out infinite;+}+@keyframes kx-sweep { 0% { transform: translateX(-110%); } 100% { transform: translateX(360%); } }+@keyframes kx-rise { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }+@keyframes cc-float { 50% { transform: translateY(-8px); } }+/* Legacy spinner kept for any other view that still references it. */.kx-spinner, .cc-spinner {margin: 26px auto 0; width: 26px; height: 26px;border: 2px solid rgba(255, 255, 255, 0.16); border-top-color: #fff;border-radius: 50%; animation: cc-spin 0.8s linear infinite;}@keyframes cc-spin { to { transform: rotate(360deg); } }+@media (prefers-reduced-motion: reduce) {+ .kx-loading-logo, .kx-loading-mark, .kx-boot-stage, .kx-loading-sub, .kx-boot-bar { animation: none; opacity: 1; }+ .kx-boot-bar span { animation: none; width: 100%; transform: none; opacity: 0.5; }+ .kx-boot-stage.kx-boot-noavatar .kx-boot-fallback { animation: none; }+}/* ---------------- lobby ---------------- */#cc-lobby {@@ -89,9 +144,13 @@ html, body {.cc-brand-logo {width: 44px; height: 44px; border-radius: var(--cc-radius);background: #fff; color: var(--cc-ink);- display: grid; place-items: center; font-size: 22px;- box-shadow: var(--cc-glow); filter: grayscale(1) contrast(1.1);+ display: grid; place-items: center;+ box-shadow: var(--cc-glow);+ transition: transform 0.18s ease, box-shadow 0.18s ease;}+.cc-brand-logo svg { width: 26px; height: 26px; display: block; }+.cc-brand-logo:hover { transform: translateY(-1px); }+.cc-brand-logo:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }.cc-brand-title { font-size: 21px; font-weight: 800; letter-spacing: 0.02em; text-transform: uppercase; }.cc-brand-sub { color: var(--cc-dim); font-size: 12px; margin-top: 3px; letter-spacing: 0.02em; }.cc-search {@@ -124,8 +183,21 @@ html, body {transition: border-color 0.12s ease, transform 0.08s ease, filter 0.15s ease;}.cc-avatar-chip img { width: 100%; height: 100%; object-fit: cover; }+/* Rendered avatar portraits frame head-to-chest, so contain + anchor to top and+ sit 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); }+/* Loading shimmer while the model renders to a portrait. */+.cc-avatar-chip.cc-avatar-loading { position: relative; }+.cc-avatar-chip.cc-avatar-loading::after {+ content: ''; position: absolute; inset: 0;+ background: linear-gradient(100deg, transparent 30%, rgba(255, 255, 255, 0.10) 50%, transparent 70%);+ background-size: 220% 100%; animation: cc-avatar-shimmer 1.1s ease-in-out infinite;+}+@keyframes cc-avatar-shimmer { from { background-position: 180% 0; } to { background-position: -80% 0; } }+@media (prefers-reduced-motion: reduce) { .cc-avatar-chip.cc-avatar-loading::after { animation: none; } }.cc-avatar-custom { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 240px; }.cc-avatar-custom input {flex: 1; background: var(--cc-bg2); border: 1px solid var(--cc-edge);@@ -134,6 +206,51 @@ html, body {}.cc-avatar-custom input:focus { border-color: var(--cc-edge-hi); }+/* bring-your-own .glb: upload button, drop target, status */+.cc-avatar-bar { position: relative; transition: border-color 0.15s ease, box-shadow 0.15s ease; }+.cc-avatar-bar.cc-drag { border-color: var(--cc-edge-hi); box-shadow: 0 0 0 1px var(--cc-edge-hi), var(--cc-glow); }+.cc-avatar-dropmsg {+ position: absolute; inset: 0; display: none; align-items: center; justify-content: center;+ border-radius: var(--cc-radius); background: rgba(6, 6, 7, 0.82); backdrop-filter: blur(2px);+ color: var(--cc-text); font-size: 14px; font-weight: 600; letter-spacing: 0.02em;+ border: 1px dashed var(--cc-edge-hi); pointer-events: none; z-index: 2;+}+.cc-avatar-bar.cc-drag .cc-avatar-dropmsg { display: flex; }++.cc-upload-file { position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none; }+.cc-upload-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-upload-btn:hover { border-color: var(--cc-edge-hi); background: var(--cc-bg3); }+.cc-upload-btn:active { transform: translateY(1px); }+.cc-upload-btn:focus-within { border-color: var(--cc-edge-hi); box-shadow: 0 0 0 1px var(--cc-edge-hi); }+.cc-upload-ico { font-size: 13px; line-height: 1; }+.cc-upload-btn.cc-busy { pointer-events: none; opacity: 0.65; }+.cc-upload-btn.cc-busy .cc-upload-ico { animation: cc-upload-pulse 0.9s ease-in-out infinite; }+@keyframes cc-upload-pulse { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-3px); } }+@media (prefers-reduced-motion: reduce) { .cc-upload-btn.cc-busy .cc-upload-ico { animation: none; } }++.cc-upload-status {+ width: 100%; margin-top: 2px; font-size: 12px; line-height: 1.4;+ display: flex; align-items: center; gap: 7px; color: var(--cc-dim);+}+.cc-upload-status::before {+ content: ''; flex: none; width: 7px; height: 7px; border-radius: 50%; background: var(--cc-dim);+}+.cc-upload-status[data-state="working"] { color: var(--cc-text); }+.cc-upload-status[data-state="working"]::before { background: var(--cc-warn); animation: cc-status-blink 1s ease-in-out infinite; }+.cc-upload-status[data-state="done"] { color: var(--cc-text); }+.cc-upload-status[data-state="done"]::before { background: var(--cc-live); box-shadow: var(--cc-glow); }+.cc-upload-status[data-state="error"] { color: var(--cc-text); }+.cc-upload-status[data-state="error"]::before { background: #ff6b6b; }+@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; }+/* coin grid */.cc-section-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.18em; color: var(--cc-faint); margin: 10px 2px 14px; }.cc-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(224px, 1fr)); gap: 14px; }@@ -186,6 +303,16 @@ html, body {font-size: 12px; letter-spacing: 0.06em; text-transform: uppercase; transition: filter 0.12s ease;}.cc-state button:hover { filter: brightness(0.92); }+.cc-state .cc-spinner-lg { margin: 0 auto 14px; width: 28px; height: 28px; }++/* Trailing "searching all of pump.fun" row shown under the live grid while a+ remote search resolves — the trending hits are already interactive. */+.cc-search-more {+ grid-column: 1 / -1; display: flex; align-items: center; justify-content: center;+ gap: 10px; padding: 18px 12px; color: var(--cc-dim);+ font-size: 12px; letter-spacing: 0.04em;+}+.cc-search-more .cc-spinner { margin: 0; width: 15px; height: 15px; border-width: 2px; }/* ---------------- in-world HUD ---------------- */#cc-hud { position: fixed; inset: 0; z-index: 20; pointer-events: none; }@@ -234,7 +361,7 @@ html, body {/* chat sidebar — dockable, minimizable, persistent log */#cc-chat {position: fixed; right: 14px; bottom: 14px; width: min(340px, 82vw);- max-height: min(60vh, 520px); z-index: 21;+ max-height: min(60vh, 520px); z-index: 23;display: flex; flex-direction: column; overflow: hidden;background: var(--cc-panel); border: 1px solid var(--cc-edge);border-radius: var(--cc-radius); box-shadow: var(--cc-shadow);@@ -303,7 +430,7 @@ html, body {/* emote tray */#cc-emotes {- position: fixed; left: 50%; bottom: 16px; transform: translateX(-50%); z-index: 21;+ position: fixed; left: 50%; bottom: 16px; transform: translateX(-50%); z-index: 22;display: flex; gap: 6px; background: var(--cc-panel); border: 1px solid var(--cc-edge);border-radius: var(--cc-radius); padding: 7px; box-shadow: var(--cc-shadow); backdrop-filter: blur(10px);}@@ -352,7 +479,7 @@ html, body {/* movement stick — bottom-left, always on (touch + mouse). Subtle on desktop,full strength on touch. Sits opposite the chat (bottom-right) so they never overlap. */#cc-joystick {- position: fixed; left: 22px; bottom: 90px; width: 120px; height: 120px; z-index: 22; touch-action: none;+ position: fixed; left: 22px; bottom: 90px; width: 120px; height: 120px; z-index: 30; touch-action: none;opacity: 0.5; transition: opacity 0.2s ease;}#cc-joystick:hover { opacity: 1; }@@ -377,21 +504,43 @@ html, body {@media (max-width: 640px) {#cc-hint { display: none; }.cc-coin-banner { max-width: 60vw; }- #cc-chat { width: 72vw; }++ /* Phone HUD reflow into three non-overlapping zones so movement, chat, and+ emotes are all usable. On a narrow screen the old layout (centered emote+ tray + 72vw chat) overlapped the bottom-left joystick and stacked the emote+ tray on top of the chat input — making both the stick and typing dead. */++ /* Movement stick: bottom-left, on top of everything, in a clear zone. */+ #cc-joystick { left: 16px; bottom: 20px; width: 104px; height: 104px; z-index: 30; opacity: 1; }++ /* Chat: docked bottom-right, narrower so its left edge clears the joystick.+ Above the emote tray so the input always receives taps. */+ #cc-chat { left: auto; right: 10px; bottom: 10px; width: min(58vw, 280px); max-height: 42vh; z-index: 24; }++ /* Emotes: compact, horizontally scrollable, pinned bottom-right just above the+ collapsed chat pill and clear of the joystick. The expanded chat (higher z)+ covers it — collapse chat to emote, which is the natural one-or-the-other. */+ #cc-emotes {+ left: auto; right: 10px; bottom: 58px; transform: none; z-index: 23;+ max-width: calc(100vw - 150px); overflow-x: auto; -webkit-overflow-scrolling: touch;+ padding: 6px; scrollbar-width: none;+ }+ #cc-emotes::-webkit-scrollbar { display: none; }+ #cc-emotes .cc-emote { flex: 0 0 auto; width: 40px; height: 40px; font-size: 19px; }}/* Adventure-mode link — entry from the social lobby into the isometric MMO (/game). */.cc-adventure {display: inline-flex; align-items: center; gap: 10px; text-decoration: none;- padding: 8px 14px; border-radius: 12px; color: #e8edf6;- background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.14);+ padding: 8px 14px; border-radius: var(--cc-radius); color: var(--cc-text);+ background: var(--cc-panel); border: 1px solid var(--cc-edge);transition: background 0.15s, border-color 0.15s, transform 0.08s;white-space: nowrap;}-.cc-adventure:hover { background: rgba(255, 255, 255, 0.1); border-color: rgba(255, 255, 255, 0.3); }+.cc-adventure:hover { background: rgba(255, 255, 255, 0.06); border-color: var(--cc-edge-hi); transform: translateY(-1px); }.cc-adventure:active { transform: translateY(1px); }-.cc-adventure:focus-visible { outline: 2px solid #cdd6e6; outline-offset: 2px; }-.cc-adventure-ico { font-size: 18px; line-height: 1; }-.cc-adventure span { display: flex; flex-direction: column; font-weight: 700; font-size: 13px; line-height: 1.2; }-.cc-adventure small { font-weight: 500; font-size: 11px; opacity: 0.6; }+.cc-adventure:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }+.cc-adventure-ico { font-size: 18px; line-height: 1; filter: grayscale(1); }+.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; } }diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 49a7cbd02..30fc97f64 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -11,16 +11,19 @@// Colyseus), reused here so a coin community is a first-class 3D space.import {- Scene, Color, Fog, WebGLRenderer, PerspectiveCamera, Group, Vector3,- HemisphereLight, DirectionalLight, AmbientLight, PCFSoftShadowMap, SRGBColorSpace,- Mesh, MeshStandardMaterial, MeshBasicMaterial, CircleGeometry, RingGeometry,+ Scene, WebGLRenderer, PerspectiveCamera, Group, Vector3, PCFSoftShadowMap, SRGBColorSpace,+ ACESFilmicToneMapping,+ Mesh, MeshStandardMaterial, MeshBasicMaterial, CircleGeometry,CylinderGeometry, PlaneGeometry,CanvasTexture, TextureLoader, DoubleSide,+ Raycaster, Vector2,} from 'three';import { AnimationManager } from '../animation-manager.js';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 { normalizeGatewayURL } from '../ipfs.js';import {loadManifest, getEmoteDefs, resolveAvatarUrl, buildAvatar, playEmoteClip,@@ -29,9 +32,36 @@ import {const WORLD_RADIUS = 58; // a touch inside the server's 60m clampconst MOVE_SPEED = 4.2;+const RUN_SPEED = 8.0; // hold Shift to sprint+const RUN_TIMESCALE = 1.7; // speed the walk cycle up so a sprint reads as a run+const JUMP_VELOCITY = 5.5; // m/s upward kick on Space; ~1m apex under GRAVITY+const GRAVITY = 15; // m/s^2 pulling the jumper back downconst 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';++// 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.+function mapCoins(raw) {+ return (Array.isArray(raw) ? raw : raw.coins || raw.items || []).map((c) => ({+ mint: c.mint || c.address,+ name: (c.name || '').trim() || 'Unnamed coin',+ symbol: (c.symbol || '').trim(),+ image: normalizeGatewayURL(c.image_uri || c.image || c.imageUri || ''),+ marketCap: c.usd_market_cap || c.market_cap_usd || c.marketCap || 0,+ })).filter((c) => c.mint);+}++// Compact USD for the jumbotron's market-cap readout: $1.2B / $940M / $12K.+function formatUsd(n) {+ const v = Number(n) || 0;+ if (v <= 0) return '';+ if (v >= 1e9) return '$' + (v / 1e9).toFixed(v >= 1e10 ? 0 : 1) + 'B';+ if (v >= 1e6) return '$' + (v / 1e6).toFixed(v >= 1e7 ? 0 : 1) + 'M';+ if (v >= 1e3) return '$' + Math.round(v / 1e3) + 'K';+ return '$' + Math.round(v);+}// A networked peer: their own avatar rig + animation + name label + chat bubble.class RemotePlayer {@@ -97,6 +127,7 @@ class RemotePlayer {while (d < -Math.PI) d += Math.PI * 2;this.curYaw += d * 0.2;this.rig.rotation.y = this.curYaw;+ if (this.anim.currentName === CLIP_WALK) this.anim.setSpeed(this.motion === 'run' ? RUN_TIMESCALE : 1);this.anim.update(dt);}dispose() {@@ -122,6 +153,8 @@ export class CoinCommunities {this.localPos = new Vector3(Math.cos(a) * rad, 0, Math.sin(a) * rad);this.localYaw = Math.PI;this.motion = 'idle';+ this.vy = 0; // vertical velocity for jumps+ this.grounded = true; // false while airbornethis._dragging = false; this._lastPtr = null;this._last = performance.now();@@ -133,6 +166,7 @@ export class CoinCommunities {onLeave: () => this.leave(),onChat: (t) => this._sendChat(t),onEmote: (n) => this._emote(n),+ onSearch: (q) => this._searchCoins(q),onRetry: () => this.net?.retry(),onAvatarChange: (url) => { this.net?.setAvatar(url); },});@@ -153,9 +187,17 @@ export class CoinCommunities {}}- _hideBootLoader() {+ async _hideBootLoader() {const l = document.getElementById('kx-loading');- if (l) { l.classList.add('kx-hidden'); setTimeout(() => l.remove(), 600); }+ if (!l) return;+ // Hold the loader until the boot avatar's first frame has rendered so the+ // character is actually seen, not flashed away. `ready` always resolves+ // (even on WebGL/asset failure) and carries its own 6s safety timeout, so+ // this can never wedge the loader open.+ const boot = window.__ccBootAvatar;+ try { await boot?.ready; } catch { /* proceed regardless */ }+ l.classList.add('kx-hidden');+ setTimeout(() => { boot?.dispose?.(); l.remove(); }, 600);}async _loadCoins() {@@ -164,20 +206,24 @@ export class CoinCommunities {const r = await fetch(TRENDING_URL, { headers: { accept: 'application/json' } });if (!r.ok) throw new Error('HTTP ' + r.status);const raw = await r.json();- const list = (Array.isArray(raw) ? raw : raw.coins || raw.items || []).map((c) => ({- mint: c.mint || c.address,- name: (c.name || '').trim() || 'Unnamed coin',- symbol: (c.symbol || '').trim(),- image: normalizeGatewayURL(c.image_uri || c.image || c.imageUri || ''),- marketCap: c.usd_market_cap || c.market_cap_usd || c.marketCap || 0,- })).filter((c) => c.mint);- this.ui.setCoins(list);+ this.ui.setCoins(mapCoins(raw));} catch (err) {console.warn('[coincommunities] coin load failed:', err?.message);this.ui.setCoinsError(() => this._loadCoins());}}+ // 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".+ async _searchCoins(query) {+ const q = (query || '').trim();+ if (!q) return [];+ const r = await fetch(`${SEARCH_URL}?q=${encodeURIComponent(q)}`, { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error('HTTP ' + r.status);+ return mapCoins(await r.json());+ }+// ---------------------------------------------------------------- render_initRenderer() {const r = new WebGLRenderer({ canvas: this.canvas, antialias: true });@@ -185,72 +231,72 @@ export class CoinCommunities {r.setSize(window.innerWidth, window.innerHeight);r.shadowMap.enabled = true; r.shadowMap.type = PCFSoftShadowMap;r.outputColorSpace = SRGBColorSpace;+ // ACES keeps the cool moonlight key and the bright avatars from clipping;+ // exposure is tuned for the dark monochrome arena (the LDR gradient backdrop+ // doesn't need the heavy pull the old HDR daylight sky did).+ r.toneMapping = ACESFilmicToneMapping;+ r.toneMappingExposure = 1.0;this.renderer = r;window.addEventListener('resize', () => this._onResize());}_initScene() {- // Monochrome world: a near-black void, graphite plaza, light drawn only as- // white. Keeps the avatars (full colour) reading as the focal subjects.+ // Nocturnal monochrome arena that flows out of the lobby: near-black ground+ // with a technical hairline grid, a glowing boundary ring, a silhouette+ // treeline melting into fog, under a single cool moonlight key. The whole+ // environment lives in world-env.js so this file stays focused on players,+ // the coin totem, and netcode.const scene = new Scene();- scene.background = new Color(0x060607);- scene.fog = new Fog(0x060607, 55, 125);this.scene = scene;- this.camera = new PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 500);-- scene.add(new HemisphereLight(0xffffff, 0x141416, 0.85));- scene.add(new AmbientLight(0xffffff, 0.22));- const sun = new DirectionalLight(0xffffff, 1.15);- sun.position.set(30, 52, 20); sun.castShadow = true;- sun.shadow.mapSize.set(2048, 2048);- const s = sun.shadow.camera; s.left = -70; s.right = 70; s.top = 70; s.bottom = -70; s.near = 1; s.far = 200;- sun.shadow.bias = -0.0004;- scene.add(sun, sun.target);-- // Plaza floor — graphite.- const floor = new Mesh(new CircleGeometry(WORLD_RADIUS + 2, 64),- new MeshStandardMaterial({ color: 0x121214, roughness: 0.92, metalness: 0.0 }));- floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true;- scene.add(floor);- // Crisp white boundary ring — the only "glow" in the scene.- const ring = new Mesh(new RingGeometry(WORLD_RADIUS, WORLD_RADIUS + 0.6, 96),- new MeshBasicMaterial({ color: 0xffffff, side: DoubleSide, transparent: true, opacity: 0.7 }));- ring.rotation.x = -Math.PI / 2; ring.position.y = 0.02;- scene.add(ring);- // Concentric guide circles for depth — faint white hairlines.- for (const rad of [14, 28, 42]) {- const g = new Mesh(new RingGeometry(rad, rad + 0.06, 96),- new MeshBasicMaterial({ color: 0xffffff, side: DoubleSide, transparent: true, opacity: 0.12 }));- g.rotation.x = -Math.PI / 2; g.position.y = 0.015; scene.add(g);- }+ // Far plane reaches the sky dome; near stays tight for close avatars.+ this.camera = new PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 9000);++ this.env = createWorldEnvironment(scene, this.renderer, WORLD_RADIUS);this.world = new Group();scene.add(this.world);}+ // Animate the world each frame: drifting clouds (owned by the environment)+ // and the slowly turning coin totem.+ _tickEnv(dt) {+ this.env?.update(dt);+ if (this._coinSpin) this._coinSpin.rotation.y += dt * 0.5;+ if (this._screenPulse) {+ this._screenT = (this._screenT || 0) + dt;+ this._screenPulse.material.opacity = 0.35 + 0.35 * (0.5 + 0.5 * Math.sin(this._screenT * 2.4));+ }+ this._chartScreen?.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: 0x1b1b1e, roughness: 0.5, metalness: 0.4 }));+ new MeshStandardMaterial({ color: 0x2a2a30, roughness: 0.7, metalness: 0.1 }));pillar.position.y = 3; pillar.castShadow = true; pillar.receiveShadow = true;g.add(pillar);- // Floating coin disc with the token image — brushed silver.+ // 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).+ 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: 0xd6d6da, roughness: 0.3, metalness: 0.85, emissive: 0x222226, emissiveIntensity: 0.3 }));- disc.rotation.x = Math.PI / 2; disc.position.y = 7.5; disc.castShadow = true;- g.add(disc);+ new MeshStandardMaterial({ color: 0xd8d8de, roughness: 0.22, metalness: 0.95, emissive: 0x202024, emissiveIntensity: 0.25 }));+ disc.rotation.x = Math.PI / 2; disc.castShadow = true;+ spin.add(disc);this._totemDisc = disc;if (coin.image) {new TextureLoader().load(coin.image, (tex) => {tex.colorSpace = SRGBColorSpace;const face = new Mesh(new CircleGeometry(1.9, 40), new MeshBasicMaterial({ map: tex }));- face.position.set(0, 7.5, 0.18); g.add(face);+ face.position.set(0, 0, 0.18); spin.add(face);const back = new Mesh(new CircleGeometry(1.9, 40), new MeshBasicMaterial({ map: tex }));- back.position.set(0, 7.5, -0.18); back.rotation.y = Math.PI; g.add(back);+ back.position.set(0, 0, -0.18); back.rotation.y = Math.PI; spin.add(back);}, undefined, () => { /* image blocked — totem still shows */ });}+ g.add(spin);+ this._coinSpin = spin;// Name banner texture.g.add(this._textBanner(coin.name || 'Community', coin.symbol ? '$' + coin.symbol : ''));// Place the totem as a landmark away from the spawn point so players don't@@ -275,6 +321,141 @@ export class CoinCommunities {return m;}+ // Stadium-style jumbotron — the coin's giant LED screen, towering over the+ // plaza so it's the first thing players see on entry. It shows the coin art,+ // name, market cap, and a LIVE readout of how many are in the community right+ // now (redrawn from _updateOnline as people join and leave). Built as a dark+ // panel on two posts at the far edge of the plaza, angled to face the spawn.+ _buildScreen(coin) {+ const W = 24, H = 13.5; // 16:9 panel, in metres+ const g = new Group();++ // Dark bezel behind the lit panel so the screen reads as a framed display.+ const bezel = new Mesh(new PlaneGeometry(W + 0.7, H + 0.7),+ new MeshStandardMaterial({ color: 0x070708, roughness: 0.6, metalness: 0.3 }));+ bezel.position.set(0, 11, -0.06); g.add(bezel);++ // The lit panel: a canvas texture (name / market cap / live count) drawn by+ // _drawScreen. Unlit material so it glows like an LED wall at any distance.+ const canvas = document.createElement('canvas');+ canvas.width = 1600; canvas.height = 900;+ const tex = new CanvasTexture(canvas); tex.colorSpace = SRGBColorSpace;+ const panel = new Mesh(new PlaneGeometry(W, H), new MeshBasicMaterial({ map: tex }));+ panel.position.set(0, 11, 0); g.add(panel);+ this._screenCanvas = canvas; this._screenTex = tex;++ // Coin artwork as its own textured plane (loaded the same CORS-safe way as+ // the totem) overlaid on the panel's left third, so compositing the image+ // into the canvas can never taint it.+ if (coin.image) {+ new TextureLoader().load(coin.image, (imgTex) => {+ imgTex.colorSpace = SRGBColorSpace;+ const art = new Mesh(new PlaneGeometry(8.4, 8.4), new MeshBasicMaterial({ map: imgTex }));+ art.position.set(-6.7, 11, 0.04); g.add(art);+ this._screenArt = art;+ }, undefined, () => { /* image blocked — panel still shows text */ });+ }++ // A LIVE bar that pulses along the panel's base (animated in _tickEnv) — the+ // cheap, always-moving signal that the room is live without redrawing canvas.+ const pulse = new Mesh(new PlaneGeometry(W - 1.2, 0.16),+ new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.6 }));+ pulse.position.set(0, 11 - H / 2 + 0.5, 0.05); g.add(pulse);+ this._screenPulse = pulse;++ // Two posts carrying the panel down to the ground.+ const postMat = new MeshStandardMaterial({ color: 0x131316, roughness: 0.5, metalness: 0.5 });+ const postH = 11 - H / 2;+ for (const sx of [-1, 1]) {+ const post = new Mesh(new CylinderGeometry(0.32, 0.42, postH, 18), postMat);+ post.position.set(sx * (W / 2 - 1.4), postH / 2, -0.1);+ post.castShadow = true; g.add(post);+ }++ // Far edge of the plaza, facing back toward the spawn/camera (+Z view).+ g.position.set(0, 0, 34);+ g.rotation.y = Math.PI;+ this.world.add(g);+ this._screen = g;+ this._drawScreen();+ }++ // Render the jumbotron's text layer: coin name, symbol, market cap, and the+ // live community count. Cheap and event-driven — only called on build and when+ // the online count changes, never per-frame.+ _drawScreen() {+ const canvas = this._screenCanvas;+ if (!canvas) return;+ const coin = this.coin || {};+ const x = canvas.getContext('2d');+ x.clearRect(0, 0, 1600, 900);++ // Panel background + inner frame.+ const bg = x.createLinearGradient(0, 0, 0, 900);+ bg.addColorStop(0, '#101013'); bg.addColorStop(1, '#050506');+ x.fillStyle = bg; x.fillRect(0, 0, 1600, 900);+ x.strokeStyle = 'rgba(255,255,255,0.10)'; x.lineWidth = 3;+ x.strokeRect(14, 14, 1572, 872);++ // Art well on the left (the coin-image plane sits over this region).+ x.beginPath(); x.roundRect(96, 210, 600, 600, 20);+ x.fillStyle = 'rgba(255,255,255,0.04)';+ x.fill(); x.strokeStyle = 'rgba(255,255,255,0.12)'; x.lineWidth = 2; x.stroke();+ if (!coin.image) {+ x.fillStyle = 'rgba(255,255,255,0.28)';+ x.font = '300 200px Inter, system-ui, sans-serif';+ x.textAlign = 'center'; x.textBaseline = 'middle';+ x.fillText('◎', 396, 500);+ }++ const colX = 770; // right text column+ x.textAlign = 'left'; x.textBaseline = 'alphabetic';++ // Coin name — shrink the font until it fits the column width.+ const name = (coin.name || 'Community').toUpperCase();+ let nameSize = 116;+ x.fillStyle = '#f5f5f6';+ do { x.font = `800 ${nameSize}px Inter, system-ui, sans-serif`; nameSize -= 4; }+ while (x.measureText(name).width > 740 && nameSize > 48);+ x.fillText(name, colX, 300);++ // $SYMBOL.+ if (coin.symbol) {+ x.fillStyle = '#8c8c92';+ x.font = '600 52px Inter, system-ui, sans-serif';+ x.fillText('$' + coin.symbol.toUpperCase(), colX, 372);+ }++ // Divider.+ x.strokeStyle = 'rgba(255,255,255,0.10)'; x.lineWidth = 2;+ x.beginPath(); x.moveTo(colX, 430); x.lineTo(1500, 430); x.stroke();++ // Market cap (only when we have it).+ const mcap = formatUsd(coin.marketCap);+ if (mcap) {+ x.fillStyle = '#5a5a60';+ x.font = '600 34px Inter, system-ui, sans-serif';+ x.fillText('MARKET CAP', colX, 500);+ x.fillStyle = '#f5f5f6';+ x.font = '800 92px Inter, system-ui, sans-serif';+ x.fillText(mcap, colX, 588);+ }++ // LIVE — N in this community.+ const n = this._online || 1;+ const baseY = 740;+ x.fillStyle = '#ffffff';+ x.beginPath(); x.arc(colX + 11, baseY - 13, 11, 0, Math.PI * 2); x.fill();+ x.font = '800 38px Inter, system-ui, sans-serif';+ x.fillText('LIVE', colX + 38, baseY);+ x.fillStyle = '#8c8c92';+ x.font = '500 38px Inter, system-ui, sans-serif';+ const label = n === 1 ? '1 in this community' : `${n} in this community`;+ x.fillText(label, colX + 150, baseY);++ this._screenTex.needsUpdate = true;+ }+// ---------------------------------------------------------------- enter/leaveasync enter(coin) {if (this.phase !== 'lobby') return;@@ -294,6 +475,12 @@ export class CoinCommunities {// Build the coin's world + local avatar.this._buildTotem(coin);+ this._buildScreen(coin);+ // 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 });this.localRig = new Group();this.localRig.position.copy(this.localPos);this.scene.add(this.localRig);@@ -324,7 +511,14 @@ export class CoinCommunities {if (this.net) { this.net.destroy(); this.net = null; }for (const [, r] of this.remotes) r.dispose();this.remotes.clear();- if (this._totem) { this.world.remove(this._totem); this._totem = null; }+ if (this._totem) { this.world.remove(this._totem); this._totem = null; this._coinSpin = null; }+ if (this._screen) {+ this.world.remove(this._screen);+ this._screenTex?.dispose();+ this._screen = null; this._screenCanvas = null; this._screenTex = null;+ this._screenArt = null; this._screenPulse = null;+ }+ if (this._chartScreen) { this._chartScreen.dispose(); this._chartScreen = null; }if (this.localRig) { this.scene.remove(this.localRig); this.localRig = null; }if (this._nipple) { this._nipple.destroy(); this._nipple = null; }this.phase = 'lobby';@@ -334,7 +528,9 @@ export class CoinCommunities {_updateOnline() {const n = (this.remotes.size + (this.net?.status === 'online' ? 1 : 0)) || 1;+ this._online = n;this.ui.setOnline(n);+ this._drawScreen(); // keep the jumbotron's LIVE count in sync}// ---------------------------------------------------------------- net events@@ -375,13 +571,32 @@ export class CoinCommunities {window.addEventListener('keydown', (e) => {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 pagethis.keys.add(e.key.toLowerCase());});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.canvas.addEventListener('pointerdown', (e) => {+ this._dragging = true; this._lastPtr = { x: e.clientX, y: e.clientY };+ this._downPtr = { x: e.clientX, y: e.clientY };+ });window.addEventListener('pointerup', () => { this._dragging = false; });+ // A tap (negligible drag) on the live chart screen opens the coin on pump.fun.+ 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();+ });window.addEventListener('pointermove', (e) => {- if (!this._dragging) return;+ if (!this._dragging) {+ // Hover cursor over the clickable screen (throttled).+ const now = performance.now();+ if (this.phase === 'world' && this._chartScreen && now - (this._hoverAt || 0) > 80) {+ this._hoverAt = now;+ this.canvas.style.cursor = this._raycastScreen(e.clientX, e.clientY) ? 'pointer' : '';+ }+ return;+ }const dx = e.clientX - this._lastPtr.x, dy = e.clientY - this._lastPtr.y;this._lastPtr = { x: e.clientX, y: e.clientY };this.camYaw -= dx * 0.005;@@ -393,6 +608,21 @@ 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;+ this._raycaster = this._raycaster || new Raycaster();+ this._ndc = this._ndc || new Vector2();+ const rect = this.canvas.getBoundingClientRect();+ this._ndc.set(+ ((clientX - rect.left) / rect.width) * 2 - 1,+ -((clientY - rect.top) / rect.height) * 2 + 1,+ );+ this._raycaster.setFromCamera(this._ndc, this.camera);+ return this._raycaster.intersectObject(this._chartScreen.mesh, false).length > 0;+ }+_initJoystick() {const zone = document.getElementById('cc-joystick');if (!zone || this._joyInit) return;@@ -463,13 +693,29 @@ export class CoinCommunities {this.localAnim?.update(dt);for (const [, r] of this.remotes) r.tick(dt);this._updateLabels();- if (this.net) this.net.sendMove({ x: this.localPos.x, y: 0, z: this.localPos.z, yaw: this.localYaw, motion: this.motion });+ if (this.net) this.net.sendMove({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z, yaw: this.localYaw, motion: this.motion });}+ this._tickEnv(dt);this._updateCamera();this.renderer.render(this.scene, this.camera);}+ // Kick the avatar into the air. Ignored while already airborne so a held key+ // can't pogo. Replicated to peers via the y we stream in _loop's sendMove.+ _jump() {+ if (this.phase !== 'world' || !this.grounded) return;+ this.vy = JUMP_VELOCITY;+ this.grounded = false;+ }+_stepLocal(dt) {+ // Vertical integration first so a jump arcs even while standing still.+ if (!this.grounded) {+ this.vy -= GRAVITY * dt;+ this.localPos.y += this.vy * dt;+ if (this.localPos.y <= 0) { this.localPos.y = 0; this.vy = 0; this.grounded = true; }+ }+// Build intent from keys + joystick, relative to camera yaw.let ix = 0, iz = 0;if (this.keys.has('w') || this.keys.has('arrowup')) iz -= 1;@@ -477,28 +723,43 @@ export class CoinCommunities {if (this.keys.has('a') || this.keys.has('arrowleft')) ix -= 1;if (this.keys.has('d') || this.keys.has('arrowright')) ix += 1;if (this._joy) { ix += this._joy.x; iz += this._joy.z; }+ const running = this.keys.has('shift');const mag = Math.hypot(ix, iz);if (mag > 0.05) {ix /= Math.max(1, mag); iz /= Math.max(1, mag);- // rotate intent by camera yaw so W is "away from camera"+ // Map intent into world space using the camera's own basis so the+ // keys read screen-relative: forward (W/up) goes straight away from+ // the camera, D/right tracks screen-right. Camera forward is+ // (sinYaw, cosYaw) and camera-right is (cosYaw, -sinYaw) — see+ // _updateCamera. world = ix*right + (-iz)*forward.const sin = Math.sin(this.camYaw), cos = Math.cos(this.camYaw);const wx = ix * cos - iz * sin;- const wz = ix * sin + iz * cos;- this.localPos.x += wx * MOVE_SPEED * dt;- this.localPos.z += wz * MOVE_SPEED * dt;+ const wz = -ix * sin - iz * cos;+ const speed = running ? RUN_SPEED : MOVE_SPEED;+ this.localPos.x += wx * speed * dt;+ this.localPos.z += wz * speed * dt;// clamp to plazaconst r = Math.hypot(this.localPos.x, this.localPos.z);if (r > WORLD_RADIUS) { this.localPos.x *= WORLD_RADIUS / r; this.localPos.z *= WORLD_RADIUS / r; }this.localYaw = Math.atan2(wx, wz);- if (this.motion !== 'walk') { this.motion = 'walk'; this.localAnim?.crossfadeTo(CLIP_WALK, 0.18); }+ const want = running ? 'run' : 'walk';+ if (this.motion !== want) { this.motion = want; this.localAnim?.crossfadeTo(CLIP_WALK, 0.18); }} else if (this.motion !== 'idle') {this.motion = 'idle'; this.localAnim?.crossfadeTo(CLIP_IDLE, 0.2);}+ // Drive the walk cycle faster while sprinting so it reads as a run.+ if (this.localAnim?.currentName === CLIP_WALK) {+ this.localAnim.setSpeed(this.motion === 'run' ? RUN_TIMESCALE : 1);+ }if (this.localRig) { this.localRig.position.copy(this.localPos); this.localRig.rotation.y = this.localYaw; }}_updateCamera() {- const target = this.phase === 'world' && this.localRig ? this.localPos : new Vector3(0, 2, 0);+ // Track the avatar on the ground plane only — ignore jump height so the+ // camera stays planted while the character hops.+ const target = this.phase === 'world' && this.localRig+ ? new Vector3(this.localPos.x, 0, this.localPos.z)+ : new Vector3(0, 2, 0);const cp = Math.cos(this.camPitch), sp = Math.sin(this.camPitch);const ox = Math.sin(this.camYaw) * cp * this.camDist;const oz = Math.cos(this.camYaw) * cp * this.camDist;diff --git a/src/game/community-net.js b/src/game/community-net.jsindex 12aa926da..5205ad9d6 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -70,6 +70,7 @@ export class CommunityNet {change: new Set(), // (player, id)remove: new Set(), // (id)chat: new Set(), // ({id, name, text, ts})+ interact: new Set(), // ({from, fromName, action, ts}) — a peer interacted with us};this._lastSent = null;this._lastSentAt = 0;@@ -115,6 +116,7 @@ export class CommunityNet {this.sessionId = this.room.sessionId;this.room.onMessage('chat', (msg) => this._emit('chat', msg));+ this.room.onMessage('interact', (msg) => this._emit('interact', msg));const $ = getStateCallbacks(this.room);$(this.room.state).players.onAdd((player, id) => {@@ -180,6 +182,7 @@ export class CommunityNet {sendEmote(name) { this.room?.send('emote', { name }); }sendChat(text) { this.room?.send('chat', { text }); }+ 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/world-env.js b/src/game/world-env.jsnew file mode 100644index 000000000..555143ded--- /dev/null+++ b/src/game/world-env.js@@ -0,0 +1,192 @@+// 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).+//+// 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.++import {+ Color, Fog, Group, Vector3, MathUtils, DoubleSide, SRGBColorSpace,+ HemisphereLight, DirectionalLight, AmbientLight,+ Mesh, MeshStandardMaterial, MeshBasicMaterial,+ CircleGeometry, RingGeometry, CylinderGeometry, ConeGeometry, IcosahedronGeometry,+ 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.+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() {+ 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);+ 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) {+ const root = new Group();+ scene.add(root);+ const rand = rng(0x3d3d3d);+ const between = (a, b) => a + (b - a) * rand();++ // --- 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);++ // --- 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));++ 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);+ sunLight.position.copy(sun).multiplyScalar(120);+ sunLight.castShadow = true;+ sunLight.shadow.mapSize.set(2048, 2048);+ const sc = sunLight.shadow.camera;+ sc.left = -70; sc.right = 70; sc.top = 70; sc.bottom = -70; sc.near = 1; sc.far = 400;+ sunLight.shadow.bias = -0.0004;+ root.add(sunLight, sunLight.target);++ // --- 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 }));+ 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 }));+ 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);+ grid.position.y = 0.02;+ grid.material.transparent = true;+ grid.material.opacity = 0.14;+ grid.material.depthWrite = false;+ root.add(grid);++ // Glowing boundary hairline — the one bright accent on the ground plane.+ 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 }));+ 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.+ const hillGeo = new IcosahedronGeometry(1, 1);+ const hillMat = new MeshStandardMaterial({ color: C_HILL, 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);+ const h = new Mesh(hillGeo, hillMat);+ const w = between(45, 80), tall = between(14, 30);+ h.scale.set(w, tall, w);+ h.position.set(Math.cos(ang) * dist, tall * 0.18 - tall, Math.sin(ang) * dist);+ 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++) {+ 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);+ }++ // 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.+ let t = 0;+ return {+ update(dt) {+ t += dt;+ ring.material.opacity = 0.26 + Math.sin(t * 1.1) * 0.08;+ },+ dispose() {+ scene.remove(root);+ scene.background?.dispose?.();+ scene.background = null;+ scene.fog = null;+ 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?.();+ }+ });+ },+ };+}diff --git a/vite.config.js b/vite.config.jsindex 55362ff34..83ac6bae0 100644--- a/vite.config.js+++ b/vite.config.js@@ -148,6 +148,7 @@ const appConfig = {'buffer','three','three/addons/loaders/GLTFLoader.js',+ 'three/addons/loaders/DRACOLoader.js','three/addons/controls/OrbitControls.js','three/addons/environments/RoomEnvironment.js','three/addons/libs/meshopt_decoder.module.js',