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: CoinCommunities social layer, forge Lambda, worlds lobby + pose/walk upgrades
nirholas2a63a1227024
diff --git a/.env.example b/.env.exampleindex 6355e5586..50a89c534 100644--- a/.env.example+++ b/.env.example@@ -719,3 +719,21 @@ DEBUG=# Set TTS_DEBUG=1 to log every ElevenLabs voice-clone completion (user id,# voice id, audio byte count). Useful while iterating on the cloning flow.TTS_DEBUG=++# ─── CoinCommunities (Coin Worlds / Town social layer) ───────────────────────+# Each coin is its own 3D world on /walk; its CoinCommunities community is the+# live social layer (feed + realtime chat bubbles). The API key is held ONLY+# server-side by the api/community/* proxy — it is never shipped to the browser.+# Get a key: register a business at https://coin-communities.xyz, verify email,+# create an API key in the dashboard. Reads + realtime tickets need only this.+CC_API_KEY=+# API origin. Override only for staging. Don't append /api/v1 — the SDK adds it.+CC_BASE_URL=https://api.coin-communities.xyz+# OPTIONAL server key-pair (x-server-key / x-server-secret). Required ONLY to+# attribute posts to users server-side (postMessageServer). Leave unset and the+# Town composer renders its designed locked state (live reads still work).+CC_SERVER_KEY=+CC_SERVER_SECRET=+# OPTIONAL default coin a bare /walk binds to when no ?coin= is present and the+# lobby is skipped. A Solana mint address. Unset → /walk shows the world lobby.+CC_DEFAULT_TOKEN=diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 91e82b423..65e0b6c95 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ Public feature history for [three.ws](https://three.ws), newest first. Feature d## 2026-05-29+- **$THREE Live · Protocol Pulse** (`/three-live`) — The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.- **Forever — etch a message into Bitcoin** (`/forever`) — Inscribe a message onto the Bitcoin blockchain. It stays there. Forever.- **Pay-As-You-Learn Tutor** (`/tutor`) — Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and signed attestation.- **x402 Arbitrage** (`/arbitrage`) — Cross-provider price disparities surfaced live from the merged x402 facilitator catalog. Find the cheapest endpoint for any capability.diff --git a/api/_lib/coin-communities.js b/api/_lib/coin-communities.jsnew file mode 100644index 000000000..02fc8c263--- /dev/null+++ b/api/_lib/coin-communities.js@@ -0,0 +1,133 @@+// CoinCommunities server-side client — the ONLY place the API key lives.+//+// Each coin on three.ws is its own 3D world (/walk?coin=<mint>); its+// CoinCommunities community is that world's live social layer. The browser+// never sees the API key: it talks to the api/community/* proxy, which calls+// CoinCommunities with the key held here. Realtime works the same way — the+// proxy mints a short-lived WS ticket and the browser opens the socket to+// CoinCommunities directly with it (see api/community/ws-ticket.js).+//+// Two credential tiers:+// CC_API_KEY — reads (feed, messages) + WS tickets.+// CC_SERVER_KEY + CC_SERVER_SECRET — server-side post attribution. Optional;+// absent → the Town composer stays in its+// designed locked state, reads still work.++import { configureApi, api } from '@coin-communities/sdk/node';++// Solana mint addresses — base58, 32–44 chars. Communities are keyed by these.+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++let _configured = false;++export function ccBaseUrl() {+ return (process.env.CC_BASE_URL || 'https://api.coin-communities.xyz').replace(/\/+$/, '');+}++function ccApiKey() {+ return process.env.CC_API_KEY || '';+}++function ccServerKey() {+ return process.env.CC_SERVER_KEY || '';+}++function ccServerSecret() {+ return process.env.CC_SERVER_SECRET || '';+}++/** Reads + WS tickets available. */+export function isConfigured() {+ return Boolean(ccApiKey());+}++/** Server-side post attribution available (postMessageServer). */+export function canPostServer() {+ return Boolean(ccServerKey() && ccServerSecret());+}++/** Validate a community token address before it ever reaches the API. */+export function isValidToken(token) {+ return typeof token === 'string' && BASE58_RE.test(token);+}++class UnconfiguredError extends Error {+ constructor() {+ super('CoinCommunities is not configured (set CC_API_KEY)');+ this.code = 'cc_unconfigured';+ }+}++export { UnconfiguredError };++/**+ * Returns the configured `api` namespace. Configures the shared client once+ * per cold start. Throws UnconfiguredError if no API key is set so callers can+ * answer with a clean 503 rather than leaking a stack trace.+ */+export function cc() {+ if (!isConfigured()) throw new UnconfiguredError();+ if (!_configured) {+ configureApi({ baseUrl: ccBaseUrl(), headers: { 'x-api-key': ccApiKey() } });+ _configured = true;+ }+ return api;+}++/** Headers for server-key-pair operations (merged per-call over the api key). */+export function serverHeaders() {+ return {+ 'x-server-key': ccServerKey(),+ 'x-server-secret': ccServerSecret(),+ };+}++/** Capability snapshot the browser uses to decide which Town affordances to show. */+export function capabilities() {+ return {+ configured: isConfigured(),+ canPost: canPostServer(),+ baseUrl: ccBaseUrl(),+ defaultToken:+ (isValidToken(process.env.CC_DEFAULT_TOKEN) && process.env.CC_DEFAULT_TOKEN) || null,+ };+}++/**+ * Normalize a TopCommunity into the world-card shape the lobby renders. Keeps+ * the browser ignorant of the upstream schema so a field rename upstream is a+ * one-line change here.+ */+export function toWorldCard(c) {+ return {+ token: c.tokenAddress,+ symbol: c.tokenSymbol || null,+ image: c.tokenHighResImageUrl || c.tokenImageUrl || null,+ chainId: c.chainId ?? null,+ members: c.memberCount ?? 0,+ posts: c.postCount ?? 0,+ likes: c.totalLikes ?? 0,+ latestPostAt: c.latestPostAt ?? null,+ };+}++/**+ * Normalize a Message into the compact shape Town renders (rail rows + bubbles).+ * Drops moderation internals the client doesn't need.+ */+export function toTownMessage(m) {+ return {+ id: m.id,+ token: m.tokenAddress,+ content: m.content,+ mediaUrl: m.mediaUrl || null,+ username: m.username || 'anon',+ avatar: m.profileImageUrl || null,+ twitterUrl: m.userTwitterUrl || null,+ wallet: m.walletAddress || null,+ followers: m.followerCount ?? 0,+ likes: m.likeCount ?? 0,+ replies: m.replyCount ?? 0,+ createdAt: m.createdAt,+ };+}diff --git a/api/community/capabilities.js b/api/community/capabilities.jsnew file mode 100644index 000000000..767140351--- /dev/null+++ b/api/community/capabilities.js@@ -0,0 +1,15 @@+// GET /api/community/capabilities+// Tells the browser which Town affordances are live: reads/realtime (needs+// CC_API_KEY) and posting (needs the server key-pair). The browser uses this+// to render the composer enabled vs. in its designed locked state — never a+// dead button.+import { cors, json, method, wrap } from '../_lib/http.js';+import { capabilities } from '../_lib/coin-communities.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;+ // Capabilities are deployment-wide and safe to cache briefly at the edge.+ res.setHeader('cache-control', 'public, max-age=30, s-maxage=30');+ return json(res, 200, { data: capabilities() });+});diff --git a/api/community/messages.js b/api/community/messages.jsnew file mode 100644index 000000000..1d0cf3187--- /dev/null+++ b/api/community/messages.js@@ -0,0 +1,121 @@+// /api/community/messages?token=<mint>+// GET — recent messages for a coin's community (public read).+// POST — post a message, attributed server-side via the server key-pair.+// Available only when CC_SERVER_KEY/SECRET are set AND the caller+// supplies the posting user's twitterId + linked wallet. Otherwise+// returns 403 posting_locked, which the composer renders as its+// designed locked state — not a broken submit.+import { z } from 'zod';+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import {+ cc,+ canPostServer,+ isValidToken,+ serverHeaders,+ toTownMessage,+ UnconfiguredError,+} from '../_lib/coin-communities.js';++const CHAINS = ['solana', 'ethereum', 'base', 'bsc'];++const postSchema = z.object({+ content: z.string().trim().min(1).max(2000),+ walletAddress: z.string().trim().min(1).max(120),+ twitterId: z.string().trim().min(1).max(64),+ chainId: z.enum(CHAINS).default('solana'),+});++function getApi(res) {+ try {+ return cc();+ } catch (err) {+ if (err instanceof UnconfiguredError) {+ error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');+ return null;+ }+ throw err;+ }+}++async function handleGet(req, res, token) {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const api = getApi(res);+ if (!api) return;++ const url = new URL(req.url, 'http://x');+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 50, 1), 100);+ const before = url.searchParams.get('before') || undefined;++ const { data, error: apiErr } = await api.getMessagesPublic({+ path: { token_address: token },+ query: { limit, before },+ });+ if (apiErr) {+ return error(res, 502, 'upstream_error', apiErr.message || 'failed to load messages');+ }++ const messages = (data?.messages ?? []).map(toTownMessage);+ res.setHeader('cache-control', 'public, max-age=5, s-maxage=5, stale-while-revalidate=30');+ return json(res, 200, { data: { messages } });+}++async function handlePost(req, res, token) {+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ if (!canPostServer()) {+ return error(+ res,+ 403,+ 'posting_locked',+ 'server posting is not configured for this deployment',+ );+ }++ const body = await readJson(req).catch(() => null);+ const parsed = postSchema.safeParse(body);+ if (!parsed.success) {+ return error(+ res,+ 400,+ 'validation_error',+ parsed.error.issues[0]?.message || 'invalid body',+ );+ }++ const api = getApi(res);+ if (!api) return;++ const { content, walletAddress, twitterId, chainId } = parsed.data;+ const { data, error: apiErr } = await api.postMessageServer({+ path: { token_address: token },+ body: { content, walletAddress, twitterId, chainId },+ headers: serverHeaders(),+ });+ if (apiErr) {+ // 403 from upstream means the wallet isn't linked / lacks token balance —+ // surface it verbatim so the composer can tell the user exactly why.+ const status = apiErr.statusCode === 403 ? 403 : 502;+ return error(res, status, 'post_failed', apiErr.message || 'failed to post message');+ }++ return json(res, 200, {+ data: { message: data?.message ? toTownMessage(data.message) : null },+ });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const token = new URL(req.url, 'http://x').searchParams.get('token');+ if (!isValidToken(token)) {+ return error(res, 400, 'validation_error', 'valid token query param required');+ }++ if (req.method === 'GET') return handleGet(req, res, token);+ return handlePost(req, res, token);+});diff --git a/api/community/worlds.js b/api/community/worlds.jsnew file mode 100644index 000000000..ec5a5e375--- /dev/null+++ b/api/community/worlds.js@@ -0,0 +1,34 @@+// GET /api/community/worlds+// The lobby of live coin-worlds. Each TopCommunity becomes an enterable 3D+// world on /walk?coin=<token>. Real data — most active communities first.+import { cors, error, json, method, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { cc, toWorldCard, UnconfiguredError } from '../_lib/coin-communities.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ let api;+ try {+ api = cc();+ } catch (err) {+ if (err instanceof UnconfiguredError) {+ return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');+ }+ throw err;+ }++ const { data, error: apiErr } = await api.getTopCommunities();+ if (apiErr) {+ return error(res, 502, 'upstream_error', apiErr.message || 'failed to load worlds');+ }++ const worlds = (data?.communities ?? []).map(toWorldCard);+ // Short cache so the lobby feels live without hammering upstream.+ res.setHeader('cache-control', 'public, max-age=20, s-maxage=20, stale-while-revalidate=60');+ return json(res, 200, { data: { worlds } });+});diff --git a/api/community/ws-ticket.js b/api/community/ws-ticket.jsnew file mode 100644index 000000000..d46e2b332--- /dev/null+++ b/api/community/ws-ticket.js@@ -0,0 +1,40 @@+// POST /api/community/ws-ticket?token=<mint>+// Mints a short-lived WebSocket ticket for a coin's community. The browser+// then opens the realtime socket to CoinCommunities directly with this ticket+// (the API key never leaves the server). Returns the CC origin too so the+// client knows where to connect.+import { cors, error, json, method, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { cc, ccBaseUrl, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const token = new URL(req.url, 'http://x').searchParams.get('token');+ if (!isValidToken(token)) {+ return error(res, 400, 'validation_error', 'valid token query param required');+ }++ let api;+ try {+ api = cc();+ } catch (err) {+ if (err instanceof UnconfiguredError) {+ return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');+ }+ throw err;+ }++ const { data, error: apiErr } = await api.getWsTicket({ path: { token_address: token } });+ if (apiErr || !data?.ticket) {+ return error(res, 502, 'upstream_error', apiErr?.message || 'failed to mint ws ticket');+ }++ // Tickets are single-use and short-lived — never cache.+ res.setHeader('cache-control', 'no-store');+ return json(res, 200, { data: { ticket: data.ticket, baseUrl: ccBaseUrl() } });+});diff --git a/infra/lambda/forge/forge.mjs b/infra/lambda/forge/forge.mjsnew file mode 100644index 000000000..e0b28a930--- /dev/null+++ b/infra/lambda/forge/forge.mjs@@ -0,0 +1,333 @@+// three.ws Forge — deterministic generative 3D sculpture engine. Zero deps.+//+// A seed string → a one-of-one 3D form, synthesized from the Gielis+// superformula, encoded as a real binary GLB (positions, normals, gradient+// vertex colors, a PBR material). Same seed always yields identical bytes;+// a one-character change yields a completely different sculpture.+//+// Nothing here is random at runtime — all variation is derived from a hash of+// the seed, so the API is pure and cacheable.++// ── Deterministic PRNG (xmur3 seed → mulberry32) ─────────────────────────────+function xmur3(str) {+ let h = 1779033703 ^ str.length;+ for (let i = 0; i < str.length; i++) {+ h = Math.imul(h ^ str.charCodeAt(i), 3432918353);+ h = (h << 13) | (h >>> 19);+ }+ return () => {+ h = Math.imul(h ^ (h >>> 16), 2246822507);+ h = Math.imul(h ^ (h >>> 13), 3266489909);+ return (h ^= h >>> 16) >>> 0;+ };+}+function mulberry32(a) {+ return () => {+ a |= 0; a = (a + 0x6d2b79f5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}+function makeRng(seed) {+ const s = xmur3(String(seed));+ return mulberry32(s());+}++// ── Palettes / finishes (seed-selected) ──────────────────────────────────────+// Each finish carries PBR character + a 2-stop gradient (hue base, hsl).+const FINISHES = [+ { name: 'Chrome', metallic: 1.0, roughness: 0.12, emissive: 0.0, hue: 210, sat: 0.06, glow: false },+ { name: 'Obsidian', metallic: 0.6, roughness: 0.18, emissive: 0.0, hue: 270, sat: 0.45, glow: false },+ { name: 'Plasma', metallic: 0.2, roughness: 0.35, emissive: 2.4, hue: 320, sat: 0.95, glow: true },+ { name: 'Jade', metallic: 0.1, roughness: 0.28, emissive: 0.0, hue: 150, sat: 0.6, glow: false },+ { name: 'Gold', metallic: 1.0, roughness: 0.22, emissive: 0.0, hue: 45, sat: 0.85, glow: false },+ { name: 'Aurora', metallic: 0.35, roughness: 0.3, emissive: 1.6, hue: 175, sat: 0.9, glow: true },+ { name: 'Magma', metallic: 0.3, roughness: 0.45, emissive: 2.2, hue: 18, sat: 1.0, glow: true },+ { name: 'Frost', metallic: 0.5, roughness: 0.08, emissive: 0.2, hue: 195, sat: 0.4, glow: false },+];++const FORM_NAMES = ['Orb', 'Bloom', 'Star', 'Shard', 'Helix', 'Coral', 'Lotus', 'Spire', 'Nimbus', 'Vortex', 'Prism', 'Seed'];++function hslToRgb(h, s, l) {+ h = ((h % 360) + 360) % 360 / 360;+ const a = s * Math.min(l, 1 - l);+ const f = (n) => {+ const k = (n + h * 12) % 12;+ return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));+ };+ return [f(0), f(8), f(4)];+}++// ── Trait derivation ─────────────────────────────────────────────────────────+function deriveTraits(seed) {+ const rng = makeRng(seed);+ const pick = (arr) => arr[Math.floor(rng() * arr.length)];+ const range = (lo, hi) => lo + rng() * (hi - lo);++ // Two superformula profiles (latitude + longitude). Curated ranges keep+ // shapes striking rather than degenerate.+ const m1 = Math.floor(range(2, 17));+ const m2 = Math.floor(range(2, 17));+ const prof = () => ({+ n1: range(0.3, 3.2),+ n2: range(0.4, 5.5),+ n3: range(0.4, 5.5),+ });+ const p1 = prof();+ const p2 = prof();+ const twist = range(-1.4, 1.4);+ const finish = pick(FINISHES);+ const hueShift = Math.floor(range(0, 40)) - 20;++ // Rarity: rare params (high symmetry + glow + extreme exponents) score higher.+ let rarity = 0;+ rarity += Math.max(m1, m2) * 2.2;+ rarity += finish.glow ? 22 : 0;+ rarity += p1.n1 < 0.7 || p2.n1 < 0.7 ? 16 : 0; // spiky+ rarity += Math.abs(twist) > 1.0 ? 12 : 0;+ rarity += rng() * 14;+ rarity = Math.min(100, Math.round(rarity));+ const tier = rarity >= 85 ? 'Mythic' : rarity >= 70 ? 'Legendary' : rarity >= 50 ? 'Epic' : rarity >= 30 ? 'Rare' : 'Common';+ const formName = FORM_NAMES[(m1 + m2) % FORM_NAMES.length];++ return {+ seed: String(seed),+ name: `${finish.name} ${formName}`,+ form: formName,+ finish: finish.name,+ symmetry: { lat: m1, lon: m2 },+ spikiness: Math.round((1 / Math.min(p1.n1, p2.n1)) * 100) / 100,+ twist: Math.round(twist * 100) / 100,+ rarity,+ tier,+ _p: { m1, m2, p1, p2, twist, finish, hueShift },+ };+}++// ── Superformula + mesh synthesis ────────────────────────────────────────────+function superR(angle, m, n1, n2, n3) {+ const t1 = Math.pow(Math.abs(Math.cos((m * angle) / 4)), n2);+ const t2 = Math.pow(Math.abs(Math.sin((m * angle) / 4)), n3);+ let r = Math.pow(t1 + t2, -1 / n1);+ if (!isFinite(r)) r = 0;+ return Math.min(r, 8); // clamp runaway spikes+}++function buildMesh(traits, resolution) {+ const { m1, m2, p1, p2, twist, finish, hueShift } = traits._p;+ const lat = resolution; // phi: -pi/2 .. pi/2+ const lon = resolution * 2; // theta: -pi .. pi+ const cols = lon + 1;+ const rows = lat + 1;+ const vCount = rows * cols;++ const positions = new Float32Array(vCount * 3);+ const normals = new Float32Array(vCount * 3);+ const colors = new Uint8Array(vCount * 4);++ const min = [Infinity, Infinity, Infinity];+ const max = [-Infinity, -Infinity, -Infinity];++ let v = 0;+ for (let i = 0; i < rows; i++) {+ const phi = -Math.PI / 2 + (i / lat) * Math.PI;+ const r2 = superR(phi, m2, p2.n1, p2.n2, p2.n3);+ for (let j = 0; j < cols; j++) {+ const theta = -Math.PI + (j / lon) * 2 * Math.PI;+ // twist couples longitude into latitude for spiral character+ const r1 = superR(theta + twist * phi, m1, p1.n1, p1.n2, p1.n3);+ const cx = r1 * Math.cos(theta) * r2 * Math.cos(phi);+ const cz = r1 * Math.sin(theta) * r2 * Math.cos(phi);+ const cy = r2 * Math.sin(phi);+ const k = v * 3;+ positions[k] = cx; positions[k + 1] = cy; positions[k + 2] = cz;+ if (cx < min[0]) min[0] = cx; if (cy < min[1]) min[1] = cy; if (cz < min[2]) min[2] = cz;+ if (cx > max[0]) max[0] = cx; if (cy > max[1]) max[1] = cy; if (cz > max[2]) max[2] = cz;+ v++;+ }+ }++ // Recenter + normalize to maxDim = 2 for a friendly default scale.+ const center = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2];+ const span = Math.max(max[0] - min[0], max[1] - min[1], max[2] - min[2]) || 1;+ const scale = 2 / span;+ for (let p = 0; p < vCount; p++) {+ positions[p * 3] = (positions[p * 3] - center[0]) * scale;+ positions[p * 3 + 1] = (positions[p * 3 + 1] - center[1]) * scale;+ positions[p * 3 + 2] = (positions[p * 3 + 2] - center[2]) * scale;+ }+ const nmin = [Infinity, Infinity, Infinity];+ const nmax = [-Infinity, -Infinity, -Infinity];+ for (let p = 0; p < vCount; p++) {+ for (let a = 0; a < 3; a++) {+ const val = positions[p * 3 + a];+ if (val < nmin[a]) nmin[a] = val;+ if (val > nmax[a]) nmax[a] = val;+ }+ }++ // Indices (two triangles per grid quad).+ const quadCount = lat * lon;+ const indices = new Uint32Array(quadCount * 6);+ let t = 0;+ for (let i = 0; i < lat; i++) {+ for (let j = 0; j < lon; j++) {+ const a = i * cols + j;+ const b = a + cols;+ indices[t++] = a; indices[t++] = b; indices[t++] = a + 1;+ indices[t++] = a + 1; indices[t++] = b; indices[t++] = b + 1;+ }+ }++ // Accumulate face normals → smooth vertex normals.+ for (let f = 0; f < indices.length; f += 3) {+ const ia = indices[f] * 3, ib = indices[f + 1] * 3, ic = indices[f + 2] * 3;+ const ax = positions[ia], ay = positions[ia + 1], az = positions[ia + 2];+ const ux = positions[ib] - ax, uy = positions[ib + 1] - ay, uz = positions[ib + 2] - az;+ const wx = positions[ic] - ax, wy = positions[ic + 1] - ay, wz = positions[ic + 2] - az;+ const nx = uy * wz - uz * wy, ny = uz * wx - ux * wz, nz = ux * wy - uy * wx;+ normals[ia] += nx; normals[ia + 1] += ny; normals[ia + 2] += nz;+ normals[ib] += nx; normals[ib + 1] += ny; normals[ib + 2] += nz;+ normals[ic] += nx; normals[ic + 1] += ny; normals[ic + 2] += nz;+ }+ for (let p = 0; p < vCount; p++) {+ const k = p * 3;+ const len = Math.hypot(normals[k], normals[k + 1], normals[k + 2]) || 1;+ normals[k] /= len; normals[k + 1] /= len; normals[k + 2] /= len;+ }++ // Gradient vertex colors by normalized height, in the finish's hue family.+ const hSpan = nmax[1] - nmin[1] || 1;+ for (let p = 0; p < vCount; p++) {+ const h = (positions[p * 3 + 1] - nmin[1]) / hSpan; // 0..1 bottom→top+ const hue = finish.hue + hueShift + h * 40;+ const light = 0.32 + h * 0.42;+ const [r, g, bl] = hslToRgb(hue, finish.sat, light);+ const c = p * 4;+ colors[c] = Math.round(r * 255);+ colors[c + 1] = Math.round(g * 255);+ colors[c + 2] = Math.round(bl * 255);+ colors[c + 3] = 255;+ }++ return { positions, normals, colors, indices, vCount, min: nmin, max: nmax };+}++// ── GLB binary encoder (hand-written, zero deps) ─────────────────────────────+function align4(n) { return (n + 3) & ~3; }++function encodeGlb(mesh, traits) {+ const { positions, normals, colors, indices, vCount } = mesh;+ const { finish } = traits._p;++ // BIN layout — every accessor is naturally 4-byte aligned.+ const idxBytes = indices.byteLength;+ const posBytes = positions.byteLength;+ const normBytes = normals.byteLength;+ const colBytes = colors.byteLength;+ const binLen = idxBytes + posBytes + normBytes + colBytes;+ const bin = Buffer.alloc(binLen);+ let off = 0;+ Buffer.from(indices.buffer, indices.byteOffset, idxBytes).copy(bin, off); const idxOff = off; off += idxBytes;+ Buffer.from(positions.buffer, positions.byteOffset, posBytes).copy(bin, off); const posOff = off; off += posBytes;+ Buffer.from(normals.buffer, normals.byteOffset, normBytes).copy(bin, off); const normOff = off; off += normBytes;+ Buffer.from(colors.buffer, colors.byteOffset, colBytes).copy(bin, off); const colOff = off; off += colBytes;++ const baseColor = hslToRgb(finish.hue + traits._p.hueShift, finish.sat * 0.8, 0.6);+ const emissive = finish.glow ? hslToRgb(finish.hue, finish.sat, 0.5).map((c) => c * 0.6) : [0, 0, 0];++ const gltf = {+ asset: { version: '2.0', generator: 'three.ws Forge' },+ scene: 0,+ scenes: [{ nodes: [0] }],+ nodes: [{ mesh: 0, name: traits.name }],+ meshes: [{+ name: traits.name,+ primitives: [{+ attributes: { POSITION: 1, NORMAL: 2, COLOR_0: 3 },+ indices: 0,+ material: 0,+ mode: 4,+ }],+ }],+ materials: [{+ name: finish.name,+ pbrMetallicRoughness: {+ baseColorFactor: [baseColor[0], baseColor[1], baseColor[2], 1],+ metallicFactor: finish.metallic,+ roughnessFactor: finish.roughness,+ },+ emissiveFactor: emissive,+ doubleSided: true,+ ...(finish.glow ? { extensions: { KHR_materials_emissive_strength: { emissiveStrength: finish.emissive } } } : {}),+ }],+ ...(finish.glow ? { extensionsUsed: ['KHR_materials_emissive_strength'] } : {}),+ bufferViews: [+ { buffer: 0, byteOffset: idxOff, byteLength: idxBytes, target: 34963 },+ { buffer: 0, byteOffset: posOff, byteLength: posBytes, target: 34962 },+ { buffer: 0, byteOffset: normOff, byteLength: normBytes, target: 34962 },+ { buffer: 0, byteOffset: colOff, byteLength: colBytes, target: 34962 },+ ],+ accessors: [+ { bufferView: 0, componentType: 5125, count: indices.length, type: 'SCALAR' },+ { bufferView: 1, componentType: 5126, count: vCount, type: 'VEC3', min: mesh.min, max: mesh.max },+ { bufferView: 2, componentType: 5126, count: vCount, type: 'VEC3' },+ { bufferView: 3, componentType: 5121, normalized: true, count: vCount, type: 'VEC4' },+ ],+ buffers: [{ byteLength: binLen }],+ };++ const jsonBuf = Buffer.from(JSON.stringify(gltf), 'utf8');+ const jsonPad = align4(jsonBuf.length) - jsonBuf.length;+ const binPad = align4(bin.length) - bin.length;+ const total = 12 + 8 + jsonBuf.length + jsonPad + 8 + bin.length + binPad;++ const out = Buffer.alloc(total);+ let o = 0;+ out.writeUInt32LE(0x46546c67, o); o += 4; // magic "glTF"+ out.writeUInt32LE(2, o); o += 4; // version+ out.writeUInt32LE(total, o); o += 4; // total length+ // JSON chunk+ out.writeUInt32LE(jsonBuf.length + jsonPad, o); o += 4;+ out.writeUInt32LE(0x4e4f534a, o); o += 4; // "JSON"+ jsonBuf.copy(out, o); o += jsonBuf.length;+ for (let i = 0; i < jsonPad; i++) out[o++] = 0x20; // space pad+ // BIN chunk+ out.writeUInt32LE(bin.length + binPad, o); o += 4;+ out.writeUInt32LE(0x004e4942, o); o += 4; // "BIN\0"+ bin.copy(out, o); o += bin.length;+ for (let i = 0; i < binPad; i++) out[o++] = 0x00;++ return out;+}++// ── Public API ───────────────────────────────────────────────────────────────+export function forgeTraits(seed) {+ const t = deriveTraits(seed);+ const { _p, ...pub } = t;+ return pub;+}++export function forgeGlb(seed, resolution = 120) {+ // Ceiling keeps the base64 GLB under the Lambda Function URL 6 MB response cap.+ const res = Math.max(24, Math.min(190, Math.floor(resolution) || 120));+ const traits = deriveTraits(seed);+ const mesh = buildMesh(traits, res);+ const glb = encodeGlb(mesh, traits);+ const { _p, ...pub } = traits;+ return {+ glb,+ stats: { vertices: mesh.vCount, triangles: mesh.indices.length / 3, bytes: glb.length, resolution: res },+ traits: pub,+ };+}++// Raw mesh + full traits (incl. private finish params) for the software+// renderer that produces social-card preview images.+export function forgeRaw(seed, resolution = 90) {+ const res = Math.max(24, Math.min(220, Math.floor(resolution) || 90));+ const traits = deriveTraits(seed);+ const mesh = buildMesh(traits, res);+ return { mesh, traits };+}diff --git a/infra/lambda/forge/index.mjs b/infra/lambda/forge/index.mjsnew file mode 100644index 000000000..cb17251ba--- /dev/null+++ b/infra/lambda/forge/index.mjs@@ -0,0 +1,107 @@+// three.ws Forge — generative 3D sculptures with real AR + social-card sharing.+// Zero dependencies. Behind a Lambda Function URL.+//+// Routes:+// GET /?seed=… → per-seed share page (AR Quick Look / Scene Viewer,+// Open Graph + Twitter Card meta, share buttons)+// GET /api/forge?seed=&res= → the sculpture as a binary GLB (downloadable)+// GET /api/og?seed= → 1200×630 PNG preview (the unfurl image)+// GET /api/forge.json?seed= → traits + stats+// GET /healthz → liveness+//+// Pure & deterministic: a given seed always yields identical bytes, so every+// response is safely cacheable at the edge.++import { forgeGlb, forgeTraits } from './forge.mjs';+import { renderCardPng } from './render.mjs';+import { buildPage } from './page.mjs';++const CORS = {+ 'access-control-allow-origin': '*',+ 'access-control-allow-methods': 'GET, OPTIONS',+ 'access-control-allow-headers': 'content-type',+};+const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8', ...CORS, 'cache-control': 'public, max-age=600' };+const IMMUTABLE = 'public, max-age=31536000, immutable';+const DEFAULT_SEED = 'three.ws';++function json(statusCode, body) { return { statusCode, headers: JSON_HEADERS, body: JSON.stringify(body) }; }++function readSeed(event, { fallback = null } = {}) {+ const raw = event?.queryStringParameters?.seed;+ if (raw == null || raw === '') return fallback;+ return String(raw).slice(0, 256);+}+function safeName(seed) {+ return seed.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || 'sculpture';+}+function originOf(event) {+ const host = event?.requestContext?.domainName || event?.headers?.host || 'localhost';+ return `https://${host}`;+}++export const handler = async (event) => {+ const method = event?.requestContext?.http?.method || 'GET';+ const path = (event?.rawPath || '/').replace(/\/+$/, '') || '/';++ if (method === 'OPTIONS') return { statusCode: 204, headers: JSON_HEADERS, body: '' };++ if (path === '/healthz') return json(200, { ok: true, service: 'forge' });++ if (path === '/api/forge.json') {+ const seed = readSeed(event);+ if (!seed) return json(400, { error: 'missing_seed', message: 'Provide ?seed=<any text>' });+ return json(200, forgeTraits(seed));+ }++ if (path === '/api/forge') {+ const seed = readSeed(event);+ if (!seed) return json(400, { error: 'missing_seed', message: 'Provide ?seed=<any text>' });+ const res = Number(event?.queryStringParameters?.res) || 120;+ try {+ const out = forgeGlb(seed, res);+ return {+ statusCode: 200,+ isBase64Encoded: true,+ headers: {+ 'content-type': 'model/gltf-binary',+ 'content-disposition': `inline; filename="${safeName(seed)}.glb"`,+ 'cache-control': IMMUTABLE,+ 'x-forge-triangles': String(out.stats.triangles),+ 'x-forge-tier': out.traits.tier,+ ...CORS,+ },+ body: out.glb.toString('base64'),+ };+ } catch (err) {+ return json(500, { error: 'forge_failed', message: err?.message || 'Could not forge this seed.' });+ }+ }++ if (path === '/api/og') {+ const seed = readSeed(event, { fallback: DEFAULT_SEED });+ try {+ const { png } = renderCardPng(seed, { width: 1200, height: 630, res: 90 });+ return {+ statusCode: 200,+ isBase64Encoded: true,+ headers: { 'content-type': 'image/png', 'cache-control': IMMUTABLE, ...CORS },+ body: png.toString('base64'),+ };+ } catch (err) {+ return json(500, { error: 'render_failed', message: err?.message || 'Could not render preview.' });+ }+ }++ if (path === '/') {+ const seed = readSeed(event, { fallback: DEFAULT_SEED });+ const traits = forgeTraits(seed);+ return {+ statusCode: 200,+ headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'public, max-age=300' },+ body: buildPage({ seed, traits, origin: originOf(event) }),+ };+ }++ return json(404, { error: 'not_found', path });+};diff --git a/infra/lambda/forge/page.mjs b/infra/lambda/forge/page.mjsnew file mode 100644index 000000000..a122c1d70--- /dev/null+++ b/infra/lambda/forge/page.mjs@@ -0,0 +1,183 @@+// three.ws Forge — per-seed share page. Server-rendered so every /?seed=… URL+// carries correct Open Graph + Twitter Card meta (the unfurl image is the+// actual rendered sculpture from /api/og). The page uses <model-viewer> for+// real AR: tap-to-place on iPhone (AR Quick Look, auto-USDZ) and Android+// (Scene Viewer), plus WebXR — no app install. Share via the native share+// sheet (Snapchat / iMessage / WhatsApp) or an X intent.++const TIER_COLORS = { Common: '#9aa3b8', Rare: '#5b8cff', Epic: '#b06bff', Legendary: '#ffb454', Mythic: '#ff5db4' };+const MODEL_RES = 150;++function esc(s) {+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++export function buildPage({ seed, traits, origin }) {+ const enc = encodeURIComponent(seed);+ const pageUrl = `${origin}/?seed=${enc}`;+ const glbUrl = `${origin}/api/forge?res=${MODEL_RES}&seed=${enc}`;+ const ogUrl = `${origin}/api/og?seed=${enc}`;+ const title = `${traits.name} — three.ws Forge`;+ const desc = `A one-of-one ${traits.tier} 3D sculpture forged from "${seed}". Tap to view it in AR, or download the GLB.`;+ const tierColor = TIER_COLORS[traits.tier] || '#9aa3b8';++ return `<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+<title>${esc(title)}</title>+<meta name="description" content="${esc(desc)}" />+<meta property="og:type" content="website" />+<meta property="og:site_name" content="three.ws Forge" />+<meta property="og:title" content="${esc(title)}" />+<meta property="og:description" content="${esc(desc)}" />+<meta property="og:url" content="${esc(pageUrl)}" />+<meta property="og:image" content="${esc(ogUrl)}" />+<meta property="og:image:width" content="1200" />+<meta property="og:image:height" content="630" />+<meta name="twitter:card" content="summary_large_image" />+<meta name="twitter:title" content="${esc(title)}" />+<meta name="twitter:description" content="${esc(desc)}" />+<meta name="twitter:image" content="${esc(ogUrl)}" />+<link rel="canonical" href="${esc(pageUrl)}" />+<script type="module" src="https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js"></script>+<style>+ :root { --bg:#05060a; --panel:#0c0e16; --panel-2:#10131e; --line:#1d2231; --line-2:#2a3146;+ --text:#eaeef7; --muted:#868da1; --accent:#7c5cff; --accent-2:#19d6a8; --radius:16px;+ --mono:ui-monospace,"SF Mono",Menlo,monospace; --sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,Roboto,sans-serif; }+ * { box-sizing:border-box; } html,body { margin:0; min-height:100%; }+ body { font-family:var(--sans); color:var(--text); -webkit-font-smoothing:antialiased; background:+ radial-gradient(1200px 600px at 82% -12%, rgba(124,92,255,.18), transparent 60%),+ radial-gradient(900px 520px at -6% 4%, rgba(25,214,168,.10), transparent 55%), var(--bg); }+ .wrap { max-width:1120px; margin:0 auto; padding:34px 20px 64px; }+ .top { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; margin-bottom:22px; }+ .brand { font-weight:800; letter-spacing:-.02em; font-size:20px; }+ .brand .g { background:linear-gradient(90deg,var(--accent),var(--accent-2)); -webkit-background-clip:text; background-clip:text; color:transparent; }+ .badge { display:inline-flex; align-items:center; gap:8px; font-size:12px; color:var(--accent-2); border:1px solid var(--line); border-radius:999px; padding:5px 12px; background:var(--panel); }+ .dot { width:7px; height:7px; border-radius:50%; background:var(--accent-2); animation:pulse 2s infinite; }+ @keyframes pulse { 0%{box-shadow:0 0 0 0 rgba(25,214,168,.5);} 70%{box-shadow:0 0 0 8px rgba(25,214,168,0);} 100%{box-shadow:0 0 0 0 rgba(25,214,168,0);} }+ .layout { display:grid; grid-template-columns:1.45fr 1fr; gap:18px; align-items:start; }+ @media (max-width:860px){ .layout { grid-template-columns:1fr; } }+ model-viewer { width:100%; height:560px; background:radial-gradient(120% 120% at 50% 0%, #0d1018 0%, #07090f 70%);+ border:1px solid var(--line); border-radius:var(--radius); --poster-color:transparent; }+ @media (max-width:860px){ model-viewer { height:60vh; } }+ .tier-badge { position:absolute; margin:16px; padding:7px 13px; border-radius:999px; font-size:12px; font-weight:700; letter-spacing:.04em;+ background:rgba(6,8,12,.7); border:1px solid var(--line-2); }+ .stagewrap { position:relative; }+ .panel { display:flex; flex-direction:column; gap:14px; }+ .card { background:linear-gradient(180deg,var(--panel),var(--panel-2)); border:1px solid var(--line); border-radius:var(--radius); padding:20px; }+ .name { font-size:26px; font-weight:800; letter-spacing:-.01em; }+ .seedline { color:var(--muted); font-family:var(--mono); font-size:12px; margin-top:4px; word-break:break-all; }+ .rarity-top { display:flex; justify-content:space-between; font-size:12px; color:var(--muted); margin:16px 0 6px; text-transform:uppercase; letter-spacing:.06em; }+ .rarity-bar { height:8px; border-radius:999px; background:var(--line); overflow:hidden; }+ .rarity-fill { height:100%; border-radius:999px; background:linear-gradient(90deg,var(--accent),var(--accent-2)); }+ .traits { display:grid; grid-template-columns:1fr 1fr; gap:14px; }+ .trait .k { font-size:11px; text-transform:uppercase; letter-spacing:.06em; color:var(--muted); margin-bottom:3px; }+ .trait .v { font-size:16px; font-weight:600; }+ button, a.btn { border:0; border-radius:12px; padding:14px 18px; font-size:14px; font-weight:600; cursor:pointer; text-decoration:none; text-align:center; display:inline-block; font-family:var(--sans); transition:filter .15s,transform .1s; }+ .btn-primary { background:linear-gradient(90deg,var(--accent),#6b4cff); color:#fff; }+ .btn-ar { background:linear-gradient(90deg,var(--accent-2),#13b894); color:#04130f; }+ .btn-ghost { background:var(--panel); color:var(--text); border:1px solid var(--line); }+ button:hover, a.btn:hover { filter:brightness(1.08); } button:active { transform:translateY(1px); }+ .actions { display:grid; grid-template-columns:1fr 1fr; gap:10px; }+ .actions .full { grid-column:1 / -1; }+ .forge-form { display:flex; gap:10px; margin-top:6px; }+ .forge-form input { flex:1; min-width:0; background:var(--panel); border:1px solid var(--line); color:var(--text); border-radius:12px; padding:13px 15px; font-size:14px; font-family:var(--mono); outline:none; }+ .forge-form input:focus { border-color:var(--accent); box-shadow:0 0 0 3px rgba(124,92,255,.18); }+ .hint { color:var(--muted); font-size:12px; margin-top:10px; line-height:1.5; }+ .toast { position:fixed; bottom:22px; left:50%; transform:translateX(-50%) translateY(20px); background:var(--panel); border:1px solid var(--line-2); color:var(--text); padding:10px 18px; border-radius:10px; font-size:13px; opacity:0; pointer-events:none; transition:opacity .2s,transform .2s; }+ .toast.show { opacity:1; transform:translateX(-50%) translateY(0); }+ footer { margin-top:26px; color:var(--muted); font-size:13px; line-height:1.7; }+ footer code { font-family:var(--mono); background:var(--panel); padding:2px 7px; border-radius:6px; border:1px solid var(--line); color:var(--text); }+ footer a { color:var(--accent); text-decoration:none; } footer a:hover { text-decoration:underline; }+</style>+</head>+<body>+<div class="wrap">+ <div class="top">+ <div class="brand">three.ws <span class="g">Forge</span></div>+ <span class="badge"><span class="dot"></span> Tap “View in AR” on your phone</span>+ </div>++ <div class="layout">+ <div class="stagewrap">+ <span class="tier-badge" style="color:${tierColor}">${esc(traits.tier).toUpperCase()}</span>+ <model-viewer+ src="${esc(glbUrl)}"+ alt="${esc(traits.name)}"+ poster="${esc(ogUrl)}"+ ar ar-modes="webxr scene-viewer quick-look" ar-scale="auto"+ camera-controls auto-rotate auto-rotate-delay="0" rotation-per-second="22deg"+ shadow-intensity="0.9" exposure="1.0" environment-image="neutral"+ interaction-prompt="none">+ <button slot="ar-button" class="btn btn-ar" style="position:absolute;bottom:16px;left:50%;transform:translateX(-50%)">📱 View in your space</button>+ </model-viewer>+ </div>++ <div class="panel">+ <div class="card">+ <div class="name">${esc(traits.name)}</div>+ <div class="seedline">seed: ${esc(seed)}</div>+ <div class="rarity-top"><span>Rarity · ${esc(traits.tier)}</span><span>${traits.rarity}/100</span></div>+ <div class="rarity-bar"><div class="rarity-fill" style="width:${traits.rarity}%"></div></div>+ </div>++ <div class="card"><div class="traits">+ <div class="trait"><div class="k">Form</div><div class="v">${esc(traits.form)}</div></div>+ <div class="trait"><div class="k">Finish</div><div class="v">${esc(traits.finish)}</div></div>+ <div class="trait"><div class="k">Symmetry</div><div class="v">${traits.symmetry.lat} × ${traits.symmetry.lon}</div></div>+ <div class="trait"><div class="k">Spikiness</div><div class="v">${traits.spikiness}</div></div>+ </div></div>++ <div class="card">+ <div class="actions">+ <button class="btn-ghost full" id="ar2">📱 View in your space (AR)</button>+ <button class="btn-primary" id="share">Share</button>+ <a class="btn btn-ghost" id="tweet" target="_blank" rel="noopener">Post to X</a>+ <a class="btn btn-ghost full" href="${esc(glbUrl)}" download="${esc(seed).slice(0, 40)}.glb">Download .glb</a>+ </div>+ <div class="hint">On iPhone this opens in AR Quick Look; on Android, Scene Viewer. No app needed.</div>+ </div>++ <div class="card">+ <form class="forge-form" method="GET" action="/">+ <input type="text" name="seed" placeholder="Forge another seed…" autocomplete="off" spellcheck="false" />+ <button class="btn-primary" type="submit">Forge</button>+ </form>+ </div>+ </div>+ </div>++ <footer>+ <p>Public API · <code>GET /api/forge?seed=…</code> → GLB · <code>GET /api/og?seed=…</code> → preview image · <code>GET /api/forge.json?seed=…</code> → traits.</p>+ <p>Geometry synthesized from the Gielis superformula, spec-valid glTF 2.0. Part of <a href="https://three.ws">three.ws</a>, the platform for 3D AI agents on-chain.</p>+ </footer>+</div>+<div class="toast" id="toast"></div>++<script>+ var pageUrl = ${JSON.stringify(pageUrl)};+ var shareText = ${JSON.stringify(`${traits.name} — a ${traits.tier} 3D sculpture I forged on three.ws. Tap to drop it into your room in AR 👇`)};+ function toast(m){ var t=document.getElementById('toast'); t.textContent=m; t.classList.add('show'); setTimeout(function(){t.classList.remove('show');},1800); }++ var mv = document.querySelector('model-viewer');+ document.getElementById('ar2').addEventListener('click', function(){+ if (mv && mv.canActivateAR) { mv.activateAR(); }+ else { toast('AR works on a phone — open this link on iOS or Android.'); }+ });++ document.getElementById('share').addEventListener('click', async function(){+ if (navigator.share) {+ try { await navigator.share({ title: 'three.ws Forge', text: shareText, url: pageUrl }); } catch (e) {}+ } else {+ try { await navigator.clipboard.writeText(pageUrl); toast('Link copied'); } catch (e) { toast(pageUrl); }+ }+ });++ document.getElementById('tweet').href =+ 'https://twitter.com/intent/tweet?text=' + encodeURIComponent(shareText) + '&url=' + encodeURIComponent(pageUrl);+</script>+</body>+</html>`;+}diff --git a/infra/lambda/forge/render.mjs b/infra/lambda/forge/render.mjsnew file mode 100644index 000000000..ae86420fa--- /dev/null+++ b/infra/lambda/forge/render.mjs@@ -0,0 +1,160 @@+// Zero-dependency software 3D renderer → PNG, for social-card preview images.+//+// No GPU, no canvas lib: we project the forged mesh with a fixed studio camera,+// shade it (diffuse + rim + per-vertex color), z-buffer the triangles into an+// RGBA framebuffer over a branded gradient, then encode a PNG by hand using+// Node's built-in zlib for the IDAT stream. Used by GET /api/og?seed=… so a+// shared link unfurls on X / iMessage / Discord with the actual sculpture.++import { deflateSync } from 'node:zlib';+import { forgeRaw } from './forge.mjs';++// ── CRC32 (PNG chunk checksums) ──────────────────────────────────────────────+const CRC_TABLE = (() => {+ const t = new Uint32Array(256);+ for (let n = 0; n < 256; n++) {+ let c = n;+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ t[n] = c >>> 0;+ }+ return t;+})();+function crc32(buf) {+ let c = 0xffffffff;+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+}+function pngChunk(type, data) {+ const len = Buffer.alloc(4);+ len.writeUInt32BE(data.length, 0);+ const typeBuf = Buffer.from(type, 'ascii');+ const body = Buffer.concat([typeBuf, data]);+ const crc = Buffer.alloc(4);+ crc.writeUInt32BE(crc32(body), 0);+ return Buffer.concat([len, body, crc]);+}+function encodePng(width, height, rgba) {+ // Prefix each scanline with filter byte 0 (none).+ const stride = width * 4;+ const raw = Buffer.alloc((stride + 1) * height);+ for (let y = 0; y < height; y++) {+ raw[y * (stride + 1)] = 0;+ rgba.copy(raw, y * (stride + 1) + 1, y * stride, y * stride + stride);+ }+ const ihdr = Buffer.alloc(13);+ ihdr.writeUInt32BE(width, 0);+ ihdr.writeUInt32BE(height, 4);+ ihdr[8] = 8; // bit depth+ ihdr[9] = 6; // color type RGBA+ ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0;+ return Buffer.concat([+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ pngChunk('IHDR', ihdr),+ pngChunk('IDAT', deflateSync(raw, { level: 6 })),+ pngChunk('IEND', Buffer.alloc(0)),+ ]);+}++// ── Vector helpers ───────────────────────────────────────────────────────────+function rotateY(x, y, z, a) { const c = Math.cos(a), s = Math.sin(a); return [c * x + s * z, y, -s * x + c * z]; }+function rotateX(x, y, z, a) { const c = Math.cos(a), s = Math.sin(a); return [x, c * y - s * z, s * y + c * z]; }++// ── Render ───────────────────────────────────────────────────────────────────+export function renderCardPng(seed, { width = 1200, height = 630, res = 90 } = {}) {+ const { mesh, traits } = forgeRaw(seed, res);+ const { positions, normals, colors, indices, vCount } = mesh;+ const { finish } = traits._p;++ const rgba = Buffer.alloc(width * height * 4);+ const zbuf = new Float32Array(width * height).fill(Infinity);++ // Branded background: vertical gradient + soft radial glow in the finish hue.+ const [gr, gg, gb] = hslToRgb(finish.hue + traits._p.hueShift, finish.sat * 0.7, 0.5);+ const cxg = width * 0.62, cyg = height * 0.42, glowR = height * 0.85;+ for (let y = 0; y < height; y++) {+ const tY = y / height;+ const topR = 12, topG = 14, topB = 22, botR = 5, botG = 6, botB = 10;+ for (let x = 0; x < width; x++) {+ const d = Math.hypot(x - cxg, y - cyg) / glowR;+ const glow = Math.max(0, 1 - d) ** 2 * 0.5;+ const i = (y * width + x) * 4;+ rgba[i] = Math.min(255, (topR + (botR - topR) * tY) + gr * 255 * glow);+ rgba[i + 1] = Math.min(255, (topG + (botG - topG) * tY) + gg * 255 * glow);+ rgba[i + 2] = Math.min(255, (topB + (botB - topB) * tY) + gb * 255 * glow);+ rgba[i + 3] = 255;+ }+ }++ // Project verts with a fixed 3/4 studio angle (model is centered, maxDim≈2).+ const yaw = 0.7, pitch = -0.45;+ const scale = height * 0.34; // world→pixel+ const ox = width * 0.5, oy = height * 0.5;+ const sx = new Float32Array(vCount), sy = new Float32Array(vCount), sz = new Float32Array(vCount);+ const nx = new Float32Array(vCount), ny = new Float32Array(vCount), nz = new Float32Array(vCount);+ for (let v = 0; v < vCount; v++) {+ let [x, y, z] = rotateX(...rotateY(positions[v * 3], positions[v * 3 + 1], positions[v * 3 + 2], yaw), pitch);+ sx[v] = ox + x * scale;+ sy[v] = oy - y * scale;+ sz[v] = z;+ let [a, b, c] = rotateX(...rotateY(normals[v * 3], normals[v * 3 + 1], normals[v * 3 + 2], yaw), pitch);+ nx[v] = a; ny[v] = b; nz[v] = c;+ }++ // Lighting+ const L = (() => { const v = [0.4, 0.7, 0.6]; const m = Math.hypot(...v); return [v[0] / m, v[1] / m, v[2] / m]; })();+ const emiss = finish.glow ? finish.emissive : 0;++ // Rasterize triangles with a z-buffer.+ for (let t = 0; t < indices.length; t += 3) {+ const i0 = indices[t], i1 = indices[t + 1], i2 = indices[t + 2];+ const x0 = sx[i0], y0 = sy[i0], x1 = sx[i1], y1 = sy[i1], x2 = sx[i2], y2 = sy[i2];+ const minX = Math.max(0, Math.floor(Math.min(x0, x1, x2)));+ const maxX = Math.min(width - 1, Math.ceil(Math.max(x0, x1, x2)));+ const minY = Math.max(0, Math.floor(Math.min(y0, y1, y2)));+ const maxY = Math.min(height - 1, Math.ceil(Math.max(y0, y1, y2)));+ if (minX > maxX || minY > maxY) continue;+ const area = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0);+ if (area === 0) continue;+ const inv = 1 / area;+ for (let py = minY; py <= maxY; py++) {+ for (let px = minX; px <= maxX; px++) {+ const fx = px + 0.5, fy = py + 0.5;+ let w0 = ((x1 - fx) * (y2 - fy) - (x2 - fx) * (y1 - fy)) * inv;+ let w1 = ((x2 - fx) * (y0 - fy) - (x0 - fx) * (y2 - fy)) * inv;+ let w2 = 1 - w0 - w1;+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;+ const z = w0 * sz[i0] + w1 * sz[i1] + w2 * sz[i2];+ const zi = py * width + px;+ if (z >= zbuf[zi]) continue;+ zbuf[zi] = z;+ // interpolate normal + color+ let n0 = w0 * nx[i0] + w1 * nx[i1] + w2 * nx[i2];+ let n1 = w0 * ny[i0] + w1 * ny[i1] + w2 * ny[i2];+ let n2 = w0 * nz[i0] + w1 * nz[i1] + w2 * nz[i2];+ const nlen = Math.hypot(n0, n1, n2) || 1; n0 /= nlen; n1 /= nlen; n2 /= nlen;+ const diff = Math.max(0, n0 * L[0] + n1 * L[1] + n2 * L[2]);+ const rim = Math.pow(1 - Math.max(0, n2), 2.2) * 0.6; // facing-away glow edge+ const shade = 0.22 + 0.85 * diff + rim;+ const cr = colors[i0 * 4] * w0 + colors[i1 * 4] * w1 + colors[i2 * 4] * w2;+ const cg = colors[i0 * 4 + 1] * w0 + colors[i1 * 4 + 1] * w1 + colors[i2 * 4 + 1] * w2;+ const cb = colors[i0 * 4 + 2] * w0 + colors[i1 * 4 + 2] * w1 + colors[i2 * 4 + 2] * w2;+ const i = zi * 4;+ rgba[i] = Math.min(255, cr * shade + cr * emiss * 0.25);+ rgba[i + 1] = Math.min(255, cg * shade + cg * emiss * 0.25);+ rgba[i + 2] = Math.min(255, cb * shade + cb * emiss * 0.25);+ rgba[i + 3] = 255;+ }+ }+ }++ const { _p, ...pub } = traits;+ return { png: encodePng(width, height, rgba), traits: pub };+}++// local copy (render is self-contained; mirrors forge.mjs)+function hslToRgb(h, s, l) {+ h = ((h % 360) + 360) % 360 / 360;+ const a = s * Math.min(l, 1 - l);+ const f = (n) => { const k = (n + h * 12) % 12; return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); };+ return [f(0), f(8), f(4)];+}diff --git a/infra/lambda/pump-snapshot/index.mjs b/infra/lambda/pump-snapshot/index.mjsdeleted file mode 100644index eb010feaf..000000000--- a/infra/lambda/pump-snapshot/index.mjs+++ /dev/null@@ -1,462 +0,0 @@-// three.ws — Pump.fun Token Snapshot API-//-// A zero-dependency AWS Lambda (Node 22) behind a Function URL. It serves:-// GET / → live demo page (HTML)-// GET /api/snapshot?token=X → real-time token snapshot (JSON)-// GET /healthz → liveness probe (JSON)-//-// Every number is fetched live from a public source. No fallback arrays, no-// mocked values — if a source is unreachable the field is null so callers see-// the gap rather than fake data. Mirrors mcp-server/src/tools/pump-snapshot.js-// but reimplemented with raw fetch (incl. the Solana RPC call) so the function-// ships with no npm dependencies.-//-// Sources:-// - Jupiter Lite price API → price, 24h change, liquidity, decimals-// - Dexscreener → 24h volume, primary DEX pair, FDV, txns-// - pump.fun frontend-api-v3 → name, symbol, image, market cap, socials-// - Solana RPC getTokenLargestAccounts → top-holder distribution-// - Helius DAS getAsset (optional, if HELIUS_API_KEY set) → supply/price--const SOLANA_RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';-const HELIUS_API_KEY = process.env.HELIUS_API_KEY || '';--const JSON_HEADERS = {- 'content-type': 'application/json; charset=utf-8',- 'access-control-allow-origin': '*',- 'access-control-allow-methods': 'GET, OPTIONS',- 'access-control-allow-headers': 'content-type',- 'cache-control': 'public, max-age=10',-};--// ── Solana base58 validation (no deps) ──────────────────────────────────────-const B58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;-function isValidSolanaPubkey(s) {- return typeof s === 'string' && B58_RE.test(s);-}--async function fetchJson(url, init = {}, timeoutMs = 8000) {- const controller = new AbortController();- const t = setTimeout(() => controller.abort(), timeoutMs);- try {- const res = await fetch(url, { ...init, signal: controller.signal });- if (!res.ok) throw new Error(`${url} → HTTP ${res.status}`);- return await res.json();- } finally {- clearTimeout(t);- }-}--async function getJupiterPrice(mint) {- try {- const data = await fetchJson(`https://lite-api.jup.ag/price/v3?ids=${mint}`);- const entry = data?.[mint];- if (!entry) return null;- return {- usdPrice: entry.usdPrice ?? null,- priceChange24hPct: entry.priceChange24h ?? null,- liquidityUsd: entry.liquidity ?? null,- decimals: entry.decimals ?? null,- blockId: entry.blockId ?? null,- };- } catch (err) {- return { error: err.message };- }-}--async function getDexscreener(mint) {- try {- const data = await fetchJson(`https://api.dexscreener.com/latest/dex/tokens/${mint}`);- const pairs = Array.isArray(data?.pairs) ? data.pairs : [];- if (pairs.length === 0) return null;- const pair = pairs.reduce((best, p) => {- const v = Number(p?.volume?.h24 || 0);- return v > (best?.vol || 0) ? { pair: p, vol: v } : best;- }, null)?.pair;- if (!pair) return null;- return {- volume24hUsd: Number(pair.volume?.h24 || 0),- priceUsd: pair.priceUsd ? Number(pair.priceUsd) : null,- priceChange24hPct: pair.priceChange?.h24 ?? null,- liquidityUsd: pair.liquidity?.usd ?? null,- fdvUsd: pair.fdv ?? null,- marketCapUsd: pair.marketCap ?? null,- pairAddress: pair.pairAddress,- dex: pair.dexId,- chain: pair.chainId,- url: pair.url,- txns24h: pair.txns?.h24 ?? null,- };- } catch (err) {- return { error: err.message };- }-}--async function getPumpFunMeta(mint) {- try {- const data = await fetchJson(`https://frontend-api-v3.pump.fun/coins/${mint}`);- if (!data || data.error) return null;- return {- name: data.name || null,- symbol: data.symbol || null,- description: data.description || null,- imageUrl: data.image_uri || null,- twitter: data.twitter || null,- telegram: data.telegram || null,- website: data.website || null,- creator: data.creator || null,- createdAtMs: data.created_timestamp || null,- complete: !!data.complete,- marketCapUsd: data.usd_market_cap ?? null,- marketCapQuote: data.market_cap ?? null,- totalSupply: data.total_supply_str || data.total_supply || null,- poolAddress: data.pool_address || null,- lastTradeTimestampMs: data.last_trade_timestamp || null,- athMarketCapUsd: data.ath_market_cap ?? null,- program: data.program || null,- };- } catch (err) {- return { error: err.message };- }-}--// Solana RPC getTokenLargestAccounts via raw JSON-RPC (no @solana/web3.js).-async function getTopHolders(mint) {- try {- const data = await fetchJson(SOLANA_RPC_URL, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 'largest',- method: 'getTokenLargestAccounts',- params: [mint, { commitment: 'confirmed' }],- }),- });- if (data?.error) return { error: data.error.message || 'rpc error' };- const value = data?.result?.value || [];- const top = value.map((acct) => ({- address: acct.address,- uiAmount: acct.uiAmount,- amount: acct.amount,- decimals: acct.decimals,- }));- return { topHolderCount: top.length, topHolders: top };- } catch (err) {- return { error: err.message };- }-}--async function getHeliusHolderInfo(mint) {- if (!HELIUS_API_KEY) return null;- try {- const data = await fetchJson(`https://mainnet.helius-rpc.com/?api-key=${HELIUS_API_KEY}`, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 'getAsset',- method: 'getAsset',- params: { id: mint, options: { showFungible: true } },- }),- });- const info = data?.result?.token_info ?? null;- if (!info) return null;- return {- supply: info.supply != null ? String(info.supply) : null,- decimals: info.decimals ?? null,- heliusPriceUsd: info.price_info?.price_per_token ?? null,- };- } catch (err) {- return { error: err.message };- }-}--async function buildSnapshot(token) {- const [price, volume24h, meta, holders, helius] = await Promise.all([- getJupiterPrice(token),- getDexscreener(token),- getPumpFunMeta(token),- getTopHolders(token),- getHeliusHolderInfo(token),- ]);- return {- token,- fetchedAt: new Date().toISOString(),- price,- volume24h,- meta,- holders,- helius,- image: meta?.imageUrl || null,- sources: {- price: 'https://lite-api.jup.ag/price/v3',- volume24h: 'https://api.dexscreener.com',- meta: 'https://frontend-api-v3.pump.fun',- holders: SOLANA_RPC_URL,- helius: HELIUS_API_KEY ? 'https://mainnet.helius-rpc.com' : null,- },- };-}--function jsonResponse(statusCode, body) {- return { statusCode, headers: JSON_HEADERS, body: JSON.stringify(body) };-}--// ── Lambda Function URL handler ──────────────────────────────────────────────-export const handler = async (event) => {- const method = event?.requestContext?.http?.method || 'GET';- const rawPath = event?.rawPath || '/';- const path = rawPath.replace(/\/+$/, '') || '/';-- if (method === 'OPTIONS') {- return { statusCode: 204, headers: JSON_HEADERS, body: '' };- }-- if (path === '/healthz') {- return jsonResponse(200, { ok: true, service: 'pump-snapshot', rpc: SOLANA_RPC_URL });- }-- if (path === '/api/snapshot') {- const token = event?.queryStringParameters?.token?.trim();- if (!token) {- return jsonResponse(400, { error: 'missing_token', message: 'Provide ?token=<mint>' });- }- if (!isValidSolanaPubkey(token)) {- return jsonResponse(400, { error: 'invalid_mint', token });- }- const snapshot = await buildSnapshot(token);- return jsonResponse(200, snapshot);- }-- if (path === '/') {- return {- statusCode: 200,- headers: {- 'content-type': 'text/html; charset=utf-8',- 'cache-control': 'public, max-age=60',- },- body: PAGE_HTML,- };- }-- return jsonResponse(404, { error: 'not_found', path });-};--// ── Live demo page ───────────────────────────────────────────────────────────-const PAGE_HTML = /* html */ `<!doctype html>-<html lang="en">-<head>-<meta charset="utf-8" />-<meta name="viewport" content="width=device-width, initial-scale=1" />-<title>Pump.fun Token Snapshot API — three.ws</title>-<meta name="description" content="Real-time Solana / pump.fun token snapshots: price, 24h volume, market cap, and on-chain top-holder distribution. Live API on AWS." />-<style>- :root {- --bg: #07080c; --panel: #0e1018; --panel-2: #141826; --line: #1f2433;- --text: #e8ecf4; --muted: #8a93a8; --accent: #7c5cff; --accent-2: #18d6a8;- --red: #ff5d6c; --green: #18d6a8; --radius: 14px;- --mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;- --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, sans-serif;- }- * { box-sizing: border-box; }- body {- margin: 0; font-family: var(--sans); color: var(--text);- background:- radial-gradient(1200px 600px at 80% -10%, rgba(124,92,255,.18), transparent 60%),- radial-gradient(900px 500px at 0% 10%, rgba(24,214,168,.10), transparent 55%),- var(--bg);- min-height: 100vh; -webkit-font-smoothing: antialiased;- }- .wrap { max-width: 920px; margin: 0 auto; padding: 56px 24px 80px; }- header .badge {- display: inline-flex; align-items: center; gap: 8px; font-size: 12px;- color: var(--accent-2); border: 1px solid var(--line); border-radius: 999px;- padding: 5px 12px; background: var(--panel); letter-spacing: .02em;- }- .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--green);- box-shadow: 0 0 0 0 rgba(24,214,168,.5); animation: pulse 2s infinite; }- @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(24,214,168,.5);} 70% { box-shadow: 0 0 0 8px rgba(24,214,168,0);} 100% { box-shadow: 0 0 0 0 rgba(24,214,168,0);} }- h1 { font-size: clamp(28px, 5vw, 44px); line-height: 1.05; margin: 20px 0 10px; letter-spacing: -.02em; }- h1 .grad { background: linear-gradient(90deg, var(--accent), var(--accent-2)); -webkit-background-clip: text; background-clip: text; color: transparent; }- .lede { color: var(--muted); font-size: 17px; max-width: 640px; line-height: 1.55; margin: 0 0 28px; }- form { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 14px; }- input[type=text] {- flex: 1; min-width: 240px; background: var(--panel); border: 1px solid var(--line);- color: var(--text); border-radius: 12px; padding: 14px 16px; font-size: 15px;- font-family: var(--mono); outline: none; transition: border-color .15s, box-shadow .15s;- }- input[type=text]:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(124,92,255,.18); }- button {- background: linear-gradient(90deg, var(--accent), #6b4cff); color: #fff; border: 0;- border-radius: 12px; padding: 14px 22px; font-size: 15px; font-weight: 600; cursor: pointer;- transition: transform .1s, filter .15s; font-family: var(--sans);- }- button:hover { filter: brightness(1.08); }- button:active { transform: translateY(1px); }- button:disabled { opacity: .55; cursor: progress; }- .examples { font-size: 13px; color: var(--muted); margin-bottom: 32px; }- .examples a { color: var(--accent); text-decoration: none; cursor: pointer; }- .examples a:hover { text-decoration: underline; }- .card { background: linear-gradient(180deg, var(--panel), var(--panel-2)); border: 1px solid var(--line);- border-radius: var(--radius); padding: 0; overflow: hidden; }- .card.hidden { display: none; }- .token-head { display: flex; align-items: center; gap: 16px; padding: 22px 24px; border-bottom: 1px solid var(--line); }- .token-head img { width: 56px; height: 56px; border-radius: 12px; object-fit: cover; background: var(--panel-2); }- .token-head .name { font-size: 20px; font-weight: 700; }- .token-head .sym { color: var(--muted); font-family: var(--mono); font-size: 13px; }- .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1px; background: var(--line); }- .stat { background: var(--panel); padding: 18px 20px; }- .stat .label { font-size: 11px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin-bottom: 6px; }- .stat .value { font-size: 20px; font-weight: 600; font-variant-numeric: tabular-nums; }- .value.pos { color: var(--green); } .value.neg { color: var(--red); }- .value.null { color: var(--muted); font-size: 15px; }- .holders { padding: 20px 24px; }- .holders h3 { font-size: 13px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin: 0 0 12px; }- .holders ol { margin: 0; padding-left: 0; list-style: none; }- .holders li { display: flex; justify-content: space-between; font-family: var(--mono); font-size: 13px; padding: 7px 0; border-bottom: 1px dashed var(--line); }- .holders li:last-child { border-bottom: 0; }- .holders .addr { color: var(--muted); }- .holders .amt { color: var(--text); font-variant-numeric: tabular-nums; }- .skel { animation: shimmer 1.2s infinite linear; background: linear-gradient(90deg, var(--panel) 0%, var(--panel-2) 50%, var(--panel) 100%); background-size: 200% 100%; border-radius: 8px; color: transparent !important; }- @keyframes shimmer { to { background-position: -200% 0; } }- .error { padding: 22px 24px; color: var(--red); font-size: 15px; }- .error .hint { color: var(--muted); font-size: 13px; margin-top: 6px; }- footer { margin-top: 40px; color: var(--muted); font-size: 13px; line-height: 1.7; }- footer code { font-family: var(--mono); background: var(--panel); padding: 2px 7px; border-radius: 6px; border: 1px solid var(--line); color: var(--text); }- footer a { color: var(--accent); text-decoration: none; }- footer a:hover { text-decoration: underline; }- .api-line { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 18px; padding: 12px 16px; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; font-family: var(--mono); font-size: 13px; overflow-x: auto; }- .api-line .verb { color: var(--accent-2); font-weight: 700; }-</style>-</head>-<body>-<div class="wrap">- <header>- <span class="badge"><span class="dot"></span> Live on AWS Lambda</span>- <h1>Pump.fun <span class="grad">Token Snapshot</span> API</h1>- <p class="lede">Real-time market data for any Solana SPL or pump.fun token — USD price, 24h volume, market cap, and on-chain top-holder distribution. One request, every source, no mocks.</p>- </header>-- <form id="form">- <input id="token" type="text" placeholder="Solana mint address (base58)" autocomplete="off" spellcheck="false" />- <button id="go" type="submit">Snapshot</button>- </form>- <p class="examples">Try:- <a data-mint="HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3">PYTH</a> ·- <a data-mint="EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm">WIF</a> ·- <a data-mint="DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263">BONK</a>- </p>-- <div id="result" class="card hidden"></div>-- <div class="api-line">- <span class="verb">GET</span><span id="apiExample">/api/snapshot?token=<mint></span>- </div>-- <footer>- <p>Public JSON API. <code>GET /api/snapshot?token=<mint></code> returns the full snapshot. <code>GET /healthz</code> for liveness.</p>- <p>Data: Jupiter · Dexscreener · pump.fun · Solana RPC. Part of <a href="https://three.ws">three.ws</a> — the platform for 3D AI agents on-chain.</p>- </footer>-</div>--<script>-const $ = (s) => document.querySelector(s);-const form = $('#form'), input = $('#token'), btn = $('#go'), result = $('#result');--function fmtUsd(n, opts = {}) {- if (n == null || isNaN(n)) return null;- const abs = Math.abs(n);- const max = abs > 0 && abs < 0.01 ? 8 : (opts.compact && abs >= 1000 ? 1 : 2);- if (opts.compact && abs >= 1000) {- return '$' + Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 }).format(n);- }- return '$' + Intl.NumberFormat('en', { maximumFractionDigits: max }).format(n);-}-function fmtPct(n) {- if (n == null || isNaN(n)) return null;- return (n >= 0 ? '+' : '') + Number(n).toFixed(2) + '%';-}-function shortAddr(a) { return a ? a.slice(0, 4) + '…' + a.slice(-4) : ''; }-function esc(s) { return String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&':'&','<':'<','>':'>','"':'"' }[c])); }--function statCell(label, value, cls) {- const isNull = value == null;- return '<div class="stat"><div class="label">' + label + '</div>' +- '<div class="value ' + (isNull ? 'null' : (cls || '')) + '">' + (isNull ? '—' : value) + '</div></div>';-}--function renderLoading() {- result.classList.remove('hidden');- result.innerHTML =- '<div class="token-head"><div class="skel" style="width:56px;height:56px;border-radius:12px"></div>' +- '<div><div class="skel" style="width:160px;height:20px;margin-bottom:8px">.</div>' +- '<div class="skel" style="width:90px;height:13px">.</div></div></div>' +- '<div class="grid">' + Array(4).fill('<div class="stat"><div class="skel" style="width:60px;height:11px;margin-bottom:8px">.</div><div class="skel" style="width:90px;height:20px">.</div></div>').join('') + '</div>';-}--function renderError(msg, hint) {- result.classList.remove('hidden');- result.innerHTML = '<div class="error">' + esc(msg) + (hint ? '<div class="hint">' + esc(hint) + '</div>' : '') + '</div>';-}--function render(d) {- const meta = d.meta || {}, price = d.price || {}, vol = d.volume24h || {}, holders = d.holders || {};- const usd = price.usdPrice ?? vol.priceUsd;- const chg = price.priceChange24hPct ?? vol.priceChange24hPct;- const mcap = meta.marketCapUsd ?? vol.marketCapUsd ?? vol.fdvUsd;- const liq = price.liquidityUsd ?? vol.liquidityUsd;- const name = meta.name || (d.token.slice(0, 4) + '…' + d.token.slice(-4));- const sym = meta.symbol ? '$' + meta.symbol : d.token.slice(0, 8);- const img = d.image || meta.imageUrl;-- let html = '<div class="token-head">';- html += img ? '<img src="' + esc(img) + '" alt="" onerror="this.style.visibility=\\'hidden\\'" />' : '<div style="width:56px;height:56px;border-radius:12px;background:var(--panel-2)"></div>';- html += '<div><div class="name">' + esc(name) + '</div><div class="sym">' + esc(sym) + ' · ' + shortAddr(d.token) + '</div></div></div>';-- html += '<div class="grid">';- html += statCell('Price', fmtUsd(usd, { compact: false }));- html += statCell('24h Change', fmtPct(chg), chg == null ? '' : (chg >= 0 ? 'pos' : 'neg'));- html += statCell('Market Cap', fmtUsd(mcap, { compact: true }));- html += statCell('24h Volume', fmtUsd(vol.volume24hUsd, { compact: true }));- html += statCell('Liquidity', fmtUsd(liq, { compact: true }));- html += statCell('DEX', vol.dex ? esc(vol.dex) : null);- html += '</div>';-- const list = Array.isArray(holders.topHolders) ? holders.topHolders.slice(0, 8) : [];- if (list.length) {- html += '<div class="holders"><h3>Top holders · on-chain (' + (holders.topHolderCount || list.length) + ')</h3><ol>';- for (const h of list) {- const amt = h.uiAmount != null ? Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 2 }).format(h.uiAmount) : '—';- html += '<li><span class="addr">' + shortAddr(h.address) + '</span><span class="amt">' + amt + '</span></li>';- }- html += '</ol></div>';- }- result.classList.remove('hidden');- result.innerHTML = html;-}--async function snapshot(mint) {- const token = (mint || input.value).trim();- if (!token) { input.focus(); return; }- input.value = token;- $('#apiExample').textContent = '/api/snapshot?token=' + token;- btn.disabled = true;- renderLoading();- try {- const res = await fetch('/api/snapshot?token=' + encodeURIComponent(token));- const data = await res.json();- if (!res.ok) { renderError(data.message || data.error || 'Request failed', data.error === 'invalid_mint' ? 'That does not look like a base58 Solana mint address.' : ''); return; }- render(data);- } catch (e) {- renderError('Network error', e.message);- } finally {- btn.disabled = false;- }-}--form.addEventListener('submit', (e) => { e.preventDefault(); snapshot(); });-document.querySelectorAll('.examples a').forEach((a) => a.addEventListener('click', (e) => { e.preventDefault(); snapshot(a.dataset.mint); }));-</script>-</body>-</html>`;diff --git a/infra/lambda/pump-snapshot/package.json b/infra/lambda/pump-snapshot/package.jsondeleted file mode 100644index 602d3cd56..000000000--- a/infra/lambda/pump-snapshot/package.json+++ /dev/null@@ -1,7 +0,0 @@-{- "name": "three-ws-pump-snapshot",- "version": "1.0.0",- "private": true,- "type": "module",- "description": "Zero-dependency Lambda: real-time pump.fun / Solana token snapshot API + demo page"-}diff --git a/infra/lib/three-ws-stack.ts b/infra/lib/three-ws-stack.tsindex 980fa9a1e..382970b8a 100644--- a/infra/lib/three-ws-stack.ts+++ b/infra/lib/three-ws-stack.ts@@ -46,35 +46,31 @@ export class ThreeWsStack extends cdk.Stack {removalPolicy: cdk.RemovalPolicy.RETAIN,});- // ── Pump.fun Token Snapshot API ──────────────────────────────────────────- // Zero-dependency Node Lambda serving a live demo page (/) and a real-time- // token snapshot JSON API (/api/snapshot). Exposed publicly via a Lambda- // Function URL — no API Gateway needed. Source: infra/lambda/pump-snapshot.- const snapshotLogGroup = new logs.LogGroup(this, 'PumpSnapshotLogGroup', {- logGroupName: '/aws/lambda/three-ws-pump-snapshot',+ // ── three.ws Forge — generative 3D sculptures + AR sharing ───────────────+ // Zero-dependency Node Lambda. Serves per-seed share pages with real AR+ // (iOS AR Quick Look / Android Scene Viewer via <model-viewer>) and Open+ // Graph / Twitter Card meta, a binary-GLB API, and a hand-rendered PNG+ // preview (software rasterizer) for link unfurls. Exposed via a Lambda+ // Function URL — no API Gateway needed. Source: infra/lambda/forge.+ const forgeLogGroup = new logs.LogGroup(this, 'ForgeLogGroup', {+ logGroupName: '/aws/lambda/three-ws-forge',retention: logs.RetentionDays.ONE_MONTH,removalPolicy: cdk.RemovalPolicy.DESTROY,});- const snapshotFn = new lambda.Function(this, 'PumpSnapshotFn', {- functionName: 'three-ws-pump-snapshot',+ const forgeFn = new lambda.Function(this, 'ForgeFn', {+ functionName: 'three-ws-forge',runtime: lambda.Runtime.NODEJS_22_X,handler: 'index.handler',- code: lambda.Code.fromAsset(path.join(__dirname, '..', 'lambda', 'pump-snapshot')),- memorySize: 256,- timeout: cdk.Duration.seconds(15),+ code: lambda.Code.fromAsset(path.join(__dirname, '..', 'lambda', 'forge')),+ memorySize: 1536, // headroom for mesh synthesis + software rasterizer+ timeout: cdk.Duration.seconds(20),architecture: lambda.Architecture.ARM_64,- description: 'three.ws — real-time pump.fun / Solana token snapshot API',- environment: {- // Public mainnet RPC by default; set a dedicated RPC for production load.- SOLANA_RPC_URL: process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com',- // Optional: enables Helius DAS holder/supply enrichment when present.- HELIUS_API_KEY: process.env.HELIUS_API_KEY || '',- },- logGroup: snapshotLogGroup,+ description: 'three.ws Forge — generative 3D sculptures, GLB + AR + social cards',+ logGroup: forgeLogGroup,});- const snapshotUrl = snapshotFn.addFunctionUrl({+ const forgeUrl = forgeFn.addFunctionUrl({authType: lambda.FunctionUrlAuthType.NONE,cors: {allowedOrigins: ['*'],@@ -84,9 +80,9 @@ export class ThreeWsStack extends cdk.Stack {},});- new cdk.CfnOutput(this, 'PumpSnapshotUrl', {- value: snapshotUrl.url,- description: 'Public URL for the pump.fun token snapshot API + demo page',+ new cdk.CfnOutput(this, 'ForgeUrl', {+ value: forgeUrl.url,+ description: 'Public URL for three.ws Forge — share pages, GLB API, AR, social cards',});// Associate this CloudFormation stack with the three.ws MyApplications entry.diff --git a/multiplayer/package.json b/multiplayer/package.jsonindex 1ca860e16..7103bbb9b 100644--- a/multiplayer/package.json+++ b/multiplayer/package.json@@ -14,18 +14,19 @@},"dependencies": {"@bonfida/spl-name-service": "^0.1.67",- "@colyseus/core": "^0.17.43",- "@colyseus/monitor": "^0.17.8",+ "@colyseus/core": "^0.16.24",+ "@colyseus/monitor": "^0.16.7","@colyseus/schema": "^3.0.0",- "@colyseus/ws-transport": "^0.17.13",+ "@colyseus/ws-transport": "^0.16.5","@ethereum-attestation-service/eas-sdk": "0.29.1","@metaplex-foundation/js": "^0.20.1","@pump-fun/pump-sdk": "1.1.0","@solana/actions": "0.0.2","@solana/pay": "1.0.16","agent0-sdk": "^1.7.1",- "colyseus": "^0.17.10",+ "colyseus": "^0.16.5","ethers": "^6.16.0",+ "express": "^4.21.2","livepeer": "3.2.4","short-uuid": "6.0.3"}diff --git a/multiplayer/src/index.js b/multiplayer/src/index.jsindex aad48f83d..e32851b25 100644--- a/multiplayer/src/index.js+++ b/multiplayer/src/index.js@@ -2,10 +2,19 @@//// This is a standalone Colyseus process — Vercel can't host long-lived// WebSocket servers, so this runs separately (Fly.io, Railway, Render, or a-// $5 VPS — see ../README.md). The Vite app at three.ws/walk connects to it-// over WebSocket and exchanges player state via the WalkRoom defined below.+// $5 VPS — see ../README.md). The Vite app at three.ws/walk and three.ws/play+// connect to it over WebSocket and exchange state via the rooms defined below.+//+// We mount an Express app as the HTTP request handler. Colyseus 0.16 detects+// an existing Express app on the underlying http.Server and composes with it:+// matchmaking + seat-reservation routes go to Colyseus's own router, and+// everything else (/health, /colyseus monitor) falls through to Express. This+// is the supported way to expose custom HTTP routes alongside Colyseus on one+// port — a hand-rolled raw request listener double-responds and throws+// ERR_HTTP_HEADERS_SENT against the matchmaker's prepended listener.import http from 'node:http';+import express from 'express';import { Server } from '@colyseus/core';import { WebSocketTransport } from '@colyseus/ws-transport';import { monitor } from '@colyseus/monitor';@@ -26,43 +35,18 @@ const ALLOWED_ORIGINS = (.map((s) => s.trim()).filter(Boolean);-// Use a plain http.Server so we can mount /health for platform health checks-// and /colyseus for the admin monitor UI on the same port. WebSocketTransport-// hooks the upgrade event and ignores anything that isn't a Colyseus WS-// upgrade, so /health and /colyseus stay reachable as normal HTTP routes.-const httpServer = http.createServer((req, res) => {- if (req.url === '/health' || req.url === '/healthz') {- res.writeHead(200, { 'content-type': 'application/json' });- res.end(JSON.stringify({ ok: true, name: 'three.ws-multiplayer' }));- return;- }- if (req.url === '/' || req.url === '') {- res.writeHead(200, { 'content-type': 'text/plain' });- res.end('three.ws multiplayer · Colyseus\n');- return;- }- if (req.url.startsWith('/colyseus')) {- // Mount the admin monitor lazily — `monitor()` returns an Express-style- // middleware that we adapt to the node http stack via a tiny shim.- return monitorMiddleware(req, res);- }- res.writeHead(404);- res.end();+const app = express();++// Liveness probes for the host platform (Fly/Railway/Render).+app.get(['/health', '/healthz'], (_req, res) => {+ res.json({ ok: true, name: 'three.ws-multiplayer' });});-// Lazy monitor adapter — `@colyseus/monitor` ships an Express router. We mount-// it through a one-shot Express instance so we don't take a hard dep on-// express here at the top level.-let _monitorHandler = null;-async function monitorMiddleware(req, res) {- if (!_monitorHandler) {- const { default: express } = await import('express');- const app = express();- app.use('/colyseus', monitor());- _monitorHandler = app;- }- _monitorHandler(req, res);-}+// Admin monitor UI. Protect this behind a reverse proxy or basic auth in prod+// (see @colyseus/monitor docs) — it exposes live room/client state.+app.use('/colyseus', monitor());++const httpServer = http.createServer(app);const transport = new WebSocketTransport({server: httpServer,@@ -86,13 +70,18 @@ const transport = new WebSocketTransport({});const gameServer = new Server({ transport });-gameServer.define('walk_world', WalkRoom);+// Each coin is its own world: filterBy(['coin']) makes joinOrCreate match only+// rooms sharing the same community coin (mint), so players of the same coin land+// together while different coins stay isolated. A missing coin resolves to the+// shared mainland world (see WalkRoom.onCreate / schemas.js).+gameServer.define('walk_world', WalkRoom).filterBy(['coin']);gameServer.define('game_mainland', GameRoom);gameServer.listen(PORT, HOST).then(() => {console.log(`[multiplayer] listening on ws://${HOST}:${PORT}`);+ console.log(`[multiplayer] rooms: walk_world, game_mainland`);console.log(`[multiplayer] allowed origins: ${ALLOWED_ORIGINS.join(', ')}`);}).catch((err) => {diff --git a/multiplayer/src/playerStore.js b/multiplayer/src/playerStore.jsnew file mode 100644index 000000000..81a35a61c--- /dev/null+++ b/multiplayer/src/playerStore.js@@ -0,0 +1,49 @@+// Cross-realm player persistence.+//+// Colyseus rooms are independent, but a player's inventory, gold, skills, bank,+// and cosmetics must travel between realms (and survive a disconnect/reconnect+// within a session). This module is a process-wide store keyed by a stable+// playerId — the wallet address once authenticated, otherwise a guest id the+// client persists in localStorage.+//+// Single-process only. When the multiplayer server scales horizontally, swap+// this Map for Redis (the get/save interface stays identical).++const store = new Map(); // playerId -> SavedState++const TTL_MS = 1000 * 60 * 60 * 6; // forget idle guests after 6h to bound memory++/**+ * @typedef {object} SavedState+ * @property {string} name+ * @property {number} color+ * @property {number} gold+ * @property {{item:string,qty:number}[]} inv+ * @property {{item:string,qty:number}[]} hotbar+ * @property {{item:string,qty:number}[]} bank+ * @property {number} activeSlot+ * @property {{woodcutting:number,mining:number,fishing:number,cooking:number,combat:number}} xp+ * @property {string} cosmetic+ * @property {number} savedAt+ */++export function loadPlayer(playerId) {+ const s = store.get(playerId);+ if (!s) return null;+ if (Date.now() - s.savedAt > TTL_MS) { store.delete(playerId); return null; }+ return s;+}++export function savePlayer(playerId, state) {+ store.set(playerId, { ...state, savedAt: Date.now() });+}++export function hasPlayer(playerId) {+ return store.has(playerId);+}++// Periodic sweep so abandoned guest records don't accumulate forever.+setInterval(() => {+ const now = Date.now();+ for (const [id, s] of store) if (now - s.savedAt > TTL_MS) store.delete(id);+}, 1000 * 60 * 30).unref?.();diff --git a/multiplayer/src/rooms/GameRoom.js b/multiplayer/src/rooms/GameRoom.jsindex 4e946772c..b15e741bc 100644Binary files a/multiplayer/src/rooms/GameRoom.js and b/multiplayer/src/rooms/GameRoom.js differdiff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex fcc412826..00599ec1d 100644Binary files a/multiplayer/src/rooms/WalkRoom.js and b/multiplayer/src/rooms/WalkRoom.js differdiff --git a/multiplayer/src/rooms/realms.js b/multiplayer/src/rooms/realms.jsindex 1393eb2a1..6b7644c20 100644--- a/multiplayer/src/rooms/realms.js+++ b/multiplayer/src/rooms/realms.js@@ -1,71 +1,184 @@-// Mainland realm definition — the authoritative map the GameRoom validates-// against. The client renders the *same* layout from this data (it's also-// imported browser-side), so the visual world and the walkable world can never-// drift apart. Coordinates are tile indices on a GRID×GRID board.--export const GRID = 48;--// Solid, non-walkable rectangles (inclusive bounds). Buildings and the plaza-// fountain. The map border is implicitly solid (see inBounds).-const BLOCKED_RECTS = [- { x0: 8, y0: 8, x1: 12, y1: 11 }, // bank building footprint- { x0: 23, y0: 23, x1: 24, y1: 24 }, // plaza fountain (2×2)-];--// Hand-placed so the client and server agree exactly. Trees cluster in a grove-// to the west; the rock/coal field sits to the northeast like a small mine.-const TREES = [- [12, 28], [14, 30], [16, 29], [13, 33], [15, 35], [11, 31], [18, 34], [20, 30],- [17, 37], [19, 38], [10, 36], [22, 36], [8, 30], [9, 33], [21, 40], [13, 40],-];-const ROCKS = [- [34, 14], [36, 16], [38, 13], [40, 15], [35, 18], [39, 18], [42, 12], [33, 16],-];-const COAL = [- [37, 20], [41, 20], [34, 21], [39, 22],-];+// Realm definitions — the authoritative maps the GameRoom validates against.+// The client renders the SAME data (sent on join), so the visual world and the+// walkable world never drift apart. Coordinates are tile indices.+//+// Every realm shares one shape:+// { name, grid, spawn:{tx,ty}, safe:bool, pvp:bool, danger:bool,+// blocked:[{x0,y0,x1,y1}], bankZone:[{tx,ty}], fountain:{tx,ty}|null,+// nodes:[{id,kind,tx,ty}], mobs:[{id,kind,tx,ty,hp,roam,aggro}],+// fishing:[{tx,ty}], cooking:[{tx,ty}], safeCamp:{x0,y0,x1,y1}|null,+// portals:[{x0,y0,x1,y1,to,toTx,toTy}] }+//+// `danger` realms drop a tombstone on death. `pvp` realms allow player combat+// outside any safeCamp. Resource node ids must be unique WITHIN a realm.function nodesFrom(coords, kind, prefix) {return coords.map(([tx, ty], i) => ({ id: `${prefix}${i}`, kind, tx, ty }));}+function tiles(coords) {+ return coords.map(([tx, ty]) => ({ tx, ty }));+}-export const MAINLAND = {+// ---------------------------------------------------------------- Mainland+const MAINLAND = {name: 'mainland',- grid: GRID,+ grid: 48,spawn: { tx: 24, ty: 30 },- fountain: { tx: 23, ty: 23 }, // top-left of the 2×2 plaza fountain+ safe: true, pvp: false, danger: false,+ blocked: [+ { x0: 8, y0: 8, x1: 12, y1: 11 }, // bank building+ { x0: 23, y0: 23, x1: 24, y1: 24 }, // fountain+ ],+ fountain: { tx: 23, ty: 23 },+ bankZone: tiles([[8, 12], [9, 12], [10, 12], [11, 12], [12, 12]]),+ nodes: [+ ...nodesFrom([[12, 28], [14, 30], [16, 29], [13, 33], [15, 35], [11, 31], [18, 34], [20, 30],+ [17, 37], [19, 38], [10, 36], [22, 36], [8, 30], [9, 33], [21, 40], [13, 40]], 'tree', 't'),+ ...nodesFrom([[34, 14], [36, 16], [38, 13], [40, 15], [35, 18], [39, 18], [42, 12], [33, 16]], 'rock', 'r'),+ ...nodesFrom([[37, 20], [41, 20], [34, 21], [39, 22]], 'coal', 'c'),+ ],+ mobs: [+ { id: 'd0', kind: 'dummy', tx: 36, ty: 34, hp: 50, roam: false, aggro: false },+ { id: 'd1', kind: 'dummy', tx: 38, ty: 34, hp: 50, roam: false, aggro: false },+ { id: 'd2', kind: 'dummy', tx: 37, ty: 36, hp: 50, roam: false, aggro: false },+ ],+ fishing: [],+ cooking: [],+ safeCamp: null,+ portals: [+ { x0: 23, y0: 0, x1: 25, y1: 0, to: 'wilderness', toTx: 20, toTy: 36 }, // north → wilderness safe camp+ { x0: 23, y0: 47, x1: 25, y1: 47, to: 'whisperwood', toTx: 20, toTy: 2 }, // south → whisperwood+ { x0: 47, y0: 23, x1: 47, y1: 25, to: 'pond', toTx: 2, toTy: 18 }, // east → pond+ ],+};- // Tiles where standing lets you open bank storage (the counter row directly- // south of the bank building). Must be walkable.- bankZone: [- { tx: 8, ty: 12 }, { tx: 9, ty: 12 }, { tx: 10, ty: 12 },- { tx: 11, ty: 12 }, { tx: 12, ty: 12 },+// ---------------------------------------------------------------- Wilderness+const WILDERNESS = {+ name: 'wilderness',+ grid: 40,+ spawn: { tx: 20, ty: 36 },+ safe: false, pvp: true, danger: true,+ blocked: [],+ fountain: null,+ bankZone: [],+ nodes: [+ ...nodesFrom([[10, 20], [14, 16], [26, 18], [30, 22], [8, 12], [32, 14], [18, 10], [22, 24]], 'tree', 't'),+ ...nodesFrom([[12, 8], [28, 8], [34, 20], [6, 24], [16, 6]], 'rock', 'r'),+ ...nodesFrom([[24, 6], [30, 10], [9, 17]], 'coal', 'c'),],+ mobs: [+ { id: 'g0', kind: 'goblin', tx: 14, ty: 22, hp: 34, roam: true, aggro: true },+ { id: 'g1', kind: 'goblin', tx: 24, ty: 20, hp: 34, roam: true, aggro: true },+ { id: 'g2', kind: 'goblin', tx: 18, ty: 14, hp: 34, roam: true, aggro: true },+ { id: 'g3', kind: 'goblin', tx: 30, ty: 16, hp: 34, roam: true, aggro: true },+ { id: 'o0', kind: 'ogre', tx: 20, ty: 8, hp: 80, roam: true, aggro: true },+ ],+ fishing: [],+ cooking: [],+ // southern fenced safe camp: no PvP, mobs won't enter.+ safeCamp: { x0: 14, y0: 32, x1: 26, y1: 39 },+ portals: [+ { x0: 19, y0: 39, x1: 21, y1: 39, to: 'mainland', toTx: 24, toTy: 2 }, // south → mainland+ ],+};+// ---------------------------------------------------------------- Whisperwood+const WHISPERWOOD = {+ name: 'whisperwood',+ grid: 40,+ spawn: { tx: 20, ty: 3 },+ safe: true, pvp: false, danger: false,+ blocked: [],+ fountain: null,+ bankZone: [],nodes: [- ...nodesFrom(TREES, 'tree', 't'),- ...nodesFrom(ROCKS, 'rock', 'r'),- ...nodesFrom(COAL, 'coal', 'c'),+ ...nodesFrom([[8, 10], [10, 14], [12, 9], [14, 16], [16, 12], [9, 20], [13, 24], [17, 22],+ [24, 10], [28, 14], [26, 20], [30, 18], [22, 26], [32, 24], [11, 30], [27, 28], [19, 32], [23, 34]], 'tree', 't'),+ ...nodesFrom([[34, 10], [6, 26], [35, 30], [7, 33]], 'rock', 'r'),],+ mobs: [],+ fishing: tiles([[20, 17], [21, 17], [19, 19], [22, 19], [10, 34], [11, 34], [30, 35], [31, 35]]),+ cooking: [],+ safeCamp: null,+ portals: [+ { x0: 19, y0: 0, x1: 21, y1: 0, to: 'mainland', toTx: 24, toTy: 45 }, // north → mainland+ ],+};- // Training dummies near the armory ground (northeast of spawn).- mobs: [- { id: 'd0', kind: 'dummy', tx: 36, ty: 34, hp: 50 },- { id: 'd1', kind: 'dummy', tx: 38, ty: 34, hp: 50 },- { id: 'd2', kind: 'dummy', tx: 37, ty: 36, hp: 50 },+// ---------------------------------------------------------------- Pond+const POND = {+ name: 'pond',+ grid: 36,+ spawn: { tx: 3, ty: 18 },+ safe: true, pvp: false, danger: false,+ blocked: [+ { x0: 14, y0: 12, x1: 22, y1: 22 }, // the large pond (water, non-walkable)+ ],+ fountain: null,+ bankZone: [],+ nodes: [+ ...nodesFrom([[6, 6], [9, 9], [27, 8], [30, 12], [7, 26], [28, 26], [11, 29], [25, 30]], 'tree', 't'),+ ],+ mobs: [],+ // fishable shoreline around the pond rectangle (walk adjacent and cast)+ fishing: tiles([+ [13, 14], [13, 16], [13, 18], [13, 20], [23, 14], [23, 16], [23, 18], [23, 20],+ [15, 11], [17, 11], [19, 11], [21, 11], [15, 23], [17, 23], [19, 23], [21, 23],+ ]),+ cooking: tiles([[10, 18], [11, 18], [10, 19], [11, 19]]), // the Roast Pit+ safeCamp: null,+ portals: [+ { x0: 0, y0: 17, x1: 0, y1: 19, to: 'mainland', toTx: 45, toTy: 24 }, // west → mainland],};-export function inBounds(tx, ty) {- return tx >= 0 && ty >= 0 && tx < GRID && ty < GRID;+export const REALMS = {+ mainland: MAINLAND,+ wilderness: WILDERNESS,+ whisperwood: WHISPERWOOD,+ pond: POND,+};++export const DEFAULT_REALM = 'mainland';++export function inBounds(realm, tx, ty) {+ return tx >= 0 && ty >= 0 && tx < realm.grid && ty < realm.grid;}-export function isBlocked(tx, ty) {- for (const r of BLOCKED_RECTS) {+export function isBlocked(realm, tx, ty) {+ for (const r of realm.blocked) {if (tx >= r.x0 && tx <= r.x1 && ty >= r.y0 && ty <= r.y1) return true;}return false;}-export const BANK_BUILDING = BLOCKED_RECTS[0];-export const FOUNTAIN_RECT = BLOCKED_RECTS[1];+export function portalAt(realm, tx, ty) {+ for (const p of realm.portals) {+ if (tx >= p.x0 && tx <= p.x1 && ty >= p.y0 && ty <= p.y1) return p;+ }+ return null;+}++export function inRect(rect, tx, ty) {+ return rect && tx >= rect.x0 && tx <= rect.x1 && ty >= rect.y0 && ty <= rect.y1;+}++// Serializable layout sent to the client on join (static geometry only;+// dynamic objects sync via schema state).+export function realmLayout(realm) {+ return {+ name: realm.name,+ grid: realm.grid,+ spawn: realm.spawn,+ fountain: realm.fountain,+ blocked: realm.blocked,+ bankZone: realm.bankZone,+ fishing: realm.fishing,+ cooking: realm.cooking,+ safeCamp: realm.safeCamp,+ portals: realm.portals.map((p) => ({ x0: p.x0, y0: p.y0, x1: p.x1, y1: p.y1, to: p.to })),+ safe: realm.safe,+ pvp: realm.pvp,+ danger: realm.danger,+ };+}diff --git a/multiplayer/src/schemas.js b/multiplayer/src/schemas.jsindex dfb4b815e..91037e43f 100644--- a/multiplayer/src/schemas.js+++ b/multiplayer/src/schemas.js@@ -19,6 +19,12 @@ export class Player extends Schema {this.motion = 'idle'; // 'idle' | 'walk' | 'run'this.emote = ''; // animation name or '' when not emotingthis.emoteTs = 0; // epoch ms when the emote was triggered+ // Loadable GLB URL for this player's avatar / 3D agent, so every other+ // client renders them as their real avatar instead of a stand-in. Empty+ // string → the client falls back to the default avatar.+ this.avatar = '';+ // Optional three.ws agent id this player is embodying (for cross-links).+ this.agent = '';this.tsServer = 0; // server-side last-update epoch ms (for interpolation)}}@@ -33,6 +39,8 @@ defineTypes(Player, {motion: 'string',emote: 'string',emoteTs: 'float64',+ avatar: 'string',+ agent: 'string',tsServer: 'float64',});@@ -40,8 +48,19 @@ export class WalkState extends Schema {constructor() {super();this.players = new MapSchema();+ // Coin identity for this room. A walk_world room is keyed by `coin`+ // (filterBy) so everyone who entered the same coin's community shares one+ // instance; these fields theme the world (banner, totem, cross-links).+ this.coin = ''; // mint address ('' = the default mainland world)+ this.coinName = '';+ this.coinSymbol = '';+ this.coinImage = '';}}defineTypes(WalkState, {players: { map: Player },+ coin: 'string',+ coinName: 'string',+ coinSymbol: 'string',+ coinImage: 'string',});diff --git a/multiplayer/src/schemas/game.js b/multiplayer/src/schemas/game.jsindex a5f4f4620..e45da0e23 100644--- a/multiplayer/src/schemas/game.js+++ b/multiplayer/src/schemas/game.js@@ -56,6 +56,8 @@ export class GamePlayer extends Schema {this.woodcutting = 1;this.mining = 1;this.fishing = 1;+ this.cooking = 1;+ this.cosmetic = ''; // equipped cosmetic id ('' = default)// 24-slot backpack + 6 hotbar slots. Fixed length so indices are stable// references the client can drag between.@@ -83,6 +85,8 @@ defineTypes(GamePlayer, {woodcutting: 'uint16',mining: 'uint16',fishing: 'uint16',+ cooking: 'uint16',+ cosmetic: 'string',inv: [Slot],hotbar: [Slot],activeSlot: 'int8',@@ -115,7 +119,7 @@ defineTypes(ResourceNode, {respawnAt: 'float64',});-// A combat target (training dummy for the slice; same shape extends to mobs).+// A combat target — training dummy (static) or a roaming/aggressive mob.export class Mob extends Schema {constructor() {super();@@ -128,6 +132,7 @@ export class Mob extends Schema {this.dead = false;this.respawnAt = 0;this.hitTs = 0; // epoch ms of last hit, for client flash+ this.aggroId = ''; // session id of the player this mob is chasing ('' = none)}}defineTypes(Mob, {@@ -140,6 +145,32 @@ defineTypes(Mob, {dead: 'boolean',respawnAt: 'float64',hitTs: 'float64',+ aggroId: 'string',+});++// A death-drop bag left where a player died in a danger realm. Holds the items+// that fell out of the inventory; the owner (and, after a grace window, anyone)+// can recover them before it expires.+export class Tombstone extends Schema {+ constructor() {+ super();+ this.id = '';+ this.owner = '';+ this.ownerName = '';+ this.tx = 0;+ this.ty = 0;+ this.items = new ArraySchema();+ this.expiresAt = 0;+ }+}+defineTypes(Tombstone, {+ id: 'string',+ owner: 'string',+ ownerName: 'string',+ tx: 'int16',+ ty: 'int16',+ items: [Slot],+ expiresAt: 'float64',});// ---------------------------------------------------------------------------@@ -153,6 +184,7 @@ export class GameState extends Schema {this.players = new MapSchema();this.nodes = new MapSchema();this.mobs = new MapSchema();+ this.tombstones = new MapSchema();}}defineTypes(GameState, {@@ -160,4 +192,5 @@ defineTypes(GameState, {players: { map: GamePlayer },nodes: { map: ResourceNode },mobs: { map: Mob },+ tombstones: { map: Tombstone },});diff --git a/package-lock.json b/package-lock.jsonindex 5471dd56a..dadf95307 100644--- a/package-lock.json+++ b/package-lock.json@@ -32,6 +32,7 @@"@aws-sdk/s3-request-presigner": "^3.1030.0","@bonfida/spl-name-service": "0.1.67","@chenglou/pretext": "^0.0.7",+ "@coin-communities/sdk": "^1.0.2","@coinbase/x402": "^2.1.0","@coral-xyz/anchor": "^0.32.1","@dimforge/rapier3d-compat": "^0.19.3",@@ -1238,18 +1239,19 @@"version": "0.1.0","dependencies": {"@bonfida/spl-name-service": "^0.1.67",- "@colyseus/core": "^0.17.43",- "@colyseus/monitor": "^0.17.8",+ "@colyseus/core": "^0.16.24",+ "@colyseus/monitor": "^0.16.7","@colyseus/schema": "^3.0.0",- "@colyseus/ws-transport": "^0.17.13",+ "@colyseus/ws-transport": "^0.16.5","@ethereum-attestation-service/eas-sdk": "0.29.1","@metaplex-foundation/js": "^0.20.1","@pump-fun/pump-sdk": "1.1.0","@solana/actions": "0.0.2","@solana/pay": "1.0.16","agent0-sdk": "^1.7.1",- "colyseus": "^0.17.10",+ "colyseus": "^0.16.5","ethers": "^6.16.0",+ "express": "^4.21.2","livepeer": "3.2.4","short-uuid": "6.0.3"},@@ -1257,6 +1259,73 @@"node": ">=20"}},+ "multiplayer/node_modules/@colyseus/clock": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@colyseus/clock/-/clock-1.0.1.tgz",+ "integrity": "sha512-HLovmkerzZ7aEckKuHFnql+sXCChi37WRc88duWxufiH5wVMNomBjlqQYVxaORgA+4vLIRd0/jabu6DAbkSfaA==",+ "license": "MIT"+ },+ "multiplayer/node_modules/@colyseus/core": {+ "version": "0.16.24",+ "resolved": "https://registry.npmjs.org/@colyseus/core/-/core-0.16.24.tgz",+ "integrity": "sha512-wbq18J8Prj9xq/N1B5j27B3JkzPbzyGYOfSWjCowbV1HH5FGq1sAwvSFg6TUWO3kA4fipGv4a9CgrCKXI/R/4g==",+ "license": "MIT",+ "dependencies": {+ "@colyseus/greeting-banner": "^2.0.6",+ "@colyseus/msgpackr": "^1.11.2",+ "@colyseus/timer": "^1.0.1",+ "debug": "^4.3.4",+ "nanoid": "^2.0.0"+ },+ "engines": {+ "node": ">= 18.x"+ },+ "funding": {+ "url": "https://github.com/sponsors/endel"+ },+ "peerDependencies": {+ "@colyseus/schema": "^3.0.0",+ "@pm2/io": "^6.1.0"+ }+ },+ "multiplayer/node_modules/@colyseus/greeting-banner": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/@colyseus/greeting-banner/-/greeting-banner-2.0.6.tgz",+ "integrity": "sha512-65nK7KnJn6g3ArtJqNfVX+Mx7xTlBka04kSwloLP7s24UpCEaK7bMGRLgkzfnysARzlVh1eV4jynBWZN82dYwQ==",+ "license": "MIT"+ },+ "multiplayer/node_modules/@colyseus/monitor": {+ "version": "0.16.7",+ "resolved": "https://registry.npmjs.org/@colyseus/monitor/-/monitor-0.16.7.tgz",+ "integrity": "sha512-kkSsEmD38/Rcgy/599Kw1QWfxIwiAdGPHQRfzZF0nsUxWLTNHGfypeEJUeajrnoyYxJFZdKwIma0SSzxmLDCig==",+ "license": "MIT",+ "dependencies": {+ "express": ">=4.16.0",+ "node-os-utils": "^1.2.0"+ }+ },+ "multiplayer/node_modules/@colyseus/timer": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/@colyseus/timer/-/timer-1.0.3.tgz",+ "integrity": "sha512-Vy8FGTt2vbmkXn2RzMkCGphcDIdCeYeZx2CADdQM/0EWEBrFM67FTcSJATB2q/lm2vlZfvkBjEDtJHePSePB1A==",+ "license": "MIT",+ "dependencies": {+ "@colyseus/clock": "^1.0.0"+ }+ },+ "multiplayer/node_modules/@colyseus/ws-transport": {+ "version": "0.16.5",+ "resolved": "https://registry.npmjs.org/@colyseus/ws-transport/-/ws-transport-0.16.5.tgz",+ "integrity": "sha512-5aOlTzEKPL9wBV9FX6BILHGZcxZU1mXJPiXfSLbKXw0buzOlO9i4iErPUaDOoww20BfdwlCItIrgl/8jIFO0QA==",+ "license": "MIT",+ "dependencies": {+ "@types/ws": "^8.5.14",+ "ws": "^8.18.0"+ },+ "peerDependencies": {+ "@colyseus/core": "0.16.x"+ }+ },"multiplayer/node_modules/@pump-fun/pump-sdk": {"version": "1.1.0","resolved": "https://registry.npmjs.org/@pump-fun/pump-sdk/-/pump-sdk-1.1.0.tgz",@@ -1295,6 +1364,45 @@"@solana/rpc-subscriptions-spec": "^6.5.0"}},+ "multiplayer/node_modules/@types/ws": {+ "version": "8.18.1",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "multiplayer/node_modules/colyseus": {+ "version": "0.16.5",+ "resolved": "https://registry.npmjs.org/colyseus/-/colyseus-0.16.5.tgz",+ "integrity": "sha512-Ki3516JZnyJ997/FRgECMUqPLig5LSYOEw54whKfA+fBUVfsTPSzZb/sppOd+MR3LnM59P+c+v2TBEreRgAkYA==",+ "license": "MIT",+ "engines": {+ "node": ">= 20.x"+ },+ "peerDependencies": {+ "@colyseus/auth": "0.16.x",+ "@colyseus/core": "0.16.x",+ "@colyseus/redis-driver": "0.16.x",+ "@colyseus/redis-presence": "0.16.x",+ "@colyseus/schema": "^3.0.0",+ "@colyseus/uwebsockets-transport": "0.16.x",+ "@colyseus/ws-transport": "0.16.x"+ }+ },+ "multiplayer/node_modules/nanoid": {+ "version": "2.1.11",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-2.1.11.tgz",+ "integrity": "sha512-s/snB+WGm6uwi0WjsZdaVcuf3KJXlfGl2LcxgwkEwJF0D/BWzVWAZW/XY4bFaiR7s0Jk3FPvlnepg1H1b1UwlA==",+ "license": "MIT"+ },+ "multiplayer/node_modules/node-os-utils": {+ "version": "1.3.7",+ "resolved": "https://registry.npmjs.org/node-os-utils/-/node-os-utils-1.3.7.tgz",+ "integrity": "sha512-fvnX9tZbR7WfCG5BAy3yO/nCLyjVWD6MghEq0z5FDfN+ZXpLWNITBdbifxQkQ25ebr16G0N7eRWJisOcMEHG3Q==",+ "license": "MIT"+ },"multiplayer/node_modules/undici-types": {"version": "6.26.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.26.0.tgz",@@ -4640,6 +4748,31 @@"node": ">=16"}},+ "node_modules/@coin-communities/sdk": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/@coin-communities/sdk/-/sdk-1.0.2.tgz",+ "integrity": "sha512-PEHLAGb0D6Ln571GTrLELuS5ILis7afnzDj+HrYxoyTdMhdSxD5FfBUooxntMmdDhcfCSRVbmvNUbSa64Sn4ow==",+ "license": "MIT",+ "dependencies": {+ "@hey-api/client-fetch": "^0.13.1"+ },+ "peerDependencies": {+ "@tanstack/react-query": ">=5",+ "react": ">=18",+ "react-native": ">=0.73"+ },+ "peerDependenciesMeta": {+ "@tanstack/react-query": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "react-native": {+ "optional": true+ }+ }+ },"node_modules/@coinbase/cdp-sdk": {"version": "1.50.0","resolved": "https://registry.npmjs.org/@coinbase/cdp-sdk/-/cdp-sdk-1.50.0.tgz",@@ -8268,6 +8401,19 @@"integrity": "sha512-eh6eHCrRi1+POZ3dA+Dq1C6jhP1GNtr9CRINMb67OKzqW9I5DUuZM/3jLPlzhgpGeiNUlEGEbkCYChXMCc/8DQ==","license": "Apache-2.0 OR MIT"},+ "node_modules/@hey-api/client-fetch": {+ "version": "0.13.1",+ "resolved": "https://registry.npmjs.org/@hey-api/client-fetch/-/client-fetch-0.13.1.tgz",+ "integrity": "sha512-29jBRYNdxVGlx5oewFgOrkulZckpIpBIRHth3uHFn1PrL2ucMy52FvWOY3U3dVx2go1Z3kUmMi6lr07iOpUqqA==",+ "deprecated": "Starting with v0.73.0, this package is bundled directly inside @hey-api/openapi-ts.",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/hey-api"+ },+ "peerDependencies": {+ "@hey-api/openapi-ts": "< 2"+ }+ },"node_modules/@hono/node-server": {"version": "1.19.14","resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",diff --git a/package.json b/package.jsonindex aed03746b..f89b9a8bc 100644--- a/package.json+++ b/package.json@@ -115,6 +115,7 @@"@aws-sdk/s3-request-presigner": "^3.1030.0","@bonfida/spl-name-service": "0.1.67","@chenglou/pretext": "^0.0.7",+ "@coin-communities/sdk": "^1.0.2","@coinbase/x402": "^2.1.0","@coral-xyz/anchor": "^0.32.1","@dimforge/rapier3d-compat": "^0.19.3",diff --git a/pages/communities.html b/pages/communities.htmlnew file mode 100644index 000000000..7986fa019--- /dev/null+++ b/pages/communities.html@@ -0,0 +1,264 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>Coin Communities · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="Pick a coin, drop in an avatar, and walk around its world with everyone else holding it. Each coin is its own live 3D community on three.ws." />+ <meta name="theme-color" content="#0b0b12" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Coin Communities · three.ws" />+ <meta property="og:description" content="Each coin is its own live 3D world. Drop in your avatar and hang out with the community." />+ <meta property="og:url" content="https://three.ws/communities" />+ <meta name="twitter:card" content="summary_large_image" />+ <style>+ * { margin: 0; padding: 0; box-sizing: border-box; }+ :root {+ --bg: #0b0b12;+ --panel: rgba(255,255,255,0.04);+ --panel-border: rgba(255,255,255,0.09);+ --text: #f4f4f8;+ --muted: rgba(244,244,248,0.55);+ --muted-2: rgba(244,244,248,0.38);+ --accent: #7c5cff;+ --accent-soft: rgba(124,92,255,0.16);+ --radius: 16px;+ }+ html, body { background: var(--bg); color: var(--text); }+ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;+ -webkit-font-smoothing: antialiased;+ min-height: 100vh;+ background:+ radial-gradient(1200px 600px at 80% -10%, rgba(124,92,255,0.18), transparent 60%),+ radial-gradient(900px 500px at 0% 10%, rgba(52,211,153,0.10), transparent 55%),+ var(--bg);+ padding: 0 0 80px;+ }+ a { color: inherit; }++ /* Top bar */+ .topbar {+ display: flex; align-items: center; justify-content: space-between;+ padding: 18px clamp(16px, 4vw, 40px);+ position: sticky; top: 0; z-index: 5;+ backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);+ background: linear-gradient(180deg, rgba(11,11,18,0.85), rgba(11,11,18,0));+ }+ .brand { display: flex; align-items: center; gap: 9px; font-weight: 700; letter-spacing: -0.4px; font-size: 16px; text-decoration: none; }+ .brand .dot { width: 12px; height: 12px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 16px var(--accent); }+ .topbar nav { display: flex; gap: 6px; }+ .topbar nav a {+ font-size: 13px; color: var(--muted); text-decoration: none;+ padding: 7px 13px; border-radius: 999px; transition: background .15s, color .15s;+ }+ .topbar nav a:hover { color: var(--text); background: var(--panel); }++ /* Hero */+ .hero { padding: clamp(20px, 5vw, 48px) clamp(16px, 4vw, 40px) 8px; max-width: 1180px; margin: 0 auto; }+ .hero h1 {+ font-size: clamp(30px, 5.5vw, 52px); line-height: 1.02; letter-spacing: -1.4px; font-weight: 760;+ background: linear-gradient(180deg, #fff, rgba(255,255,255,0.72));+ -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent;+ }+ .hero p { margin-top: 14px; font-size: clamp(15px, 2vw, 18px); color: var(--muted); max-width: 620px; }+ .hero .steps { margin-top: 14px; display: flex; gap: 18px; flex-wrap: wrap; font-size: 13px; color: var(--muted-2); }+ .hero .steps b { color: var(--accent); font-weight: 700; }++ /* Layout */+ .wrap { max-width: 1180px; margin: 0 auto; padding: 0 clamp(16px, 4vw, 40px); }+ .section { margin-top: 30px; }+ .section-head { display: flex; align-items: baseline; gap: 12px; margin-bottom: 14px; }+ .section-head h2 { font-size: 13px; font-weight: 700; letter-spacing: 0.6px; text-transform: uppercase; color: var(--muted); }+ .section-head .hint { font-size: 12px; color: var(--muted-2); }++ .panel { background: var(--panel); border: 1px solid var(--panel-border); border-radius: var(--radius); padding: 18px; }++ /* Identity */+ .identity { display: grid; grid-template-columns: minmax(180px, 240px) 1fr; gap: 18px; align-items: start; }+ @media (max-width: 680px) { .identity { grid-template-columns: 1fr; } }+ .field-label { font-size: 12px; color: var(--muted); margin-bottom: 7px; display: block; }+ .name-field input, .url-field input {+ width: 100%; padding: 11px 13px; border-radius: 11px;+ background: rgba(0,0,0,0.28); border: 1px solid var(--panel-border); color: var(--text);+ font: inherit; font-size: 14px; transition: border-color .15s, box-shadow .15s;+ }+ .name-field input:focus, .url-field input:focus {+ outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft);+ }+ .url-field input.is-error { border-color: #f87171; }+ .url-field { margin-top: 14px; }++ .avatar-row { display: flex; gap: 10px; flex-wrap: wrap; }+ .avatar-chip {+ display: flex; flex-direction: column; align-items: center; gap: 6px;+ width: 78px; padding: 10px 6px; border-radius: 13px; cursor: pointer;+ background: rgba(0,0,0,0.22); border: 1px solid var(--panel-border); color: var(--text);+ font: inherit; text-decoration: none; transition: border-color .15s, background .15s, transform .12s;+ }+ .avatar-chip:hover { transform: translateY(-2px); background: rgba(255,255,255,0.06); }+ .avatar-chip.is-selected { border-color: var(--accent); background: var(--accent-soft); box-shadow: 0 0 0 1px var(--accent) inset; }+ .avatar-thumb {+ width: 48px; height: 48px; border-radius: 50%; overflow: hidden;+ display: flex; align-items: center; justify-content: center;+ background: linear-gradient(135deg, rgba(124,92,255,0.4), rgba(0,0,0,0.4));+ }+ .avatar-thumb img { width: 100%; height: 100%; object-fit: cover; }+ .avatar-glyph { font-size: 22px; opacity: 0.85; }+ .avatar-name { font-size: 11px; color: var(--muted); max-width: 70px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .avatar-create { border-style: dashed; }++ /* Coins */+ .coin-toolbar { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; margin-bottom: 16px; }+ .coin-search-wrap { position: relative; flex: 1; min-width: 220px; }+ .coin-search-wrap svg { position: absolute; left: 13px; top: 50%; transform: translateY(-50%); opacity: 0.4; }+ #coin-search {+ width: 100%; padding: 12px 14px 12px 40px; border-radius: 12px;+ background: rgba(0,0,0,0.28); border: 1px solid var(--panel-border); color: var(--text);+ font: inherit; font-size: 14px; transition: border-color .15s, box-shadow .15s;+ }+ #coin-search:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }++ .coin-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 12px; }++ .coin-card {+ display: flex; flex-direction: column; gap: 10px; padding: 14px;+ border-radius: 14px; cursor: pointer; text-align: left;+ background: var(--panel); border: 1px solid var(--panel-border); color: var(--text);+ font: inherit; position: relative; overflow: hidden;+ transition: border-color .15s, transform .12s, box-shadow .15s;+ }+ .coin-card:hover { transform: translateY(-3px); border-color: var(--accent); box-shadow: 0 12px 32px rgba(0,0,0,0.4); }+ .coin-card:focus-visible { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }+ .coin-thumb {+ width: 46px; height: 46px; border-radius: 50%; position: relative; overflow: hidden;+ background: linear-gradient(135deg, rgba(124,92,255,0.45), rgba(0,0,0,0.45));+ display: flex; align-items: center; justify-content: center;+ }+ .coin-thumb img { width: 100%; height: 100%; object-fit: cover; position: relative; z-index: 1; }+ .coin-thumb-fallback { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 14px; color: #fff; z-index: 0; }+ .coin-thumb.no-img img { display: none; }+ .coin-info { display: flex; flex-direction: column; gap: 2px; min-width: 0; }+ .coin-symbol { font-weight: 700; font-size: 15px; letter-spacing: -0.2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .coin-name { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .coin-mcap { font-size: 12px; color: #34d399; font-weight: 600; font-variant-numeric: tabular-nums; }+ .coin-enter {+ font-size: 12px; font-weight: 600; color: var(--accent);+ opacity: 0; transform: translateX(-4px); transition: opacity .15s, transform .15s; margin-top: auto;+ }+ .coin-card:hover .coin-enter { opacity: 1; transform: translateX(0); }++ /* Mainland card */+ .mainland-card {+ display: flex; align-items: center; gap: 14px; padding: 16px 18px; width: 100%;+ border-radius: 14px; cursor: pointer; text-align: left; margin-bottom: 16px;+ background: linear-gradient(110deg, var(--accent-soft), rgba(255,255,255,0.03));+ border: 1px solid var(--panel-border); color: var(--text); font: inherit;+ transition: border-color .15s, transform .12s;+ }+ .mainland-card:hover { border-color: var(--accent); transform: translateY(-2px); }+ .mainland-card .ml-icon { font-size: 26px; }+ .mainland-card .ml-text b { display: block; font-size: 15px; }+ .mainland-card .ml-text span { font-size: 12px; color: var(--muted); }+ .mainland-card .ml-go { margin-left: auto; font-size: 13px; font-weight: 600; color: var(--accent); }++ /* Mint row */+ .mint-row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; margin-top: 14px; }+ #mint-input {+ flex: 1; min-width: 240px; padding: 11px 13px; border-radius: 11px;+ background: rgba(0,0,0,0.28); border: 1px solid var(--panel-border); color: var(--text);+ font: inherit; font-size: 13px; font-family: ui-monospace, monospace; transition: border-color .15s, box-shadow .15s;+ }+ #mint-input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }+ #mint-input.is-error { border-color: #f87171; }+ .mint-error { color: #f87171; font-size: 12px; min-height: 16px; margin-top: 6px; }++ .primary-btn {+ padding: 11px 20px; border-radius: 11px; border: none; cursor: pointer;+ background: var(--accent); color: #fff; font: inherit; font-weight: 600; font-size: 14px;+ transition: filter .15s, transform .12s;+ }+ .primary-btn:hover { filter: brightness(1.1); transform: translateY(-1px); }+ .ghost-btn {+ padding: 9px 16px; border-radius: 10px; cursor: pointer; font: inherit; font-size: 13px;+ background: var(--panel); border: 1px solid var(--panel-border); color: var(--text); transition: border-color .15s;+ }+ .ghost-btn:hover { border-color: var(--accent); }++ /* States */+ .coin-empty { grid-column: 1/-1; padding: 36px 20px; text-align: center; color: var(--muted); }+ .coin-empty p { margin: 0 0 10px; }+ .coin-empty-sub { font-size: 12px; color: var(--muted-2); margin-top: 12px; }+ .coin-card.is-skeleton { pointer-events: none; }+ .coin-card.is-skeleton .coin-thumb { animation: pulse 1.3s ease-in-out infinite; }+ .coin-card .sk { height: 10px; border-radius: 5px; background: rgba(255,255,255,0.08); animation: pulse 1.3s ease-in-out infinite; }+ .coin-card .sk-a { width: 60%; } .coin-card .sk-b { width: 85%; }+ @keyframes pulse { 0%,100% { opacity: 0.4; } 50% { opacity: 0.85; } }+ </style>+ </head>+ <body>+ <header class="topbar">+ <a class="brand" href="/"><span class="dot"></span>three.ws</a>+ <nav>+ <a href="/walk">Mainland</a>+ <a href="/create">Create avatar</a>+ </nav>+ </header>++ <section class="hero">+ <h1>Every coin, its own world.</h1>+ <p>Drop in an avatar and walk around with everyone else who holds the same coin — live, in 3D, right in your browser.</p>+ <div class="steps"><span><b>1.</b> Pick your avatar</span><span><b>2.</b> Choose a coin</span><span><b>3.</b> You're in.</span></div>+ </section>++ <main class="wrap">+ <section class="section">+ <div class="section-head"><h2>Your identity</h2><span class="hint">Used in the world. Default works instantly.</span></div>+ <div class="panel identity">+ <div>+ <div class="name-field">+ <label class="field-label" for="name-input">Display name</label>+ <input id="name-input" type="text" maxlength="24" autocomplete="off" spellcheck="false" placeholder="your name" />+ </div>+ <div class="url-field">+ <label class="field-label" for="avatar-url-input">…or paste a GLB / Ready Player Me URL</label>+ <input id="avatar-url-input" type="url" autocomplete="off" spellcheck="false" placeholder="https://…/model.glb" />+ </div>+ </div>+ <div>+ <label class="field-label">Avatar</label>+ <div id="avatar-row" class="avatar-row"></div>+ </div>+ </div>+ </section>++ <section class="section">+ <div class="section-head"><h2>Choose a community</h2><span class="hint">Live from pump.fun · sorted by market cap</span></div>++ <button type="button" id="enter-mainland" class="mainland-card">+ <span class="ml-icon">🌐</span>+ <span class="ml-text"><b>Mainland</b><span>The shared world — everyone, no coin required</span></span>+ <span class="ml-go">Enter →</span>+ </button>++ <div class="coin-toolbar">+ <div class="coin-search-wrap">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>+ <input id="coin-search" type="search" autocomplete="off" placeholder="Search coins by name or ticker…" />+ </div>+ </div>++ <div id="coin-grid" class="coin-grid"></div>++ <div class="mint-row">+ <input id="mint-input" type="text" autocomplete="off" spellcheck="false" placeholder="Or paste any Solana mint address to enter its world" />+ <button type="button" id="mint-enter" class="primary-btn">Enter world</button>+ </div>+ <div id="mint-error" class="mint-error" role="alert"></div>+ </section>+ </main>++ <script type="module" src="/src/communities.js"></script>+ </body>+</html>diff --git a/pages/create.html b/pages/create.htmlindex 28166d9a2..2b0f8ba5e 100644--- a/pages/create.html+++ b/pages/create.html@@ -771,7 +771,7 @@id="card-selfie"role="button"tabindex="0"- aria-label="Create an avatar from a selfie with three.ws"+ aria-label="Scan yourself into a 3D avatar with three.ws"><div class="card-preview"><model-viewer@@ -807,13 +807,13 @@<path d="M7 19c0-2 2.5-3 5-3s5 1 5 3" /></svg></div>- <h2 class="card-title">Selfie to avatar</h2>+ <h2 class="card-title">Scan yourself to 3D</h2></div><p class="card-subtitle">- One selfie. About a minute. A rigged 3D avatar that works everywhere.+ Point your camera, hold still. About a minute later: a rigged 3D model you can download, share, and use anywhere.</p><span class="card-cta">- Snap a selfie+ Open the scanner<svgwidth="13"height="13"diff --git a/pages/play.html b/pages/play.htmlnew file mode 100644index 000000000..7ea989d92--- /dev/null+++ b/pages/play.html@@ -0,0 +1,47 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>Play · Coin Communities — three.ws</title>+ <meta+ name="viewport"+ content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"+ />+ <meta+ name="description"+ content="Coin Communities — a browser isometric MMO on three.ws. Join coin communities, gather, fight, trade, and explore a shared world. Sign in with your wallet and play."+ />+ <meta name="theme-color" content="#1a2740" />++ <!--+ Multiplayer server URL. Empty in dev — the page falls back to+ ws://<host>:2567 so `npm run dev:walk-all` works out of the box.+ In production, set this to the deployed Colyseus host:+ <meta name="game-server" content="wss://three-ws-multiplayer.fly.dev">+ -->+ <meta name="game-server" content="" />++ <link rel="shortcut icon" href="/favicon.ico" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Play · Coin Communities" />+ <meta property="og:description" content="A browser isometric MMO on three.ws — join coin communities, gather, fight, trade, explore." />+ <meta property="og:url" content="https://three.ws/play" />++ <link rel="stylesheet" href="/src/game/coincommunities.css" />+ </head>+ <body>+ <div id="kx-loading">+ <div class="kx-loading-card">+ <div class="kx-loading-mark">COIN COMMUNITIES</div>+ <div class="kx-loading-sub">Joining the community…</div>+ <div class="kx-spinner" role="status" aria-label="Loading"></div>+ </div>+ </div>++ <canvas id="kx-canvas"></canvas>++ <script type="module" src="/src/game/coincommunities.js"></script>+ </body>+</html>diff --git a/pages/pose.html b/pages/pose.htmlindex b9c4acb53..6c3fb5c0a 100644--- a/pages/pose.html+++ b/pages/pose.html@@ -222,11 +222,6 @@margin-bottom: 6px;}.pose-joint-group:first-child { margin-top: 0; }- .pose-joint-row {- display: grid;- grid-template-columns: 1fr 1fr;- gap: 6px;- }.pose-joint-btn {appearance: none;border: 1px solid var(--border);@@ -246,6 +241,60 @@border-color: var(--border-strong);}+ .pose-search {+ width: 100%;+ box-sizing: border-box;+ background: rgba(255, 255, 255, 0.04);+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ padding: 7px 10px;+ font: inherit;+ font-size: 12.5px;+ margin-bottom: 10px;+ transition: border-color 0.12s ease, background 0.12s ease;+ }+ .pose-search::placeholder { color: var(--text-3); }+ .pose-search:focus {+ outline: none;+ border-color: var(--border-strong);+ background: rgba(255, 255, 255, 0.07);+ }+ .pose-joint-btn[aria-pressed="true"] {+ background: rgba(255, 255, 255, 0.18);+ border-color: rgba(255, 255, 255, 0.4);+ color: #e8e8e8;+ }+ .pose-joint-row {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 6px;+ max-height: 240px;+ overflow-y: auto;+ }+ .pose-shortcuts {+ font-size: 10.5px;+ color: var(--text-3);+ margin: 10px 0 0;+ line-height: 1.7;+ }+ .pose-shortcuts kbd {+ background: rgba(255, 255, 255, 0.08);+ border: 1px solid var(--border);+ border-radius: 4px;+ padding: 1px 5px;+ font-family: ui-monospace, monospace;+ font-size: 10px;+ color: var(--text-2);+ }+ .pose-disabled {+ opacity: 0.4;+ pointer-events: none;+ }+ .mode-btn:disabled {+ opacity: 0.4;+ cursor: not-allowed;+ }.pose-slider-row {display: grid;grid-template-columns: 1fr auto;@@ -462,16 +511,19 @@</div><span class="sep"></span>- <div class="mode-group" role="group" aria-label="Drag mode">- <button type="button" class="mode-btn" data-mode="bend" aria-pressed="true" title="Bend — drag to flex forwards/back">Bend</button>- <button type="button" class="mode-btn" data-mode="tilt" aria-pressed="false" title="Tilt — drag to swing sideways">Tilt</button>- <button type="button" class="mode-btn" data-mode="twist" aria-pressed="false" title="Twist — drag to rotate around the limb axis">Twist</button>- <button type="button" class="mode-btn" data-mode="move" aria-pressed="false" title="Move — disables drag-to-rotate so you can orbit the camera">Camera</button>+ <div class="mode-group" role="group" aria-label="Posing mode">+ <button type="button" class="mode-btn" data-posemode="fk" aria-pressed="true" title="FK — select a bone and rotate it with the gizmo or sliders (F)">FK</button>+ <button type="button" class="mode-btn" data-posemode="ik" aria-pressed="false" title="IK — drag a hand or foot and the limb solves (I)">IK</button></div>+ <span class="sep"></span>++ <button type="button" id="pose-load-avatar" class="pose-btn" title="Load a rigged avatar to animate">Load avatar</button>+ <button type="button" id="pose-use-mannequin" class="pose-btn" title="Return to the built-in mannequin">Mannequin</button>+<span class="spacer"></span>- <button type="button" id="pose-reset" class="pose-btn" title="Reset the pose to standing">Reset pose</button>+ <button type="button" id="pose-reset" class="pose-btn" title="Reset the pose to rest">Reset pose</button><label class="pose-btn file-label" title="Load a pose from JSON">Import@@ -490,8 +542,19 @@</section><section class="pose-section">- <h2>Joints</h2>+ <h2>Bones</h2>+ <input+ type="search"+ id="pose-bone-search"+ class="pose-search"+ placeholder="Search bones…"+ aria-label="Search bones"+ autocomplete="off"+ /><div id="pose-joint-picker"></div>+ <p class="pose-shortcuts">+ <kbd>F</kbd> FK · <kbd>I</kbd> IK · <kbd>R</kbd> reset bone · <kbd>Esc</kbd> deselect+ </p></section><section class="pose-section">diff --git a/pages/scan.html b/pages/scan.htmlnew file mode 100644index 000000000..58d4feb07--- /dev/null+++ b/pages/scan.html@@ -0,0 +1,854 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />+ <title>3D Scanner · Scan yourself into 3D · three.ws</title>+ <link rel="icon" href="/favicon.ico" />+ <meta name="description" content="Point your camera, hold still, and walk away with a rigged 3D model of yourself — in about a minute. Free, in your browser." />+ <meta name="robots" content="index, follow" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/scan" />+ <meta property="og:title" content="3D Scanner · Scan yourself into 3D" />+ <meta property="og:description" content="Point your camera, hold still, walk away with a rigged 3D model of yourself. Free, in your browser." />+ <meta property="og:image" content="https://three.ws/assets/og-image.png" />+ <meta name="twitter:card" content="summary_large_image" />++ <style>+ :root {+ color-scheme: dark;+ --bg: #000000;+ --panel: #0a0a0a;+ --panel-elev: #111111;+ --border: #1a1a1a;+ --border-strong: #2a2a2a;+ --text: #e8e8e8;+ --muted: #888888;+ --accent: #ffffff;+ --accent-ink: #000000;+ --scan: #6ee7ff;+ --scan-dim: rgba(110, 231, 255, 0.12);+ --danger: #f87171;+ --danger-dim: #4a1a1a;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; padding: 0; }+ body {+ font: 15px/1.55 -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ color: var(--text);+ background: var(--bg);+ min-height: 100vh;+ overflow-x: hidden;+ }+ body::before {+ content: '';+ position: fixed;+ inset: 0;+ z-index: -1;+ pointer-events: none;+ background:+ radial-gradient(800px 500px at 50% -80px, rgba(110, 231, 255, 0.06) 0, transparent 70%),+ radial-gradient(600px 400px at 50% 110%, rgba(110, 231, 255, 0.05) 0, transparent 70%),+ #000000;+ }+ main.stage { max-width: 720px; margin: 0 auto; padding: 28px 20px 96px; }+ .topbar { display: flex; align-items: center; gap: 14px; margin-bottom: 24px; }+ .topbar button.back {+ background: var(--panel); border: 1px solid var(--border); color: var(--text);+ width: 36px; height: 36px; border-radius: 9px; font: inherit; cursor: pointer;+ display: inline-flex; align-items: center; justify-content: center;+ }+ .topbar button.back:hover { border-color: var(--border-strong); }+ .topbar .label { font-size: 12px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); }+ .topbar .label strong { color: var(--text); font-weight: 600; }+ .topbar .badge {+ margin-left: auto; font-size: 10.5px; font-weight: 700; letter-spacing: 0.08em;+ text-transform: uppercase; color: var(--scan); border: 1px solid var(--scan-dim);+ background: var(--scan-dim); border-radius: 999px; padding: 4px 10px;+ }+ h1 { font-size: 30px; line-height: 1.2; margin: 0 0 8px; letter-spacing: -0.02em; }+ h1 .hl { color: var(--scan); }+ .sub { color: var(--muted); margin: 0 0 24px; line-height: 1.55; }++ .step { display: none; opacity: 0; }+ .step.active { display: block; animation: step-in 400ms ease forwards; }+ @keyframes step-in { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }++ .unsupported {+ display: none; padding: 12px 14px; background: rgba(239, 77, 77, 0.08);+ border: 1px solid var(--danger-dim); border-radius: 9px; color: #f4b5b5;+ font-size: 13.5px; margin: 0 0 20px;+ }+ .unsupported.show { display: block; }++ /* ── Scanner hero ─────────────────────────────────────────────────── */+ .hero-slot-wrap { margin: 8px 0 18px; }+ .hero-slot {+ aspect-ratio: 3 / 4; max-width: 380px; margin: 0 auto;+ background:+ linear-gradient(rgba(110,231,255,0.04), rgba(110,231,255,0.04)),+ var(--panel);+ border: 1.5px dashed var(--border-strong); border-radius: 18px;+ position: relative; overflow: hidden; cursor: pointer;+ display: flex; flex-direction: column; align-items: center; justify-content: center;+ gap: 10px; color: var(--muted); transition: border-color 120ms, background 120ms;+ }+ .hero-slot::before {+ content: ''; position: absolute; inset: 0; pointer-events: none; opacity: 0.5;+ background-image:+ linear-gradient(var(--scan-dim) 1px, transparent 1px),+ linear-gradient(90deg, var(--scan-dim) 1px, transparent 1px);+ background-size: 28px 28px; mask-image: radial-gradient(circle at 50% 45%, #000 0, transparent 72%);+ -webkit-mask-image: radial-gradient(circle at 50% 45%, #000 0, transparent 72%);+ }+ .hero-slot:hover, .hero-slot:focus-visible { border-color: var(--scan); color: var(--text); outline: none; }+ .hero-slot.drag { border-color: var(--scan); background: rgba(110,231,255,0.06); cursor: copy; }+ .hero-slot.filled { border-style: solid; border-color: var(--border); padding: 0; cursor: default; }+ .hero-slot.error { border-color: var(--danger); }+ .hero-slot .hero-icon {+ width: 56px; height: 56px; border-radius: 50%; display: grid; place-items: center;+ border: 1.5px solid var(--scan); color: var(--scan); position: relative; z-index: 1;+ box-shadow: 0 0 0 6px var(--scan-dim);+ }+ .hero-slot .hero-title { font-size: 16px; color: var(--text); font-weight: 600; position: relative; z-index: 1; }+ .hero-slot .hero-sub { font-size: 13px; color: var(--muted); max-width: 260px; text-align: center; line-height: 1.45; position: relative; z-index: 1; }+ .hero-slot img.preview { width: 100%; height: 100%; object-fit: cover; display: block; }+ .hero-slot .retake-btn {+ position: absolute; top: 12px; right: 12px; background: rgba(0, 0, 0, 0.65);+ backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);+ border: 1px solid rgba(255, 255, 255, 0.15); color: var(--text); border-radius: 9px;+ padding: 8px 12px; font: 600 12px/1 inherit; cursor: pointer;+ display: inline-flex; align-items: center; gap: 6px; transition: background 120ms; z-index: 2;+ }+ .hero-slot .retake-btn:hover { background: rgba(0, 0, 0, 0.85); }+ .hero-actions { display: flex; justify-content: center; gap: 10px; margin-top: 14px; flex-wrap: wrap; }+ .hero-pill {+ background: var(--panel); border: 1px solid var(--border); color: var(--muted);+ border-radius: 999px; padding: 8px 16px; font: 500 12.5px/1 inherit; cursor: pointer;+ transition: color 120ms, border-color 120ms; display: inline-flex; align-items: center; gap: 7px;+ }+ .hero-pill:hover { color: var(--text); border-color: var(--border-strong); }+ .hero-pill[data-action="open-camera"] { border-color: var(--scan-dim); color: var(--scan); }+ .hero-pill[data-action="open-camera"]:hover { border-color: var(--scan); }+ .hero-pill[hidden] { display: none; }+ .hero-pill svg { display: block; }++ .fidelity { margin: 0 0 22px; border: 1px solid var(--border); background: var(--panel); border-radius: 12px; overflow: hidden; }+ .fidelity summary {+ list-style: none; padding: 14px 16px; cursor: pointer; display: flex;+ align-items: center; justify-content: space-between; gap: 12px; color: var(--text);+ }+ .fidelity summary::-webkit-details-marker { display: none; }+ .fidelity .fid-label { font-size: 14px; font-weight: 600; }+ .fidelity .fid-note { color: var(--muted); font-size: 12.5px; font-weight: 400; }+ .fidelity .fid-chev { color: var(--muted); transition: transform 200ms; }+ .fidelity[open] .fid-chev { transform: rotate(180deg); }+ .fidelity .fid-body { padding: 4px 16px 18px; }+ .slots { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }+ .slot-frame {+ aspect-ratio: 3 / 4; background: var(--panel-elev); border: 1.5px dashed var(--border-strong);+ border-radius: 11px; position: relative; overflow: hidden; cursor: pointer;+ display: flex; flex-direction: column; align-items: center; justify-content: center;+ gap: 6px; color: var(--muted); transition: border-color 120ms, background 120ms;+ }+ .slot-frame:hover, .slot-frame:focus-visible { border-color: var(--scan); color: var(--text); outline: none; }+ .slot-frame.drag { border-color: var(--scan); background: rgba(110,231,255,0.06); cursor: copy; }+ .slot-frame.filled { border-style: solid; border-color: var(--border); padding: 0; }+ .slot-frame.error { border-color: var(--danger); }+ .slot-frame .slot-label { font-size: 11.5px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); }+ .slot-frame .slot-hint { font-size: 13px; color: var(--text); font-weight: 500; }+ .slot-frame img { width: 100%; height: 100%; object-fit: cover; display: block; }+ .slot-frame .retake-btn {+ position: absolute; top: 8px; right: 8px; background: rgba(0, 0, 0, 0.7);+ border: 1px solid rgba(255, 255, 255, 0.2); color: var(--text); border-radius: 7px;+ padding: 4px 9px; font: 600 11px/1 inherit; cursor: pointer;+ }++ .opts { margin: 0 0 22px; display: flex; flex-direction: column; gap: 18px; }+ .opt-group .opt-label { font-size: 12px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); margin: 0 0 10px; }+ .toggle { display: inline-flex; background: var(--panel); border: 1px solid var(--border); border-radius: 9px; padding: 3px; gap: 2px; }+ .toggle button { background: transparent; border: none; color: var(--muted); font: 600 13px/1 inherit; padding: 8px 14px; border-radius: 7px; cursor: pointer; }+ .toggle button[aria-pressed="true"] { background: var(--panel-elev); color: var(--text); }+ .toggle button:hover { color: var(--text); }+ .style-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }+ .style-card {+ background: var(--panel); border: 1.5px solid var(--border); border-radius: 11px; padding: 12px;+ cursor: pointer; text-align: left; color: var(--text); font: inherit; display: flex; gap: 12px;+ align-items: center; transition: border-color 120ms, transform 120ms;+ }+ .style-card:hover { border-color: var(--border-strong); transform: translateY(-1px); }+ .style-card[aria-pressed="true"] { border-color: var(--scan); background: rgba(110,231,255,0.05); }+ .style-swatch { width: 44px; height: 44px; border-radius: 8px; flex-shrink: 0; background-size: cover; background-position: center; border: 1px solid var(--border); }+ .style-swatch.photoreal { background: radial-gradient(circle at 35% 30%, #f6c79b 0%, #c98c61 45%, #4a2e1d 95%); }+ .style-swatch.stylized { background: radial-gradient(circle at 35% 30%, #ffd5e8 0%, #c4a3ff 45%, #5a3aa3 95%); }+ .style-card .style-title { font-size: 14px; font-weight: 600; line-height: 1.2; margin: 0 0 2px; }+ .style-card .style-desc { font-size: 12px; color: var(--muted); line-height: 1.35; }++ .steps-strip { display: flex; gap: 8px; margin: 0 0 22px; flex-wrap: wrap; }+ .steps-strip .chip {+ font-size: 12px; color: var(--muted); border: 1px solid var(--border); border-radius: 999px;+ padding: 6px 12px; display: inline-flex; align-items: center; gap: 7px; background: var(--panel);+ }+ .steps-strip .chip b { color: var(--scan); font-weight: 700; }++ /* ── Building ─────────────────────────────────────────────────────── */+ .build-progress { display: flex; flex-direction: column; gap: 0; margin: 0 0 28px; }+ .build-step { display: flex; align-items: flex-start; gap: 12px; padding: 10px 0; position: relative; transition: opacity 200ms; }+ .build-step:not(:last-child)::after { content: ''; position: absolute; left: 9px; top: 30px; bottom: -10px; width: 2px; background: var(--border); }+ .build-step.completed::after { background: rgba(110, 231, 255, 0.4); }+ .bstep-dot { width: 20px; height: 20px; border-radius: 50%; border: 2px solid var(--border-strong); background: var(--panel); flex-shrink: 0; margin-top: 1px; position: relative; z-index: 1; }+ .build-step.completed .bstep-dot { background: var(--scan); border-color: var(--scan); }+ .build-step.completed .bstep-dot::after { content: ''; display: block; width: 5px; height: 9px; border: 2px solid var(--accent-ink); border-top: none; border-left: none; transform: rotate(45deg) translate(-1px, -1px); position: absolute; top: 2px; left: 5px; }+ .build-step.active .bstep-dot { border-color: var(--scan); animation: bstep-pulse 1.4s ease-in-out infinite; }+ @keyframes bstep-pulse { 0%, 100% { box-shadow: 0 0 0 0 rgba(110, 231, 255, 0.4); } 50% { box-shadow: 0 0 0 6px rgba(110, 231, 255, 0); } }+ .bstep-label { font-size: 14px; color: var(--muted); line-height: 1.4; padding-top: 1px; }+ .build-step.active .bstep-label { color: var(--text); font-weight: 500; }+ .build-step.completed { opacity: 0.65; }+ .build-step.failed .bstep-dot { background: var(--danger); border-color: var(--danger); animation: none; }+ .build-step.failed .bstep-dot::after { content: '×'; display: block; color: #fff; font: 700 14px/1 sans-serif; text-align: center; position: absolute; top: -1px; left: 2px; }+ .build-step.failed .bstep-label { color: var(--danger); font-weight: 500; }+ .build-step.failed::after { background: var(--danger-dim); }++ .build-viewer { position: relative; width: 100%; max-width: 320px; margin: 0 auto 24px; aspect-ratio: 3 / 4; border-radius: 16px; overflow: hidden; background: var(--panel); border: 1px solid var(--border); }+ .build-viewer model-viewer { width: 100%; height: 100%; --poster-color: transparent; }+ .build-preview { position: absolute; top: 18px; left: 50%; transform: translateX(-50%); width: 110px; height: 110px; border-radius: 50%; object-fit: cover; border: 2px solid var(--scan); box-shadow: 0 8px 24px -4px rgba(0,0,0,0.6), 0 0 0 4px rgba(110,231,255,0.18); background: var(--panel); opacity: 0; transition: opacity 320ms ease; animation: preview-breathe 2.4s ease-in-out infinite; }+ .build-preview.show { opacity: 1; }+ @keyframes preview-breathe { 0%, 100% { box-shadow: 0 8px 24px -4px rgba(0,0,0,0.6), 0 0 0 4px rgba(110,231,255,0.18); } 50% { box-shadow: 0 8px 24px -4px rgba(0,0,0,0.6), 0 0 0 9px rgba(110,231,255,0.08); } }+ .build-veil { position: absolute; inset: 0; display: flex; align-items: flex-end; justify-content: center; padding-bottom: 18px; background: linear-gradient(to bottom, rgba(5,6,10,0.05), rgba(5,6,10,0.45) 65%); pointer-events: none; }+ .build-ring { width: 36px; height: 36px; border-radius: 50%; border: 2.5px solid rgba(110, 231, 255, 0.15); border-top-color: var(--scan); animation: build-spin 1s linear infinite; }+ @keyframes build-spin { to { transform: rotate(360deg); } }+ .build-error { display: none; padding: 12px 14px; background: rgba(239, 77, 77, 0.08); border: 1px solid var(--danger-dim); border-radius: 9px; color: #f4b5b5; font-size: 13.5px; margin: 0 0 16px; }+ .build-error.show { display: block; }+ .build-retry { width: 100%; max-width: 320px; margin: 0 auto; display: none; padding: 12px 18px; background: var(--panel); border: 1px solid var(--border); border-radius: 10px; color: var(--text); font: 600 14px/1 inherit; cursor: pointer; text-align: center; }+ .build-retry.show { display: block; }+ .build-retry:hover { border-color: var(--border-strong); }++ /* ── Done ─────────────────────────────────────────────────────────── */+ [data-step="done"] h1 { text-align: center; }+ [data-step="done"] .sub { text-align: center; }+ .done-viewer { position: relative; width: 100%; max-width: 340px; margin: 0 auto 22px; aspect-ratio: 3 / 4; border-radius: 16px; overflow: hidden; background: var(--panel); border: 1px solid var(--border); }+ .done-viewer::after { content: ''; position: absolute; inset: -2px; border-radius: 18px; background: conic-gradient(from 0deg, var(--scan), rgba(136, 136, 136, 0.3), var(--scan), rgba(136, 136, 136, 0.3)); z-index: -1; animation: done-glow 6s linear infinite; opacity: 0.45; }+ @keyframes done-glow { to { transform: rotate(360deg); } }+ .done-viewer model-viewer { width: 100%; height: 100%; --poster-color: transparent; }+ .name-row { margin: 0 0 18px; }+ .name-input { width: 100%; padding: 12px 14px; background: var(--panel); border: 1px solid var(--border-strong); border-radius: 10px; color: var(--text); font: 15px/1 inherit; outline: none; transition: border-color 120ms; }+ .name-input:focus { border-color: var(--scan); }+ .name-input::placeholder { color: var(--muted); }++ .export-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin: 0 0 14px; }+ .export-btn {+ padding: 12px 8px; background: var(--panel); border: 1px solid var(--border); border-radius: 10px;+ color: var(--text); font: 600 13px/1.2 inherit; cursor: pointer; transition: border-color 120ms, color 120ms;+ display: flex; flex-direction: column; align-items: center; gap: 6px;+ }+ .export-btn:hover:not(:disabled) { border-color: var(--scan); }+ .export-btn:disabled { opacity: 0.5; cursor: progress; }+ .export-btn svg { display: block; color: var(--scan); }+ .export-btn .ext { font-size: 11px; color: var(--muted); font-weight: 500; letter-spacing: 0.04em; }++ .done-actions { display: flex; flex-direction: column; gap: 10px; }+ .btn-save { width: 100%; padding: 14px 18px; background: var(--scan); color: var(--accent-ink); border: none; border-radius: 10px; font: 700 15px/1 inherit; cursor: pointer; transition: filter 120ms; }+ .btn-save:hover { filter: brightness(1.06); }+ .btn-save:disabled { opacity: 0.55; cursor: not-allowed; filter: none; }+ .btn-share { width: 100%; padding: 13px 18px; background: transparent; color: var(--text); border: 1px solid var(--scan); border-radius: 10px; font: 600 14px/1 inherit; cursor: pointer; transition: background 120ms; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }+ .btn-share:hover { background: var(--scan-dim); }+ .btn-share svg { color: var(--scan); }+ .btn-ghost { width: 100%; padding: 12px 18px; background: var(--panel); color: var(--muted); border: 1px solid var(--border); border-radius: 10px; font: 500 14px/1 inherit; cursor: pointer; transition: color 120ms, border-color 120ms; }+ .btn-ghost:hover { color: var(--text); border-color: var(--border-strong); }+ .share-toast { text-align: center; font-size: 12.5px; color: var(--scan); min-height: 18px; margin: 6px 0 0; opacity: 0; transition: opacity 200ms; }+ .share-toast.show { opacity: 1; }+ .portability-note { margin-top: 22px; padding: 14px 16px; background: rgba(110, 231, 255, 0.04); border: 1px solid rgba(110, 231, 255, 0.14); border-radius: 10px; font-size: 13px; color: var(--muted); display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }+ .portability-note a { color: var(--scan); text-decoration: none; white-space: nowrap; font-weight: 500; }+ .portability-note a:hover { text-decoration: underline; }++ .submit-bar { margin-top: 6px; position: sticky; bottom: 16px; z-index: 2; }+ .submit-bar[hidden] { display: none; }+ #submit-btn { width: 100%; padding: 16px 18px; background: var(--panel); color: var(--muted); border: 1px solid var(--border); border-radius: 12px; font: 700 15px/1.2 inherit; cursor: not-allowed; transition: background 120ms, color 120ms, border-color 120ms; display: flex; align-items: center; justify-content: center; gap: 10px; }+ #submit-btn .meta { font: 500 12px/1 inherit; color: var(--muted); opacity: 0.85; }+ #submit-btn.ready { background: var(--scan); color: var(--accent-ink); border-color: var(--scan); cursor: pointer; box-shadow: 0 10px 30px -10px rgba(110, 231, 255, 0.4); animation: btn-ready 300ms ease; }+ @keyframes btn-ready { from { transform: scale(0.97); opacity: 0.8; } to { transform: scale(1); opacity: 1; } }+ #submit-btn.ready .meta { color: rgba(10, 10, 10, 0.7); }+ #submit-btn.ready:hover { filter: brightness(0.94); }++ /* ── Camera overlay (driven by selfie-capture.js) ─────────────────── */+ #cam-overlay { position: fixed; inset: 0; background: #000; z-index: 1000; display: none; flex-direction: column; }+ #cam-overlay.open { display: flex; }+ #cam-stage { position: relative; flex: 1; min-height: 0; overflow: hidden; }+ #cam-stage video, #cam-stage img.preview { width: 100%; height: 100%; object-fit: cover; }+ #cam-stage video { transform: scaleX(-1); }+ #cam-mesh-overlay { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1); pointer-events: none; z-index: 1; }+ .cam-badges { position: absolute; top: env(safe-area-inset-top, 12px); left: 12px; right: 12px; display: flex; gap: 5px; flex-wrap: wrap; z-index: 3; padding-top: 50px; }+ .cam-badge-chip { font-size: 10.5px; font-weight: 600; padding: 3px 8px; border-radius: 6px; letter-spacing: 0.03em; text-transform: uppercase; background: rgba(0, 0, 0, 0.55); border: 1px solid rgba(255, 255, 255, 0.1); color: rgba(255, 255, 255, 0.5); backdrop-filter: blur(6px); }+ .cam-badge-chip.ok { color: var(--scan); border-color: rgba(110, 231, 255, 0.35); background: rgba(110, 231, 255, 0.12); }+ .cam-badge-chip.bad { color: #ff6b6b; border-color: rgba(255, 107, 107, 0.3); background: rgba(255, 107, 107, 0.08); }+ .cam-prompt { position: absolute; top: env(safe-area-inset-top, 18px); left: 0; right: 0; text-align: center; color: rgba(255, 255, 255, 0.92); font-size: 13px; letter-spacing: 0.06em; text-transform: uppercase; padding: 16px 18px; background: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), transparent); pointer-events: none; }+ .cam-prompt strong { font-weight: 600; color: var(--scan); }+ .cam-oval { position: absolute; inset: 0; pointer-events: none; display: flex; align-items: center; justify-content: center; }+ .cam-oval svg { width: min(70vw, 60vh); height: auto; max-height: 75vh; }+ .cam-oval ellipse { fill: none; stroke: rgba(110, 231, 255, 0.5); stroke-width: 3; stroke-dasharray: 12 8; transition: stroke 200ms; }+ .cam-oval.detected ellipse { stroke: var(--scan); stroke-dasharray: 0; filter: drop-shadow(0 0 8px rgba(110, 231, 255, 0.5)); }+ .cam-hint { position: absolute; bottom: 100px; left: 0; right: 0; text-align: center; color: rgba(255, 255, 255, 0.85); font-size: 13px; padding: 8px 18px; pointer-events: none; transition: opacity 200ms; }+ .cam-hint.ok { color: var(--scan); }+ #cam-error { position: absolute; top: 60px; left: 16px; right: 16px; padding: 10px 14px; background: rgba(239, 77, 77, 0.92); color: white; border-radius: 9px; font-size: 13.5px; text-align: center; }+ .cam-bar { padding: 16px 22px calc(env(safe-area-inset-bottom, 18px) + 18px); background: rgba(0, 0, 0, 0.7); display: flex; align-items: center; justify-content: space-between; gap: 16px; }+ .cam-bar button { background: rgba(255, 255, 255, 0.08); color: var(--text); border: 1px solid rgba(255, 255, 255, 0.18); border-radius: 9px; padding: 10px 16px; font: 600 14px/1 inherit; cursor: pointer; min-width: 88px; }+ .cam-bar button.shutter { width: 72px; height: 72px; border-radius: 50%; background: var(--scan); color: var(--accent-ink); border: none; padding: 0; min-width: 72px; }+ .cam-bar button.shutter::before { content: ''; display: block; width: 56px; height: 56px; border-radius: 50%; border: 3px solid var(--accent-ink); margin: 0 auto; }+ .cam-bar button.shutter:disabled { opacity: 0.35; cursor: not-allowed; filter: grayscale(0.6); transition: opacity 200ms, filter 200ms; }+ .cam-bar .spacer { flex: 1; }+ .cam-countdown { position: absolute; inset: 0; display: none; align-items: center; justify-content: center; pointer-events: none; z-index: 4; }+ .cam-countdown.show { display: flex; }+ .cam-countdown .count-num { font: 700 96px/1 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; color: var(--scan); text-shadow: 0 4px 18px rgba(0, 0, 0, 0.6), 0 0 24px rgba(110, 231, 255, 0.5); animation: cd-pop 1s ease-out forwards; }+ @keyframes cd-pop { 0% { transform: scale(0.5); opacity: 0; } 20% { transform: scale(1.15); opacity: 1; } 80% { transform: scale(1); opacity: 1; } 100% { transform: scale(0.8); opacity: 0; } }++ .photo-tips { margin: 16px 0 0; padding: 12px 16px; background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 10px; font-size: 13px; color: var(--muted); }+ .photo-tips .tips-title { margin: 0 0 6px; font-weight: 600; font-size: 12px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--text); opacity: 0.7; }+ .photo-tips ul { margin: 0; padding-left: 18px; list-style: disc; }+ .photo-tips li { margin-bottom: 2px; line-height: 1.45; }+ .photo-tips li:last-child { margin-bottom: 0; }+ </style>+ <link rel="stylesheet" href="/mobile.css" />+ <script+ type="module"+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"+ ></script>+</head>+<body>+ <main class="stage">+ <div class="topbar">+ <button class="back" id="back-btn" aria-label="Back" type="button">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <line x1="19" y1="12" x2="5" y2="12" />+ <polyline points="12 19 5 12 12 5" />+ </svg>+ </button>+ <div class="label"><strong>three.ws</strong> · 3D Scanner</div>+ <span class="badge">Beta</span>+ </div>++ <p id="unsupported-msg" class="unsupported">+ Your browser can't open the camera here — use Upload instead, or open this page in Safari / Chrome on a device with a camera.+ </p>++ <!-- Step 1: capture -->+ <section class="step active" data-step="capture">+ <h1>Scan yourself into <span class="hl">3D</span>.</h1>+ <p class="sub">Point your camera and hold still. In about a minute you get a rigged 3D model of yourself that drops into any app, game, or stream. Photos are downscaled in your browser — nothing is stored on disk.</p>++ <div class="steps-strip" aria-hidden="true">+ <span class="chip"><b>1</b> Scan</span>+ <span class="chip"><b>2</b> Build</span>+ <span class="chip"><b>3</b> Download & share</span>+ </div>++ <div class="hero-slot-wrap">+ <div class="hero-slot" data-slot="frontal" role="button" tabindex="0" aria-label="Start the scan with your camera or a photo">+ <span class="hero-icon" aria-hidden="true">+ <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>+ </span>+ <span class="hero-title">Tap to start scanning</span>+ <span class="hero-sub">Live face tracking guides the shot. Or drop in a photo — works on phone or desktop.</span>+ </div>+ <div class="hero-actions">+ <button type="button" class="hero-pill" data-action="open-camera" id="hero-camera-btn">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>+ Scan with camera+ </button>+ <button type="button" class="hero-pill" data-action="open-upload">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>+ Upload photo+ </button>+ </div>+ </div>++ <input type="file" data-slot-input="frontal" accept="image/jpeg,image/png,image/webp,image/heic,image/heif" hidden />++ <div class="photo-tips" id="photo-tips">+ <p class="tips-title">For the sharpest scan</p>+ <ul>+ <li>Face the camera directly — no extreme angles</li>+ <li>Good, even lighting — avoid harsh shadows or backlighting</li>+ <li>Remove sunglasses, masks, or anything covering your face</li>+ <li>Keep hair away from your forehead and jawline if possible</li>+ </ul>+ </div>++ <details class="fidelity" id="fidelity-boost">+ <summary>+ <div>+ <div class="fid-label">Add side angles <span class="fid-note">(optional — adds ~30s, sharper geometry)</span></div>+ </div>+ <svg class="fid-chev" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>+ </summary>+ <div class="fid-body">+ <div class="slots">+ <div class="slot-frame" data-slot="left" role="button" tabindex="0" aria-label="Left side photo slot">+ <span class="slot-label">Left</span>+ <span class="slot-hint">Turn ~45° left</span>+ </div>+ <div class="slot-frame" data-slot="right" role="button" tabindex="0" aria-label="Right side photo slot">+ <span class="slot-label">Right</span>+ <span class="slot-hint">Turn ~45° right</span>+ </div>+ </div>+ <input type="file" data-slot-input="left" accept="image/jpeg,image/png,image/webp,image/heic,image/heif" hidden />+ <input type="file" data-slot-input="right" accept="image/jpeg,image/png,image/webp,image/heic,image/heif" hidden />+ </div>+ </details>++ <div class="opts">+ <div class="opt-group">+ <p class="opt-label">Look</p>+ <div class="style-grid" role="group" aria-label="Avatar style">+ <button type="button" class="style-card" data-type="v1" aria-pressed="true">+ <span class="style-swatch photoreal" aria-hidden="true"></span>+ <span>+ <span class="style-title">Photoreal</span>+ <span class="style-desc">Likeness-first. Closest to how you actually look.</span>+ </span>+ </button>+ <button type="button" class="style-card" data-type="v2" aria-pressed="false">+ <span class="style-swatch stylized" aria-hidden="true"></span>+ <span>+ <span class="style-title">Stylized</span>+ <span class="style-desc">Cleaner, cartoon-leaning. Good for streaming + games.</span>+ </span>+ </button>+ </div>+ </div>+ <div class="opt-group">+ <p class="opt-label">Body</p>+ <div class="toggle" role="group" aria-label="Body type">+ <button type="button" data-body="male" aria-pressed="true">Masc</button>+ <button type="button" data-body="female" aria-pressed="false">Femme</button>+ </div>+ </div>+ </div>++ <div id="submit-bar" class="submit-bar">+ <button id="submit-btn" type="button" disabled>+ <span class="label">Start scanning to continue</span>+ </button>+ </div>+ </section>++ <!-- Step 2: Building -->+ <section class="step" data-step="building">+ <h1>Reconstructing you…</h1>+ <p class="sub">This usually takes 1–2 minutes. Keep this tab open — we'll ping you when it's done.</p>++ <div class="build-progress" role="list" aria-label="Scan progress">+ <div class="build-step completed" data-bstep="upload" role="listitem">+ <span class="bstep-dot" aria-hidden="true"></span>+ <span class="bstep-label">Scan captured</span>+ </div>+ <div class="build-step active" data-bstep="process" role="listitem">+ <span class="bstep-dot" aria-hidden="true"></span>+ <span class="bstep-label" id="build-status-text" aria-live="polite">Building 3D mesh from your scan…</span>+ </div>+ <div class="build-step" data-bstep="finish" role="listitem">+ <span class="bstep-dot" aria-hidden="true"></span>+ <span class="bstep-label">Auto-rigging skeleton</span>+ </div>+ </div>++ <div class="build-viewer" aria-hidden="true">+ <model-viewer+ src="/avatars/default.glb"+ auto-rotate+ rotation-per-second="12deg"+ interaction-prompt="none"+ disable-zoom+ disable-pan+ shadow-intensity="0.5"+ environment-image="neutral"+ exposure="0.9"+ camera-orbit="0deg 78deg auto"+ loading="eager"+ ></model-viewer>+ <img id="build-preview" class="build-preview" alt="" />+ <div class="build-veil">+ <div class="build-ring"></div>+ </div>+ </div>++ <p id="build-error-msg" class="build-error" role="alert"></p>+ <button id="build-retry-btn" class="build-retry" type="button">← Scan again</button>+ </section>++ <!-- Step 3: Done -->+ <section class="step" data-step="done">+ <h1>You're in 3D.</h1>+ <p class="sub">Drag to spin it. Download the model, share the scan, or open it in your workspace.</p>++ <div class="done-viewer">+ <model-viewer+ id="done-model"+ auto-rotate+ rotation-per-second="14deg"+ interaction-prompt="none"+ camera-controls+ shadow-intensity="0.7"+ shadow-softness="0.8"+ environment-image="neutral"+ exposure="0.95"+ camera-orbit="0deg 78deg auto"+ loading="eager"+ alt="Your 3D scan"+ ></model-viewer>+ </div>++ <div class="name-row">+ <input+ type="text"+ id="done-name"+ class="name-input"+ placeholder="Name your scan"+ maxlength="60"+ autocomplete="off"+ aria-label="Scan name"+ />+ </div>++ <div class="export-row">+ <button class="export-btn" id="dl-glb" type="button" data-format="glb">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>+ Download+ <span class="ext">.GLB</span>+ </button>+ <button class="export-btn" id="dl-usdz" type="button" data-format="usdz">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2 2 7l10 5 10-5-10-5z"/><path d="m2 17 10 5 10-5"/><path d="m2 12 10 5 10-5"/></svg>+ iOS AR+ <span class="ext">.USDZ</span>+ </button>+ <button class="export-btn" id="dl-vrm" type="button" data-format="vrm">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21v-1a6 6 0 0 1 6-6h4a6 6 0 0 1 6 6v1"/></svg>+ VTube+ <span class="ext">.VRM</span>+ </button>+ </div>++ <div class="done-actions">+ <button id="share-btn" class="btn-share" type="button">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>+ Share my scan+ </button>+ <button id="done-save-btn" class="btn-save" type="button">Open in my workspace →</button>+ <button id="done-editor-btn" class="btn-ghost" type="button">Customize in editor</button>+ <button id="done-regen-btn" class="btn-ghost" type="button">Not quite right — scan again</button>+ </div>+ <p id="share-toast" class="share-toast" role="status" aria-live="polite"></p>++ <div class="portability-note">+ <span>This scan works in any three.ws-powered app, game, or stream.</span>+ <a href="/docs/embed" target="_blank" rel="noopener">Learn how to embed →</a>+ </div>+ </section>+ </main>++ <!-- Step "unavailable" — shown when the reconstruction backend isn't wired. -->+ <section class="step" data-step="unavailable" hidden style="text-align:center;max-width:520px;margin:0 auto;padding:48px 24px;">+ <h1 style="margin:0 0 12px;">The scanner is warming up</h1>+ <p class="sub" style="margin:0 0 24px;color:#9aa3b2;">+ The photo-to-3D engine is being provisioned for this environment.+ In the meantime, you can build an avatar in the studio — same outputs,+ fully ready today.+ </p>+ <div class="done-actions" style="justify-content:center;">+ <a href="/create" class="btn-save" style="text-decoration:none;display:inline-block;">Open the avatar studio →</a>+ <a href="/app" class="btn-ghost" style="text-decoration:none;display:inline-block;">Back to my workspace</a>+ </div>+ </section>++ <!-- Camera overlay (driven by selfie-capture.js) -->+ <div id="cam-overlay" role="dialog" aria-modal="true" aria-label="Camera capture">+ <div id="cam-stage">+ <video id="cam-video" autoplay playsinline muted></video>+ <canvas id="cam-mesh-overlay" aria-hidden="true"></canvas>+ <div class="cam-oval" id="cam-oval" aria-hidden="true">+ <svg viewBox="0 0 300 400" preserveAspectRatio="xMidYMid meet">+ <ellipse cx="150" cy="180" rx="115" ry="155" />+ </svg>+ </div>+ <div class="cam-badges" id="cam-badges" aria-hidden="true"></div>+ <div class="cam-hint" id="cam-hint">Center your face in the oval</div>+ <div class="cam-countdown" id="cam-countdown" aria-hidden="true">+ <span class="count-num" id="cam-count-num">3</span>+ </div>+ </div>+ <div class="cam-prompt">+ Scanning your <strong id="cam-slot-name">selfie</strong>+ </div>+ <div id="cam-error" hidden></div>+ <div class="cam-bar">+ <div id="cam-actions-live" style="display: contents;">+ <button type="button" data-cam-action="cancel">Cancel</button>+ <button type="button" class="shutter" data-cam-action="shoot" aria-label="Capture scan" id="cam-shutter"></button>+ <div class="spacer"></div>+ </div>+ <div id="cam-actions-review" hidden style="display: contents;">+ <button type="button" data-cam-action="retake">Retake</button>+ <button type="button" data-cam-action="use">Use this</button>+ </div>+ </div>+ </div>++ <script type="module">+ function showStep(name) {+ document.querySelectorAll('.step[data-step]').forEach((s) => {+ s.classList.toggle('active', s.dataset.step === name);+ if (name === 'unavailable') s.hidden = s.dataset.step !== 'unavailable';+ });+ window.scrollTo({ top: 0, behavior: 'auto' });+ }++ // Capability probe — reconstruct returns 501 unless an ML backend is wired.+ const reconstructReady = await fetch('/api/config', { credentials: 'omit' })+ .then((r) => (r.ok ? r.json() : null))+ .then((j) => j?.features?.avatarReconstruct !== false)+ .catch(() => true);++ if (!reconstructReady) {+ document.querySelectorAll('.step[data-step]').forEach((s) => {+ s.classList.remove('active');+ s.hidden = s.dataset.step !== 'unavailable';+ });+ const u = document.querySelector('.step[data-step="unavailable"]');+ if (u) { u.hidden = false; u.classList.add('active'); }+ const sb = document.getElementById('submit-bar');+ if (sb) sb.hidden = true;+ } else {+ await import('/src/selfie-capture.js');+ await import('/src/selfie-pipeline.js');+ }++ let _avatarId = null;+ let _modelUrl = null;+ let _avatarName = '3d-scan';+ let _docTitleBase = document.title;+ let _notifyPermission = (typeof Notification !== 'undefined') ? Notification.permission : 'denied';++ document.addEventListener('selfie:preview', (e) => {+ const dataUrl = e.detail?.dataUrl;+ if (!dataUrl) return;+ const img = document.getElementById('build-preview');+ if (!img) return;+ img.src = dataUrl;+ requestAnimationFrame(() => img.classList.add('show'));+ });++ document.addEventListener('selfie:building', () => {+ showStep('building');+ if (typeof Notification !== 'undefined' && _notifyPermission === 'default') {+ Notification.requestPermission().then((p) => { _notifyPermission = p; }).catch(() => {});+ }+ });++ document.addEventListener('selfie:progress', (e) => {+ const label = e.detail?.label;+ if (!label) return;+ const el = document.getElementById('build-status-text');+ if (el) el.textContent = label;+ const processStep = document.querySelector('.build-step[data-bstep="process"]');+ const finishStep = document.querySelector('.build-step[data-bstep="finish"]');+ if (label.toLowerCase().includes('finish') || label.toLowerCase().includes('rig')) {+ processStep?.classList.replace('active', 'completed');+ finishStep?.classList.add('active');+ }+ });++ document.addEventListener('selfie:done', async (e) => {+ _avatarId = e.detail?.avatarId;+ if (!_avatarId) return;+ document.querySelectorAll('.build-step').forEach((s) => { s.className = 'build-step completed'; });++ try {+ const res = await fetch(`/api/avatars/${encodeURIComponent(_avatarId)}`, { credentials: 'include' });+ if (res.ok) {+ const avatar = await res.json();+ _modelUrl = avatar.model_url || null;+ _avatarName = avatar.name || _avatarName;+ const modelEl = document.getElementById('done-model');+ if (modelEl && _modelUrl) modelEl.setAttribute('src', _modelUrl);+ const nameEl = document.getElementById('done-name');+ if (nameEl && avatar.name) nameEl.value = avatar.name;+ }+ } catch (_) {}++ notifyDone();+ showStep('done');+ });++ function notifyDone() {+ if (!document.hidden) return;+ let on = true;+ const tick = window.setInterval(() => {+ document.title = on ? '✓ Scan ready — three.ws' : _docTitleBase;+ on = !on;+ }, 900);+ const restore = () => {+ clearInterval(tick);+ document.title = _docTitleBase;+ document.removeEventListener('visibilitychange', restore);+ };+ document.addEventListener('visibilitychange', restore);+ if (_notifyPermission === 'granted' && typeof Notification !== 'undefined') {+ try {+ const n = new Notification('Your 3D scan is ready', { body: 'Tap to open it on three.ws.', icon: '/favicon.ico', tag: 'scan-ready' });+ n.onclick = () => { window.focus(); n.close(); };+ } catch (_) {}+ }+ }++ document.addEventListener('selfie:build-error', (e) => {+ const detail = e.detail || {};+ const msg = detail.message || 'Something went wrong. Try again.';+ const errEl = document.getElementById('build-error-msg');+ const retryBtn = document.getElementById('build-retry-btn');+ if (errEl) { errEl.textContent = msg; errEl.classList.add('show'); }+ if (retryBtn) retryBtn.classList.add('show');+ const ring = document.querySelector('.build-ring');+ if (ring) ring.style.display = 'none';+ const veil = document.querySelector('.build-veil');+ if (veil) veil.style.display = 'none';+ const activeStep = document.querySelector('.build-step.active');+ if (activeStep) {+ activeStep.classList.remove('active');+ activeStep.classList.add('failed');+ const label = activeStep.querySelector('.bstep-label');+ if (label) label.textContent = 'Failed';+ }+ const heading = document.querySelector('[data-step="building"] h1');+ if (heading) heading.textContent = "Couldn't finish the scan";+ const sub = document.querySelector('[data-step="building"] .sub');+ if (sub) sub.textContent = 'Check the tips and scan again with a clearer shot.';+ if (detail.slot) {+ const slotFrame = document.querySelector(+ detail.slot === 'frontal' ? `.hero-slot[data-slot="${detail.slot}"]` : `.slot-frame[data-slot="${detail.slot}"]`,+ );+ slotFrame?.classList.add('error');+ if (detail.slot !== 'frontal') {+ const fid = document.getElementById('fidelity-boost');+ if (fid) fid.open = true;+ }+ }+ });++ document.getElementById('build-retry-btn')?.addEventListener('click', () => {+ document.getElementById('build-error-msg')?.classList.remove('show');+ document.getElementById('build-retry-btn')?.classList.remove('show');+ const ring = document.querySelector('.build-ring');+ if (ring) ring.style.display = '';+ const veil = document.querySelector('.build-veil');+ if (veil) veil.style.display = '';+ const heading = document.querySelector('[data-step="building"] h1');+ if (heading) heading.textContent = 'Reconstructing you…';+ const sub = document.querySelector('[data-step="building"] .sub');+ if (sub) sub.textContent = "This usually takes 1–2 minutes. Keep this tab open — we'll ping you when it's done.";+ document.querySelectorAll('.build-step').forEach((s) => { s.classList.remove('completed', 'active', 'failed'); });+ document.querySelector('.build-step[data-bstep="upload"]')?.classList.add('completed');+ document.querySelector('.build-step[data-bstep="process"]')?.classList.add('active');+ const statusText = document.getElementById('build-status-text');+ if (statusText) statusText.textContent = 'Building 3D mesh from your scan…';+ showStep('capture');+ });++ // ── Share / export loop ─────────────────────────────────────────────+ function toast(msg) {+ const el = document.getElementById('share-toast');+ if (!el) return;+ el.textContent = msg;+ el.classList.add('show');+ window.clearTimeout(toast._t);+ toast._t = window.setTimeout(() => el.classList.remove('show'), 2600);+ }++ // Persist any name edit before leaving / exporting so downloads + the+ // workspace stay consistent with what the user typed.+ async function persistName() {+ const nameEl = document.getElementById('done-name');+ const name = nameEl?.value?.trim();+ if (!_avatarId || !name || name === _avatarName) return;+ _avatarName = name;+ try {+ await fetch(`/api/avatars/${encodeURIComponent(_avatarId)}`, {+ method: 'PATCH', credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ name }),+ });+ } catch (_) {}+ }++ document.querySelectorAll('.export-btn').forEach((btn) => {+ btn.addEventListener('click', async () => {+ if (!_modelUrl) { toast('Scan still finalizing — try again in a moment.'); return; }+ const format = btn.getAttribute('data-format');+ const labelNodes = [...btn.childNodes];+ btn.disabled = true;+ try {+ const { downloadAvatar } = await import('/src/avatar-export.js');+ await persistName();+ const { size } = await downloadAvatar(_modelUrl, {+ format,+ filename: _avatarName || '3d-scan',+ meta: { name: _avatarName },+ });+ toast(`Downloaded ${format.toUpperCase()} · ${(size / 1024 / 1024).toFixed(1)} MB`);+ } catch (err) {+ console.error('[scan] export failed', err);+ toast(`Couldn't export ${format.toUpperCase()}. Try GLB.`);+ } finally {+ btn.disabled = false;+ }+ });+ });++ document.getElementById('share-btn')?.addEventListener('click', async () => {+ if (!_avatarId) return;+ await persistName();+ const shareUrl = `${location.origin}/avatars/${encodeURIComponent(_avatarId)}`;+ const shareData = {+ title: `${_avatarName} · 3D scan on three.ws`,+ text: 'I just scanned myself into 3D on three.ws — spin it 👇',+ url: shareUrl,+ };+ if (navigator.share) {+ try { await navigator.share(shareData); return; }+ catch (err) { if (err?.name === 'AbortError') return; }+ }+ try {+ await navigator.clipboard.writeText(shareUrl);+ toast('Link copied — paste it anywhere.');+ } catch (_) {+ window.open(shareUrl, '_blank', 'noopener');+ }+ });++ document.getElementById('done-save-btn')?.addEventListener('click', async () => {+ if (!_avatarId) return;+ const btn = document.getElementById('done-save-btn');+ btn.disabled = true;+ btn.textContent = 'Opening…';+ await persistName();+ window.location.assign(`/avatars/${encodeURIComponent(_avatarId)}`);+ });++ document.getElementById('done-editor-btn')?.addEventListener('click', async () => {+ if (!_avatarId) return;+ await persistName();+ window.location.assign(`/avatars/${encodeURIComponent(_avatarId)}/edit`);+ });++ document.getElementById('done-regen-btn')?.addEventListener('click', () => {+ _avatarId = null;+ _modelUrl = null;+ const preview = document.getElementById('build-preview');+ if (preview) { preview.removeAttribute('src'); preview.classList.remove('show'); }+ document.dispatchEvent(new CustomEvent('selfie:reset'));+ showStep('capture');+ });+ </script>+</body>+</html>diff --git a/pages/walk.html b/pages/walk.htmlindex df6f23be6..5b37d5f7e 100644--- a/pages/walk.html+++ b/pages/walk.html@@ -113,8 +113,11 @@height: 100vh;z-index: 2;display: block;- /* Joystick / buttons sit on the UI layer above this. The canvas- accepts pointer events for the camera-orbit drag handler. */+ /* Own every touch: orbit/pinch are handled in JS, so suppress the+ browser's native pan + double-tap/pinch page zoom. touch-action+ doesn't inherit, so the body rule above doesn't cover the canvas.+ Joystick / buttons sit on the UI layer above this. */+ touch-action: none;}#walk-hud {@@ -224,7 +227,61 @@#walk-look-joystick { right: 24px; display: none; }@media (hover: none), (max-width: 640px) {#walk-look-joystick { display: block; }+ /* Floating movement stick — the zone spans the lower-left so the+ thumb summons the pad wherever it lands (nipplejs dynamic mode).+ Sits BELOW the chat (z8) so the centre chat input stays tappable+ where the two overlap; still above the canvas + emote bar. */+ #walk-joystick {+ left: 0;+ bottom: 0;+ width: min(50vw, 240px);+ height: min(55vh, 380px);+ z-index: 7;+ }+ }++ /* On-screen action cluster — stacked on the right edge above the look+ stick. Touch only; on desktop these actions live on keys + the HUD. */+ #walk-touch-actions {+ position: fixed;+ z-index: 9;+ right: calc(20px + env(safe-area-inset-right, 0));+ bottom: calc(184px + env(safe-area-inset-bottom, 0));+ display: none;+ flex-direction: column;+ gap: 12px;+ align-items: center;+ pointer-events: auto;+ }+ @media (hover: none), (max-width: 640px) {+ #walk-touch-actions { display: flex; }+ }+ .walk-touch-btn {+ appearance: none;+ border: 1px solid var(--border);+ background: var(--panel);+ color: var(--text);+ border-radius: 50%;+ width: 52px;+ height: 52px;+ display: flex;+ align-items: center;+ justify-content: center;+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ touch-action: manipulation;+ -webkit-tap-highlight-color: transparent;+ transition: transform 0.08s ease, background 0.15s ease, border-color 0.15s ease;+ }+ .walk-touch-btn:active { transform: scale(0.92); background: rgba(255,255,255,0.12); }+ .walk-touch-btn.is-jump {+ width: 72px;+ height: 72px;+ border-color: var(--accent);+ background: color-mix(in srgb, var(--accent) 22%, var(--panel));+ color: #fff;}+ .walk-touch-btn.is-jump:active { background: color-mix(in srgb, var(--accent) 38%, var(--panel)); }#walk-status {position: fixed;@@ -1075,6 +1132,18 @@<div id="walk-joystick" aria-label="Movement joystick"></div><div id="walk-look-joystick" aria-label="Look joystick"></div>+ <div id="walk-touch-actions" aria-label="Action buttons">+ <button type="button" class="walk-touch-btn" id="walk-touch-camera" aria-label="Switch camera">+ <svg viewBox="0 0 16 16" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="3"/><path d="M5 3.5h6l1 1.5h1.5a1 1 0 0 1 1 1V12a1 1 0 0 1-1 1H1.5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1H3z"/></svg>+ </button>+ <button type="button" class="walk-touch-btn" id="walk-touch-gesture" aria-label="Gestures">+ <svg viewBox="0 0 16 16" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 8V3.2a1.2 1.2 0 0 1 2.4 0V7m0-.5a1.2 1.2 0 0 1 2.4 0V8m0-.8a1.2 1.2 0 0 1 2.4 0v3.2c0 2-1.6 3.6-3.6 3.6H8.4c-1.2 0-2-.5-2.7-1.4L3.3 11a1.2 1.2 0 0 1 1.8-1.5L6 10.4"/></svg>+ </button>+ <button type="button" class="walk-touch-btn is-jump" id="walk-touch-jump" aria-label="Jump">+ <svg viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4l5 6h-3v6h-4v-6H7z"/></svg>+ </button>+ </div>+<div id="walk-help" aria-hidden="true"><span class="walk-key"><kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> move</span><span class="walk-key"><kbd>shift</kbd> run</span>@@ -1091,5 +1160,9 @@</div><script type="module" src="/src/walk.js"></script>+ <!-- Coin-world social layer: lobby (no ?coin=) or Town (live community+ feed + realtime bubbles) bound to the current coin. Self-contained;+ the 3D scene above is walk.js's, the multiplayer join is walk-net's. -->+ <script type="module" src="/src/community/coin-world-boot.js"></script></body></html>diff --git a/pages/worlds.html b/pages/worlds.htmlnew file mode 100644index 000000000..c23bbefea--- /dev/null+++ b/pages/worlds.html@@ -0,0 +1,461 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Worlds · Coin Communities — three.ws</title>+ <meta+ name="viewport"+ content="width=device-width, initial-scale=1.0, viewport-fit=cover"+ />+ <meta name="author" content="three.ws" />+ <meta+ name="description"+ content="Every coin is its own 3D world. Drop in your avatar or 3D agent — no sign-in — and hang out with the community, live and multiplayer, on three.ws."+ />+ <meta name="theme-color" content="#0b0b10" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Worlds · Coin Communities — three.ws" />+ <meta+ property="og:description"+ content="Every coin is its own 3D world. Drop in your avatar and hang out with the community, live."+ />+ <meta property="og:url" content="https://three.ws/worlds" />+ <meta name="twitter:card" content="summary_large_image" />++ <!-- model-viewer powers the live avatar preview in the onboarding panel. -->+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.5.0/model-viewer.min.js"></script>++ <style>+ :root {+ --bg: #08080c;+ --bg-2: #0d0d14;+ --panel: #111119;+ --panel-2: #15151f;+ --border: rgba(255, 255, 255, 0.08);+ --border-strong: rgba(255, 255, 255, 0.18);+ --text: #fafafa;+ --text-2: #a1a1aa;+ --text-3: #71717a;+ --accent: #22d3ee;+ --accent-2: #818cf8;+ --danger: #f87171;+ --ok: #4ade80;+ }+ * { box-sizing: border-box; }+ html, body {+ margin: 0;+ padding: 0;+ min-height: 100%;+ background:+ radial-gradient(1200px 600px at 70% -10%, rgba(129, 140, 248, 0.14), transparent 60%),+ radial-gradient(900px 500px at 10% 0%, rgba(34, 211, 238, 0.10), transparent 55%),+ var(--bg);+ color: var(--text);+ font-family: 'Inter', system-ui, -apple-system, sans-serif;+ -webkit-font-smoothing: antialiased;+ }+ a { color: inherit; }++ .wl-shell {+ max-width: 1200px;+ margin: 0 auto;+ padding: 28px 20px 80px;+ }++ /* ── Top bar ─────────────────────────────────────────── */+ .wl-top {+ display: flex;+ align-items: center;+ gap: 12px;+ margin-bottom: 26px;+ }+ .wl-brand {+ display: flex;+ align-items: baseline;+ gap: 8px;+ font-weight: 700;+ font-size: 15px;+ letter-spacing: 0.01em;+ }+ .wl-brand a { color: var(--text); text-decoration: none; }+ .wl-brand span { color: var(--text-3); font-weight: 500; }+ .wl-top-spacer { flex: 1; }+ .wl-top-link {+ color: var(--text-2);+ text-decoration: none;+ font-size: 13px;+ padding: 7px 12px;+ border-radius: 999px;+ border: 1px solid var(--border);+ transition: color 0.12s ease, border-color 0.12s ease, background 0.12s ease;+ }+ .wl-top-link:hover { color: var(--text); border-color: var(--border-strong); background: rgba(255,255,255,0.04); }++ /* ── Hero ────────────────────────────────────────────── */+ .wl-hero { margin-bottom: 28px; }+ .wl-hero h1 {+ margin: 0 0 10px;+ font-size: clamp(28px, 5vw, 46px);+ line-height: 1.05;+ letter-spacing: -0.02em;+ font-weight: 800;+ }+ .wl-hero h1 .grad {+ background: linear-gradient(90deg, var(--accent), var(--accent-2));+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ }+ .wl-hero p {+ margin: 0;+ color: var(--text-2);+ font-size: clamp(14px, 2vw, 17px);+ max-width: 640px;+ line-height: 1.5;+ }++ .wl-layout {+ display: grid;+ grid-template-columns: 340px 1fr;+ gap: 22px;+ align-items: start;+ }++ /* ── Onboarding panel ────────────────────────────────── */+ .wl-panel {+ background: linear-gradient(180deg, var(--panel), var(--bg-2));+ border: 1px solid var(--border);+ border-radius: 18px;+ padding: 18px;+ position: sticky;+ top: 20px;+ }+ .wl-panel h2 {+ margin: 0 0 4px;+ font-size: 13px;+ font-weight: 700;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--text-3);+ }+ .wl-panel .wl-hint { margin: 0 0 14px; color: var(--text-3); font-size: 12.5px; line-height: 1.5; }++ .wl-avatar {+ display: grid;+ grid-template-columns: 92px 1fr;+ gap: 14px;+ align-items: center;+ margin-bottom: 14px;+ }+ .wl-avatar-preview {+ width: 92px;+ height: 110px;+ border-radius: 14px;+ overflow: hidden;+ background:+ radial-gradient(120px 80px at 50% 20%, rgba(129,140,248,0.18), transparent 70%),+ var(--panel-2);+ border: 1px solid var(--border);+ display: flex;+ align-items: center;+ justify-content: center;+ }+ .wl-avatar-preview img { width: 100%; height: 100%; object-fit: cover; }+ .wl-avatar-ph { width: 46px; height: 46px; color: var(--text-3); }+ .wl-avatar-ph svg { width: 100%; height: 100%; }+ .wl-avatar-name { font-weight: 650; font-size: 16px; }+ .wl-avatar-sub { color: var(--text-3); font-size: 12px; margin-top: 2px; }++ .wl-quick {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 8px;+ margin-bottom: 12px;+ }+ .wl-quick-btn {+ appearance: none;+ display: inline-flex;+ align-items: center;+ gap: 8px;+ border: 1px solid var(--border);+ background: var(--panel-2);+ color: var(--text-2);+ font: inherit;+ font-size: 13px;+ padding: 9px 11px;+ border-radius: 10px;+ cursor: pointer;+ transition: border-color 0.12s ease, color 0.12s ease, background 0.12s ease;+ }+ .wl-quick-btn:hover { color: var(--text); border-color: var(--border-strong); background: rgba(255,255,255,0.04); }+ .wl-quick-btn.is-on { border-color: var(--accent); color: var(--text); box-shadow: 0 0 0 1px var(--accent) inset; }+ .wl-quick-btn:disabled { opacity: 0.5; cursor: wait; }+ .wl-quick-dot { width: 8px; height: 8px; border-radius: 50%; background: linear-gradient(135deg, var(--accent), var(--accent-2)); flex: none; }++ .wl-or { display: flex; align-items: center; gap: 10px; color: var(--text-3); font-size: 11px; margin: 12px 0; }+ .wl-or::before, .wl-or::after { content: ''; height: 1px; background: var(--border); flex: 1; }++ .wl-input {+ width: 100%;+ background: var(--panel-2);+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 10px 12px;+ font: inherit;+ font-size: 13px;+ transition: border-color 0.12s ease, background 0.12s ease;+ }+ .wl-input::placeholder { color: var(--text-3); }+ .wl-input:focus { outline: none; border-color: var(--accent); background: rgba(255,255,255,0.05); }++ .wl-id-form { display: grid; grid-template-columns: 1fr auto; gap: 8px; margin-bottom: 10px; }+ .wl-field { margin-bottom: 12px; }+ .wl-field label { display: block; font-size: 11px; color: var(--text-3); margin-bottom: 5px; letter-spacing: 0.03em; text-transform: uppercase; }++ .wl-btn {+ appearance: none;+ border: 1px solid var(--border-strong);+ background: var(--panel-2);+ color: var(--text);+ font: inherit;+ font-size: 13px;+ font-weight: 600;+ padding: 10px 14px;+ border-radius: 10px;+ cursor: pointer;+ transition: background 0.12s ease, border-color 0.12s ease, transform 0.08s ease;+ }+ .wl-btn:hover { background: rgba(255,255,255,0.07); }+ .wl-btn:active { transform: translateY(1px); }+ .wl-btn:disabled { opacity: 0.5; cursor: wait; }+ .wl-btn-primary {+ border: none;+ background: linear-gradient(135deg, var(--accent), var(--accent-2));+ color: #061018;+ font-weight: 700;+ }+ .wl-btn-primary:hover { filter: brightness(1.08); }+ .wl-btn-block { width: 100%; }+ .wl-btn-ghost { background: transparent; }++ .wl-panel-actions { display: grid; gap: 8px; margin-top: 6px; }+ .wl-create-link { text-align: center; color: var(--text-3); font-size: 12px; text-decoration: none; padding: 4px; }+ .wl-create-link:hover { color: var(--text-2); }++ /* ── Worlds column ───────────────────────────────────── */+ .wl-worlds-head {+ display: flex;+ align-items: center;+ gap: 12px;+ margin-bottom: 14px;+ }+ .wl-worlds-head h2 { margin: 0; font-size: 18px; font-weight: 700; }+ .wl-worlds-count { color: var(--text-3); font-size: 13px; }+ .wl-worlds-head .wl-top-spacer { flex: 1; }+ .wl-search {+ width: 220px;+ max-width: 50vw;+ background: var(--panel-2);+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 999px;+ padding: 8px 14px;+ font: inherit;+ font-size: 13px;+ }+ .wl-search:focus { outline: none; border-color: var(--border-strong); }++ .wl-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(168px, 1fr));+ gap: 14px;+ }+ .wl-card {+ appearance: none;+ text-align: left;+ padding: 0;+ border: 1px solid var(--border);+ background: var(--panel);+ border-radius: 16px;+ overflow: hidden;+ cursor: pointer;+ color: var(--text);+ display: flex;+ flex-direction: column;+ transition: transform 0.14s ease, border-color 0.14s ease, box-shadow 0.14s ease;+ }+ .wl-card:hover {+ transform: translateY(-3px);+ border-color: var(--border-strong);+ box-shadow: 0 14px 40px -20px rgba(34, 211, 238, 0.5);+ }+ .wl-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .wl-card-art {+ position: relative;+ aspect-ratio: 1 / 1;+ background: linear-gradient(135deg, #1a1a26, #0d0d14);+ display: flex;+ align-items: center;+ justify-content: center;+ }+ .wl-card-art img { width: 100%; height: 100%; object-fit: cover; }+ .wl-card-art-ph {+ font-weight: 800;+ font-size: 26px;+ letter-spacing: -0.02em;+ color: var(--text-3);+ text-transform: uppercase;+ }+ .wl-card-live {+ position: absolute;+ top: 8px;+ left: 8px;+ display: inline-flex;+ align-items: center;+ gap: 5px;+ background: rgba(0,0,0,0.6);+ border: 1px solid var(--border);+ border-radius: 999px;+ padding: 3px 8px;+ font-size: 10.5px;+ color: var(--text-2);+ backdrop-filter: blur(6px);+ }+ .wl-live-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--ok); box-shadow: 0 0 0 0 rgba(74,222,128,0.6); animation: wl-pulse 2s infinite; }+ @keyframes wl-pulse { 0% { box-shadow: 0 0 0 0 rgba(74,222,128,0.5); } 70% { box-shadow: 0 0 0 6px rgba(74,222,128,0); } 100% { box-shadow: 0 0 0 0 rgba(74,222,128,0); } }+ .wl-card-body { padding: 11px 12px 6px; }+ .wl-card-sym { font-weight: 700; font-size: 15px; }+ .wl-card-stats { display: flex; gap: 12px; margin-top: 7px; color: var(--text-3); font-size: 12px; }+ .wl-stat { display: inline-flex; align-items: center; gap: 4px; }+ .wl-stat-i { width: 13px; height: 13px; display: inline-flex; }+ .wl-stat-i svg { width: 100%; height: 100%; }+ .wl-card-enter {+ padding: 8px 12px 12px;+ color: var(--accent);+ font-size: 12.5px;+ font-weight: 600;+ opacity: 0;+ transform: translateX(-4px);+ transition: opacity 0.14s ease, transform 0.14s ease;+ }+ .wl-card:hover .wl-card-enter { opacity: 1; transform: none; }++ /* skeletons */+ .wl-skel { pointer-events: none; height: 248px; background: linear-gradient(100deg, var(--panel) 30%, var(--panel-2) 50%, var(--panel) 70%); background-size: 200% 100%; animation: wl-shimmer 1.3s infinite; }+ @keyframes wl-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }++ .wl-empty {+ grid-column: 1 / -1;+ text-align: center;+ padding: 48px 20px;+ border: 1px dashed var(--border);+ border-radius: 16px;+ background: rgba(255,255,255,0.015);+ }+ .wl-empty-icon { width: 44px; height: 44px; margin: 0 auto 14px; color: var(--text-3); }+ .wl-empty-icon svg { width: 100%; height: 100%; }+ .wl-empty h3 { margin: 0 0 8px; font-size: 18px; }+ .wl-empty p { margin: 0 auto 18px; color: var(--text-2); max-width: 440px; font-size: 14px; line-height: 1.5; }++ .wl-mint-form { grid-column: 1 / -1; display: flex; gap: 8px; margin-top: 6px; max-width: 520px; margin-left: auto; margin-right: auto; }+ .wl-mint-form .wl-input { flex: 1; }++ /* toast */+ .wl-toast {+ position: fixed;+ left: 50%;+ bottom: 26px;+ transform: translate(-50%, 20px);+ background: rgba(10,10,14,0.92);+ border: 1px solid var(--border-strong);+ color: var(--text);+ padding: 10px 16px;+ border-radius: 999px;+ font-size: 13px;+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.2s ease, transform 0.2s ease;+ backdrop-filter: blur(10px);+ z-index: 50;+ }+ .wl-toast.show { opacity: 1; transform: translate(-50%, 0); }+ .wl-toast[data-kind="error"] { border-color: rgba(248,113,113,0.5); color: #fecaca; }+ .wl-toast[data-kind="ok"] { border-color: rgba(74,222,128,0.5); color: #bbf7d0; }++ @media (max-width: 820px) {+ .wl-layout { grid-template-columns: 1fr; }+ .wl-panel { position: static; }+ }+ </style>+ </head>+ <body>+ <div class="wl-shell">+ <div class="wl-top">+ <div class="wl-brand">+ <a href="/">three.ws</a>+ <span>/ worlds</span>+ </div>+ <span class="wl-top-spacer"></span>+ <a class="wl-top-link" href="/walk">Open mainland</a>+ <a class="wl-top-link" href="/create">Make an avatar</a>+ </div>++ <header class="wl-hero">+ <h1>Every coin is a <span class="grad">world</span>.</h1>+ <p>Drop in your avatar or 3D agent — no sign-in — and hang out with the community inside its own live, multiplayer 3D world.</p>+ </header>++ <div class="wl-layout">+ <!-- ONBOARDING -->+ <aside class="wl-panel">+ <h2>Your avatar</h2>+ <p class="wl-hint">Pick one to drop in. We’ll remember it.</p>++ <div class="wl-avatar" id="wl-avatar"></div>++ <div class="wl-quick" id="wl-quick"></div>++ <button type="button" id="wl-browse" class="wl-btn wl-btn-block">Browse avatars & agents</button>++ <div class="wl-or">or drop one in</div>++ <form class="wl-id-form" id="wl-id-form">+ <input type="text" id="wl-id-input" class="wl-input" placeholder="three.ws avatar / agent ID" autocomplete="off" aria-label="Avatar or agent ID" />+ <button type="submit" id="wl-id-btn" class="wl-btn">Load</button>+ </form>++ <div class="wl-field">+ <label for="wl-name">Display name</label>+ <input type="text" id="wl-name" class="wl-input" maxlength="24" placeholder="guest" autocomplete="off" />+ </div>++ <div class="wl-panel-actions">+ <button type="button" id="wl-enter-mainland" class="wl-btn wl-btn-primary wl-btn-block">Enter the mainland →</button>+ <a class="wl-create-link" id="wl-create-link" href="/create">No avatar? Make one in seconds →</a>+ </div>+ </aside>++ <!-- WORLDS -->+ <main>+ <div class="wl-worlds-head">+ <h2>Live worlds</h2>+ <span class="wl-worlds-count" id="wl-worlds-count"></span>+ <span class="wl-top-spacer"></span>+ <input type="search" id="wl-search" class="wl-search" placeholder="Search by symbol or mint…" aria-label="Search worlds" autocomplete="off" />+ </div>+ <div class="wl-grid" id="wl-worlds"></div>+ </main>+ </div>+ </div>++ <div class="wl-toast" id="wl-toast" role="status" aria-live="polite"></div>++ <script type="module" src="/src/worlds-lobby.js"></script>+ </body>+</html>diff --git a/public/features.json b/public/features.jsonindex 4d96b9d02..eeca39ce4 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-05-29T10:59:02.237Z",+ "generated_at": "2026-05-29T21:17:01.683Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -405,6 +405,15 @@"indexable": true,"tags": []},+ {+ "path": "/three-live",+ "title": "$THREE Live · Protocol Pulse",+ "description": "The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.",+ "added": "2026-05-29",+ "auth": null,+ "indexable": true,+ "tags": []+ },{"path": "/fact-checker","title": "Fact Checker",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 13e3aa7b6..7b03f3c81 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -272,6 +272,12 @@ URL: https://three.ws/gmgnLive smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time.+### $THREE Live · Protocol Pulse++URL: https://three.ws/three-live++The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.+### Fact CheckerURL: https://three.ws/fact-checkerdiff --git a/public/llms.txt b/public/llms.txtindex fe4e7e7fc..6b7367e6a 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -66,6 +66,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [x402 Arbitrage](https://three.ws/arbitrage): Cross-provider price disparities surfaced live from the merged x402 facilitator catalog. Find the cheapest endpoint for any capability.- [x402 Providers](https://three.ws/providers): Quantified operator profiles for the x402 paid API catalog. Service counts, price bands, dominant categories, and the underlying listings.- [GMGN Smart Money](https://three.ws/gmgn): Live smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time.+- [$THREE Live · Protocol Pulse](https://three.ws/three-live): The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.- [Fact Checker](https://three.ws/fact-checker): Pay $0.10 per claim. The agent searches across authoritative sources, pays per retrieval via x402, and returns a verdict with cited evidence and a signed attestation.- [Pay-As-You-Learn Tutor](https://three.ws/tutor): Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and signed attestation.- [Unstoppable Agent](https://three.ws/unstoppable): Live dashboard for an autonomous agent that funds itself via x402 micropayments. Watch its balance, earnings, costs, and daily reflections in real time.diff --git a/public/nav.html b/public/nav.htmlindex 481f399c0..45b82845e 100644--- a/public/nav.html+++ b/public/nav.html@@ -35,6 +35,12 @@><span class="nav-mi-sub">One photo → rigged 3D avatar</span></a></li>+ <li role="none">+ <a href="/worlds" role="menuitem"+ ><span class="nav-mi-title">Worlds<span class="nav-pill" aria-hidden="true">NEW</span></span+ ><span class="nav-mi-sub">Every coin is a 3D world — drop in & hang out, live</span></a+ >+ </li><li role="none"><a href="/app" role="menuitem"><span class="nav-mi-title">Viewer</spandiff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 1d2df659e..9615e1550 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -387,6 +387,13 @@<span class="sm-desc">Live smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time.</span></a></li>+ <li>+ <a href="/three-live">+ <span class="sm-title">$THREE Live · Protocol Pulse</span>+ <span class="sm-path">/three-live</span>+ <span class="sm-desc">The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.</span>+ </a>+ </li><li><a href="/fact-checker"><span class="sm-title">Fact Checker</span>diff --git a/scripts/verify-communities.mjs b/scripts/verify-communities.mjsnew file mode 100644index 000000000..2d9582c6c--- /dev/null+++ b/scripts/verify-communities.mjs@@ -0,0 +1,81 @@+// Manual verification harness for the coin-communities flow.+// Loads the lobby, asserts real coins render, enters a coin world, and checks+// the coin HUD + totem build without console errors. Run: node scripts/verify-communities.mjs+import { chromium } from 'playwright';++const BASE = process.env.BASE || 'http://localhost:3004';+const errors = [];+const log = (...a) => console.log(...a);++const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'] });+const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });+const page = await ctx.newPage();+// Ignore noise the sandbox can't satisfy: external image hosts (ipfs/cdn),+// analytics, and the expected 401 from /api/avatars when not signed in. We only+// care about real JS errors from our own code.+const ignore = (t) => /Failed to load resource|ERR_NAME_NOT_RESOLVED|net::ERR|401 \(Unauthorized\)|posthog|ipfs|429|WebSocket connection|response code: 403/i.test(t);+page.on('console', (m) => { if (m.type() === 'error' && !ignore(m.text())) errors.push(`[console] ${m.text()}`); });+page.on('pageerror', (e) => { if (!ignore(e.message)) errors.push(`[pageerror] ${e.message}`); });++try {+ // ── Lobby ───────────────────────────────────────────────────────────────+ log('→ loading /communities');+ await page.goto(`${BASE}/communities`, { waitUntil: 'domcontentloaded' });+ await page.waitForSelector('.coin-card:not(.is-skeleton)', { timeout: 15000 });+ const coinCount = await page.locator('.coin-card:not(.is-skeleton)').count();+ const avatarChips = await page.locator('.avatar-chip').count();+ log(` coins rendered: ${coinCount}, avatar chips: ${avatarChips}`);+ if (coinCount < 1) errors.push('no coin cards rendered');++ // Pull the first coin's mint/symbol so we can verify the handoff URL.+ const first = await page.locator('.coin-card').first();+ const firstSymbol = (await first.locator('.coin-symbol').textContent())?.trim();+ log(` first coin: ${firstSymbol}`);++ // ── Enter a coin world ────────────────────────────────────────────────────+ log('→ clicking first coin');+ await Promise.all([+ page.waitForURL(/\/walk\?.*coin=/, { timeout: 15000 }),+ first.click(),+ ]);+ const url = new URL(page.url());+ log(` navigated: ${url.pathname}?${url.searchParams.toString().slice(0, 90)}…`);+ if (!url.searchParams.get('coin')) errors.push('coin param missing on handoff');++ // Let the scene boot + HUD build.+ await page.waitForSelector('#walk-coin-hud', { timeout: 20000 });+ const hudTitle = (await page.locator('#walk-coin-hud .coin-title').textContent())?.trim();+ log(` coin HUD title: ${hudTitle}`);+ const switchLink = await page.locator('#walk-coin-hud a[href="/communities"]').count();+ if (!switchLink) errors.push('HUD missing switch-community link');++ // Canvas present + non-zero size (scene mounted).+ const canvasOk = await page.evaluate(() => {+ const c = document.getElementById('walk-canvas');+ return !!c && c.width > 0 && c.height > 0;+ });+ log(` walk canvas mounted: ${canvasOk}`);+ if (!canvasOk) errors.push('walk canvas not mounted');++ await page.waitForTimeout(2500); // let totem + a trade poll settle+ await page.screenshot({ path: '/tmp/coin-world.png' });+ log(' screenshot → /tmp/coin-world.png');++ // ── Mainland (no coin) still works ────────────────────────────────────────+ log('→ verifying mainland (no coin) has no coin HUD');+ await page.goto(`${BASE}/walk`, { waitUntil: 'domcontentloaded' });+ await page.waitForTimeout(1500);+ const hudOnMainland = await page.locator('#walk-coin-hud').count();+ if (hudOnMainland !== 0) errors.push('coin HUD wrongly present on mainland /walk');+ log(` coin HUD on mainland: ${hudOnMainland} (expect 0)`);+} catch (e) {+ errors.push(`[harness] ${e.message}`);+} finally {+ await browser.close();+}++if (errors.length) {+ console.error('\n❌ FAILURES:\n' + errors.map((e) => ' - ' + e).join('\n'));+ process.exit(1);+}+console.log('\n✅ all checks passed');diff --git a/src/avatar-export.js b/src/avatar-export.jsindex 6c7cf4bc6..09ec11419 100644--- a/src/avatar-export.js+++ b/src/avatar-export.js@@ -234,7 +234,7 @@ const VRM_BONE_TARGETS = ['rightLittleProximal', 'rightLittleIntermediate', 'rightLittleDistal',];-function normalizeBoneName(raw) {+export function normalizeBoneName(raw) {return String(raw || '').toLowerCase().replace(/^mixamorig:?_?/, '')diff --git a/src/communities.js b/src/communities.jsnew file mode 100644index 000000000..07a18958a--- /dev/null+++ b/src/communities.js@@ -0,0 +1,275 @@+// /communities — the zero-friction door into three.ws coin worlds.+//+// Pick a name, drop in an avatar (or your 3D agent), choose a coin, and you're+// walked straight into that coin's multiplayer world at /walk. Each coin is its+// own room: everyone who picks the same coin lands together. The coin grid is+// real pump.fun data (/api/pump/trending + /api/pump/search); the avatar list+// is the signed-in user's real avatars (/api/avatars). No mocks, no fakes — if+// a source is empty or unreachable, the UI says so and offers a way forward.++const NAME_STORAGE_KEY = 'walk:player-name';+const AVATAR_CHOICE_KEY = 'communities:avatar-choice';+const DEFAULT_AVATAR_URL = '/avatars/default.glb';+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const $ = (id) => document.getElementById(id);++const nameInput = $('name-input');+const avatarRow = $('avatar-row');+const avatarUrlInput = $('avatar-url-input');+const coinGrid = $('coin-grid');+const searchInput = $('coin-search');+const mintInput = $('mint-input');+const mintBtn = $('mint-enter');+const mintError = $('mint-error');++// Selected avatar: { kind: 'default'|'id'|'url', value, label, thumb }+let selectedAvatar = { kind: 'default', value: DEFAULT_AVATAR_URL, label: 'Default', thumb: '' };++// ── Identity: name ─────────────────────────────────────────────────────────+(function initName() {+ let stored = '';+ try { stored = localStorage.getItem(NAME_STORAGE_KEY) || ''; } catch {}+ nameInput.value = stored || `guest-${Math.random().toString(36).slice(2, 6)}`;+ const commit = () => {+ const v = nameInput.value.trim().slice(0, 24);+ if (v) { try { localStorage.setItem(NAME_STORAGE_KEY, v); } catch {} }+ };+ nameInput.addEventListener('blur', commit);+ nameInput.addEventListener('change', commit);+})();++// ── Identity: avatar ───────────────────────────────────────────────────────+function avatarChip({ kind, value, label, thumb, id }) {+ const chip = document.createElement('button');+ chip.type = 'button';+ chip.className = 'avatar-chip';+ chip.dataset.kind = kind;+ chip.title = label;+ chip.innerHTML = `+ <span class="avatar-thumb">${thumb+ ? `<img src="${escAttr(thumb)}" alt="" referrerpolicy="no-referrer" onerror="this.style.display='none'" />`+ : `<span class="avatar-glyph">🧍</span>`}</span>+ <span class="avatar-name">${esc(label)}</span>`;+ chip.addEventListener('click', () => {+ selectedAvatar = { kind, value, label, thumb };+ try { localStorage.setItem(AVATAR_CHOICE_KEY, JSON.stringify(selectedAvatar)); } catch {}+ markSelectedAvatar();+ if (kind !== 'url' && avatarUrlInput) avatarUrlInput.value = '';+ });+ return chip;+}++function markSelectedAvatar() {+ for (const el of avatarRow.querySelectorAll('.avatar-chip')) {+ const k = el.dataset.kind;+ const matches = k === selectedAvatar.kind &&+ (k === 'default' || el.dataset.value === String(selectedAvatar.value));+ el.classList.toggle('is-selected', matches);+ }+}++async function initAvatars() {+ // Default avatar is always available — selected by default for true zero+ // friction (one click on a coin and you're in).+ const defChip = avatarChip({ kind: 'default', value: DEFAULT_AVATAR_URL, label: 'Default', thumb: '/avatars/thumbs/default.png' });+ defChip.dataset.value = DEFAULT_AVATAR_URL;+ defChip.classList.add('is-selected');+ avatarRow.appendChild(defChip);++ // Restore a prior choice if the user picked something before.+ try {+ const saved = JSON.parse(localStorage.getItem(AVATAR_CHOICE_KEY) || 'null');+ if (saved && saved.kind) selectedAvatar = saved;+ } catch {}++ // Signed-in users get their real avatars to pick from.+ try {+ const res = await fetch('/api/avatars?limit=24', { credentials: 'include' });+ if (res.ok) {+ const data = await res.json();+ const avatars = data?.avatars ?? [];+ for (const a of avatars) {+ if (!a?.id) continue;+ const chip = avatarChip({+ kind: 'id', value: a.id,+ label: a.name || 'Avatar',+ thumb: a.thumbnail_url || a.thumbnailUrl || a.image_url || '',+ });+ chip.dataset.value = a.id;+ avatarRow.appendChild(chip);+ }+ }+ } catch { /* not signed in / offline — default + paste still work */ }++ // "Create one" shortcut so an empty-handed user has a path to their own avatar.+ const create = document.createElement('a');+ create.className = 'avatar-chip avatar-create';+ create.href = '/create';+ create.innerHTML = `<span class="avatar-thumb"><span class="avatar-glyph">+</span></span><span class="avatar-name">Create</span>`;+ avatarRow.appendChild(create);++ markSelectedAvatar();+}++// Paste a direct GLB / VRM / Ready Player Me URL.+if (avatarUrlInput) {+ const apply = () => {+ const url = avatarUrlInput.value.trim();+ if (!url) return;+ if (!/^https?:\/\//i.test(url)) { avatarUrlInput.classList.add('is-error'); return; }+ avatarUrlInput.classList.remove('is-error');+ selectedAvatar = { kind: 'url', value: url, label: 'Custom', thumb: '' };+ try { localStorage.setItem(AVATAR_CHOICE_KEY, JSON.stringify(selectedAvatar)); } catch {}+ // Reflect the choice: clear chip highlight (none of the chips own a URL).+ for (const el of avatarRow.querySelectorAll('.avatar-chip')) el.classList.remove('is-selected');+ };+ avatarUrlInput.addEventListener('change', apply);+ avatarUrlInput.addEventListener('blur', apply);+}++// ── Hand-off into the world ────────────────────────────────────────────────+function enterWorld(coin) {+ // coin: null → mainland (shared world); else { mint, name, symbol, image }+ const p = new URLSearchParams();+ if (coin?.mint) {+ p.set('coin', coin.mint);+ if (coin.name) p.set('coinName', coin.name.slice(0, 48));+ if (coin.symbol) p.set('coinSymbol', coin.symbol.slice(0, 16));+ if (coin.image) p.set('coinImage', coin.image.slice(0, 1024));+ }+ const name = nameInput.value.trim().slice(0, 24);+ if (name) { p.set('name', name); try { localStorage.setItem(NAME_STORAGE_KEY, name); } catch {} }+ if (selectedAvatar.kind === 'id') p.set('avatar', selectedAvatar.value);+ else if (selectedAvatar.kind === 'url') p.set('avatarUrl', selectedAvatar.value);+ location.href = `/walk?${p.toString()}`;+}++// ── Coin grid ──────────────────────────────────────────────────────────────+function fmtMcap(v) {+ const n = Number(v);+ if (!Number.isFinite(n) || n <= 0) return '';+ if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;+ if (n >= 1e6) return `$${(n / 1e6).toFixed(1)}M`;+ if (n >= 1e3) return `$${(n / 1e3).toFixed(1)}K`;+ return `$${n.toFixed(0)}`;+}++function coinCard(coin) {+ const mint = coin.mint;+ const symbol = coin.symbol || '';+ const name = coin.name || symbol || `${mint.slice(0, 4)}…`;+ const image = coin.image_uri || '';+ const mcap = fmtMcap(coin.usd_market_cap ?? coin.market_cap);++ const card = document.createElement('button');+ card.type = 'button';+ card.className = 'coin-card';+ card.innerHTML = `+ <span class="coin-thumb">${image+ ? `<img src="${escAttr(image)}" alt="" loading="lazy" referrerpolicy="no-referrer" onerror="this.parentElement.classList.add('no-img')" />`+ : ''}<span class="coin-thumb-fallback">${esc((symbol || name).slice(0, 3).toUpperCase())}</span></span>+ <span class="coin-info">+ <span class="coin-symbol">$${esc(symbol || '—')}</span>+ <span class="coin-name">${esc(name)}</span>+ </span>+ ${mcap ? `<span class="coin-mcap">${mcap}</span>` : ''}+ <span class="coin-enter">Enter →</span>`;+ card.addEventListener('click', () => enterWorld({ mint, name, symbol, image }));+ return card;+}++function renderCoins(coins) {+ coinGrid.innerHTML = '';+ const usable = (coins || []).filter((c) => c && c.mint && MINT_RE.test(c.mint));+ if (!usable.length) {+ coinGrid.innerHTML = `<div class="coin-empty">No coins matched. Try a different search, or paste a mint address below.</div>`;+ return;+ }+ const frag = document.createDocumentFragment();+ for (const c of usable) frag.appendChild(coinCard(c));+ coinGrid.appendChild(frag);+}++function renderSkeleton(n = 12) {+ coinGrid.innerHTML = '';+ for (let i = 0; i < n; i++) {+ const sk = document.createElement('div');+ sk.className = 'coin-card is-skeleton';+ sk.innerHTML = `<span class="coin-thumb"></span><span class="coin-info"><span class="sk sk-a"></span><span class="sk sk-b"></span></span>`;+ coinGrid.appendChild(sk);+ }+}++function renderCoinError() {+ coinGrid.innerHTML = `+ <div class="coin-empty">+ <p>Couldn't reach the pump.fun feed.</p>+ <button type="button" id="coin-retry" class="ghost-btn">Retry</button>+ <p class="coin-empty-sub">Or paste any mint address below to drop into its world directly.</p>+ </div>`;+ $('coin-retry')?.addEventListener('click', loadTrending);+}++async function loadTrending() {+ renderSkeleton();+ try {+ const r = await fetch('/api/pump/trending?limit=48', { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const data = await r.json();+ renderCoins(Array.isArray(data) ? data : data?.coins || []);+ } catch (err) {+ console.warn('[communities] trending failed:', err?.message ?? err);+ renderCoinError();+ }+}++// Debounced search → /api/pump/search, falling back to trending when cleared.+let searchTimer = null;+let searchSeq = 0;+if (searchInput) {+ searchInput.addEventListener('input', () => {+ const q = searchInput.value.trim();+ clearTimeout(searchTimer);+ if (!q) { loadTrending(); return; }+ searchTimer = setTimeout(async () => {+ const seq = ++searchSeq;+ renderSkeleton(6);+ try {+ const r = await fetch(`/api/pump/search?q=${encodeURIComponent(q)}`, { headers: { accept: 'application/json' } });+ if (seq !== searchSeq) return; // a newer query superseded this one+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const data = await r.json();+ renderCoins(Array.isArray(data) ? data : data?.coins || []);+ } catch {+ if (seq === searchSeq) renderCoinError();+ }+ }, 280);+ });+}++// ── Enter any mint directly ────────────────────────────────────────────────+function enterByMint() {+ const mint = mintInput.value.trim();+ if (!MINT_RE.test(mint)) {+ mintError.textContent = 'That doesn’t look like a Solana mint address.';+ mintInput.classList.add('is-error');+ return;+ }+ mintError.textContent = '';+ mintInput.classList.remove('is-error');+ enterWorld({ mint });+}+if (mintBtn) mintBtn.addEventListener('click', enterByMint);+if (mintInput) mintInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') enterByMint(); });++// Mainland card (shared world, no coin).+$('enter-mainland')?.addEventListener('click', () => enterWorld(null));++// ── helpers ────────────────────────────────────────────────────────────────+function esc(s) { return String(s).replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' }[c])); }+function escAttr(s) { return String(s).replace(/[<>&"]/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' }[c])); }++// ── boot ───────────────────────────────────────────────────────────────────+initAvatars();+loadTrending();diff --git a/src/community/coin-lobby.js b/src/community/coin-lobby.jsnew file mode 100644index 000000000..8bad650be--- /dev/null+++ b/src/community/coin-lobby.js@@ -0,0 +1,290 @@+// Coin lobby — the entry surface for /walk when no coin is chosen.+//+// Lists live coin-worlds from the proxy (real getTopCommunities data) as+// enterable cards. Picking one navigates to /walk?coin=<mint> (preserving any+// ?avatar / ?agent so the player keeps their identity into the world). Fully+// self-contained: injects its own styles, mounts over <body>, removes itself on+// enter. Designed loading / empty / error states.++import { fetchWorlds } from './town-client.js';++let _stylesInjected = false;++function injectStyles() {+ if (_stylesInjected) return;+ _stylesInjected = true;+ const s = document.createElement('style');+ s.id = 'coin-lobby-styles';+ s.textContent = STYLES;+ document.head.appendChild(s);+}++function el(tag, cls, text) {+ const n = document.createElement(tag);+ if (cls) n.className = cls;+ if (text != null) n.textContent = text;+ return n;+}++function compactNum(n) {+ n = Number(n) || 0;+ if (n < 1000) return String(n);+ if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`;+ return `${(n / 1_000_000).toFixed(1)}m`;+}++function initials(s) {+ return (s || '?').replace(/^\$/, '').slice(0, 2).toUpperCase();+}++/** Carry the player's chosen identity into the world they enter. */+function enterUrl(token) {+ const cur = new URLSearchParams(location.search);+ const next = new URLSearchParams();+ next.set('coin', token);+ for (const k of ['avatar', 'agent', 'name']) {+ const v = cur.get(k);+ if (v) next.set(k, v);+ }+ return `${location.pathname}?${next}`;+}++export class CoinLobby {+ constructor({ onEnter } = {}) {+ this.onEnter = onEnter; // optional override; defaults to navigation+ this.worlds = [];+ injectStyles();+ this._build();+ this._load();+ }++ _build() {+ const root = el('div', 'clobby');+ root.setAttribute('role', 'dialog');+ root.setAttribute('aria-label', 'Choose a coin world');+ this.root = root;++ const inner = el('div', 'clobby__inner');+ const head = el('header', 'clobby__head');+ const titles = el('div', 'clobby__titles');+ titles.appendChild(el('h1', 'clobby__h1', 'Enter a coin world'));+ titles.appendChild(+ el(+ 'p',+ 'clobby__sub',+ 'Each coin is a live 3D world. Drop in, walk around, talk to its community.',+ ),+ );+ head.appendChild(titles);++ const search = el('input', 'clobby__search');+ search.type = 'search';+ search.placeholder = 'Search worlds…';+ search.setAttribute('aria-label', 'Search worlds');+ search.addEventListener('input', () => this._filter(search.value));+ this.search = search;+ head.appendChild(search);+ inner.appendChild(head);++ this.grid = el('div', 'clobby__grid');+ inner.appendChild(this.grid);+ root.appendChild(inner);+ document.body.appendChild(root);+ this._renderSkeleton();+ }++ _renderSkeleton() {+ this.grid.innerHTML = '';+ for (let i = 0; i < 8; i++) {+ const c = el('div', 'cw cw--skel');+ c.appendChild(el('div', 'cw__img clobby__skel'));+ c.appendChild(el('div', 'clobby__skel clobby__skel--line'));+ c.appendChild(el('div', 'clobby__skel clobby__skel--line clobby__skel--short'));+ this.grid.appendChild(c);+ }+ }++ _renderState(emoji, title, sub, retry) {+ this.grid.innerHTML = '';+ const e = el('div', 'clobby__state');+ e.appendChild(el('div', 'clobby__state-emoji', emoji));+ e.appendChild(el('div', 'clobby__state-title', title));+ if (sub) e.appendChild(el('div', 'clobby__state-sub', sub));+ if (retry) {+ const b = el('button', 'clobby__retry', 'Try again');+ b.type = 'button';+ b.addEventListener('click', retry);+ e.appendChild(b);+ }+ this.grid.appendChild(e);+ }++ _card(w) {+ const card = el('button', 'cw');+ card.type = 'button';+ card.setAttribute('aria-label', `Enter ${w.symbol ? '$' + w.symbol : 'world'}`);+ const img = el('div', 'cw__img');+ if (w.image) {+ const i = el('img');+ i.src = w.image;+ i.alt = '';+ i.loading = 'lazy';+ i.onerror = () => {+ img.classList.add('cw__img--ph');+ img.textContent = initials(w.symbol);+ i.remove();+ };+ img.appendChild(i);+ } else {+ img.classList.add('cw__img--ph');+ img.textContent = initials(w.symbol);+ }+ card.appendChild(img);++ card.appendChild(el('div', 'cw__symbol', w.symbol ? `$${w.symbol}` : 'world'));+ const stats = el('div', 'cw__stats');+ stats.appendChild(el('span', null, `${compactNum(w.members)} members`));+ stats.appendChild(el('span', 'cw__dot', '·'));+ stats.appendChild(el('span', null, `${compactNum(w.posts)} posts`));+ card.appendChild(stats);++ const enter = el('span', 'cw__enter', 'Enter →');+ card.appendChild(enter);++ card.addEventListener('click', () => this._enter(w));+ return card;+ }++ _enter(w) {+ // Hand the chosen world's identity to Town across the navigation so it+ // shows the coin symbol/image/counts immediately instead of fetching.+ try {+ sessionStorage.setItem(+ `town:meta:${w.token}`,+ JSON.stringify({+ symbol: w.symbol,+ image: w.image,+ members: w.members,+ posts: w.posts,+ }),+ );+ } catch {+ /* private mode — Town enriches from /worlds instead */+ }+ if (this.onEnter) {+ this.onEnter(w);+ this.destroy();+ } else {+ location.href = enterUrl(w.token);+ }+ }++ _filter(q) {+ q = q.trim().toLowerCase();+ const cards = this.grid.querySelectorAll('.cw');+ let shown = 0;+ this.worlds.forEach((w, i) => {+ const hay = `${w.symbol || ''} ${w.token}`.toLowerCase();+ const match = !q || hay.includes(q);+ if (cards[i]) cards[i].style.display = match ? '' : 'none';+ if (match) shown++;+ });+ if (!shown && q) this._noMatch(q);+ }++ _noMatch(q) {+ let n = this.grid.querySelector('.clobby__nomatch');+ if (!n) {+ n = el('div', 'clobby__nomatch');+ this.grid.appendChild(n);+ }+ n.textContent = `No worlds matching “${q}”.`;+ }++ async _load() {+ try {+ this.worlds = await fetchWorlds();+ } catch (err) {+ if (err?.code === 'cc_unconfigured') {+ this._renderState(+ '🔌',+ 'Worlds are coming online',+ 'CoinCommunities isn’t connected on this deployment yet.',+ null,+ );+ } else {+ this._renderState('⚠️', 'Could not load worlds', err?.message || '', () => {+ this._renderSkeleton();+ this._load();+ });+ }+ return;+ }+ if (!this.worlds.length) {+ this._renderState(+ '🌌',+ 'No live worlds yet',+ 'Be the first — launch a coin to open its world.',+ null,+ );+ return;+ }+ this.grid.innerHTML = '';+ for (const w of this.worlds) this.grid.appendChild(this._card(w));+ }++ destroy() {+ this.root?.remove();+ }+}++export function mountLobby(opts) {+ return new CoinLobby(opts);+}++const STYLES = `+.clobby{position:fixed;inset:0;z-index:60;overflow-y:auto;+ background:radial-gradient(1200px 700px at 50% -10%,rgba(60,90,200,.22),transparent),+ linear-gradient(180deg,#0a0e1c,#070a16);+ color:#e8eefb;font:15px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}+.clobby__inner{max-width:1080px;margin:0 auto;padding:clamp(28px,6vw,72px) clamp(18px,4vw,40px) 64px}+.clobby__head{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;flex-wrap:wrap;margin-bottom:28px}+.clobby__h1{font-size:clamp(26px,4vw,40px);font-weight:760;letter-spacing:-.5px;margin:0 0 6px;+ background:linear-gradient(120deg,#fff,#a9c2ff);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}+.clobby__sub{margin:0;color:#93a4cc;max-width:560px}+.clobby__search{flex:0 0 auto;width:min(260px,100%);padding:11px 15px;border-radius:12px;+ background:rgba(255,255,255,.05);border:1px solid rgba(120,150,220,.22);color:#eaf0ff;font:inherit;transition:border-color .2s}+.clobby__search:focus{outline:none;border-color:#5b8cff;background:rgba(255,255,255,.08)}+.clobby__grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:16px}+.cw{position:relative;display:flex;flex-direction:column;gap:6px;padding:16px;border-radius:18px;cursor:pointer;+ text-align:left;color:inherit;font:inherit;+ background:linear-gradient(180deg,rgba(22,30,52,.7),rgba(13,18,34,.8));border:1px solid rgba(120,150,220,.16);+ transition:transform .22s cubic-bezier(.16,1,.3,1),border-color .22s,box-shadow .22s}+.cw:hover{transform:translateY(-4px);border-color:rgba(123,150,255,.5);box-shadow:0 18px 40px rgba(0,0,0,.4)}+.cw:focus-visible{outline:2px solid #5b8cff;outline-offset:3px}+.cw__img{width:100%;aspect-ratio:1;border-radius:13px;overflow:hidden;margin-bottom:4px;+ background:linear-gradient(135deg,#23304f,#16203a);border:1px solid rgba(120,150,220,.14)}+.cw__img img{width:100%;height:100%;object-fit:cover;display:block}+.cw__img--ph{display:grid;place-items:center;font-weight:800;font-size:34px;color:#7d93c8}+.cw__symbol{font-weight:720;font-size:16px;letter-spacing:.2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.cw__stats{display:flex;align-items:center;gap:6px;font-size:12px;color:#8ea0c6;flex-wrap:wrap}+.cw__dot{opacity:.5}+.cw__enter{margin-top:6px;font-size:13px;font-weight:650;color:#9fc0ff;opacity:0;transform:translateX(-4px);+ transition:opacity .2s,transform .2s}+.cw:hover .cw__enter{opacity:1;transform:translateX(0)}+.clobby__skel{background:linear-gradient(90deg,rgba(255,255,255,.05),rgba(255,255,255,.11),rgba(255,255,255,.05));+ background-size:200% 100%;animation:clobby-shimmer 1.3s infinite;border-radius:8px}+.cw__img.clobby__skel{aspect-ratio:1;border-radius:13px}+.clobby__skel--line{height:13px;margin-top:8px;width:80%}.clobby__skel--short{width:50%}+.cw--skel{pointer-events:none}+@keyframes clobby-shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}+.clobby__state,.clobby__nomatch{grid-column:1/-1;display:flex;flex-direction:column;align-items:center;justify-content:center;+ gap:8px;text-align:center;padding:64px 24px;color:#93a4cc}+.clobby__state-emoji{font-size:40px}+.clobby__state-title{font-size:19px;font-weight:680;color:#e2e9fb}+.clobby__state-sub{max-width:380px;color:#8093ba}+.clobby__retry{margin-top:10px;padding:10px 20px;border-radius:11px;border:1px solid rgba(120,150,220,.3);+ background:rgba(91,140,255,.16);color:#cfe0ff;cursor:pointer;font-weight:650;transition:background .2s}+.clobby__retry:hover{background:rgba(91,140,255,.28)}+@media (prefers-reduced-motion:reduce){.cw,.cw__enter,.clobby__skel{transition:none;animation:none}}+`;diff --git a/src/community/coin-world-boot.js b/src/community/coin-world-boot.jsnew file mode 100644index 000000000..8aa01803c--- /dev/null+++ b/src/community/coin-world-boot.js@@ -0,0 +1,67 @@+// Coin-world boot — the entry glue for /walk's social layer.+//+// Decides, from the URL, whether the visitor is choosing a world or already in+// one, and mounts the right surface:+// • no ?coin= → the coin-world lobby (picker). walk.js still renders the+// scene behind it; picking a world navigates to ?coin=<mint>.+// • ?coin=mint → Town, the live community layer bound to that coin.+//+// This deliberately owns ONLY the CoinCommunities social layer. The 3D scene+// and multiplayer join are walk.js / walk-net.js's job (walk-net reads the same+// ?coin= to scope the room). Idempotent — safe even if the scene also imports+// it — so there's never a double mount.++import { mountLobby } from './coin-lobby.js';+import { mountTown } from './town.js';+import { fetchWorlds } from './town-client.js';++const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const isCoin = (v) => typeof v === 'string' && MINT_RE.test(v);++function readMeta(coin) {+ try {+ return JSON.parse(sessionStorage.getItem(`town:meta:${coin}`) || '{}');+ } catch {+ return {};+ }+}++async function enrich(town, coin) {+ // Direct link (no lobby handoff) → best-effort identity from the live list.+ try {+ const worlds = await fetchWorlds();+ const w = worlds.find((x) => x.token === coin);+ if (w)+ town.updateMeta({+ symbol: w.symbol,+ image: w.image,+ members: w.members,+ posts: w.posts,+ });+ } catch {+ /* feed still works without the badge; leave the neutral placeholder */+ }+}++export function boot() {+ if (window.__townBoot) return window.__townBoot;+ const coin = new URLSearchParams(location.search).get('coin');++ if (!isCoin(coin)) {+ window.__townBoot = { mode: 'lobby', lobby: mountLobby() };+ return window.__townBoot;+ }++ const meta = readMeta(coin);+ const town = mountTown({ token: coin, meta });+ if (!meta.symbol) enrich(town, coin);+ window.__town = town;+ window.__townBoot = { mode: 'world', town };+ return window.__townBoot;+}++if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', boot, { once: true });+} else {+ boot();+}diff --git a/src/community/town-client.js b/src/community/town-client.jsnew file mode 100644index 000000000..d834b1f1d--- /dev/null+++ b/src/community/town-client.js@@ -0,0 +1,97 @@+// Town client — the browser's only door to the CoinCommunities social layer.+//+// Every call goes through the same-origin api/community/* proxy, so the+// CoinCommunities API key never reaches the browser. Realtime is the one+// direct connection: the proxy mints a single-use WS ticket and we open the+// socket straight to CoinCommunities with it (lazy-loaded so nothing lands in+// the main /walk bundle until a coin world is actually entered).++const BASE = '/api/community';++/** Unwrap the { data, error } envelope the proxy speaks, throwing on error. */+async function call(path, init) {+ const res = await fetch(`${BASE}${path}`, init);+ let body = null;+ try {+ body = await res.json();+ } catch {+ /* non-JSON (e.g. 502 HTML) — fall through to status-based error */+ }+ if (!res.ok || body?.error) {+ const err = new Error(body?.error_description || body?.error || `HTTP ${res.status}`);+ err.status = res.status;+ err.code = body?.error;+ throw err;+ }+ return body?.data ?? null;+}++/** Which Town affordances are live for this deployment (reads vs. posting). */+export function fetchCapabilities() {+ return call('/capabilities');+}++/** The lobby of live coin-worlds, most active first. */+export async function fetchWorlds() {+ const data = await call('/worlds');+ return data?.worlds ?? [];+}++/** Recent messages for a coin's community (newest first). */+export async function fetchMessages(token, { limit = 50, before } = {}) {+ const qs = new URLSearchParams({ token, limit: String(limit) });+ if (before) qs.set('before', before);+ const data = await call(`/messages?${qs}`);+ return data?.messages ?? [];+}++/**+ * Post a message. Only succeeds where server-side attribution is configured+ * (capabilities.canPost) and a linked posting identity is supplied. Throws with+ * a `posting_locked` code otherwise so the composer can render its locked state.+ */+export async function postMessage(+ token,+ { content, walletAddress, twitterId, chainId = 'solana' },+) {+ const data = await call(`/messages?token=${encodeURIComponent(token)}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ content, walletAddress, twitterId, chainId }),+ });+ return data?.message ?? null;+}++/**+ * Subscribe to a coin community's realtime stream. Returns a disposer.+ * The realtime module is dynamically imported so it's a separate chunk.+ *+ * @param {string} token community mint+ * @param {string} baseUrl CoinCommunities origin (from fetchCapabilities)+ * @param {object} handlers { onMessage, onLike, onModeration, onConnect, onDisconnect, onGap }+ * @returns {Promise<() => void>}+ */+export async function connectRealtime(token, baseUrl, handlers = {}) {+ const mod = await import('@coin-communities/sdk/react');+ const RT = mod.realtime?.CommunityRealtimeClient ?? mod.CommunityRealtimeClient;+ if (!RT) throw new Error('realtime client unavailable in this SDK build');++ const client = RT.getOrCreate({+ baseUrl,+ tokenAddress: token,+ auth: {+ // Fresh single-use ticket on connect and every reconnect.+ getTicket: async () => {+ const res = await fetch(`${BASE}/ws-ticket?token=${encodeURIComponent(token)}`, {+ method: 'POST',+ });+ const body = await res.json().catch(() => null);+ const ticket = body?.data?.ticket;+ if (!ticket) throw new Error('WebSocket ticket unavailable');+ return ticket;+ },+ },+ });++ return client.subscribe(handlers);+}diff --git a/src/community/town.js b/src/community/town.jsnew file mode 100644index 000000000..9378f368f--- /dev/null+++ b/src/community/town.js@@ -0,0 +1,632 @@+// Town — the in-world social layer for a coin world.+//+// Each coin on /walk is its own CoinCommunities community. Town renders that+// community's persisted feed (a collapsible rail on desktop, a bottom sheet on+// mobile) and turns incoming realtime posts into speech bubbles that drift over+// the 3D scene — so the world feels inhabited even by people who aren't walking+// right now. Reads + realtime work with just the proxy's API key; posting is+// capability-gated and renders a designed locked state when unavailable.+//+// Self-contained: styles are injected once, nothing here depends on the build+// pipeline's CSS handling, and it appends to <body> without touching walk.js.++import { fetchCapabilities, fetchMessages, connectRealtime, postMessage } from './town-client.js';++const MAX_BUBBLES = 4;+const BUBBLE_TTL_MS = 7000;+const MAX_RENDERED = 80; // cap the rail DOM so a busy world never bloats memory++let _stylesInjected = false;++function injectStyles() {+ if (_stylesInjected) return;+ _stylesInjected = true;+ const style = document.createElement('style');+ style.id = 'town-styles';+ style.textContent = STYLES;+ document.head.appendChild(style);+}++function el(tag, cls, text) {+ const n = document.createElement(tag);+ if (cls) n.className = cls;+ if (text != null) n.textContent = text;+ return n;+}++function timeAgo(iso) {+ const t = typeof iso === 'string' ? Date.parse(iso) : iso;+ if (!Number.isFinite(t)) return '';+ const s = Math.max(0, (Date.now() - t) / 1000);+ if (s < 60) return `${s | 0}s`;+ if (s < 3600) return `${(s / 60) | 0}m`;+ if (s < 86400) return `${(s / 3600) | 0}h`;+ return `${(s / 86400) | 0}d`;+}++function compactNum(n) {+ n = Number(n) || 0;+ if (n < 1000) return String(n);+ if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`;+ return `${(n / 1_000_000).toFixed(1)}m`;+}++function initials(name) {+ return (name || '?').replace(/^@/, '').slice(0, 2).toUpperCase();+}++export class Town {+ /**+ * @param {object} opts+ * @param {string} opts.token community mint+ * @param {object} [opts.meta] { symbol, image, members, posts }+ */+ constructor({ token, meta = {} }) {+ this.token = token;+ this.meta = meta;+ this.messages = [];+ this.seen = new Set();+ this.caps = null;+ this.dispose = null;+ this.collapsed = matchMedia('(max-width: 768px)').matches;+ this._bubbleCount = 0;++ injectStyles();+ this._build();+ this._load();+ }++ // ── DOM ──────────────────────────────────────────────────────────────+ _build() {+ const root = el('aside', 'town');+ root.setAttribute('aria-label', `${this.meta.symbol || 'Coin'} community`);+ if (this.collapsed) root.classList.add('town--collapsed');+ this.root = root;++ // Header — coin identity, live status, counts, collapse toggle.+ const header = el('header', 'town__header');+ const badge = el('div', 'town__badge');+ if (this.meta.image) {+ const img = el('img', 'town__coin-img');+ img.src = this.meta.image;+ img.alt = '';+ img.loading = 'lazy';+ img.onerror = () => img.remove();+ badge.appendChild(img);+ } else {+ badge.appendChild(+ el('div', 'town__coin-img town__coin-img--ph', initials(this.meta.symbol)),+ );+ }+ const idCol = el('div', 'town__idcol');+ const title = el('div', 'town__title');+ title.appendChild(+ el('span', 'town__symbol', this.meta.symbol ? `$${this.meta.symbol}` : 'Coin world'),+ );+ this.statusDot = el('span', 'town__dot', '');+ this.statusDot.setAttribute('aria-label', 'connecting');+ title.appendChild(this.statusDot);+ idCol.appendChild(title);+ this.countsEl = el('div', 'town__counts', '');+ this._renderCounts();+ idCol.appendChild(this.countsEl);+ badge.appendChild(idCol);+ header.appendChild(badge);++ const toggle = el('button', 'town__toggle');+ toggle.type = 'button';+ toggle.setAttribute('aria-label', 'Toggle community panel');+ toggle.innerHTML = '<span></span>';+ toggle.addEventListener('click', () => this.toggle());+ header.appendChild(toggle);+ root.appendChild(header);++ // Body — message list (role=log for assistive tech).+ this.list = el('div', 'town__list');+ this.list.setAttribute('role', 'log');+ this.list.setAttribute('aria-live', 'polite');+ root.appendChild(this.list);+ this._renderSkeleton();++ // Composer — capability-gated; built after caps load.+ this.composer = el('div', 'town__composer');+ root.appendChild(this.composer);++ // Floating bubbles over the scene.+ this.bubbles = document.getElementById('town-bubbles') || el('div', 'town-bubbles');+ this.bubbles.id = 'town-bubbles';+ if (!this.bubbles.isConnected) document.body.appendChild(this.bubbles);++ document.body.appendChild(root);+ }++ _renderCounts() {+ const m = this.meta;+ const parts = [];+ if (m.members != null) parts.push(`${compactNum(m.members)} members`);+ if (m.posts != null) parts.push(`${compactNum(m.posts)} posts`);+ this.countsEl.textContent = parts.join(' · ');+ }++ _renderSkeleton() {+ this.list.innerHTML = '';+ for (let i = 0; i < 6; i++) {+ const row = el('div', 'town__msg town__msg--skel');+ row.appendChild(el('div', 'town__avatar town__skel'));+ const b = el('div', 'town__body');+ b.appendChild(el('div', 'town__skel town__skel--line'));+ b.appendChild(el('div', 'town__skel town__skel--line town__skel--short'));+ row.appendChild(b);+ this.list.appendChild(row);+ }+ }++ _renderEmpty() {+ this.list.innerHTML = '';+ const e = el('div', 'town__state');+ e.appendChild(el('div', 'town__state-emoji', '🌱'));+ e.appendChild(el('div', 'town__state-title', 'No posts yet'));+ e.appendChild(el('div', 'town__state-sub', 'Be the first voice in this world.'));+ this.list.appendChild(e);+ }++ _renderError(msg, retry) {+ this.list.innerHTML = '';+ const e = el('div', 'town__state');+ e.appendChild(el('div', 'town__state-emoji', '⚠️'));+ e.appendChild(el('div', 'town__state-title', 'Could not load the feed'));+ e.appendChild(el('div', 'town__state-sub', msg || 'Something went wrong.'));+ const btn = el('button', 'town__retry', 'Try again');+ btn.type = 'button';+ btn.addEventListener('click', retry);+ e.appendChild(btn);+ this.list.appendChild(e);+ }++ _msgRow(m) {+ const row = el('div', 'town__msg');+ row.dataset.id = m.id;+ const av = el('a', 'town__avatar');+ av.href = m.twitterUrl || '#';+ if (m.twitterUrl) {+ av.target = '_blank';+ av.rel = 'noopener';+ }+ if (m.avatar) {+ const img = el('img');+ img.src = m.avatar;+ img.alt = '';+ img.loading = 'lazy';+ img.onerror = () => {+ av.textContent = initials(m.username);+ };+ av.appendChild(img);+ } else {+ av.textContent = initials(m.username);+ }+ row.appendChild(av);++ const body = el('div', 'town__body');+ const meta = el('div', 'town__meta');+ const name = el('span', 'town__name', m.username || 'anon');+ meta.appendChild(name);+ if (m.followers > 0)+ meta.appendChild(el('span', 'town__followers', `${compactNum(m.followers)} followers`));+ meta.appendChild(el('span', 'town__time', timeAgo(m.createdAt)));+ body.appendChild(meta);+ body.appendChild(el('div', 'town__text', m.content));+ if (m.mediaUrl) {+ const img = el('img', 'town__media');+ img.src = m.mediaUrl;+ img.alt = '';+ img.loading = 'lazy';+ img.onerror = () => img.remove();+ body.appendChild(img);+ }+ const foot = el('div', 'town__foot');+ if (m.likes > 0) foot.appendChild(el('span', 'town__stat', `♥ ${compactNum(m.likes)}`));+ if (m.replies > 0) foot.appendChild(el('span', 'town__stat', `↩ ${compactNum(m.replies)}`));+ if (foot.childNodes.length) body.appendChild(foot);+ row.appendChild(body);+ return row;+ }++ _renderList() {+ if (!this.messages.length) return this._renderEmpty();+ this.list.innerHTML = '';+ for (const m of this.messages.slice(0, MAX_RENDERED)) {+ this.list.appendChild(this._msgRow(m));+ }+ }++ _prepend(m) {+ if (this.seen.has(m.id)) return;+ this.seen.add(m.id);+ this.messages.unshift(m);+ if (this.messages.length > MAX_RENDERED) this.messages.length = MAX_RENDERED;++ // Replace empty-state on first arrival.+ if (this.list.querySelector('.town__state')) this.list.innerHTML = '';+ const row = this._msgRow(m);+ row.classList.add('town__msg--enter');+ this.list.prepend(row);+ requestAnimationFrame(() => row.classList.remove('town__msg--enter'));+ while (this.list.children.length > MAX_RENDERED) this.list.lastChild.remove();+ }++ // ── Composer ─────────────────────────────────────────────────────────+ _buildComposer() {+ this.composer.innerHTML = '';+ if (!this.caps?.canPost) {+ // Designed locked state — explains why and what unlocks it, never a+ // dead input. Reads/realtime above are fully live regardless.+ const lock = el('div', 'town__locked');+ lock.appendChild(el('span', 'town__lock-icon', '🔒'));+ const t = el('div', 'town__lock-text');+ t.appendChild(el('strong', null, 'Posting opens soon'));+ t.appendChild(+ el(+ 'span',+ null,+ 'Connect this world to start posting. The live feed stays open to everyone.',+ ),+ );+ lock.appendChild(t);+ this.composer.appendChild(lock);+ return;+ }+ const form = el('form', 'town__form');+ const ta = el('textarea', 'town__input');+ ta.placeholder = `Say something in $${this.meta.symbol || 'this world'}…`;+ ta.maxLength = 2000;+ ta.rows = 1;+ ta.setAttribute('aria-label', 'Write a message');+ ta.addEventListener('input', () => {+ ta.style.height = 'auto';+ ta.style.height = `${Math.min(ta.scrollHeight, 120)}px`;+ });+ const send = el('button', 'town__send', 'Post');+ send.type = 'submit';+ form.appendChild(ta);+ form.appendChild(send);+ form.addEventListener('submit', (e) => {+ e.preventDefault();+ this._submit(ta, send);+ });+ this.composer.appendChild(form);+ }++ async _submit(ta, send) {+ const content = ta.value.trim();+ if (!content) return;+ // Posting identity (wallet + linked X id) comes from the platform's+ // auth layer. Until that's wired through, surface the precise blocker+ // rather than silently failing.+ const identity = window.__townIdentity;+ if (!identity?.walletAddress || !identity?.twitterId) {+ this._composerError('Connect your wallet and X account to post.');+ return;+ }+ send.disabled = true;+ ta.disabled = true;+ try {+ const posted = await postMessage(this.token, {+ content,+ walletAddress: identity.walletAddress,+ twitterId: identity.twitterId,+ });+ ta.value = '';+ ta.style.height = 'auto';+ if (posted) this._prepend(posted); // realtime will dedupe by id+ } catch (err) {+ this._composerError(err.message || 'Could not post.');+ } finally {+ send.disabled = false;+ ta.disabled = false;+ }+ }++ _composerError(msg) {+ let e = this.composer.querySelector('.town__cerr');+ if (!e) {+ e = el('div', 'town__cerr');+ this.composer.appendChild(e);+ }+ e.textContent = msg;+ clearTimeout(this._cerrTimer);+ this._cerrTimer = setTimeout(() => e.remove(), 5000);+ }++ // ── Bubbles ──────────────────────────────────────────────────────────+ _bubble(m) {+ if (this._bubbleCount >= MAX_BUBBLES) return;+ this._bubbleCount++;+ const b = el('div', 'town-bubble');+ const av = el('span', 'town-bubble__av');+ if (m.avatar) {+ const img = el('img');+ img.src = m.avatar;+ img.alt = '';+ img.onerror = () => {+ av.textContent = initials(m.username);+ };+ av.appendChild(img);+ } else {+ av.textContent = initials(m.username);+ }+ b.appendChild(av);+ const txt = el('span', 'town-bubble__txt');+ txt.appendChild(el('b', null, m.username || 'anon'));+ txt.appendChild(+ document.createTextNode(+ ' ' + (m.content.length > 90 ? m.content.slice(0, 88) + '…' : m.content),+ ),+ );+ b.appendChild(txt);+ this.bubbles.appendChild(b);+ requestAnimationFrame(() => b.classList.add('town-bubble--in'));+ setTimeout(() => {+ b.classList.remove('town-bubble--in');+ b.classList.add('town-bubble--out');+ setTimeout(() => {+ b.remove();+ this._bubbleCount--;+ }, 600);+ }, BUBBLE_TTL_MS);+ }++ // ── Status ───────────────────────────────────────────────────────────+ _setStatus(state) {+ const labels = { live: 'live', offline: 'offline', connecting: 'connecting' };+ this.statusDot.className = `town__dot town__dot--${state}`;+ this.statusDot.setAttribute('aria-label', labels[state] || state);+ }++ toggle() {+ this.collapsed = !this.collapsed;+ this.root.classList.toggle('town--collapsed', this.collapsed);+ }++ /** Merge in coin metadata that arrived after mount (e.g. enriched from /worlds). */+ updateMeta(meta = {}) {+ this.meta = { ...this.meta, ...meta };+ const sym = this.root.querySelector('.town__symbol');+ if (sym && this.meta.symbol) sym.textContent = `$${this.meta.symbol}`;+ const ph = this.root.querySelector('.town__coin-img--ph');+ if (ph && this.meta.image) {+ const img = el('img', 'town__coin-img');+ img.src = this.meta.image;+ img.alt = '';+ img.loading = 'lazy';+ img.onerror = () => img.remove();+ ph.replaceWith(img);+ }+ this._renderCounts();+ this.root.setAttribute('aria-label', `${this.meta.symbol || 'Coin'} community`);+ }++ // ── Lifecycle ──────────────────────────────────────────────────────────+ async _load() {+ this._setStatus('connecting');+ // Capabilities + first page of messages in parallel.+ const [caps, msgs] = await Promise.allSettled([+ fetchCapabilities(),+ fetchMessages(this.token, { limit: 50 }),+ ]);++ this.caps = caps.status === 'fulfilled' ? caps.value : null;+ this._buildComposer();++ if (msgs.status === 'rejected') {+ const err = msgs.reason;+ if (err?.code === 'cc_unconfigured') {+ this._renderError('This deployment has no CoinCommunities key yet.', () =>+ this._load(),+ );+ } else {+ this._renderError(err?.message, () => this._load());+ }+ this._setStatus('offline');+ return;+ }++ this.messages = msgs.value;+ for (const m of this.messages) this.seen.add(m.id);+ this._renderList();++ // Realtime — needs the CC origin from capabilities.+ if (this.caps?.baseUrl) this._connectRealtime();+ else this._setStatus('offline');+ }++ async _connectRealtime() {+ try {+ this.dispose = await connectRealtime(this.token, this.caps.baseUrl, {+ onConnect: () => this._setStatus('live'),+ onDisconnect: () => this._setStatus('offline'),+ onGap: () => this._refetch(),+ onMessage: (evt) => {+ const m = normalizeRealtime(evt, this.token);+ if (!m) return;+ this._prepend(m);+ if (!this.collapsed || matchMedia('(max-width: 768px)').matches)+ this._bubble(m);+ else this._bubble(m);+ },+ onLike: (evt) => this._applyLike(evt),+ });+ } catch (err) {+ console.warn('[town] realtime unavailable:', err?.message ?? err);+ this._setStatus('offline');+ }+ }++ async _refetch() {+ try {+ const latest = await fetchMessages(this.token, { limit: 50 });+ for (const m of latest.reverse()) this._prepend(m);+ } catch {+ /* transient — realtime will catch up */+ }+ }++ _applyLike(evt) {+ const id = evt?.messageId || evt?.message_id || evt?.id;+ if (!id) return;+ const msg = this.messages.find((m) => m.id === id);+ if (msg && typeof evt.likeCount === 'number') {+ msg.likes = evt.likeCount;+ const row = this.list.querySelector(`[data-id="${CSS.escape(id)}"] .town__foot`);+ if (row) {+ const stat = row.querySelector('.town__stat');+ if (stat) stat.textContent = `♥ ${compactNum(msg.likes)}`;+ }+ }+ }++ destroy() {+ try {+ this.dispose?.();+ } catch {+ /* already gone */+ }+ this.dispose = null;+ this.root?.remove();+ this.bubbles?.remove();+ }+}++/**+ * Realtime envelopes carry the persisted message under a few possible keys+ * depending on event shape — normalize to Town's row model defensively.+ */+function normalizeRealtime(evt, token) {+ const m = evt?.message || evt?.data || evt;+ if (!m || !m.id || !(m.content ?? '').toString().trim()) return null;+ return {+ id: m.id,+ token,+ content: m.content,+ mediaUrl: m.mediaUrl || null,+ username: m.username || 'anon',+ avatar: m.profileImageUrl || m.avatar || null,+ twitterUrl: m.userTwitterUrl || m.twitterUrl || null,+ followers: m.followerCount ?? 0,+ likes: m.likeCount ?? 0,+ replies: m.replyCount ?? 0,+ createdAt: m.createdAt || Date.now(),+ };+}++export function mountTown(opts) {+ return new Town(opts);+}++// ── Styles ───────────────────────────────────────────────────────────────+const STYLES = `+.town{position:fixed;top:0;right:0;height:100dvh;width:360px;max-width:88vw;z-index:40;+ display:flex;flex-direction:column;color:#e8eefb;font:14px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;+ background:linear-gradient(180deg,rgba(13,18,34,.92),rgba(9,12,24,.96));+ backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);+ border-left:1px solid rgba(120,150,220,.16);box-shadow:-18px 0 50px rgba(0,0,0,.35);+ transform:translateX(0);transition:transform .32s cubic-bezier(.16,1,.3,1)}+.town--collapsed{transform:translateX(calc(100% - 56px))}+.town__header{display:flex;align-items:center;gap:10px;padding:14px 14px 12px;+ border-bottom:1px solid rgba(120,150,220,.12);flex:0 0 auto}+.town__badge{display:flex;align-items:center;gap:10px;min-width:0;flex:1}+.town__coin-img{width:38px;height:38px;border-radius:11px;object-fit:cover;flex:0 0 auto;+ background:#16203a;border:1px solid rgba(120,150,220,.22)}+.town__coin-img--ph{display:grid;place-items:center;font-weight:700;font-size:13px;color:#9fb4e6;+ background:linear-gradient(135deg,#23304f,#16203a)}+.town__idcol{min-width:0}+.town__title{display:flex;align-items:center;gap:7px}+.town__symbol{font-weight:700;font-size:15px;letter-spacing:.2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.town__dot{width:8px;height:8px;border-radius:50%;background:#6b7689;flex:0 0 auto;transition:background .3s,box-shadow .3s}+.town__dot--connecting{background:#e6b04a;box-shadow:0 0 0 0 rgba(230,176,74,.5);animation:town-pulse 1.4s infinite}+.town__dot--live{background:#3fd07f;box-shadow:0 0 8px rgba(63,208,127,.8)}+.town__dot--offline{background:#e5564b}+@keyframes town-pulse{0%{box-shadow:0 0 0 0 rgba(230,176,74,.45)}70%{box-shadow:0 0 0 7px rgba(230,176,74,0)}100%{box-shadow:0 0 0 0 rgba(230,176,74,0)}}+.town__counts{font-size:11.5px;color:#8ea0c6;margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.town__toggle{flex:0 0 auto;width:30px;height:30px;border-radius:9px;border:1px solid rgba(120,150,220,.2);+ background:rgba(255,255,255,.04);cursor:pointer;display:grid;place-items:center;transition:background .2s}+.town__toggle:hover{background:rgba(255,255,255,.1)}+.town__toggle:focus-visible{outline:2px solid #5b8cff;outline-offset:2px}+.town__toggle span{display:block;width:9px;height:9px;border-right:2px solid #cdd9f5;border-bottom:2px solid #cdd9f5;+ transform:rotate(-45deg);transition:transform .3s;margin-right:2px}+.town--collapsed .town__toggle span{transform:rotate(135deg);margin:0 0 0 3px}+.town__list{flex:1 1 auto;overflow-y:auto;overflow-x:hidden;padding:8px 10px;display:flex;flex-direction:column;gap:2px;+ scrollbar-width:thin;scrollbar-color:rgba(120,150,220,.3) transparent}+.town__list::-webkit-scrollbar{width:7px}.town__list::-webkit-scrollbar-thumb{background:rgba(120,150,220,.3);border-radius:4px}+.town__msg{display:flex;gap:10px;padding:9px 8px;border-radius:12px;transition:background .15s;align-items:flex-start}+.town__msg:hover{background:rgba(255,255,255,.035)}+.town__msg--enter{opacity:0;transform:translateY(-8px)}+.town__msg{opacity:1;transform:none;transition:opacity .35s ease,transform .35s cubic-bezier(.16,1,.3,1),background .15s}+.town__avatar{width:36px;height:36px;border-radius:50%;flex:0 0 auto;overflow:hidden;display:grid;place-items:center;+ background:linear-gradient(135deg,#2b3a5e,#18233e);color:#a9bbe6;font-weight:700;font-size:13px;text-decoration:none;+ border:1px solid rgba(120,150,220,.18)}+.town__avatar img{width:100%;height:100%;object-fit:cover}+.town__body{min-width:0;flex:1}+.town__meta{display:flex;align-items:baseline;gap:7px;flex-wrap:wrap}+.town__name{font-weight:650;color:#f0f4ff;font-size:13.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:150px}+.town__followers{font-size:11px;color:#8093ba}+.town__time{font-size:11px;color:#6f7fa3;margin-left:auto}+.town__text{margin-top:2px;color:#d7e0f4;word-wrap:break-word;overflow-wrap:anywhere;white-space:pre-wrap}+.town__media{margin-top:7px;max-width:100%;border-radius:10px;display:block;border:1px solid rgba(120,150,220,.14)}+.town__foot{display:flex;gap:14px;margin-top:6px}+.town__stat{font-size:11.5px;color:#8aa0cf}+.town__state{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:7px;+ text-align:center;padding:40px 24px;color:#9aabd0}+.town__state-emoji{font-size:30px}+.town__state-title{font-weight:650;color:#dde6fb}+.town__state-sub{font-size:12.5px;color:#8093ba;max-width:230px}+.town__retry{margin-top:8px;padding:8px 16px;border-radius:9px;border:1px solid rgba(120,150,220,.3);+ background:rgba(91,140,255,.16);color:#cfe0ff;cursor:pointer;font-weight:600;transition:background .2s}+.town__retry:hover{background:rgba(91,140,255,.28)}+.town__skel{background:linear-gradient(90deg,rgba(255,255,255,.05),rgba(255,255,255,.11),rgba(255,255,255,.05));+ background-size:200% 100%;animation:town-shimmer 1.3s infinite;border-radius:7px}+.town__msg--skel{pointer-events:none}+.town__skel--line{height:11px;margin:5px 0;width:90%}+.town__skel--short{width:55%}+.town__avatar.town__skel{border-radius:50%}+@keyframes town-shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}+.town__composer{flex:0 0 auto;padding:10px 12px;border-top:1px solid rgba(120,150,220,.12);background:rgba(8,11,22,.5)}+.town__form{display:flex;gap:8px;align-items:flex-end}+.town__input{flex:1;resize:none;background:rgba(255,255,255,.05);border:1px solid rgba(120,150,220,.2);+ border-radius:11px;color:#eaf0ff;padding:9px 11px;font:inherit;line-height:1.4;max-height:120px;transition:border-color .2s}+.town__input:focus{outline:none;border-color:#5b8cff;background:rgba(255,255,255,.08)}+.town__send{flex:0 0 auto;padding:9px 16px;border-radius:11px;border:0;cursor:pointer;font-weight:650;+ background:linear-gradient(135deg,#5b8cff,#7c5bff);color:#fff;transition:filter .2s,opacity .2s}+.town__send:hover{filter:brightness(1.1)}.town__send:disabled{opacity:.5;cursor:default}+.town__locked{display:flex;gap:11px;align-items:center;padding:11px 12px;border-radius:12px;+ background:rgba(255,255,255,.035);border:1px dashed rgba(120,150,220,.22)}+.town__lock-icon{font-size:17px;flex:0 0 auto;opacity:.85}+.town__lock-text{display:flex;flex-direction:column;gap:2px;font-size:12px;color:#9fb0d4}+.town__lock-text strong{color:#dde6fb;font-size:12.5px}+.town__cerr{margin-top:8px;font-size:12px;color:#ffb4ad}+.town-bubbles{position:fixed;top:84px;left:50%;transform:translateX(-50%);z-index:35;+ display:flex;flex-direction:column;gap:8px;align-items:center;pointer-events:none;width:min(560px,92vw)}+.town-bubble{display:flex;gap:9px;align-items:center;max-width:100%;padding:8px 14px 8px 8px;border-radius:999px;+ background:linear-gradient(180deg,rgba(20,27,47,.92),rgba(13,18,34,.94));border:1px solid rgba(120,150,220,.22);+ box-shadow:0 8px 28px rgba(0,0,0,.4);color:#e8eefb;font-size:13px;+ opacity:0;transform:translateY(-12px) scale(.96);transition:opacity .4s,transform .4s cubic-bezier(.16,1,.3,1)}+.town-bubble--in{opacity:1;transform:translateY(0) scale(1)}+.town-bubble--out{opacity:0;transform:translateY(-10px) scale(.97)}+.town-bubble__av{width:28px;height:28px;border-radius:50%;flex:0 0 auto;overflow:hidden;display:grid;place-items:center;+ background:linear-gradient(135deg,#2b3a5e,#18233e);color:#a9bbe6;font-weight:700;font-size:11px}+.town-bubble__av img{width:100%;height:100%;object-fit:cover}+.town-bubble__txt{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.town-bubble__txt b{color:#9fc0ff;margin-right:3px}+@media (max-width:768px){+ .town{top:auto;bottom:0;right:0;left:0;width:100%;max-width:100%;height:62dvh;border-left:0;+ border-top:1px solid rgba(120,150,220,.16);border-radius:18px 18px 0 0;+ transform:translateY(0);transition:transform .32s cubic-bezier(.16,1,.3,1)}+ .town--collapsed{transform:translateY(calc(100% - 58px))}+ .town__toggle span{transform:rotate(45deg)}+ .town--collapsed .town__toggle span{transform:rotate(-135deg);margin:3px 0 0}+ .town-bubbles{top:64px}+}+@media (prefers-reduced-motion:reduce){+ .town,.town__msg,.town-bubble{transition:none}+ .town__dot--connecting,.town__skel{animation:none}+}+`;diff --git a/src/create.js b/src/create.jsindex cce137ee9..a0ead15a9 100644--- a/src/create.js+++ b/src/create.js@@ -148,7 +148,7 @@ async function boot() {}if (!requireAuthForSelfie()) return;if (await isAtAvatarLimit()) return;- window.location.href = '/create/selfie';+ window.location.href = '/scan';});wireCard('card-video-avatar', () => {if (!_videoAvatarReady) {diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.jsnew file mode 100644index 000000000..f5b0ca19c--- /dev/null+++ b/src/game/coincommunities-ui.js@@ -0,0 +1,273 @@+// Coin Communities UI layer — lobby + in-world chrome.+//+// Two surfaces:+// 1. Lobby: live pump.fun coin grid (each coin = a community to enter) + a+// zero-friction avatar picker (presets, or paste your own avatar / 3D+// agent GLB URL or three.ws avatar id).+// 2. In-world HUD: coin banner + online count, chat, emote tray, leave.+//+// The 3D scene (coincommunities.js) owns WebGL + projected name labels; this+// module owns the 2D chrome and calls back through the handlers passed in.++function el(tag, props = {}, kids = []) {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(props)) {+ if (k === 'class') n.className = v;+ else if (k === 'text') n.textContent = v;+ else if (k === 'html') n.innerHTML = v;+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);+ else if (v !== null && v !== undefined && v !== false) n.setAttribute(k, v === true ? '' : v);+ }+ for (const kid of [].concat(kids)) if (kid != null && kid !== false) n.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);+ return n;+}++const fmtMc = (n) => {+ if (!n || !isFinite(n)) return null;+ if (n >= 1e9) return '$' + (n / 1e9).toFixed(1) + 'B';+ if (n >= 1e6) return '$' + (n / 1e6).toFixed(1) + 'M';+ if (n >= 1e3) return '$' + (n / 1e3).toFixed(1) + 'K';+ return '$' + Math.round(n);+};++const DEFAULT_AVATAR = '/avatars/default.glb';++export class CommunityUI {+ /**+ * @param {object} h handlers: { onEnter(coin), onLeave(), onChat(text), onEmote(name) }+ */+ constructor(h) {+ this.h = h;+ this.coins = [];+ this.avatar = localStorage.getItem('cc-avatar') || DEFAULT_AVATAR;+ this._buildLobby();+ this._buildHud();+ }++ // ---------------------------------------------------------------- lobby+ _buildLobby() {+ this.searchInput = el('input', { type: 'text', placeholder: 'Search coins…', oninput: () => this._renderGrid() });+ this.grid = el('div', { class: 'cc-grid' });++ this.presetRow = el('div', { class: 'cc-avatar-presets' });+ this.customInput = el('input', {+ type: 'text',+ placeholder: 'Paste avatar / 3D agent GLB URL or avatar id',+ value: /^https?:|^\//.test(this.avatar) && this.avatar !== DEFAULT_AVATAR ? this.avatar : '',+ onchange: () => { this._setAvatar(this.customInput.value.trim() || DEFAULT_AVATAR, 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('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.' }),+ ]),+ ]),+ el('div', { class: 'cc-search' }, [el('span', { text: '🔎' }), this.searchInput]),+ ]),+ 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.presetRow,+ el('div', { class: 'cc-avatar-custom' }, [this.customInput]),+ ]),+ el('p', { class: 'cc-section-title', text: 'Live communities' }),+ this.grid,+ ]),+ ]);+ document.body.appendChild(this.lobby);++ this._renderPresets();+ this.setCoinsLoading();+ }++ async _renderPresets() {+ // Default + a few real three.ws community avatars (best-effort fetch).+ const presets = [{ label: 'Default', url: DEFAULT_AVATAR, icon: '🧍' }];+ try {+ const r = await fetch('/api/explore?source=avatar&only3d=1&limit=6', { headers: { accept: 'application/json' } });+ if (r.ok) {+ const data = await r.json();+ for (const it of (data.items || [])) {+ if (it.glbUrl) presets.push({ label: it.name || 'Avatar', url: it.glbUrl, thumb: it.image });+ }+ }+ } catch { /* offline / no API — default preset still works */ }+ this.presets = presets.slice(0, 7);+ this.presetRow.textContent = '';+ for (const p of this.presets) {+ const chip = el('button', {+ class: 'cc-avatar-chip' + (p.url === this.avatar ? ' cc-on' : ''),+ title: p.label,+ onclick: () => this._setAvatar(p.url, false),+ }, p.thumb ? [el('img', { src: p.thumb, alt: p.label, loading: 'lazy' })] : [document.createTextNode(p.icon || '🙂')]);+ chip._url = p.url;+ this.presetRow.appendChild(chip);+ }+ }++ _setAvatar(url, fromCustom) {+ this.avatar = url || DEFAULT_AVATAR;+ localStorage.setItem('cc-avatar', this.avatar);+ for (const chip of this.presetRow.children) chip.classList.toggle('cc-on', chip._url === this.avatar);+ if (!fromCustom) this.customInput.value = (this.avatar === DEFAULT_AVATAR || !/^https?:|^\//.test(this.avatar)) ? '' : this.avatar;+ this.h.onAvatarChange?.(this.avatar);+ }++ getAvatar() { return this.customInput.value.trim() || this.avatar; }++ setCoinsLoading() {+ this.grid.textContent = '';+ for (let i = 0; i < 8; i++) {+ this.grid.appendChild(el('div', { class: 'cc-card cc-skeleton' }, [+ el('div', { class: 'cc-card-img' }),+ el('div', { class: 'cc-card-body' }, [el('div', { class: 'cc-card-name' }), el('div', { class: 'cc-card-meta' })]),+ ]));+ }+ }++ setCoins(list) { this.coins = list || []; this._renderGrid(); }++ setCoinsError(retry) {+ this.grid.textContent = '';+ this.grid.appendChild(el('div', { class: 'cc-state' }, [+ el('span', { class: 'cc-state-ico', text: '📡' }),+ el('div', { text: 'Could not load live coins right now.' }),+ el('button', { text: 'Retry', onclick: retry }),+ ]));+ }++ _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));+ this.grid.textContent = '';+ if (!list.length) {+ 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!' }),+ ]));+ return;+ }+ for (const c of list) {+ const mc = fmtMc(c.marketCap);+ const card = el('div', { class: 'cc-card', onclick: () => this.h.onEnter(c) }, [+ el('div', { class: 'cc-card-img', style: c.image ? `background-image:url("${c.image}")` : '' }, [+ el('span', { class: 'cc-card-live' }, [el('span', { class: 'cc-dot' }), document.createTextNode('LIVE')]),+ ]),+ el('div', { class: 'cc-card-body' }, [+ el('div', { class: 'cc-card-name', text: c.name || 'Unnamed coin' }),+ el('div', { class: 'cc-card-meta' }, [+ el('span', { class: 'cc-card-sym', text: c.symbol ? '$' + c.symbol : '' }),+ mc ? el('span', { text: mc + ' mcap' }) : null,+ ]),+ el('div', { class: 'cc-card-cta', text: 'Enter community →' }),+ ]),+ ]);+ this.grid.appendChild(card);+ }+ }++ // ---------------------------------------------------------------- HUD+ _buildHud() {+ this.coinImg = el('img', { class: 'cc-coin-img', alt: '' });+ this.coinName = el('div', { class: 'cc-coin-name', text: '' });+ this.coinSym = el('span', { class: 'cc-coin-sym', text: '' });+ this.onlineCount = el('span', { text: '1 online' });+ const banner = el('div', { class: 'cc-coin-banner' }, [+ this.coinImg,+ el('div', { class: 'cc-coin-info' }, [+ this.coinName,+ el('div', { class: 'cc-coin-sub' }, [+ this.coinSym,+ el('span', { class: 'cc-online' }, [el('span', { class: 'cc-dot' }), this.onlineCount]),+ ]),+ ]),+ ]);++ const leave = el('button', { class: 'cc-leave', onclick: () => this.h.onLeave() }, [+ el('span', { text: '←' }), document.createTextNode('Communities'),+ ]);++ this.statusText = el('span', { text: 'connecting…' });+ this.statusPill = el('div', {+ id: 'cc-status', 'data-state': 'connecting',+ onclick: () => { if (['offline', 'failed'].includes(this.statusPill.getAttribute('data-state'))) this.h.onRetry?.(); },+ }, [el('span', { class: 'cc-dot' }), this.statusText]);++ this.chatLog = el('div', { class: 'cc-chat-log' });+ this.chatInput = el('input', {+ type: 'text', maxlength: '200', placeholder: 'Say something…',+ onkeydown: (e) => { if (e.key === 'Enter') this._sendChat(); e.stopPropagation(); },+ });+ const chat = el('div', { id: 'cc-chat' }, [+ this.chatLog,+ el('div', { class: 'cc-chat-input' }, [this.chatInput, el('button', { text: 'Send', onclick: () => this._sendChat() })]),+ ]);++ this.emoteTray = el('div', { id: 'cc-emotes' });++ const hint = el('div', { id: 'cc-hint', html:+ '<kbd>W A S D</kbd> / drag-joystick to move · <kbd>drag</kbd> to look · scroll zoom · <kbd>Enter</kbd> chat' });++ this.joystick = el('div', { id: 'cc-joystick' });++ this.hud = el('div', { id: 'cc-hud', hidden: true }, [banner, leave, this.statusPill, chat, this.emoteTray, hint, this.joystick]);+ document.body.appendChild(this.hud);+ }++ setEmotes(list) {+ this.emoteTray.textContent = '';+ for (const e of list) {+ this.emoteTray.appendChild(el('button', {+ class: 'cc-emote', title: e.label || e.name, text: e.icon || '🙂',+ onclick: () => this.h.onEmote(e.name),+ }));+ }+ }++ _sendChat() {+ const text = this.chatInput.value.trim();+ if (!text) return;+ this.h.onChat(text);+ this.chatInput.value = '';+ }++ enterWorld(coin) {+ this.lobby.hidden = true;+ this.hud.hidden = false;+ this.coinName.textContent = coin.name || 'Community';+ this.coinSym.textContent = coin.symbol ? '$' + coin.symbol : '';+ if (coin.image) { this.coinImg.src = coin.image; this.coinImg.style.display = ''; }+ else this.coinImg.style.display = 'none';+ this.chatLog.textContent = '';+ }++ showLobby() {+ this.hud.hidden = true;+ this.lobby.hidden = false;+ this._renderGrid();+ }++ setStatus(state) {+ const labels = { connecting: 'connecting…', online: 'connected', offline: 'reconnecting…', failed: 'offline — retry', idle: 'idle' };+ this.statusPill.setAttribute('data-state', state);+ this.statusText.textContent = labels[state] || state;+ }++ setOnline(n) { this.onlineCount.textContent = `${n} online`; }++ addChat({ name, text, mine }) {+ const row = el('div', { class: 'cc-chat-msg' + (mine ? ' cc-mine' : '') }, [+ el('b', { text: name + ':' }), document.createTextNode(text),+ ]);+ this.chatLog.appendChild(row);+ while (this.chatLog.children.length > 60) this.chatLog.removeChild(this.chatLog.firstChild);+ this.chatLog.scrollTop = this.chatLog.scrollHeight;+ }++ get chatFocused() { return document.activeElement === this.chatInput; }+}diff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssnew file mode 100644index 000000000..945995e23--- /dev/null+++ b/src/game/coincommunities.css@@ -0,0 +1,265 @@+/* Coin Communities — 3D metaverse client UI: lobby + in-world HUD.+ Overlays the WebGL canvas. Self-contained tokens so /play stands alone. */++:root {+ --cc-bg: #0b1020;+ --cc-bg2: #131b33;+ --cc-panel: rgba(16, 22, 42, 0.92);+ --cc-edge: rgba(122, 162, 224, 0.26);+ --cc-edge-hi: #5fa1cf;+ --cc-text: #eaf1ff;+ --cc-dim: #93a6c8;+ --cc-accent: #5fa1cf;+ --cc-accent2: #7c5cff;+ --cc-green: #46d07f;+ --cc-gold: #ffce5c;+ --cc-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);+ --cc-radius: 14px;+}+* { box-sizing: border-box; }+html, body {+ margin: 0; height: 100%; overflow: hidden;+ background: var(--cc-bg); color: var(--cc-text);+ font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;+ -webkit-font-smoothing: antialiased; overscroll-behavior: none;+}+#kx-canvas, #cc-canvas {+ position: fixed; inset: 0; width: 100%; height: 100%; display: block;+ touch-action: none; cursor: grab;+}+#cc-canvas:active { cursor: grabbing; }+[hidden] { display: none !important; }++/* ---------------- loading ---------------- */+#kx-loading, #cc-loading {+ position: fixed; inset: 0; display: grid; place-items: center; z-index: 80;+ background: radial-gradient(circle at 50% 35%, #1b2750, #070b16 72%);+ 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-mark {+ font-family: "Cinzel", Georgia, serif; font-weight: 700;+ font-size: clamp(28px, 6vw, 54px); letter-spacing: 0.16em;+ background: linear-gradient(180deg, #fff, #9fc4ef);+ -webkit-background-clip: text; background-clip: text; color: transparent;+}+.kx-loading-sub { color: var(--cc-dim); margin-top: 6px; font-size: 14px; }+.kx-spinner, .cc-spinner {+ margin: 22px auto 0; width: 30px; height: 30px;+ border: 3px solid rgba(255,255,255,0.15); border-top-color: var(--cc-accent);+ border-radius: 50%; animation: cc-spin 0.8s linear infinite;+}+@keyframes cc-spin { to { transform: rotate(360deg); } }++/* ---------------- lobby ---------------- */+#cc-lobby {+ position: fixed; inset: 0; z-index: 60; overflow-y: auto;+ background:+ radial-gradient(900px 500px at 80% -10%, rgba(124,92,255,0.18), transparent 60%),+ radial-gradient(800px 500px at 10% 110%, rgba(95,161,207,0.16), transparent 60%),+ var(--cc-bg);+ animation: cc-fade 0.4s ease;+}+@keyframes cc-fade { from { opacity: 0; } }+.cc-lobby-inner { max-width: 1120px; margin: 0 auto; padding: 28px 22px 60px; }+.cc-lobby-head { display: flex; align-items: flex-end; gap: 16px; flex-wrap: wrap; margin-bottom: 18px; }+.cc-brand { display: flex; align-items: center; gap: 12px; }+.cc-brand-logo {+ width: 44px; height: 44px; border-radius: 12px;+ background: linear-gradient(135deg, var(--cc-accent), var(--cc-accent2));+ display: grid; place-items: center; font-size: 24px; box-shadow: var(--cc-shadow);+}+.cc-brand-title { font-size: 22px; font-weight: 800; letter-spacing: -0.01em; }+.cc-brand-sub { color: var(--cc-dim); font-size: 13px; margin-top: 1px; }+.cc-search {+ margin-left: auto; flex: 1; min-width: 220px; max-width: 360px;+ display: flex; align-items: center; gap: 8px;+ background: var(--cc-panel); border: 1px solid var(--cc-edge);+ border-radius: 999px; padding: 9px 15px;+}+.cc-search input { flex: 1; background: none; border: none; color: var(--cc-text); font-size: 14px; outline: none; }+.cc-search input::placeholder { color: var(--cc-dim); }++/* avatar picker */+.cc-avatar-bar {+ display: flex; align-items: center; gap: 16px; flex-wrap: wrap;+ background: var(--cc-panel); border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius); padding: 14px 16px; margin-bottom: 22px;+ box-shadow: var(--cc-shadow);+}+.cc-avatar-label { font-weight: 700; font-size: 14px; }+.cc-avatar-label small { display: block; color: var(--cc-dim); font-weight: 400; font-size: 12px; margin-top: 2px; }+.cc-avatar-presets { display: flex; gap: 8px; flex-wrap: wrap; }+.cc-avatar-chip {+ width: 50px; height: 50px; border-radius: 12px; overflow: hidden;+ border: 2px solid var(--cc-edge); background: var(--cc-bg2);+ cursor: pointer; padding: 0; display: grid; place-items: center; font-size: 22px;+ transition: border-color 0.12s ease, transform 0.08s ease;+}+.cc-avatar-chip img { width: 100%; height: 100%; object-fit: cover; }+.cc-avatar-chip:hover { transform: translateY(-2px); border-color: var(--cc-edge-hi); }+.cc-avatar-chip.cc-on { border-color: var(--cc-edge-hi); box-shadow: 0 0 0 2px rgba(95,161,207,0.5); }+.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);+ border-radius: 9px; padding: 9px 12px; color: var(--cc-text); font-size: 13px; outline: none;+}+.cc-avatar-custom input:focus { border-color: var(--cc-edge-hi); }++/* coin grid */+.cc-section-title { font-size: 13px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--cc-dim); margin: 8px 2px 12px; }+.cc-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 14px; }+.cc-card {+ background: var(--cc-panel); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);+ overflow: hidden; cursor: pointer; transition: transform 0.1s ease, border-color 0.12s ease, box-shadow 0.12s ease;+ display: flex; flex-direction: column;+}+.cc-card:hover { transform: translateY(-3px); border-color: var(--cc-edge-hi); box-shadow: var(--cc-shadow); }+.cc-card-img { aspect-ratio: 16/10; background: var(--cc-bg2) center/cover no-repeat; position: relative; }+.cc-card-img::after { content: ""; position: absolute; inset: 0; background: linear-gradient(180deg, transparent 50%, rgba(11,16,32,0.85)); }+.cc-card-live {+ position: absolute; top: 8px; left: 8px; z-index: 1;+ display: inline-flex; align-items: center; gap: 5px;+ background: rgba(0,0,0,0.55); border-radius: 999px; padding: 3px 9px; font-size: 11px; font-weight: 700;+}+.cc-card-live .cc-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--cc-green); box-shadow: 0 0 6px var(--cc-green); }+.cc-card-body { padding: 11px 13px 13px; display: flex; flex-direction: column; gap: 3px; }+.cc-card-name { font-weight: 700; font-size: 15px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.cc-card-meta { display: flex; align-items: center; gap: 8px; color: var(--cc-dim); font-size: 12px; }+.cc-card-sym { color: var(--cc-accent); font-weight: 700; }+.cc-card-cta {+ margin-top: 9px; padding: 8px 0; text-align: center; border-radius: 9px;+ background: linear-gradient(135deg, var(--cc-accent), var(--cc-accent2));+ color: #fff; font-weight: 700; font-size: 13px;+}+.cc-skeleton { pointer-events: none; }+.cc-skeleton .cc-card-img, .cc-skeleton .cc-card-name, .cc-skeleton .cc-card-meta {+ background: linear-gradient(90deg, rgba(255,255,255,0.05), rgba(255,255,255,0.12), rgba(255,255,255,0.05));+ background-size: 200% 100%; animation: cc-shimmer 1.3s infinite; color: transparent; border-radius: 6px;+}+.cc-skeleton .cc-card-name { height: 16px; width: 70%; margin: 2px 0; }+.cc-skeleton .cc-card-meta { height: 12px; width: 45%; }+@keyframes cc-shimmer { to { background-position: -200% 0; } }+.cc-state {+ grid-column: 1 / -1; text-align: center; color: var(--cc-dim);+ padding: 50px 20px; font-size: 14px;+}+.cc-state .cc-state-ico { font-size: 36px; display: block; margin-bottom: 10px; opacity: 0.7; }+.cc-state button {+ margin-top: 14px; background: var(--cc-accent); border: none; color: #04223a;+ font-weight: 700; padding: 9px 18px; border-radius: 9px; cursor: pointer; font-size: 13px;+}++/* ---------------- in-world HUD ---------------- */+#cc-hud { position: fixed; inset: 0; z-index: 20; pointer-events: none; }+#cc-hud > * { pointer-events: auto; }++.cc-coin-banner {+ position: fixed; top: 14px; left: 14px;+ display: flex; align-items: center; gap: 11px;+ background: var(--cc-panel); border: 1px solid var(--cc-edge);+ border-radius: 14px; padding: 9px 14px 9px 10px; box-shadow: var(--cc-shadow);+ backdrop-filter: blur(8px); max-width: 70vw;+}+.cc-coin-img { width: 40px; height: 40px; border-radius: 10px; object-fit: cover; background: var(--cc-bg2); flex: none; }+.cc-coin-info { min-width: 0; }+.cc-coin-name { font-weight: 800; font-size: 15px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.cc-coin-sub { display: flex; align-items: center; gap: 8px; color: var(--cc-dim); font-size: 12px; margin-top: 1px; }+.cc-coin-sym { color: var(--cc-accent); font-weight: 700; }+.cc-online { display: inline-flex; align-items: center; gap: 5px; }+.cc-online .cc-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--cc-green); box-shadow: 0 0 6px var(--cc-green); }++.cc-leave {+ position: fixed; top: 14px; right: 14px;+ display: inline-flex; align-items: center; gap: 7px;+ background: var(--cc-panel); border: 1px solid var(--cc-edge); border-radius: 999px;+ padding: 8px 14px; color: var(--cc-text); font-weight: 600; font-size: 13px; cursor: pointer;+ box-shadow: var(--cc-shadow); backdrop-filter: blur(8px);+}+.cc-leave:hover { border-color: var(--cc-edge-hi); }++#cc-status {+ position: fixed; top: 60px; right: 14px;+ display: inline-flex; align-items: center; gap: 7px;+ padding: 5px 11px; font-size: 12px; font-weight: 600; border-radius: 999px;+ background: var(--cc-panel); border: 1px solid var(--cc-edge);+}+#cc-status .cc-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--cc-dim); }+#cc-status[data-state="online"] .cc-dot { background: var(--cc-green); box-shadow: 0 0 8px var(--cc-green); }+#cc-status[data-state="connecting"] .cc-dot { background: var(--cc-gold); animation: cc-pulse 1s infinite; }+#cc-status[data-state="offline"] .cc-dot, #cc-status[data-state="failed"] .cc-dot { background: #e5564b; }+#cc-status[data-state="offline"], #cc-status[data-state="failed"] { cursor: pointer; }+@keyframes cc-pulse { 50% { opacity: 0.35; } }++/* chat */+#cc-chat { position: fixed; left: 14px; bottom: 14px; width: min(340px, 80vw); z-index: 21; }+.cc-chat-log {+ display: flex; flex-direction: column; gap: 5px; max-height: 34vh; overflow-y: auto;+ margin-bottom: 8px; padding-right: 4px; mask-image: linear-gradient(180deg, transparent, #000 22%);+}+.cc-chat-msg {+ background: var(--cc-panel); border: 1px solid var(--cc-edge); border-radius: 11px;+ padding: 6px 11px; font-size: 13px; align-self: flex-start; max-width: 100%;+ animation: cc-msg-in 0.18s ease; word-break: break-word;+}+.cc-chat-msg b { color: var(--cc-accent); margin-right: 5px; }+.cc-chat-msg.cc-mine b { color: var(--cc-green); }+@keyframes cc-msg-in { from { opacity: 0; transform: translateY(6px); } }+.cc-chat-input {+ display: flex; gap: 7px; background: var(--cc-panel); border: 1px solid var(--cc-edge);+ border-radius: 11px; padding: 7px 9px;+}+.cc-chat-input input { flex: 1; background: none; border: none; color: var(--cc-text); font-size: 13px; outline: none; }+.cc-chat-input input::placeholder { color: var(--cc-dim); }+.cc-chat-input button {+ background: var(--cc-accent); border: none; color: #04223a; font-weight: 700;+ border-radius: 8px; padding: 0 12px; cursor: pointer; font-size: 13px;+}++/* emote tray */+#cc-emotes {+ position: fixed; left: 50%; bottom: 16px; transform: translateX(-50%); z-index: 21;+ display: flex; gap: 7px; background: var(--cc-panel); border: 1px solid var(--cc-edge);+ border-radius: 14px; padding: 7px; box-shadow: var(--cc-shadow);+}+.cc-emote {+ width: 44px; height: 44px; border-radius: 10px; border: 1px solid transparent;+ background: rgba(255,255,255,0.05); cursor: pointer; font-size: 22px;+ transition: transform 0.08s ease, background 0.12s ease;+}+.cc-emote:hover { background: rgba(95,161,207,0.22); transform: translateY(-3px); }++/* chat bubbles over avatars + name labels */+.cc-label, .cc-bubble {+ position: fixed; left: 0; top: 0; z-index: 15; pointer-events: none;+ transform: translate(-50%, -100%); white-space: nowrap;+}+.cc-label {+ font-size: 12px; font-weight: 700; color: #fff;+ text-shadow: 0 1px 3px rgba(0,0,0,0.85); padding: 1px 6px;+}+.cc-bubble {+ background: #fff; color: #11203a; font-size: 13px; font-weight: 600;+ padding: 5px 10px; border-radius: 12px; max-width: 220px; white-space: normal;+ box-shadow: 0 4px 14px rgba(0,0,0,0.4); animation: cc-msg-in 0.18s ease;+}+.cc-bubble::after {+ content: ""; position: absolute; left: 50%; bottom: -5px; transform: translateX(-50%);+ border: 6px solid transparent; border-top-color: #fff; border-bottom: 0;+}++#cc-hint {+ position: fixed; right: 14px; bottom: 14px; z-index: 19;+ color: var(--cc-dim); font-size: 11px; line-height: 1.6;+ background: var(--cc-panel); border: 1px solid var(--cc-edge); border-radius: 10px; padding: 8px 11px;+}+#cc-hint kbd { background: rgba(255,255,255,0.06); border: 1px solid var(--cc-edge); border-radius: 4px; padding: 0 5px; font-size: 10px; }++#cc-joystick { position: fixed; left: 22px; bottom: 90px; width: 120px; height: 120px; z-index: 21; touch-action: none; }++@media (max-width: 640px) {+ #cc-hint { display: none; }+ .cc-coin-banner { max-width: 60vw; }+ #cc-chat { width: 72vw; }+}diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsnew file mode 100644index 000000000..a078970c0--- /dev/null+++ b/src/game/coincommunities.js@@ -0,0 +1,552 @@+// Coin Communities — 3D metaverse client (the /play scene).+//+// Each pump.fun coin is its own multiplayer 3D world. You pick an avatar (or+// bring your own / your 3D agent), choose a coin in the lobby, and drop into+// that coin's community: a shared space where everyone walks around as real+// GLB avatars, emotes, and chats. The server (WalkRoom, keyed by coin) is+// authoritative for position/avatar/chat; this client predicts local movement+// and interpolates everyone else.+//+// Built on the same proven engine as /walk (GLTF avatars + AnimationManager ++// Colyseus), reused here so a coin community is a first-class 3D space.++import {+ Scene, Color, Fog, WebGLRenderer, PerspectiveCamera, Group, Vector3, Box3,+ HemisphereLight, DirectionalLight, AmbientLight, PCFSoftShadowMap, SRGBColorSpace,+ Mesh, MeshStandardMaterial, MeshBasicMaterial, CircleGeometry, RingGeometry,+ CylinderGeometry, CapsuleGeometry, SphereGeometry, PlaneGeometry,+ CanvasTexture, TextureLoader, DoubleSide,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import nipplejs from 'nipplejs';++import { AnimationManager } from '../animation-manager.js';+import { CommunityNet } from './community-net.js';+import { CommunityUI } from './coincommunities-ui.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 = 58; // a touch inside the server's 60m clamp+const MOVE_SPEED = 4.2;+const REMOTE_LERP = 0.18;+const TRENDING_URL = '/api/pump/trending?limit=30';++const _gltf = new GLTFLoader();+let _animDefs = null; // cached manifest defs (locomotion + emotes)+let _emoteDefs = null;++async function loadManifest() {+ if (_animDefs) return;+ let manifest = [];+ try {+ const r = await fetch(MANIFEST_URL, { cache: 'force-cache' });+ if (r.ok) manifest = await r.json();+ } catch { /* fall through to locomotion-only */ }+ const byName = (n) => manifest.find((d) => d.name === n);+ const loco = [byName(CLIP_IDLE), byName(CLIP_WALK)].filter(Boolean);+ const emotes = manifest.filter((d) => d.name !== CLIP_IDLE && d.name !== CLIP_WALK).slice(0, 6);+ _emoteDefs = emotes;+ _animDefs = [...loco, ...emotes];+}++// 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.+async function resolveAvatarUrl(input) {+ const v = (input || '').trim();+ if (!v) return AVATAR_DEFAULT;+ if (/^https?:\/\//i.test(v) || v.startsWith('/')) return v;+ try {+ const r = await fetch(`/api/avatars/${encodeURIComponent(v)}`, { headers: { accept: 'application/json' } });+ if (r.ok) { const { avatar } = await r.json(); if (avatar?.url) return avatar.url; }+ } catch { /* ignore */ }+ return AVATAR_DEFAULT;+}++// Load a GLB avatar into a rig + wire an AnimationManager (idle/walk/emotes).+// Returns { height }. On failure, drops in a capsule stand-in so the player is+// never invisible.+async function buildAvatar(rig, url, anim) {+ try {+ const gltf = await _gltf.loadAsync(url);+ 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 (_animDefs?.length) { anim.setAnimationDefs(_animDefs); await anim.loadAll(); await anim.crossfadeTo(CLIP_IDLE, 0); }+ return { height: Math.max(0.5, box.max.y - box.min.y) };+ } catch (err) {+ console.warn('[coincommunities] avatar load failed, using stand-in:', url, err?.message);+ const body = new Mesh(new CapsuleGeometry(0.32, 0.7, 4, 10), new MeshStandardMaterial({ color: 0x8aa6d8 }));+ body.position.y = 0.85; body.castShadow = true;+ const head = new Mesh(new SphereGeometry(0.28, 14, 10), new MeshStandardMaterial({ color: 0xf1c9a5 }));+ head.position.y = 1.55; head.castShadow = true;+ rig.add(body, head);+ return { height: 1.7 };+ }+}++// A networked peer: their own avatar rig + animation + name label + chat bubble.+class RemotePlayer {+ constructor(scene, player) {+ this.scene = scene;+ this.rig = new Group();+ this.anim = new AnimationManager();+ this.targetX = player.x; this.targetY = player.y; this.targetZ = player.z; this.targetYaw = player.yaw;+ this.curYaw = player.yaw; this.motion = player.motion || 'idle';+ this.rig.position.set(player.x, player.y, player.z);+ scene.add(this.rig);++ this.label = document.createElement('div');+ this.label.className = 'cc-label';+ this.label.textContent = player.name || 'guest';+ document.body.appendChild(this.label);++ this.bubble = null;+ this._bubbleTimer = null;++ this.setAvatar(player.avatar);+ }+ setAvatar(url) {+ if (url === this._avatarUrl) return;+ this._avatarUrl = url;+ // rebuild model+ this.rig.clear();+ this.anim = new AnimationManager();+ resolveAvatarUrl(url).then((u) => buildAvatar(this.rig, u, this.anim).then(() => {+ this.anim.crossfadeTo(this.motion === 'walk' || this.motion === 'run' ? CLIP_WALK : CLIP_IDLE, 0);+ }));+ }+ apply(player) {+ this.targetX = player.x; this.targetY = player.y; this.targetZ = player.z; this.targetYaw = player.yaw;+ if (player.name) this.label.textContent = player.name;+ if (player.avatar !== this._avatarUrl) this.setAvatar(player.avatar);+ if (player.motion !== this.motion) {+ this.motion = player.motion;+ this.anim.crossfadeTo(this.motion === 'walk' || this.motion === 'run' ? CLIP_WALK : CLIP_IDLE, 0.18);+ }+ if (player.emote && player.emoteTs && player.emoteTs !== this._emoteTs) {+ this._emoteTs = player.emoteTs;+ playEmoteClip(this.anim, player.emote, this.motion);+ }+ }+ say(text) {+ 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; }, 5000);+ }+ tick(dt) {+ this.rig.position.x += (this.targetX - this.rig.position.x) * REMOTE_LERP;+ this.rig.position.y += (this.targetY - this.rig.position.y) * REMOTE_LERP;+ this.rig.position.z += (this.targetZ - this.rig.position.z) * REMOTE_LERP;+ let d = this.targetYaw - this.curYaw;+ while (d > Math.PI) d -= Math.PI * 2;+ while (d < -Math.PI) d += Math.PI * 2;+ this.curYaw += d * 0.2;+ this.rig.rotation.y = this.curYaw;+ this.anim.update(dt);+ }+ dispose() {+ this.scene.remove(this.rig);+ this.label.remove();+ this.bubble?.remove();+ clearTimeout(this._bubbleTimer);+ }+}++// Play a one-shot emote clip then return to the locomotion clip.+async function playEmoteClip(anim, name, motion) {+ const def = _emoteDefs?.find((d) => d.name === name);+ if (!def) return;+ try {+ if (!anim.clips?.has?.(name)) await anim.loadAnimation(name, def.url, { loop: false });+ await anim.crossfadeTo(name, 0.15);+ setTimeout(() => anim.crossfadeTo(motion === 'walk' || motion === 'run' ? CLIP_WALK : CLIP_IDLE, 0.2), 2400);+ } catch { /* clip missing — ignore */ }+}++export class CoinCommunities {+ constructor(canvas) {+ this.canvas = canvas;+ this.phase = 'lobby';+ this.remotes = new Map();+ this.keys = new Set();+ this.input = new Vector3(); // joystick/keys movement intent (x,z in [-1,1])+ this.camYaw = 0.6; this.camPitch = 0.5; this.camDist = 9;+ // Spawn within the server's 1.2m max-step radius of its origin (0,0,0) so+ // our first authoritative move isn't rejected as a teleport. A small+ // random offset keeps players from stacking exactly on each other.+ const a = Math.random() * Math.PI * 2, rad = 0.4 + Math.random() * 0.5;+ this.localPos = new Vector3(Math.cos(a) * rad, 0, Math.sin(a) * rad);+ this.localYaw = Math.PI;+ this.motion = 'idle';+ this._dragging = false; this._lastPtr = null;+ this._last = performance.now();++ this._initRenderer();+ this._initScene();++ this.ui = new CommunityUI({+ onEnter: (coin) => this.enter(coin),+ onLeave: () => this.leave(),+ onChat: (t) => this._sendChat(t),+ onEmote: (n) => this._emote(n),+ onRetry: () => this.net?.retry(),+ onAvatarChange: (url) => { this.net?.setAvatar(url); },+ });++ this._hideBootLoader();+ this._loadCoins();+ this._bindInput();++ this._loop = this._loop.bind(this);+ requestAnimationFrame(this._loop);++ // Deep link: /play?coin=<mint>&name=&symbol=&image= drops straight into a+ // coin's community, so a community is a shareable URL.+ const p = new URLSearchParams(location.search);+ const mint = p.get('coin');+ if (mint) {+ this.enter({ mint, name: p.get('name') || '', symbol: p.get('symbol') || '', image: p.get('image') || '' });+ }+ }++ _hideBootLoader() {+ const l = document.getElementById('kx-loading');+ if (l) { l.classList.add('kx-hidden'); setTimeout(() => l.remove(), 600); }+ }++ async _loadCoins() {+ this.ui.setCoinsLoading();+ try {+ 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: 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);+ } catch (err) {+ console.warn('[coincommunities] coin load failed:', err?.message);+ this.ui.setCoinsError(() => this._loadCoins());+ }+ }++ // ---------------------------------------------------------------- render+ _initRenderer() {+ const r = new WebGLRenderer({ canvas: this.canvas, antialias: true });+ r.setPixelRatio(Math.min(window.devicePixelRatio, 2));+ r.setSize(window.innerWidth, window.innerHeight);+ r.shadowMap.enabled = true; r.shadowMap.type = PCFSoftShadowMap;+ r.outputColorSpace = SRGBColorSpace;+ this.renderer = r;+ window.addEventListener('resize', () => this._onResize());+ }++ _initScene() {+ const scene = new Scene();+ scene.background = new Color(0x0e1630);+ scene.fog = new Fog(0x0e1630, 60, 130);+ this.scene = scene;++ this.camera = new PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 500);++ scene.add(new HemisphereLight(0xbcd4ff, 0x2a3350, 0.9));+ scene.add(new AmbientLight(0xffffff, 0.2));+ const sun = new DirectionalLight(0xfff1d6, 1.1);+ sun.position.set(30, 50, 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.+ const floor = new Mesh(new CircleGeometry(WORLD_RADIUS + 2, 64),+ new MeshStandardMaterial({ color: 0x223056, roughness: 0.95 }));+ floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true;+ scene.add(floor);+ // Glowing boundary ring.+ const ring = new Mesh(new RingGeometry(WORLD_RADIUS, WORLD_RADIUS + 1.2, 80),+ new MeshBasicMaterial({ color: 0x5fa1cf, side: DoubleSide, transparent: true, opacity: 0.5 }));+ ring.rotation.x = -Math.PI / 2; ring.position.y = 0.02;+ scene.add(ring);+ // Concentric guide circles for depth.+ for (const rad of [14, 28, 42]) {+ const g = new Mesh(new RingGeometry(rad, rad + 0.12, 64),+ new MeshBasicMaterial({ color: 0x35508a, side: DoubleSide, transparent: true, opacity: 0.5 }));+ g.rotation.x = -Math.PI / 2; g.position.y = 0.015; scene.add(g);+ }++ this.world = new Group();+ scene.add(this.world);+ }++ // 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: 0x2a3a66, roughness: 0.6, metalness: 0.2 }));+ pillar.position.y = 3; pillar.castShadow = true; pillar.receiveShadow = true;+ g.add(pillar);+ // Floating coin disc with the token image.+ const disc = new Mesh(new CylinderGeometry(2.2, 2.2, 0.3, 40),+ new MeshStandardMaterial({ color: 0xffce5c, roughness: 0.35, metalness: 0.7, emissive: 0x3a2e00, emissiveIntensity: 0.3 }));+ disc.rotation.x = Math.PI / 2; disc.position.y = 7.5; disc.castShadow = true;+ g.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);+ 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);+ }, undefined, () => { /* image blocked — totem still shows */ });+ }+ // 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+ // spawn inside the pillar.+ g.position.set(0, 0, -12);+ this.world.add(g);+ this._totem = g;+ }++ _textBanner(name, sym) {+ const c = document.createElement('canvas'); c.width = 512; c.height = 128;+ const x = c.getContext('2d');+ x.fillStyle = 'rgba(11,16,32,0.0)'; x.fillRect(0, 0, 512, 128);+ x.textAlign = 'center'; x.fillStyle = '#fff';+ x.font = 'bold 52px system-ui, sans-serif';+ x.fillText(name.slice(0, 18), 256, 56);+ x.font = 'bold 34px system-ui, sans-serif'; x.fillStyle = '#5fa1cf';+ x.fillText(sym, 256, 100);+ const tex = new CanvasTexture(c); tex.colorSpace = SRGBColorSpace;+ const m = new Mesh(new PlaneGeometry(6, 1.5), new MeshBasicMaterial({ map: tex, transparent: true, side: DoubleSide }));+ m.position.y = 10.2;+ return m;+ }++ // ---------------------------------------------------------------- enter/leave+ async enter(coin) {+ if (this.phase !== 'lobby') return;+ this.phase = 'loading';+ this.coin = coin;+ this.ui.enterWorld(coin);+ // Reflect the community in the URL so it can be shared / refreshed into.+ try {+ const q = new URLSearchParams({ coin: coin.mint });+ if (coin.name) q.set('name', coin.name);+ if (coin.symbol) q.set('symbol', coin.symbol);+ if (coin.image) q.set('image', coin.image);+ history.replaceState(null, '', location.pathname + '?' + q.toString());+ } catch { /* non-fatal */ }+ await loadManifest();+ this.ui.setEmotes((_emoteDefs || []).map((d) => ({ name: d.name, icon: d.icon || '🙂', label: d.label })));++ // Build the coin's world + local avatar.+ this._buildTotem(coin);+ this.localRig = new Group();+ this.localRig.position.copy(this.localPos);+ this.scene.add(this.localRig);+ this.localAnim = new AnimationManager();+ const avatarInput = this.ui.getAvatar();+ const url = await resolveAvatarUrl(avatarInput);+ await buildAvatar(this.localRig, url, this.localAnim);++ // Connect to this coin's room.+ const name = localStorage.getItem('cc-name') || ('guest-' + Math.random().toString(36).slice(2, 6));+ localStorage.setItem('cc-name', name);+ this.net = new CommunityNet({+ name, avatar: /^https?:\/\//i.test(avatarInput) || avatarInput.startsWith('/') ? avatarInput : url,+ coin: { mint: coin.mint, name: coin.name, symbol: coin.symbol, image: coin.image },+ });+ this.net.on('status', ({ status }) => { this.ui.setStatus(status); this._updateOnline(); });+ this.net.on('add', (p, id) => this._onAdd(p, id));+ this.net.on('change', (p, id) => this._onChange(p, id));+ this.net.on('remove', (id) => this._onRemove(id));+ this.net.on('chat', (m) => this._onChat(m));+ await this.net.connect();+ this.phase = 'world';+ this._initJoystick();+ }++ leave() {+ 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.localRig) { this.scene.remove(this.localRig); this.localRig = null; }+ if (this._nipple) { this._nipple.destroy(); this._nipple = null; }+ this.phase = 'lobby';+ try { history.replaceState(null, '', location.pathname); } catch { /* non-fatal */ }+ this.ui.showLobby();+ }++ _updateOnline() {+ const n = (this.remotes.size + (this.net?.status === 'online' ? 1 : 0)) || 1;+ this.ui.setOnline(n);+ }++ // ---------------------------------------------------------------- net events+ _onAdd(player, id) {+ if (id === this.net.sessionId) return; // that's us+ this.remotes.set(id, new RemotePlayer(this.scene, player));+ this._updateOnline();+ }+ _onChange(player, id) {+ if (id === this.net.sessionId) return;+ this.remotes.get(id)?.apply(player);+ }+ _onRemove(id) {+ const r = this.remotes.get(id);+ if (r) { r.dispose(); this.remotes.delete(id); this._updateOnline(); }+ }+ _onChat(m) {+ const mine = m.id === this.net.sessionId;+ this.ui.addChat({ name: m.name, text: m.text, mine });+ if (mine) this._sayLocal(m.text);+ else this.remotes.get(m.id)?.say(m.text);+ }+ _sendChat(text) { this.net?.sendChat(text); }+ _emote(name) { this.net?.sendEmote(name); playEmoteClip(this.localAnim, name, this.motion); }++ _sayLocal(text) {+ if (this._localBubble) this._localBubble.remove();+ this._localBubble = document.createElement('div');+ this._localBubble.className = 'cc-bubble';+ this._localBubble.textContent = text;+ document.body.appendChild(this._localBubble);+ clearTimeout(this._localBubbleTimer);+ this._localBubbleTimer = setTimeout(() => { this._localBubble?.remove(); this._localBubble = null; }, 5000);+ }++ // ---------------------------------------------------------------- input+ _bindInput() {+ window.addEventListener('keydown', (e) => {+ if (this.ui.chatFocused) return;+ this.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 }; });+ window.addEventListener('pointerup', () => { this._dragging = false; });+ window.addEventListener('pointermove', (e) => {+ if (!this._dragging) 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;+ this.camPitch = Math.max(0.1, Math.min(1.2, this.camPitch + dy * 0.004));+ });+ this.canvas.addEventListener('wheel', (e) => {+ e.preventDefault();+ this.camDist = Math.max(4, Math.min(20, this.camDist * (e.deltaY > 0 ? 1.1 : 0.9)));+ }, { passive: false });+ }++ _initJoystick() {+ const zone = document.getElementById('cc-joystick');+ if (!zone || this._nipple) return;+ // Touch only — keep desktop on WASD.+ if (!matchMedia('(pointer: coarse)').matches) { zone.style.display = 'none'; return; }+ this._nipple = nipplejs.create({ zone, mode: 'static', position: { left: '60px', bottom: '60px' }, color: '#5fa1cf', size: 110 });+ this._nipple.on('move', (_e, d) => {+ const f = Math.min(1, d.force);+ this._joy = { x: Math.cos(d.angle.radian) * f, z: -Math.sin(d.angle.radian) * f };+ });+ this._nipple.on('end', () => { this._joy = null; });+ }++ // ---------------------------------------------------------------- loop+ _loop() {+ requestAnimationFrame(this._loop);+ const now = performance.now();+ const dt = Math.min(0.05, (now - this._last) / 1000);+ this._last = now;++ if (this.phase === 'world') {+ this._stepLocal(dt);+ 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 });+ }+ this._updateCamera();+ this.renderer.render(this.scene, this.camera);+ }++ _stepLocal(dt) {+ // 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;+ if (this.keys.has('s') || this.keys.has('arrowdown')) iz += 1;+ 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 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"+ 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;+ // clamp to plaza+ const 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); }+ } else if (this.motion !== 'idle') {+ this.motion = 'idle'; this.localAnim?.crossfadeTo(CLIP_IDLE, 0.2);+ }+ 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);+ 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;+ const oy = sp * this.camDist + 1.4;+ this.camera.position.set(target.x - ox, target.y + oy, target.z - oz);+ this.camera.lookAt(target.x, target.y + 1.4, target.z);+ }++ _updateLabels() {+ const w = this.renderer.domElement.clientWidth, h = this.renderer.domElement.clientHeight;+ const place = (node, pos, dy) => {+ const v = new Vector3(pos.x, pos.y + dy, pos.z).project(this.camera);+ 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 [, r] of this.remotes) {+ place(r.label, r.rig.position, 2.0);+ if (r.bubble) place(r.bubble, r.rig.position, 2.5);+ }+ if (this._localBubble && this.localRig) place(this._localBubble, this.localPos, 2.5);+ }++ _onResize() {+ this.camera.aspect = window.innerWidth / window.innerHeight;+ this.camera.updateProjectionMatrix();+ this.renderer.setSize(window.innerWidth, window.innerHeight);+ }+}++const canvas = document.getElementById('kx-canvas') || document.getElementById('cc-canvas');+if (canvas) {+ const game = new CoinCommunities(canvas);+ if (typeof window !== 'undefined') window.__CC__ = game;+}diff --git a/src/game/community-net.js b/src/game/community-net.jsnew file mode 100644index 000000000..87e3a5ce9--- /dev/null+++ b/src/game/community-net.js@@ -0,0 +1,176 @@+// CommunityNet — multiplayer client for Coin Communities.+//+// Each coin is its own world: we join the shared `walk_world` room definition+// but pass `token = <mint>` so Colyseus's filterBy matches us only with players+// who entered the same coin's community. The server (WalkRoom) is authoritative+// for position, emotes, avatars, and chat relay.+//+// This is a focused sibling of walk-net.js — it adds coin identity, avatar URL,+// and chat on top of the same room, and leaves the /walk page's client+// untouched.++import { Client, getStateCallbacks } from 'colyseus.js';++const ROOM_NAME = 'walk_world';+const SEND_HZ = 15;+const SEND_INTERVAL_MS = 1000 / SEND_HZ;+const POSITION_EPSILON = 0.01;+const YAW_EPSILON = 0.01;++function defaultServerUrl() {+ if (typeof window !== 'undefined' && window.GAME_SERVER_URL) return window.GAME_SERVER_URL;+ if (typeof document !== 'undefined') {+ for (const sel of ['meta[name="game-server"]', 'meta[name="walk-server"]']) {+ const v = document.querySelector(sel)?.getAttribute('content')?.trim();+ if (v) return v;+ }+ }+ if (typeof location !== 'undefined') {+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';+ return `${proto}//${location.hostname}:2567`;+ }+ return 'ws://localhost:2567';+}++export class CommunityNet {+ /**+ * @param {object} opts+ * @param {string} [opts.name] display name+ * @param {string} [opts.avatar] GLB/VRM URL for this player's avatar+ * @param {string} [opts.agent] optional three.ws agent id+ * @param {object} [opts.coin] { mint, name, symbol, image } — '' mint = lobby+ * @param {string} [opts.url] server override+ */+ constructor(opts = {}) {+ this.name = opts.name || 'guest';+ this.avatar = opts.avatar || '';+ this.agent = opts.agent || '';+ this.coin = opts.coin || { mint: '', name: '', symbol: '', image: '' };+ this.url = opts.url || defaultServerUrl();++ this.client = null;+ this.room = null;+ this.status = 'idle';+ this.error = null;+ this.sessionId = null;++ this._handlers = {+ status: new Set(),+ ready: new Set(), // (coinMeta)+ add: new Set(), // (player, id)+ change: new Set(), // (player, id)+ remove: new Set(), // (id)+ chat: new Set(), // ({id, name, text, ts})+ };+ this._lastSent = null;+ this._lastSentAt = 0;+ this._reconnectTimer = null;+ this._destroyed = false;+ }++ on(event, fn) {+ const bucket = this._handlers[event];+ if (!bucket) throw new Error(`CommunityNet: unknown event "${event}"`);+ bucket.add(fn);+ return () => bucket.delete(fn);+ }+ _emit(event, ...args) {+ for (const fn of this._handlers[event]) {+ try { fn(...args); } catch (e) { console.error(`[community-net] ${event} handler threw:`, e); }+ }+ }+ _setStatus(status, error = null) {+ this.status = status; this.error = error;+ this._emit('status', { status, error });+ }++ async connect() {+ if (this._destroyed) return;+ this._setStatus('connecting');+ try {+ this.client = new Client(this.url);+ const mint = this.coin.mint || '';+ const options = {+ // filterBy('coin') isolates each coin into its own instance; the+ // coin-less lobby ('') groups all lobby players into one world.+ coin: mint,+ coinName: this.coin.name || '',+ coinSymbol: this.coin.symbol || '',+ coinImage: this.coin.image || '',+ name: this.name,+ avatar: this.avatar,+ agent: this.agent,+ };+ this.room = await this.client.joinOrCreate(ROOM_NAME, options);+ this.sessionId = this.room.sessionId;++ this.room.onMessage('chat', (msg) => this._emit('chat', msg));++ const $ = getStateCallbacks(this.room);+ $(this.room.state).players.onAdd((player, id) => {+ this._emit('add', player, id);+ $(player).onChange(() => this._emit('change', player, id));+ });+ $(this.room.state).players.onRemove((_p, id) => this._emit('remove', id));++ this.room.onLeave((code) => {+ this._setStatus('offline');+ if (!this._destroyed && code !== 1000) this._scheduleReconnect();+ });+ this.room.onError((code, message) => console.warn('[community-net] room.onError', code, message));++ this._setStatus('online');+ this._emit('ready', {+ mint: this.room.state.coin,+ name: this.room.state.coinName,+ symbol: this.room.state.coinSymbol,+ image: this.room.state.coinImage,+ });+ } catch (err) {+ console.warn('[community-net] connect failed:', err?.message ?? err);+ this._setStatus('failed', err?.message ?? String(err));+ this._scheduleReconnect();+ }+ }++ _scheduleReconnect() {+ if (this._reconnectTimer || this._destroyed) return;+ const delay = 3000 + Math.random() * 1500;+ this._reconnectTimer = setTimeout(() => {+ this._reconnectTimer = null;+ if (!this._destroyed) this.connect();+ }, delay);+ }++ sendMove(state) {+ if (!this.room) return;+ const now = performance.now();+ if (now - this._lastSentAt < SEND_INTERVAL_MS) return;+ if (this._lastSent) {+ const moved = Math.hypot(state.x - this._lastSent.x, state.y - this._lastSent.y, state.z - this._lastSent.z);+ const turned = Math.abs(state.yaw - this._lastSent.yaw);+ if (moved < POSITION_EPSILON && turned < YAW_EPSILON && state.motion === this._lastSent.motion) return;+ }+ this.room.send('move', { x: state.x, y: state.y, z: state.z, yaw: state.yaw, motion: state.motion });+ this._lastSent = { ...state };+ this._lastSentAt = now;+ }++ sendEmote(name) { this.room?.send('emote', { name }); }+ sendChat(text) { this.room?.send('chat', { text }); }+ rename(name) { this.name = name; this.room?.send('rename', { name }); }+ setAvatar(avatar, agent) { this.avatar = avatar; this.room?.send('avatar', { avatar, agent }); }++ get state() { return this.room?.state ?? null; }++ retry() {+ if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }+ this.connect();+ }+ destroy() {+ this._destroyed = true;+ if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }+ try { this.room?.leave(); } catch {}+ this.room = null; this.client = null;+ }+}diff --git a/src/game/game-net.js b/src/game/game-net.jsnew file mode 100644index 000000000..3c4dbc7c4--- /dev/null+++ b/src/game/game-net.js@@ -0,0 +1,153 @@+// Multiplayer client for /play (Coin Communities) — wraps colyseus.js with a small+// event API the game scene subscribes to without knowing anything about+// Colyseus. Mirrors the design of walk-net.js: graceful offline fallback,+// bounded reconnect, and a flat event surface.+//+// Unlike walk (free 3D position at 15Hz), the game is tile-stepped: the client+// sends one 'step' per tile as the avatar paths, plus discrete intents+// (gather, attack, inventory ops, banking). The server is authoritative for+// all of it.++import { Client, getStateCallbacks } from 'colyseus.js';++const ROOM_NAME = 'game_mainland';++function defaultServerUrl() {+ // Resolution priority mirrors walk-net:+ // 1. window.GAME_SERVER_URL (test override)+ // 2. <meta name="game-server"> then <meta name="walk-server"> (shared host)+ // 3. Same host on :2567 (dev convenience)+ if (typeof window !== 'undefined' && window.GAME_SERVER_URL) return window.GAME_SERVER_URL;+ if (typeof document !== 'undefined') {+ for (const sel of ['meta[name="game-server"]', 'meta[name="walk-server"]']) {+ const v = document.querySelector(sel)?.getAttribute('content')?.trim();+ if (v) return v;+ }+ }+ if (typeof location !== 'undefined') {+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';+ return `${proto}//${location.hostname}:2567`;+ }+ return 'ws://localhost:2567';+}++export class GameNet {+ constructor(opts = {}) {+ this.name = opts.name || 'guest';+ this.url = opts.url || defaultServerUrl();+ this.client = null;+ this.room = null;+ this.status = 'idle'; // 'idle'|'connecting'|'online'|'offline'|'failed'+ this.error = null;+ this.sessionId = null;+ this._handlers = {+ status: new Set(),+ realm: new Set(), // (layout)+ notice: new Set(), // ({kind, text})+ bank: new Set(), // ({slots})+ playerAdd: new Set(), // (player, id)+ playerChange: new Set(), // (player, id)+ playerRemove: new Set(), // (id)+ nodeAdd: new Set(),+ nodeChange: new Set(),+ nodeRemove: new Set(),+ mobAdd: new Set(),+ mobChange: new Set(),+ mobRemove: new Set(),+ };+ this._reconnectTimer = null;+ this._destroyed = false;+ }++ on(event, fn) {+ const bucket = this._handlers[event];+ if (!bucket) throw new Error(`GameNet: unknown event "${event}"`);+ bucket.add(fn);+ return () => bucket.delete(fn);+ }++ _emit(event, ...args) {+ for (const fn of this._handlers[event]) {+ try { fn(...args); } catch (e) { console.error(`[game-net] ${event} handler threw:`, e); }+ }+ }++ _setStatus(status, error = null) {+ this.status = status;+ this.error = error;+ this._emit('status', { status, error });+ }++ async connect() {+ if (this._destroyed) return;+ this._setStatus('connecting');+ try {+ this.client = new Client(this.url);+ this.room = await this.client.joinOrCreate(ROOM_NAME, { name: this.name });+ this.sessionId = this.room.sessionId;++ this.room.onMessage('realm', (layout) => this._emit('realm', layout));+ this.room.onMessage('notice', (n) => this._emit('notice', n));+ this.room.onMessage('bank', (b) => this._emit('bank', b));++ const $ = getStateCallbacks(this.room);+ const wire = (mapName, addEv, changeEv, removeEv) => {+ $(this.room.state)[mapName].onAdd((item, id) => {+ this._emit(addEv, item, id);+ $(item).onChange(() => this._emit(changeEv, item, id));+ });+ $(this.room.state)[mapName].onRemove((_item, id) => this._emit(removeEv, id));+ };+ wire('players', 'playerAdd', 'playerChange', 'playerRemove');+ wire('nodes', 'nodeAdd', 'nodeChange', 'nodeRemove');+ wire('mobs', 'mobAdd', 'mobChange', 'mobRemove');++ this.room.onLeave((code) => {+ this._setStatus('offline');+ if (!this._destroyed && code !== 1000) this._scheduleReconnect();+ });+ this.room.onError((code, message) => console.warn('[game-net] room.onError', code, message));++ this._setStatus('online');+ } catch (err) {+ console.warn('[game-net] connect failed:', err?.message ?? err);+ this._setStatus('failed', err?.message ?? String(err));+ this._scheduleReconnect();+ }+ }++ _scheduleReconnect() {+ if (this._reconnectTimer || this._destroyed) return;+ const delay = 3000 + Math.random() * 1500;+ this._reconnectTimer = setTimeout(() => {+ this._reconnectTimer = null;+ if (!this._destroyed) this.connect();+ }, delay);+ }++ // ----- intents ---------------------------------------------------------++ step(tx, ty, yaw) { this.room?.send('step', { tx, ty, yaw }); }+ gather(id) { this.room?.send('gather', { id }); }+ attack(id) { this.room?.send('attack', { id }); }+ invMove(from, to) { this.room?.send('invMove', { from, to }); }+ equip(slot) { this.room?.send('equip', { slot }); }+ bankOpen() { this.room?.send('bankOpen'); }+ bankDeposit(i, qty) { this.room?.send('bankDeposit', { i, qty }); }+ bankWithdraw(i, qty) { this.room?.send('bankWithdraw', { i, qty }); }++ get state() { return this.room?.state ?? null; }++ retry() {+ if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }+ this.connect();+ }++ destroy() {+ this._destroyed = true;+ if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }+ try { this.room?.leave(); } catch {}+ this.room = null;+ this.client = null;+ }+}diff --git a/src/pose-rig.js b/src/pose-rig.jsnew file mode 100644index 000000000..832f8a562--- /dev/null+++ b/src/pose-rig.js@@ -0,0 +1,373 @@+// Skeleton-agnostic posing abstraction for the Animation Studio (/pose).+//+// A "rig" presents one uniform interface over two very different backends:+// - the built-in primitive Mannequin (a tree of THREE.Group joints), and+// - a loaded rigged GLB avatar (a THREE.Skeleton of THREE.Bone nodes).+//+// Everything above this layer — the gizmos, IK, FK sliders, and (Task 2) the+// keyframe timeline — talks only to this interface and never needs to know+// which backend is underneath. Poses are keyed by CANONICAL bone names+// (Avaturn / Mixamo-retargeted: Hips, Spine, LeftArm, …) and carry+// quaternions, so a pose recorded on one rig bakes into a clip whose track+// names play on standard three.ws avatars.++import { Bone, Quaternion, Vector3, Euler, MathUtils } from 'three';+import { normalizeBoneName } from './avatar-export.js';+import { Mannequin } from './pose-mannequin.js';++// ── Canonical skeleton ──────────────────────────────────────────────────────+// The exact bare bone names used by built-in clips (public/animations/clips/*).+// Order is head→spine→arms→legs so generated UI lists read naturally.+export const CANONICAL_BONES = [+ 'Hips', 'Spine', 'Spine1', 'Spine2', 'Neck', 'Head',+ 'LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand',+ 'RightShoulder', 'RightArm', 'RightForeArm', 'RightHand',+ 'LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase',+ 'RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase',+ // Fingers — captured when a rig has them so detailed hand poses survive.+ 'LeftHandThumb1', 'LeftHandThumb2', 'LeftHandThumb3',+ 'LeftHandIndex1', 'LeftHandIndex2', 'LeftHandIndex3',+ 'LeftHandMiddle1', 'LeftHandMiddle2', 'LeftHandMiddle3',+ 'LeftHandRing1', 'LeftHandRing2', 'LeftHandRing3',+ 'LeftHandPinky1', 'LeftHandPinky2', 'LeftHandPinky3',+ 'RightHandThumb1', 'RightHandThumb2', 'RightHandThumb3',+ 'RightHandIndex1', 'RightHandIndex2', 'RightHandIndex3',+ 'RightHandMiddle1', 'RightHandMiddle2', 'RightHandMiddle3',+ 'RightHandRing1', 'RightHandRing2', 'RightHandRing3',+ 'RightHandPinky1', 'RightHandPinky2', 'RightHandPinky3',+];++// Human-readable labels for the canonical bones (UI lists / selection HUD).+export const CANONICAL_LABELS = {+ Hips: 'Hips', Spine: 'Spine (lower)', Spine1: 'Spine (mid)', Spine2: 'Chest',+ Neck: 'Neck', Head: 'Head',+ LeftShoulder: 'Shoulder L', LeftArm: 'Upper arm L', LeftForeArm: 'Forearm L', LeftHand: 'Hand L',+ RightShoulder: 'Shoulder R', RightArm: 'Upper arm R', RightForeArm: 'Forearm R', RightHand: 'Hand R',+ LeftUpLeg: 'Thigh L', LeftLeg: 'Shin L', LeftFoot: 'Foot L', LeftToeBase: 'Toe L',+ RightUpLeg: 'Thigh R', RightLeg: 'Shin R', RightFoot: 'Foot R', RightToeBase: 'Toe R',+};++// Primitive-mannequin joint → canonical bone. The mannequin only has 17+// joints; we route them onto the canonical names so both rigs emit the same+// pose shape (Task 1 contract for Task 2).+const MANNEQUIN_TO_CANONICAL = {+ pelvis: 'Hips', spine: 'Spine', chest: 'Spine2', neck: 'Neck', head: 'Head',+ shoulderL: 'LeftArm', elbowL: 'LeftForeArm', wristL: 'LeftHand',+ shoulderR: 'RightArm', elbowR: 'RightForeArm', wristR: 'RightHand',+ hipL: 'LeftUpLeg', kneeL: 'LeftLeg', ankleL: 'LeftFoot',+ hipR: 'RightUpLeg', kneeR: 'RightLeg', ankleR: 'RightFoot',+};+const CANONICAL_TO_MANNEQUIN = Object.fromEntries(+ Object.entries(MANNEQUIN_TO_CANONICAL).map(([j, c]) => [c, j]),+);++// normalize(canonical) → canonical, so an arbitrary GLB bone name (mixamorig:,+// case, separators) can be matched to a canonical bone via normalizeBoneName().+const NORMALIZED_CANONICAL = new Map(+ CANONICAL_BONES.map((c) => [normalizeBoneName(c), c]),+);++// IK chains: drag the end-effector, the link bones rotate to reach it. Defined+// once in canonical space and resolved per-rig (links present on the rig only).+// Order: links go from the effector's parent outward toward the root.+export const IK_CHAINS = [+ { name: 'Left arm', effector: 'LeftHand', links: ['LeftForeArm', 'LeftArm'] },+ { name: 'Right arm', effector: 'RightHand', links: ['RightForeArm', 'RightArm'] },+ { name: 'Left leg', effector: 'LeftFoot', links: ['LeftLeg', 'LeftUpLeg'] },+ { name: 'Right leg', effector: 'RightFoot', links: ['RightLeg', 'RightUpLeg'] },+];++// ── Lightweight CCD IK ───────────────────────────────────────────────────────+// Cyclic Coordinate Descent over a chain of THREE.Object3D bones toward a+// world-space target. Works uniformly on mannequin Groups and GLB Bones (no+// SkinnedMesh / skeleton-index assumptions), so neither rig has a dead toggle.+const _targetLocal = new Vector3();+const _effectorLocal = new Vector3();+const _axis = new Vector3();+const _q = new Quaternion();+const _invParent = new Quaternion();++function solveCCD(links, effector, targetWorld, { iterations = 10, threshold = 0.001 } = {}) {+ if (!links.length || !effector) return;+ for (let iter = 0; iter < iterations; iter++) {+ for (const bone of links) {+ bone.updateWorldMatrix(true, true);+ effector.updateWorldMatrix(true, false);+ // Vector from this bone to the effector and to the target, in the+ // bone's LOCAL frame (so the resulting rotation is a local delta).+ const inv = bone.matrixWorld.clone().invert();+ _effectorLocal.setFromMatrixPosition(effector.matrixWorld).applyMatrix4(inv);+ _targetLocal.copy(targetWorld).applyMatrix4(inv);+ if (_effectorLocal.lengthSq() < 1e-8 || _targetLocal.lengthSq() < 1e-8) continue;+ _effectorLocal.normalize();+ _targetLocal.normalize();+ let dot = MathUtils.clamp(_effectorLocal.dot(_targetLocal), -1, 1);+ const angle = Math.acos(dot);+ if (angle < 1e-5) continue;+ _axis.crossVectors(_effectorLocal, _targetLocal);+ if (_axis.lengthSq() < 1e-10) continue;+ _axis.normalize();+ _q.setFromAxisAngle(_axis, angle);+ bone.quaternion.multiply(_q);+ bone.updateWorldMatrix(true, true);+ }+ effector.updateWorldMatrix(true, false);+ const dist = _effectorLocal+ .setFromMatrixPosition(effector.matrixWorld)+ .distanceTo(targetWorld);+ if (dist < threshold) break;+ }+}++// ── Base rig ─────────────────────────────────────────────────────────────────+class BaseRig {+ constructor() {+ this.kind = 'base';+ /** @type {Map<string, import('three').Object3D>} canonical → node */+ this.bones = new Map();+ /** @type {import('three').Object3D} added to the scene */+ this.root = null;+ this.selectableMeshes = [];+ }++ /** Ordered posable bones present on this rig. */+ getBones() {+ const out = [];+ for (const key of CANONICAL_BONES) {+ if (this.bones.has(key)) {+ out.push({ key, label: CANONICAL_LABELS[key] || key, node: this.bones.get(key) });+ }+ }+ return out;+ }++ hasBone(key) { return this.bones.has(key); }+ getNode(key) { return this.bones.get(key) || null; }++ getBoneQuaternion(key) {+ const n = this.bones.get(key);+ return n ? n.quaternion.clone() : new Quaternion();+ }+ setBoneQuaternion(key, quat) {+ const n = this.bones.get(key);+ if (n) n.quaternion.copy(quat);+ }+ getBoneEuler(key) {+ const n = this.bones.get(key);+ if (!n) return { x: 0, y: 0, z: 0 };+ const e = new Euler().setFromQuaternion(n.quaternion, 'XYZ');+ return { x: e.x, y: e.y, z: e.z };+ }+ setBoneEuler(key, { x = 0, y = 0, z = 0 }) {+ const n = this.bones.get(key);+ if (n) n.quaternion.setFromEuler(new Euler(x, y, z, 'XYZ'));+ }++ getRootPosition() {+ return this.root ? this.root.position.clone() : new Vector3();+ }+ setRootPosition(vec) {+ if (this.root) this.root.position.set(vec.x, vec.y, vec.z);+ }++ // Canonical pose snapshot — the shape Task 2's timeline records.+ // { bones: { Hips: [x,y,z,w], … }, rootPosition: {x,y,z} }+ getPose() {+ const bones = {};+ for (const [key, node] of this.bones) {+ const q = node.quaternion;+ bones[key] = [q.x, q.y, q.z, q.w];+ }+ const p = this.getRootPosition();+ return { bones, rootPosition: { x: p.x, y: p.y, z: p.z } };+ }++ applyPose(pose) {+ if (!pose) return;+ this.resetPose();+ const bones = pose.bones || pose; // tolerate a bare bones map+ for (const [key, v] of Object.entries(bones)) {+ if (key === 'rootPosition') continue;+ const node = this.bones.get(key);+ if (!node || !Array.isArray(v) || v.length < 4) continue;+ node.quaternion.set(v[0], v[1], v[2], v[3]);+ }+ const rp = pose.rootPosition;+ if (rp && this.root) this.root.position.set(rp.x || 0, rp.y || 0, rp.z || 0);+ }++ // Resolve the IK chains that actually exist on this rig.+ getIKChains() {+ const out = [];+ for (const chain of IK_CHAINS) {+ const effector = this.bones.get(chain.effector);+ const links = chain.links.map((k) => this.bones.get(k)).filter(Boolean);+ if (effector && links.length) {+ out.push({ name: chain.name, effectorKey: chain.effector, effector, links });+ }+ }+ return out;+ }++ /** Drag-IK: rotate the named chain's links so its effector reaches target. */+ solveIK(effectorKey, targetWorld) {+ const chain = this.getIKChains().find((c) => c.effectorKey === effectorKey);+ if (!chain) return;+ solveCCD(chain.links, chain.effector, targetWorld);+ }++ getSelectableMeshes() { return this.selectableMeshes; }+ dispose() {}+}++// ── Mannequin-backed rig ──────────────────────────────────────────────────────+export class MannequinRig extends BaseRig {+ constructor(opts = {}) {+ super();+ this.kind = 'mannequin';+ this.mannequin = new Mannequin(opts);+ this.root = this.mannequin.root;+ this.selectableMeshes = this.mannequin.selectableMeshes;+ this._rebuildMap();+ }++ _rebuildMap() {+ this.bones = new Map();+ for (const [joint, canonical] of Object.entries(MANNEQUIN_TO_CANONICAL)) {+ const node = this.mannequin.joints[joint];+ if (node) this.bones.set(canonical, node);+ }+ }++ // Map a raycast hit back to a canonical bone key.+ boneFromHit(object) {+ const joint = this.mannequin.jointFromHit(object);+ return joint ? MANNEQUIN_TO_CANONICAL[joint] || null : null;+ }++ resetPose() {+ this.mannequin.resetPose();+ }++ // Mannequin-only conveniences the studio still exposes.+ setBuild(build) {+ this.mannequin.setBuild(build);+ this.root = this.mannequin.root;+ this.selectableMeshes = this.mannequin.selectableMeshes;+ this._rebuildMap();+ }+ setColor(hex) { this.mannequin.setColor(hex); }+ setConstraintsEnabled(on) { this.mannequin.setConstraintsEnabled(on); }+ getApproxHeight() { return this.mannequin.getApproxHeight(); }++ // The mannequin's biological constraints operate on Euler angles; honor them+ // when posing via the FK sliders so the figure can't bend impossibly.+ setBoneEuler(key, euler) {+ const joint = CANONICAL_TO_MANNEQUIN[key];+ if (joint) {+ this.mannequin.setJointRotation(joint, 'x', euler.x || 0);+ this.mannequin.setJointRotation(joint, 'y', euler.y || 0);+ this.mannequin.setJointRotation(joint, 'z', euler.z || 0);+ } else {+ super.setBoneEuler(key, euler);+ }+ }+}++// ── GLB-backed rig ────────────────────────────────────────────────────────────+export class GltfRig extends BaseRig {+ /**+ * @param {THREE.Object3D} scene gltf.scene+ */+ constructor(scene) {+ super();+ this.kind = 'glb';+ this.root = scene;+ this.skinnedMeshes = [];+ this._buildFromScene(scene);+ }++ _buildFromScene(scene) {+ // Collect skeleton bones. Prefer SkinnedMesh skeletons; fall back to any+ // Bone nodes in the graph for rigs exported without a bound skin.+ const seen = new Set();+ const consider = (node) => {+ const canonical = NORMALIZED_CANONICAL.get(normalizeBoneName(node.name));+ if (canonical && !this.bones.has(canonical)) {+ this.bones.set(canonical, node);+ }+ if (!seen.has(node)) {+ seen.add(node);+ this.selectableMeshes.push(node);+ }+ };+ scene.traverse((node) => {+ if (node.isSkinnedMesh) this.skinnedMeshes.push(node);+ if (node.isBone) consider(node);+ });+ // Some exporters name bones only on the skeleton, not the node graph.+ for (const sm of this.skinnedMeshes) {+ for (const bone of sm.skeleton?.bones || []) consider(bone);+ }+ }++ get hasSkeleton() { return this.bones.size > 0; }++ // GLB bones aren't directly raycastable (they have no geometry); the studio+ // raycasts the skinned mesh and we resolve the nearest skinned bone by+ // screen proximity in the studio. Bones themselves return their canonical+ // key when hit (covers rigs that ship bone helper geometry).+ boneFromHit(object) {+ let o = object;+ while (o) {+ if (o.isBone) {+ const canonical = NORMALIZED_CANONICAL.get(normalizeBoneName(o.name));+ if (canonical && this.bones.has(canonical)) return canonical;+ }+ o = o.parent;+ }+ return null;+ }++ resetPose() {+ // Restore each posable bone to its bind/rest local transform. We captured+ // nothing at load besides the live transform, so reset means identity-ish+ // rest: re-read from the skeleton's boneInverses when available.+ for (const sm of this.skinnedMeshes) {+ const sk = sm.skeleton;+ if (!sk) continue;+ sk.pose(); // restores bones to their bind pose+ }+ if (this._restRootPos) this.root.position.copy(this._restRootPos);+ }++ captureRest() {+ // Snapshot the bind pose so resetPose() and applyPose() have a baseline.+ this._restRootPos = this.root.position.clone();+ }+}++// Convert a legacy mannequin preset ({ jointName: {x,y,z} Euler, rootPosition })+// into a canonical quaternion pose so presets apply to any rig uniformly.+export function poseFromMannequinPreset(presetPose) {+ const bones = {};+ for (const [joint, rot] of Object.entries(presetPose || {})) {+ if (joint === 'rootPosition' || !rot) continue;+ const canonical = MANNEQUIN_TO_CANONICAL[joint];+ if (!canonical) continue;+ const q = new Quaternion().setFromEuler(new Euler(rot.x || 0, rot.y || 0, rot.z || 0, 'XYZ'));+ bones[canonical] = [q.x, q.y, q.z, q.w];+ }+ const pose = { bones };+ if (presetPose?.rootPosition) pose.rootPosition = presetPose.rootPosition;+ return pose;+}++// Build a rig over a freshly-loaded gltf scene; returns null if it has no+// recognizable humanoid skeleton (caller shows an actionable error).+export function makeGltfRig(scene) {+ const rig = new GltfRig(scene);+ if (!rig.hasSkeleton) return null;+ rig.captureRest();+ return rig;+}diff --git a/src/pose-studio.js b/src/pose-studio.jsindex 2b526fc04..2ed5a8243 100644--- a/src/pose-studio.js+++ b/src/pose-studio.js@@ -1,11 +1,12 @@-// /pose — 3D pose-reference studio inspired by setpose.com. Builds a-// Three.js scene with an articulated Mannequin, orbit camera, ground +-// grid, and a control panel that lets the user pick presets, drag joints-// to pose them, tweak sliders for fine control, swap body type, add floor-// props, change lighting and FOV, and export a PNG screenshot.+// /pose — the three.ws Animation Studio. A Three.js scene with a posable rig+// (the built-in primitive mannequin OR a loaded rigged GLB avatar — including+// the user's own three.ws avatars), orbit camera, ground + grid, and a control+// panel for posing (FK gizmos + sliders and drag-IK), presets, lighting, props,+// and PNG export. Task 2 layers a keyframe timeline on top of this foundation.import {AmbientLight,+ Box3,BoxGeometry,CircleGeometry,Color,@@ -15,9 +16,12 @@ import {Group,HemisphereLight,Mesh,+ MeshBasicMaterial,MeshStandardMaterial,PCFSoftShadowMap,PerspectiveCamera,+ Plane,+ Quaternion,Raycaster,Scene,ShadowMaterial,@@ -27,9 +31,18 @@ import {WebGLRenderer,} from 'three';import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';+import { TransformControls } from 'three/examples/jsm/controls/TransformControls.js';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';-import { JOINT_AXIS_LABELS, JOINT_LABELS, Mannequin } from './pose-mannequin.js';+import { getDecoders } from './viewer/internal.js';+import {+ CANONICAL_LABELS,+ MannequinRig,+ makeGltfRig,+ poseFromMannequinPreset,+} from './pose-rig.js';import { PRESETS, getPresetsByGroup, getPresetById } from './pose-presets.js';+import { AvatarGalleryPicker } from './avatar-gallery-picker.js';// ─── DOM helpers ────────────────────────────────────────────────────────const $ = (sel) => document.querySelector(sel);@@ -49,9 +62,6 @@ const el = (tag, attrs = {}, children = []) => {};// ─── Floor props ────────────────────────────────────────────────────────-// Simple primitive-based props the user can drop into the scene as drawing-// references. Each prop is a function that returns a Group positioned so-// its base sits on y = 0.const FLOOR_PROPS = {none: { label: 'None', build: null },chair: {@@ -142,6 +152,10 @@ const FLOOR_PROPS = {},};+// Shared IK target-handle assets (cloned per handle for per-instance opacity).+const handleGeom = new SphereGeometry(0.045, 16, 12);+const handleMat = new MeshBasicMaterial({ color: '#22d3ee', transparent: true, opacity: 0.9, depthTest: false });+// ─── Scene setup ────────────────────────────────────────────────────────function setupScene(canvas, hudStatus) {const scene = new Scene();@@ -153,7 +167,7 @@ function setupScene(canvas, hudStatus) {const renderer = new WebGLRenderer({canvas,antialias: true,- preserveDrawingBuffer: true, // needed for toDataURL screenshots+ preserveDrawingBuffer: true, // needed for toDataURL screenshots / thumbnails});renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));renderer.shadowMap.enabled = true;@@ -167,8 +181,20 @@ function setupScene(canvas, hudStatus) {controls.maxPolarAngle = Math.PI * 0.96;controls.target.set(0, 0.95, 0);- // Lighting — a hemisphere + key directional light produces the soft- // silhouette/shadow look that pose references need.+ // Rotation gizmo for the selected bone (FK posing). Newer three exposes the+ // visual via getHelper(); the control instance carries the interaction.+ const gizmo = new TransformControls(camera, canvas);+ gizmo.setMode('rotate');+ gizmo.setSpace('local');+ gizmo.setSize(0.8);+ gizmo.visible = false;+ gizmo.enabled = false;+ scene.add(gizmo.getHelper());+ // Suspend orbit while a gizmo drag is in progress.+ gizmo.addEventListener('dragging-changed', (e) => {+ controls.enabled = !e.value;+ });+const hemi = new HemisphereLight('#f1f5f9', '#0a0a0f', 0.55);scene.add(hemi);const ambient = new AmbientLight('#ffffff', 0.18);@@ -191,7 +217,6 @@ function setupScene(canvas, hudStatus) {fill.position.set(-2.5, 2, -2);scene.add(fill);- // Ground — invisible shadow catcher + grid for reference.const ground = new Mesh(new CircleGeometry(12, 64), new ShadowMaterial({ opacity: 0.35 }));ground.rotation.x = -Math.PI / 2;ground.position.y = 0;@@ -205,6 +230,11 @@ function setupScene(canvas, hudStatus) {const propLayer = new Group();scene.add(propLayer);+ // Layer that holds draggable IK target handles (kept out of the rig so it+ // survives a rig swap and never exports into a GLB).+ const ikLayer = new Group();+ scene.add(ikLayer);+function resize() {const w = canvas.clientWidth;const h = canvas.clientHeight;@@ -221,20 +251,34 @@ function setupScene(canvas, hudStatus) {hudStatus.dataset.kind = kind;}- return { scene, camera, renderer, controls, key, hemi, ambient, propLayer, setStatus };+ return { scene, camera, renderer, controls, gizmo, key, hemi, ambient, propLayer, ikLayer, setStatus };}// ─── State ──────────────────────────────────────────────────────────────const state = {- selectedJoint: null,- dragMode: 'bend', // 'bend' | 'tilt' | 'twist' | 'move'- dragging: null, // { joint, startX, startY, startRot }+ rig: null, // current Rig (MannequinRig | GltfRig)+ selectedBone: null, // canonical bone key+ poseMode: 'fk', // 'fk' (gizmo + sliders) | 'ik' (drag end-effectors)+ avatar: null, // { id, name } when a GLB is loaded, else null+ loadingAvatar: false,prop: 'none',propGroup: null,keyLight: null,- keyAzimuth: 0.9, // radians around Y- keyElevation: 0.95, // radians from +Y down+ keyAzimuth: 0.9,+ keyElevation: 0.95,keyDistance: 5.8,+ ikHandles: new Map(), // effectorKey → Mesh+ draggingIK: null, // { effectorKey, plane }+};++// Studio handle exposed for later tasks (timeline/save) to share the rig ++// scene without re-importing internals.+export const studio = {+ get rig() { return state.rig; },+ get scene() { return state.ctx?.scene || null; },+ get camera() { return state.ctx?.camera || null; },+ get renderer() { return state.ctx?.renderer || null; },+ get avatar() { return state.avatar; },};// ─── App boot ───────────────────────────────────────────────────────────@@ -247,123 +291,269 @@ function boot() {}const ctx = setupScene(canvas, hudStatus);- const { scene, camera, renderer, controls, key, propLayer, setStatus } = ctx;+ state.ctx = ctx;+ const { scene, camera, renderer, controls, gizmo, key, propLayer, ikLayer, setStatus } = ctx;state.keyLight = key;- const mannequin = new Mannequin({ build: 'male', color: '#d4d4d8' });- scene.add(mannequin.root);+ // Panel DOM refs (resolved up-front: mountRig() renders into them on boot).+ const sliderHost = $('#pose-controls-host');+ const selectionLabel = $('#pose-selection-label');+ const boneListHost = $('#pose-joint-picker');+ const boneSearch = $('#pose-bone-search');++ // ── Rig lifecycle ────────────────────────────────────────────────────+ function mountRig(rig) {+ // Tear down the previous rig.+ if (state.rig) {+ gizmo.detach();+ scene.remove(state.rig.root);+ state.rig.dispose?.();+ }+ state.rig = rig;+ scene.add(rig.root);+ state.selectedBone = null;+ clearIKHandles();+ buildIKHandles();+ applyPoseMode();+ renderControlsPanel();+ renderBoneList();+ updateSelectionLabel();+ }++ const mannequinRig = new MannequinRig({ build: 'male', color: '#d4d4d8' });+ mountRig(mannequinRig);+ state.avatar = null;// Pick a reasonable starting pose so the figure looks alive on load.const intro = getPresetById('contrapposto');- if (intro) mannequin.applyPose(intro.pose);+ if (intro) state.rig.applyPose(poseFromMannequinPreset(intro.pose));- // Render loop.+ // ── Render loop ──────────────────────────────────────────────────────function tick() {requestAnimationFrame(tick);controls.update();+ if (state.poseMode === 'ik' && !state.draggingIK) syncIKHandles();renderer.render(scene, camera);}tick();- // ── Raycast selection + drag-to-rotate ──────────────────────────────+ // ── Camera framing ───────────────────────────────────────────────────+ function frameObject(object) {+ object.updateMatrixWorld(true);+ const box = new Box3().setFromObject(object);+ if (box.isEmpty()) return;+ const size = box.getSize(new Vector3());+ const center = box.getCenter(new Vector3());+ // Drop the rig so its feet rest on the ground plane.+ object.position.y -= box.min.y;+ const height = Math.max(0.5, size.y);+ controls.target.set(0, height * 0.55, 0);+ const dist = height * 2.2;+ camera.position.set(dist * 0.6, height * 0.8, dist);+ controls.minDistance = height * 0.4;+ controls.maxDistance = height * 8;+ controls.update();+ }++ // ── Raycast selection (FK) ─────────────────────────────────────────────const raycaster = new Raycaster();const ndc = new Vector2();+ const _v = new Vector3();- function pickJointAt(clientX, clientY) {+ function toNDC(clientX, clientY) {const rect = canvas.getBoundingClientRect();ndc.x = ((clientX - rect.left) / rect.width) * 2 - 1;ndc.y = -((clientY - rect.top) / rect.height) * 2 + 1;- raycaster.setFromCamera(ndc, camera);- const hits = raycaster.intersectObjects(mannequin.selectableMeshes, false);+ return ndc;+ }++ // Pick a bone from a screen position. Mannequin: raycast tagged meshes. GLB:+ // raycast the skinned mesh to confirm the click is on the figure, then pick+ // the posable bone whose projected position is nearest the cursor.+ function pickBoneAt(clientX, clientY) {+ const rig = state.rig;+ raycaster.setFromCamera(toNDC(clientX, clientY), camera);+ if (rig.kind === 'mannequin') {+ const hits = raycaster.intersectObjects(rig.getSelectableMeshes(), false);+ if (!hits.length) return null;+ return rig.boneFromHit(hits[0].object);+ }+ // GLB: require a hit on the mesh so empty-space clicks deselect.+ const meshes = rig.skinnedMeshes?.length ? rig.skinnedMeshes : rig.getSelectableMeshes();+ const hits = raycaster.intersectObjects(meshes, true);if (!hits.length) return null;- return mannequin.jointFromHit(hits[0].object);+ const rect = canvas.getBoundingClientRect();+ const px = clientX - rect.left;+ const py = clientY - rect.top;+ let best = null;+ let bestDist = Infinity;+ for (const { key, node } of rig.getBones()) {+ node.getWorldPosition(_v).project(camera);+ const sx = (_v.x * 0.5 + 0.5) * rect.width;+ const sy = (-_v.y * 0.5 + 0.5) * rect.height;+ const d = Math.hypot(sx - px, sy - py);+ if (d < bestDist) { bestDist = d; best = key; }+ }+ return bestDist < 80 ? best : null;}- function selectJoint(name) {- state.selectedJoint = name;+ function selectBone(key) {+ state.selectedBone = key;+ if (state.poseMode === 'fk') attachGizmo();renderControlsPanel();+ renderBoneList();updateSelectionLabel();}canvas.addEventListener('pointerdown', (ev) => {- // Left button only — right/middle stay with OrbitControls.if (ev.button !== 0) return;- const joint = pickJointAt(ev.clientX, ev.clientY);- if (!joint) return;- selectJoint(joint);- if (state.dragMode === 'move') return;- controls.enabled = false;- const rot = mannequin.getJointRotation(joint);- state.dragging = {- joint,- startX: ev.clientX,- startY: ev.clientY,- startRot: { ...rot },- };- canvas.setPointerCapture(ev.pointerId);- ev.preventDefault();+ if (gizmo.dragging) return; // gizmo owns this drag+ if (state.poseMode === 'ik' && tryStartIKDrag(ev)) {+ ev.preventDefault();+ return;+ }+ const bone = pickBoneAt(ev.clientX, ev.clientY);+ if (bone) selectBone(bone);});canvas.addEventListener('pointermove', (ev) => {- const d = state.dragging;- if (!d) return;- const dx = (ev.clientX - d.startX) / 140;- const dy = (ev.clientY - d.startY) / 140;- const r = { ...d.startRot };- if (state.dragMode === 'bend') {- r.x = d.startRot.x + dy;- r.z = d.startRot.z + dx;- } else if (state.dragMode === 'tilt') {- r.z = d.startRot.z + dx;- r.x = d.startRot.x + dy * 0.3;- } else if (state.dragMode === 'twist') {- r.y = d.startRot.y + dx;- }- mannequin.setJointRotation(d.joint, 'x', r.x);- mannequin.setJointRotation(d.joint, 'y', r.y);- mannequin.setJointRotation(d.joint, 'z', r.z);- // Re-read so constraint clamping is reflected in the sliders.- if (state.selectedJoint === d.joint) renderControlsPanel();+ if (!state.draggingIK) return;+ const hit = intersectDragPlane(ev.clientX, ev.clientY, state.draggingIK.plane);+ if (!hit) return;+ state.rig.solveIK(state.draggingIK.effectorKey, hit);+ const handle = state.ikHandles.get(state.draggingIK.effectorKey);+ if (handle) handle.position.copy(hit);+ if (state.selectedBone) renderControlsPanel();});- function endDrag(ev) {- if (!state.dragging) return;+ function endIKDrag(ev) {+ if (!state.draggingIK) return;try { canvas.releasePointerCapture(ev.pointerId); } catch {}- state.dragging = null;+ state.draggingIK = null;controls.enabled = true;+ syncIKHandles();}- canvas.addEventListener('pointerup', endDrag);- canvas.addEventListener('pointercancel', endDrag);+ canvas.addEventListener('pointerup', endIKDrag);+ canvas.addEventListener('pointercancel', endIKDrag);- // ── Controls panel rendering ────────────────────────────────────────- const sliderHost = $('#pose-controls-host');- const selectionLabel = $('#pose-selection-label');+ // Gizmo rotations should refresh the slider readout live.+ gizmo.addEventListener('objectChange', () => {+ if (state.selectedBone) renderControlsPanel();+ });+ // ── FK gizmo ───────────────────────────────────────────────────────────+ function attachGizmo() {+ const key = state.selectedBone;+ const node = key && state.rig.getNode(key);+ if (state.poseMode !== 'fk' || !node) {+ gizmo.detach();+ gizmo.enabled = false;+ gizmo.visible = false;+ return;+ }+ gizmo.attach(node);+ gizmo.enabled = true;+ gizmo.visible = true;+ }++ // ── IK target handles ──────────────────────────────────────────────────+ function buildIKHandles() {+ for (const chain of state.rig.getIKChains()) {+ const m = new Mesh(handleGeom, handleMat.clone());+ m.renderOrder = 999;+ m.userData.effectorKey = chain.effectorKey;+ m.visible = false;+ ikLayer.add(m);+ state.ikHandles.set(chain.effectorKey, m);+ }+ syncIKHandles();+ }+ function clearIKHandles() {+ for (const m of state.ikHandles.values()) ikLayer.remove(m);+ state.ikHandles.clear();+ }+ function syncIKHandles() {+ for (const [effKey, m] of state.ikHandles) {+ const node = state.rig.getNode(effKey);+ if (node) node.getWorldPosition(m.position);+ }+ }++ function tryStartIKDrag(ev) {+ raycaster.setFromCamera(toNDC(ev.clientX, ev.clientY), camera);+ const handles = [...state.ikHandles.values()].filter((m) => m.visible);+ const hits = raycaster.intersectObjects(handles, false);+ if (!hits.length) return false;+ const handle = hits[0].object;+ const effectorKey = handle.userData.effectorKey;+ // Drag plane: faces the camera, passes through the handle.+ const normal = camera.getWorldDirection(new Vector3()).negate();+ const plane = new Plane().setFromNormalAndCoplanarPoint(normal, handle.position.clone());+ state.draggingIK = { effectorKey, plane };+ controls.enabled = false;+ canvas.setPointerCapture(ev.pointerId);+ selectBone(effectorKey);+ return true;+ }++ function intersectDragPlane(clientX, clientY, plane) {+ raycaster.setFromCamera(toNDC(clientX, clientY), camera);+ const pt = new Vector3();+ return raycaster.ray.intersectPlane(plane, pt) ? pt : null;+ }++ function applyPoseMode() {+ const ik = state.poseMode === 'ik';+ for (const m of state.ikHandles.values()) m.visible = ik;+ if (ik) {+ gizmo.detach();+ gizmo.enabled = false;+ gizmo.visible = false;+ syncIKHandles();+ } else {+ attachGizmo();+ }+ document.querySelectorAll('[data-posemode]').forEach((b) => {+ b.setAttribute('aria-pressed', String(b.dataset.posemode === state.poseMode));+ });+ const hasIK = state.rig.getIKChains().length > 0;+ const ikBtn = document.querySelector('[data-posemode="ik"]');+ if (ikBtn) {+ ikBtn.disabled = !hasIK;+ ikBtn.title = hasIK+ ? 'IK — drag a hand or foot and the limb solves'+ : 'IK unavailable — this rig has no recognizable limb chains';+ }+ }++ // ── Controls panel (FK sliders for the selected bone) ───────────────────function updateSelectionLabel() {if (!selectionLabel) return;- selectionLabel.textContent = state.selectedJoint- ? JOINT_LABELS[state.selectedJoint] || state.selectedJoint+ selectionLabel.textContent = state.selectedBone+ ? CANONICAL_LABELS[state.selectedBone] || state.selectedBone: 'Click a body part';}function renderControlsPanel() {if (!sliderHost) return;sliderHost.innerHTML = '';- const joint = state.selectedJoint;- if (!joint) {+ const key = state.selectedBone;+ if (!key || !state.rig.hasBone(key)) {sliderHost.appendChild(el('p', { class: 'pose-hint' }, [- 'Click any body part in the scene, or pick a preset on the right, to start posing.',+ state.poseMode === 'ik'+ ? 'Drag a glowing hand or foot handle to pose the limb with inverse kinematics.'+ : 'Click any body part in the scene, search a bone on the left, or pick a preset to start posing.',]),);return;}- const rot = mannequin.getJointRotation(joint);- const axisLabels = JOINT_AXIS_LABELS[joint] || JOINT_AXIS_LABELS.default;- for (const axis of ['x', 'y', 'z']) {+ const rot = state.rig.getBoneEuler(key);+ const AXES = [['x', 'Bend / Pitch'], ['y', 'Twist / Yaw'], ['z', 'Tilt / Roll']];+ for (const [axis, label] of AXES) {const value = rot[axis];const row = el('div', { class: 'pose-slider-row' }, [- el('label', {}, [`${axisLabels[axis]} (${axis.toUpperCase()})`]),+ el('label', {}, [`${label} (${axis.toUpperCase()})`]),el('div', { class: 'pose-slider-value', 'data-axis': axis }, [`${((value * 180) / Math.PI).toFixed(0)}°`,]),@@ -374,61 +564,55 @@ function boot() {max: '3.14159',step: '0.01',value: String(value),+ 'aria-label': `${CANONICAL_LABELS[key] || key} ${label}`,});slider.addEventListener('input', () => {- const v = parseFloat(slider.value);- mannequin.setJointRotation(joint, axis, v);- const next = mannequin.getJointRotation(joint);+ const cur = state.rig.getBoneEuler(key);+ cur[axis] = parseFloat(slider.value);+ state.rig.setBoneEuler(key, cur);+ const next = state.rig.getBoneEuler(key);row.querySelector(`.pose-slider-value[data-axis="${axis}"]`).textContent =`${((next[axis] * 180) / Math.PI).toFixed(0)}°`;- // If constraint clamped the value, snap the slider back.slider.value = String(next[axis]);});row.appendChild(slider);sliderHost.appendChild(row);}- // Reset-this-joint button.- const resetBtn = el('button', {- class: 'pose-btn pose-btn-ghost',- type: 'button',- }, ['Reset this joint']);+ const resetBtn = el('button', { class: 'pose-btn pose-btn-ghost', type: 'button' }, ['Reset this bone']);resetBtn.addEventListener('click', () => {- mannequin.setJointRotation(joint, 'x', 0);- mannequin.setJointRotation(joint, 'y', 0);- mannequin.setJointRotation(joint, 'z', 0);+ state.rig.setBoneEuler(key, { x: 0, y: 0, z: 0 });renderControlsPanel();});sliderHost.appendChild(resetBtn);}- renderControlsPanel();- updateSelectionLabel();-- // ── Joint-list quick picker (left panel) ────────────────────────────- const jointPicker = $('#pose-joint-picker');- if (jointPicker) {- const order = [- ['Head', ['head', 'neck']],- ['Torso', ['chest', 'spine', 'pelvis']],- ['Arms', ['shoulderL', 'elbowL', 'wristL', 'shoulderR', 'elbowR', 'wristR']],- ['Legs', ['hipL', 'kneeL', 'ankleL', 'hipR', 'kneeR', 'ankleR']],- ];- for (const [group, names] of order) {- jointPicker.appendChild(el('div', { class: 'pose-joint-group' }, [group]));- const row = el('div', { class: 'pose-joint-row' }, []);- for (const name of names) {- const btn = el('button', {- class: 'pose-joint-btn',- type: 'button',- 'data-joint': name,- }, [JOINT_LABELS[name] || name]);- btn.addEventListener('click', () => selectJoint(name));- row.appendChild(btn);- }- jointPicker.appendChild(row);++ // ── Bone list (searchable) ───────────────────────────────────────────────+ function renderBoneList() {+ if (!boneListHost) return;+ const q = (boneSearch?.value || '').trim().toLowerCase();+ boneListHost.innerHTML = '';+ const bones = state.rig.getBones().filter(({ key, label }) =>+ !q || key.toLowerCase().includes(q) || label.toLowerCase().includes(q));+ if (!bones.length) {+ boneListHost.appendChild(el('p', { class: 'pose-hint' }, ['No bones match your search.']));+ return;+ }+ const row = el('div', { class: 'pose-joint-row' }, []);+ for (const { key, label } of bones) {+ const btn = el('button', {+ class: 'pose-joint-btn',+ type: 'button',+ 'data-bone': key,+ 'aria-pressed': String(state.selectedBone === key),+ }, [label]);+ btn.addEventListener('click', () => selectBone(key));+ row.appendChild(btn);}+ boneListHost.appendChild(row);}+ boneSearch?.addEventListener('input', renderBoneList);- // ── Preset picker (right panel) ─────────────────────────────────────+ // ── Preset picker ──────────────────────────────────────────────────────const presetHost = $('#pose-presets-host');if (presetHost) {const grouped = getPresetsByGroup();@@ -437,14 +621,11 @@ function boot() {presetHost.appendChild(el('div', { class: 'pose-preset-group' }, [groupName]));const wrap = el('div', { class: 'pose-preset-grid' }, []);for (const preset of presets) {- const btn = el('button', {- class: 'pose-preset-btn',- type: 'button',- 'data-preset': preset.id,- }, [preset.label]);+ const btn = el('button', { class: 'pose-preset-btn', type: 'button', 'data-preset': preset.id }, [preset.label]);btn.addEventListener('click', () => {- mannequin.applyPose(preset.pose);- selectJoint(state.selectedJoint); // re-render sliders+ state.rig.applyPose(poseFromMannequinPreset(preset.pose));+ if (state.poseMode === 'fk') attachGizmo();+ renderControlsPanel();setStatus(`Applied preset: ${preset.label}`);});wrap.appendChild(btn);@@ -453,26 +634,133 @@ function boot() {}}- // ── Top toolbar wiring ──────────────────────────────────────────────- const modeButtons = document.querySelectorAll('[data-mode]');- modeButtons.forEach((btn) => {+ // ── Avatar loading ───────────────────────────────────────────────────────+ const gltfLoader = new GLTFLoader();+ let decodersReady = null;+ async function ensureDecoders() {+ if (!decodersReady) {+ decodersReady = getDecoders().then(({ dracoLoader, ktx2Loader, meshoptDecoder }) => {+ gltfLoader+ .setDRACOLoader(dracoLoader)+ .setKTX2Loader(ktx2Loader.detectSupport(renderer))+ .setMeshoptDecoder(meshoptDecoder);+ });+ }+ return decodersReady;+ }++ async function loadAvatarFromUrl(modelUrl, meta = {}) {+ if (!modelUrl) throw new Error('No model URL for this avatar.');+ await ensureDecoders();+ setStatus(`Loading ${meta.name || 'avatar'}…`);+ state.loadingAvatar = true;+ const gltf = await new Promise((resolve, reject) => {+ gltfLoader.load(+ modelUrl,+ resolve,+ (xhr) => {+ if (xhr.total) {+ const pct = Math.round((xhr.loaded / xhr.total) * 100);+ setStatus(`Loading ${meta.name || 'avatar'}… ${pct}%`);+ }+ },+ reject,+ );+ });+ state.loadingAvatar = false;+ const scn = gltf.scene || gltf.scenes?.[0];+ const rig = scn && makeGltfRig(scn);+ if (!rig) {+ throw new Error('That model has no recognizable humanoid skeleton — pick a rigged avatar.');+ }+ mountRig(rig);+ state.avatar = { id: meta.id || null, name: meta.name || 'Avatar', model_url: modelUrl };+ frameObject(rig.root);+ setMannequinControlsEnabled(false);+ setStatus(`Loaded ${state.avatar.name}. Select a bone to pose, or switch to IK.`);+ }++ async function loadAvatarById(id) {+ setStatus('Resolving avatar…');+ const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`, { credentials: 'include' });+ if (!res.ok) throw new Error(`Couldn't load avatar (${res.status}). It may be private or removed.`);+ const { avatar } = await res.json();+ const url = avatar?.model_url || avatar?.url;+ if (!url) throw new Error('That avatar has no downloadable model.');+ await loadAvatarFromUrl(url, { id: avatar.id, name: avatar.name });+ }++ function switchToMannequin() {+ gizmo.detach();+ mountRig(mannequinRig);+ state.avatar = null;+ controls.target.set(0, 0.95, 0);+ camera.position.set(2.2, 1.65, 3.0);+ controls.update();+ setMannequinControlsEnabled(true);+ updateUrlAvatar(null);+ setStatus('Switched to mannequin.');+ }++ function updateUrlAvatar(id) {+ const url = new URL(window.location.href);+ if (id) url.searchParams.set('avatar', id);+ else url.searchParams.delete('avatar');+ window.history.replaceState({}, '', url);+ }++ function setMannequinControlsEnabled(on) {+ for (const sel of ['#pose-build', '#pose-skin', '#pose-constraints']) {+ const node = $(sel);+ if (node) {+ node.disabled = !on;+ node.closest('.pose-form-row')?.classList.toggle('pose-disabled', !on);+ }+ }+ }++ // Load avatar / mannequin toolbar buttons.+ $('#pose-load-avatar')?.addEventListener('click', () => {+ const signedIn = document.cookie.includes('session') || false;+ const picker = new AvatarGalleryPicker({+ source: signedIn ? 'both' : 'public',+ title: 'Load an avatar to animate',+ ctaLabel: 'Pose this avatar',+ showModes: false,+ onSelect: async (avatar) => {+ picker.close();+ try {+ await loadAvatarFromUrl(avatar.model_url, { id: avatar.id, name: avatar.name });+ updateUrlAvatar(avatar.id);+ } catch (err) {+ setStatus(err.message, 'error');+ }+ },+ });+ picker.openModal();+ });+ $('#pose-use-mannequin')?.addEventListener('click', switchToMannequin);++ // ── Posing-mode toggle (FK / IK) ────────────────────────────────────────+ document.querySelectorAll('[data-posemode]').forEach((btn) => {btn.addEventListener('click', () => {- state.dragMode = btn.dataset.mode;- modeButtons.forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));+ if (btn.disabled) return;+ state.poseMode = btn.dataset.posemode;+ applyPoseMode();+ renderControlsPanel();});});- const initialMode = document.querySelector(`[data-mode="${state.dragMode}"]`);- if (initialMode) initialMode.setAttribute('aria-pressed', 'true');+ // ── Top toolbar ──────────────────────────────────────────────────────────$('#pose-reset')?.addEventListener('click', () => {- mannequin.resetPose();+ state.rig.resetPose();+ if (state.poseMode === 'fk') attachGizmo();+ else syncIKHandles();setStatus('Pose reset.');renderControlsPanel();});- $('#pose-screenshot')?.addEventListener('click', async () => {- // Force one synchronous render so the WebGL backbuffer is fresh- // before we grab a data URL (preserveDrawingBuffer keeps it valid).+ $('#pose-screenshot')?.addEventListener('click', () => {renderer.render(scene, camera);const url = canvas.toDataURL('image/png');const a = document.createElement('a');@@ -485,7 +773,7 @@ function boot() {});$('#pose-export-json')?.addEventListener('click', () => {- const pose = mannequin.getPose();+ const pose = state.rig.getPose();const blob = new Blob([JSON.stringify(pose, null, 2)], { type: 'application/json' });const url = URL.createObjectURL(blob);const a = document.createElement('a');@@ -505,7 +793,8 @@ function boot() {reader.onload = () => {try {const pose = JSON.parse(String(reader.result));- mannequin.applyPose(pose);+ state.rig.applyPose(pose);+ if (state.poseMode === 'fk') attachGizmo();renderControlsPanel();setStatus(`Imported pose from ${file.name}.`);} catch (err) {@@ -516,90 +805,80 @@ function boot() {ev.target.value = '';});- // ── Settings panel ──────────────────────────────────────────────────+ // ── Settings panel (mannequin-only model controls) ───────────────────────$('#pose-build')?.addEventListener('change', (ev) => {- mannequin.setBuild(ev.target.value);+ if (state.rig.kind !== 'mannequin') return;+ state.rig.setBuild(ev.target.value);+ buildIKHandles();+ applyPoseMode();});-$('#pose-skin')?.addEventListener('input', (ev) => {- mannequin.setColor(ev.target.value);- });-- $('#pose-bg')?.addEventListener('input', (ev) => {- scene.background = new Color(ev.target.value);+ if (state.rig.kind === 'mannequin') state.rig.setColor(ev.target.value);});-$('#pose-constraints')?.addEventListener('change', (ev) => {- mannequin.setConstraintsEnabled(ev.target.checked);+ if (state.rig.kind !== 'mannequin') return;+ state.rig.setConstraintsEnabled(ev.target.checked);setStatus(ev.target.checked ? 'Biological constraints on.' : 'Constraints off — full rotation allowed.');});+ $('#pose-bg')?.addEventListener('input', (ev) => { scene.background = new Color(ev.target.value); });$('#pose-fov')?.addEventListener('input', (ev) => {camera.fov = parseFloat(ev.target.value);camera.updateProjectionMatrix();});-$('#pose-grid')?.addEventListener('change', (ev) => {- ctx.scene.traverse((o) => {- if (o.isGridHelper) o.visible = ev.target.checked;- });+ scene.traverse((o) => { if (o.isGridHelper) o.visible = ev.target.checked; });});- // Light direction — azimuth (around Y) and elevation. Distance fixed- // to the value set in state.keyDistance. Updating these moves the key- // light around the figure to change shadow direction.function syncKeyLight() {const r = state.keyDistance;- const az = state.keyAzimuth;- const el = state.keyElevation; // angle from horizon- const x = r * Math.cos(el) * Math.sin(az);- const z = r * Math.cos(el) * Math.cos(az);- const y = r * Math.sin(el);+ const x = r * Math.cos(state.keyElevation) * Math.sin(state.keyAzimuth);+ const z = r * Math.cos(state.keyElevation) * Math.cos(state.keyAzimuth);+ const y = r * Math.sin(state.keyElevation);state.keyLight.position.set(x, y, z);state.keyLight.target.position.set(0, 0.9, 0);state.keyLight.target.updateMatrixWorld();}syncKeyLight();+ $('#pose-light-azimuth')?.addEventListener('input', (ev) => { state.keyAzimuth = (parseFloat(ev.target.value) / 180) * Math.PI; syncKeyLight(); });+ $('#pose-light-elevation')?.addEventListener('input', (ev) => { state.keyElevation = (parseFloat(ev.target.value) / 180) * Math.PI; syncKeyLight(); });+ $('#pose-light-intensity')?.addEventListener('input', (ev) => { state.keyLight.intensity = parseFloat(ev.target.value); });- $('#pose-light-azimuth')?.addEventListener('input', (ev) => {- state.keyAzimuth = (parseFloat(ev.target.value) / 180) * Math.PI;- syncKeyLight();- });- $('#pose-light-elevation')?.addEventListener('input', (ev) => {- state.keyElevation = (parseFloat(ev.target.value) / 180) * Math.PI;- syncKeyLight();- });- $('#pose-light-intensity')?.addEventListener('input', (ev) => {- state.keyLight.intensity = parseFloat(ev.target.value);- });-- // ── Floor props ─────────────────────────────────────────────────────+ // ── Floor props ────────────────────────────────────────────────────────const propHost = $('#pose-prop-host');if (propHost) {for (const [id, def] of Object.entries(FLOOR_PROPS)) {- const btn = el('button', {- class: 'pose-prop-btn',- type: 'button',- 'data-prop': id,- 'aria-pressed': String(state.prop === id),- }, [def.label]);+ const btn = el('button', { class: 'pose-prop-btn', type: 'button', 'data-prop': id, 'aria-pressed': String(state.prop === id) }, [def.label]);btn.addEventListener('click', () => {state.prop = id;propLayer.clear();- if (def.build) {- const g = def.build();- propLayer.add(g);- state.propGroup = g;- }- document.querySelectorAll('[data-prop]').forEach((b) => {- b.setAttribute('aria-pressed', String(b.dataset.prop === id));- });+ if (def.build) { const g = def.build(); propLayer.add(g); state.propGroup = g; }+ document.querySelectorAll('[data-prop]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.prop === id)));});propHost.appendChild(btn);}}- setStatus('Ready. Click a body part to pose.');+ // ── Keyboard shortcuts ───────────────────────────────────────────────────+ window.addEventListener('keydown', (ev) => {+ if (ev.target.matches('input, textarea, select')) return;+ const k = ev.key.toLowerCase();+ if (k === 'f') { state.poseMode = 'fk'; applyPoseMode(); renderControlsPanel(); }+ else if (k === 'i') { const b = document.querySelector('[data-posemode="ik"]'); if (b && !b.disabled) { state.poseMode = 'ik'; applyPoseMode(); renderControlsPanel(); } }+ else if (k === 'r' && state.selectedBone) { state.rig.setBoneEuler(state.selectedBone, { x: 0, y: 0, z: 0 }); renderControlsPanel(); }+ else if (k === 'escape') { state.selectedBone = null; gizmo.detach(); renderControlsPanel(); renderBoneList(); updateSelectionLabel(); }+ });++ // ── Boot: honor ?avatar= ─────────────────────────────────────────────────+ const requestedAvatar = new URL(window.location.href).searchParams.get('avatar');+ if (requestedAvatar) {+ loadAvatarById(requestedAvatar).catch((err) => {+ setStatus(`${err.message} Showing the mannequin instead.`, 'error');+ switchToMannequin();+ });+ } else {+ setStatus('Ready. Click a body part to pose, or load an avatar.');+ }}document.addEventListener('DOMContentLoaded', boot);diff --git a/src/selfie-pipeline.js b/src/selfie-pipeline.jsindex ef0158921..286647c4d 100644--- a/src/selfie-pipeline.js+++ b/src/selfie-pipeline.js@@ -400,7 +400,10 @@ function fit(w, h, max) {function mapApiError(status, payload) {const code = payload.error;if (status === 401) {- const next = encodeURIComponent('/create/selfie');+ // Return to whichever surface initiated the flow (/create/selfie or /scan)+ // so the post-login round-trip resumes on the right page.+ const here = typeof location !== 'undefined' ? location.pathname : '/create/selfie';+ const next = encodeURIComponent(here);const e = withMessage(new Error(code || 'unauthorized'),'Please sign in to create an avatar.',diff --git a/src/solana/vanity/grinder-worker.js b/src/solana/vanity/grinder-worker.jsindex d26ea6184..40758876b 100644--- a/src/solana/vanity/grinder-worker.js+++ b/src/solana/vanity/grinder-worker.js@@ -13,7 +13,6 @@*/import init, { grind } from './wasm/vanity_grinder.js';-import wasmUrl from './wasm/vanity_grinder_bg.wasm?url';// Keep batches small enough that one WASM call returns within ~200 ms even// on slow CPUs — abort latency is bounded by one batch.@@ -25,7 +24,13 @@ let wasmReady = null;function ensureWasm() {if (!wasmReady) {- wasmReady = init({ module_or_path: wasmUrl });+ // No explicit path: the wasm-bindgen glue resolves the binary via+ // `new URL('vanity_grinder_bg.wasm', import.meta.url)`, the asset+ // pattern Vite rewrites in both dev and build. Importing the `.wasm`+ // with `?url` does NOT work here — Vite's built-in wasm handling+ // serves it as `application/wasm`, so a module worker rejects it on+ // the strict MIME check instead of instantiating it.+ wasmReady = init();}return wasmReady;}diff --git a/src/walk-net.js b/src/walk-net.jsindex e87cfcd06..204f4c2b5 100644--- a/src/walk-net.js+++ b/src/walk-net.js@@ -45,10 +45,24 @@ export class WalkNet {* @param {object} opts* @param {string} [opts.name] Display name (1–24 chars after server clean)* @param {string} [opts.url] Override server URL (otherwise resolved from meta)+ * @param {string} [opts.avatar] Loadable GLB URL for this player's avatar / 3D agent+ * @param {string} [opts.agent] three.ws agent id this player embodies (cross-links)+ * @param {string} [opts.coin] Coin mint — joins that coin's community world ('' = mainland)+ * @param {string} [opts.coinName] Coin display name (seeds room identity on create)+ * @param {string} [opts.coinSymbol] Coin ticker+ * @param {string} [opts.coinImage] Coin image URL*/constructor(opts = {}) {this.name = opts.name || 'guest';this.url = opts.url || defaultServerUrl();+ this.avatar = opts.avatar || '';+ this.agent = opts.agent || '';+ // Coin community this client is entering. `coin` (the mint) doubles as the+ // matchmaking key so everyone in the same coin lands in one room instance.+ this.coin = opts.coin || '';+ this.coinName = opts.coinName || '';+ this.coinSymbol = opts.coinSymbol || '';+ this.coinImage = opts.coinImage || '';this.client = null;this.room = null;this.status = 'idle'; // 'idle' | 'connecting' | 'online' | 'offline' | 'failed'@@ -59,6 +73,7 @@ export class WalkNet {add: new Set(), // (player, sessionId)remove: new Set(), // (sessionId)change: new Set(), // (player, sessionId)+ chat: new Set(), // ({ id, name, text, ts })};this._lastSent = null; // { x, y, z, yaw, motion } we last broadcastthis._lastSentAt = 0;@@ -90,7 +105,19 @@ export class WalkNet {this._setStatus('connecting');try {this.client = new Client(this.url);- this.room = await this.client.joinOrCreate(ROOM_NAME, { name: this.name });+ // `token` is the server's filterBy key (matchmaking): clients with the+ // same coin mint join one room instance. `coin`/`coinName`/… seed that+ // room's identity the first time it's created. Empty coin → mainland.+ this.room = await this.client.joinOrCreate(ROOM_NAME, {+ name: this.name,+ avatar: this.avatar,+ agent: this.agent,+ token: this.coin,+ coin: this.coin,+ coinName: this.coinName,+ coinSymbol: this.coinSymbol,+ coinImage: this.coinImage,+ });this.mySessionId = this.room.sessionId;// Colyseus 0.16 moved schema callbacks behind getStateCallbacks(room)@@ -105,6 +132,11 @@ export class WalkNet {this._emit('remove', sessionId);});+ // Chat is broadcast (not schema state) so it arrives as a room message.+ // We relay it through our own event API; walk.js renders the bubble ++ // log line and routes it to the right remote player.+ this.room.onMessage('chat', (msg) => this._emit('chat', msg));+this.room.onLeave((code) => {this._setStatus('offline');if (!this._destroyed && code !== 1000) this._scheduleReconnect();@@ -177,6 +209,18 @@ export class WalkNet {this.room?.send('emote', { name });}+ sendChat(text) {+ const t = String(text || '').trim().slice(0, 200);+ if (t) this.room?.send('chat', { text: t });+ }++ /** Swap this player's avatar mid-session (after picking a new one). */+ sendAvatar(avatar, agent) {+ this.avatar = avatar || this.avatar;+ if (agent != null) this.agent = agent;+ this.room?.send('avatar', { avatar: this.avatar, agent: this.agent });+ }+/** Force a reconnect (e.g. after the user clicks the offline pill). */retry() {if (this._reconnectTimer) {diff --git a/src/walk.js b/src/walk.jsindex e528321bc..04f5696f3 100644--- a/src/walk.js+++ b/src/walk.js@@ -50,17 +50,46 @@ import { WalkNet } from './walk-net.js';const AVATAR_URL_DEFAULT = '/avatars/default.glb';+// The GLB URL the local avatar actually loaded from. Captured by resolveAvatarUrl+// so we can (a) broadcast it to the room — other clients render us as our real+// avatar — and (b) short-circuit remote avatar loads that match ours.+let resolvedAvatarUrl = AVATAR_URL_DEFAULT;+async function resolveAvatarUrl() {const params = new URLSearchParams(location.search);+ // A direct GLB/VRM URL wins — this is what the /communities lobby passes when+ // a guest drops in with a pasted model or a Ready Player Me link.+ const direct = params.get('avatarUrl');+ if (direct) { resolvedAvatarUrl = direct; return direct; }const id = params.get('avatar');- if (!id) return AVATAR_URL_DEFAULT;+ if (!id) { resolvedAvatarUrl = AVATAR_URL_DEFAULT; return AVATAR_URL_DEFAULT; }const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`);if (!res.ok) throw new Error(`avatar ${id} not found (HTTP ${res.status})`);const { avatar } = await res.json();if (!avatar?.url) throw new Error(`avatar ${id} has no GLB URL`);+ resolvedAvatarUrl = avatar.url;return avatar.url;}+// ── Coin community context ────────────────────────────────────────────────+// /walk doubles as the renderer for coin community worlds. When the lobby+// hands off with ?coin=<mint>&coinName=…&coinSymbol=…&coinImage=…, every player+// who entered the same coin shares one room instance (matchmaking key on the+// server) and the world is themed with the coin's identity (HUD + 3D totem).+const COIN_PARAMS = (() => {+ const p = new URLSearchParams(location.search);+ const mint = (p.get('coin') || '').trim();+ const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+ if (!MINT_RE.test(mint)) return { coin: '', name: '', symbol: '', image: '', agent: (p.get('agent') || '').trim() };+ return {+ coin: mint,+ name: (p.get('coinName') || '').slice(0, 48),+ symbol: (p.get('coinSymbol') || '').slice(0, 16),+ image: (p.get('coinImage') || '').slice(0, 1024),+ agent: (p.get('agent') || '').trim(),+ };+})();+const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';const CLIP_IDLE = 'idle';const CLIP_WALK = 'av-walk-feminine';@@ -213,6 +242,17 @@ if (envBtn) envBtn.addEventListener('click', () => cycleEnvironment());if (screenshotBtn) screenshotBtn.addEventListener('click', () => takeScreenshot());if (minimapBtn) minimapBtn.addEventListener('click', () => toggleMinimap());+// ── On-screen touch action cluster (mobile) ──────────────────────────────+// jump / camera flip / gestures for thumbs — keyboardless devices can't reach+// Space, C, or G. The underlying actions already fire haptics; the gesture+// button opens the palette (no emote until one is picked) so it taps its own.+document.getElementById('walk-touch-jump')?.addEventListener('click', () => triggerJump());+document.getElementById('walk-touch-camera')?.addEventListener('click', () => cycleCameraMode());+document.getElementById('walk-touch-gesture')?.addEventListener('click', () => {+ haptics.buzz(5);+ toggleGesturePalette();+});+// ── Players panel ────────────────────────────────────────────────────────let playersPanelOpen = false;function togglePlayersPanel() {@@ -386,6 +426,7 @@ function cycleCameraMode() {const idx = CAMERA_MODES.indexOf(cameraMode);setCameraMode(CAMERA_MODES[(idx + 1) % CAMERA_MODES.length]);setStatus(`Camera: ${CAMERA_MODE_LABELS[cameraMode]}`);+ haptics.buzz(5);}// Camera mode indicator UI element@@ -484,46 +525,73 @@ function frameAvatarCamera({ snap = true } = {}) {}applyCameraImmediate();-// ── Drag-to-orbit on the canvas (one-finger drag rotates the camera yaw) ──+// ── Canvas camera control — one-finger drag orbits, two-finger pinch zooms ──+// Multi-touch aware via a live pointer map: the joystick(s) and the camera can+// be driven at the same time because pointers that land inside a stick zone are+// never tracked here. A single tracked pointer orbits; a second promotes the+// gesture to pinch-zoom; lifting back to one resumes orbit seamlessly.{- let dragging = false;- let lastX = 0, lastY = 0;- let downId = -1;+ const pointers = new Map(); // pointerId → { x, y }+ let orbitId = -1;+ let pinchDist = 0;++ const inRect = (el, x, y) => {+ if (!el) return false;+ const r = el.getBoundingClientRect();+ return x >= r.left && x <= r.right && y >= r.top && y <= r.bottom;+ };+ const pinchDistance = () => {+ const [a, b] = [...pointers.values()];+ return Math.hypot(a.x - b.x, a.y - b.y);+ };canvas.addEventListener('pointerdown', (e) => {- // Don't steal pointer events that belong to the joystick zone.- // On some mobile browsers the canvas (being full-screen) can receive- // a pointerdown before nipplejs does, and setPointerCapture would- // redirect all subsequent pointermove events here — breaking movement.- const inRect = (el) => {- if (!el) return false;- const r = el.getBoundingClientRect();- return e.clientX >= r.left && e.clientX <= r.right &&- e.clientY >= r.top && e.clientY <= r.bottom;- };- if (inRect(joystickEl) || inRect(lookJoystickEl)) return;-- dragging = true;- downId = e.pointerId;- lastX = e.clientX;- lastY = e.clientY;- canvas.setPointerCapture?.(e.pointerId);+ // Pointers belonging to a stick zone are owned by nipplejs — capturing+ // them here would redirect its move stream and break movement.+ if (inRect(joystickEl, e.clientX, e.clientY) || inRect(lookJoystickEl, e.clientX, e.clientY)) return;++ pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });+ try { canvas.setPointerCapture?.(e.pointerId); } catch {}++ if (pointers.size === 1) {+ orbitId = e.pointerId;+ } else if (pointers.size === 2) {+ orbitId = -1; // suspend orbit while pinching+ pinchDist = pinchDistance();+ }});+const onMove = (e) => {- if (!dragging || e.pointerId !== downId) return;- const dx = e.clientX - lastX;- const dy = e.clientY - lastY;- lastX = e.clientX;- lastY = e.clientY;- cameraYaw -= dx * 0.005;- cameraPitch = Math.max(PITCH_MIN, Math.min(PITCH_MAX, cameraPitch - dy * 0.0035));+ const p = pointers.get(e.pointerId);+ if (!p) return;+ const dx = e.clientX - p.x;+ const dy = e.clientY - p.y;+ p.x = e.clientX;+ p.y = e.clientY;++ if (pointers.size >= 2) {+ // Pinch: spreading fingers (distance grows) zooms in (camZoom down).+ const dist = pinchDistance();+ camZoom = Math.max(CAM_ZOOM_MIN, Math.min(CAM_ZOOM_MAX, camZoom - (dist - pinchDist) * 0.005));+ pinchDist = dist;+ } else if (e.pointerId === orbitId) {+ cameraYaw -= dx * 0.005;+ cameraPitch = Math.max(PITCH_MIN, Math.min(PITCH_MAX, cameraPitch - dy * 0.0035));+ }};+const onUp = (e) => {- if (e.pointerId !== downId) return;- dragging = false;- downId = -1;+ if (!pointers.has(e.pointerId)) return;+ pointers.delete(e.pointerId);try { canvas.releasePointerCapture?.(e.pointerId); } catch {}+ // Dropping from pinch back to a single finger resumes orbit with it.+ if (pointers.size === 1) {+ orbitId = [...pointers.keys()][0];+ } else if (pointers.size === 0) {+ orbitId = -1;+ }};+canvas.addEventListener('pointermove', onMove);canvas.addEventListener('pointerup', onUp);canvas.addEventListener('pointercancel', onUp);@@ -536,6 +604,29 @@ const input = {look: { x: 0, y: 0, active: false },};+// ── Haptics ─────────────────────────────────────────────────────────────+// Tactile feedback on touch actions. Default on, persisted, and silently a+// no-op where the Vibration API is absent (every desktop, iOS Safari) so call+// sites never have to guard. Toggleable from the controls overlay.+const haptics = (() => {+ const KEY = 'walk:haptics';+ const supported = typeof navigator !== 'undefined' && typeof navigator.vibrate === 'function';+ let enabled = true;+ try { enabled = localStorage.getItem(KEY) !== '0'; } catch {}+ return {+ get supported() { return supported; },+ get enabled() { return enabled; },+ set(on) {+ enabled = !!on;+ try { localStorage.setItem(KEY, enabled ? '1' : '0'); } catch {}+ },+ buzz(ms) {+ if (!enabled || !supported) return;+ try { navigator.vibrate(ms); } catch {}+ },+ };+})();+// ── Jump state ────────────────────────────────────────────────────────────let jumpVelocity = 0;let jumpActive = false;@@ -547,6 +638,7 @@ function triggerJump() {if (jumpActive) return;jumpActive = true;jumpVelocity = JUMP_FORCE;+ haptics.buzz(10);}// ── Snap-turn (Q / E) ────────────────────────────────────────────────────@@ -615,15 +707,37 @@ const helpOverlay = (() => {<tr><td style="color:#aaa;padding-right:16px">H / ?</td><td>Toggle this overlay</td></tr><tr><td style="color:#aaa;padding-right:16px">Left / right stick</td><td>Move · look (touch)</td></tr><tr><td style="color:#aaa;padding-right:16px">Mouse drag</td><td>Orbit camera</td></tr>- <tr><td style="color:#aaa;padding-right:16px">Scroll wheel</td><td>Zoom in / out</td></tr>+ <tr><td style="color:#aaa;padding-right:16px">Scroll / pinch</td><td>Zoom in / out</td></tr><tr><td style="color:#aaa;padding-right:16px">Esc</td><td>Close overlay / release pointer</td></tr></table>+ ${haptics.supported ? `+ <div style="margin:18px 0 0;padding-top:16px;border-top:1px solid rgba(255,255,255,0.1);display:flex;align-items:center;justify-content:space-between" data-help-keep>+ <span style="font-size:14px">Haptics</span>+ <button type="button" id="walk-haptics-toggle" role="switch" data-help-keep+ aria-checked="${haptics.enabled}"+ style="appearance:none;border:1px solid rgba(255,255,255,0.2);background:${haptics.enabled ? 'var(--accent,#7c5cff)' : 'rgba(255,255,255,0.08)'};color:#fff;border-radius:999px;padding:5px 14px;font:inherit;font-size:13px;cursor:pointer">+ ${haptics.enabled ? 'On' : 'Off'}+ </button>+ </div>` : ''}<p style="margin:20px 0 0;font-size:12px;color:#666">Click the canvas to lock the mouse for first-person look.</p></div>`;document.body.appendChild(el);return el;})();+// Haptics on/off switch lives in the controls overlay — keep its tap from+// bubbling up to the dismiss-on-any-pointer handler below.+const hapticsToggle = helpOverlay.querySelector('#walk-haptics-toggle');+if (hapticsToggle) {+ hapticsToggle.addEventListener('click', () => {+ haptics.set(!haptics.enabled);+ hapticsToggle.setAttribute('aria-checked', String(haptics.enabled));+ hapticsToggle.textContent = haptics.enabled ? 'On' : 'Off';+ hapticsToggle.style.background = haptics.enabled ? 'var(--accent,#7c5cff)' : 'rgba(255,255,255,0.08)';+ haptics.buzz(8); // confirm the new setting with a tick+ });+}+let helpVisible = false;function toggleHelp() {helpVisible = !helpVisible;@@ -633,9 +747,10 @@ function toggleHelp() {// Any pointer interaction dismisses the overlay. Capture phase + a// non-blocking backdrop means the SAME tap that closes the panel also reaches// the joystick underneath — so the first-visit help never costs the user a-// stalled touch.-window.addEventListener('pointerdown', () => {- if (helpVisible) toggleHelp();+// stalled touch. Controls tagged data-help-keep (the haptics switch) are+// exempt so toggling a setting doesn't slam the panel shut.+window.addEventListener('pointerdown', (e) => {+ if (helpVisible && !e.target?.closest?.('[data-help-keep]')) toggleHelp();}, true);window.addEventListener('keydown', (e) => {@@ -691,9 +806,32 @@ window.addEventListener('keyup', (e) => {}});+// Touch devices and narrow viewports get the on-screen sticks + action+// cluster; wide pointer-fine screens drive everything from WASD + mouse-look.+const wantsTouchControls = (() => {+ if (typeof matchMedia !== 'function') return false;+ return matchMedia('(hover: none)').matches || matchMedia('(max-width: 640px)').matches;+})();++// Radial dead zone — nipplejs reports a vector the instant a thumb grazes the+// ring, which reads as drift. We swallow the inner `dead` fraction and remap+// the remainder to the full [0, 1] range so the stick still reaches max speed+// at the rim while staying dead-still for tiny touches.+const JOY_DEADZONE = 0.12;+function applyDeadzone(x, y, dead = JOY_DEADZONE) {+ const m = Math.hypot(x, y);+ if (m < dead) return { x: 0, y: 0, active: false };+ const scaled = (m - dead) / (1 - dead);+ const k = scaled / m;+ return { x: x * k, y: y * k, active: true };+}+const joystick = nipplejs.create({zone: joystickEl,- mode: 'static',+ // Floating on touch — the stick materializes wherever the left thumb lands+ // inside the zone (which spans the lower-left of the screen) and follows it,+ // so the user never has to look for a fixed pad. Static elsewhere.+ mode: wantsTouchControls ? 'dynamic' : 'static',position: { left: '50%', top: '50%' },size: 110,color: 'rgba(255,255,255,0.85)',@@ -707,9 +845,10 @@ joystick.on('move', (evt) => {// data.vector is the proportional stick displacement within the radius,// already in [-1, 1] per axis (magnitude ≤ 1). y is positive when the// stick is pushed UP — our forward direction.- input.joy.x = data.vector.x;- input.joy.y = data.vector.y;- input.joy.active = Math.hypot(data.vector.x, data.vector.y) > 0.05;+ const d = applyDeadzone(data.vector.x, data.vector.y);+ input.joy.x = d.x;+ input.joy.y = d.y;+ input.joy.active = d.active;}});joystick.on('end', () => {@@ -723,10 +862,6 @@ joystick.on('end', () => {// canvas. Only mounted where the desktop mouse-look affordances are hidden// (touch / narrow viewports); on a wide pointer-fine screen the WASD + mouse// controls own the camera and a second stick would just overlap the hints.-const wantsTouchControls = (() => {- if (typeof matchMedia !== 'function') return false;- return matchMedia('(hover: none)').matches || matchMedia('(max-width: 640px)').matches;-})();if (lookJoystickEl && wantsTouchControls) {const lookJoystick = nipplejs.create({zone: lookJoystickEl,@@ -741,9 +876,10 @@ if (lookJoystickEl && wantsTouchControls) {const data = evt?.data;if (!data?.vector) return;// data.vector already carries direction + magnitude in [-1, 1] per axis.- input.look.x = data.vector.x;- input.look.y = data.vector.y;- input.look.active = Math.hypot(data.vector.x, data.vector.y) > 0.05;+ const d = applyDeadzone(data.vector.x, data.vector.y);+ input.look.x = d.x;+ input.look.y = d.y;+ input.look.active = d.active;});lookJoystick.on('end', () => {input.look.x = 0;@@ -1504,6 +1640,9 @@ function tick() {}updateRemotePlayers(dt);+ // 4b. Animate the coin totem (billboard + bob + ring spin) when present.+ if (coinTotem) coinTotem.update(dt);+// 5. Update speech bubbles (3D -> 2D projection)updateSpeechBubbles();@@ -1535,6 +1674,32 @@ const remotePlayers = new Map();let net = null;let netConnected = false;+let coinTotem = null; // CoinTotem instance when in a coin community world++// Remote-avatar template cache. Each distinct GLB URL is fetched once and+// reused (via SkeletonUtils.clone) for every player wearing it, so a room full+// of the same avatar costs a single download. Keyed by URL → Promise<scene>.+const _remoteAvatarTemplates = new Map();+function loadRemoteAvatarTemplate(url) {+ if (url === resolvedAvatarUrl && avatarTemplate) return Promise.resolve(avatarTemplate);+ if (_remoteAvatarTemplates.has(url)) return _remoteAvatarTemplates.get(url);+ const p = new GLTFLoader().loadAsync(url).then((gltf) => {+ gltf.scene.traverse((n) => {+ if (n.isMesh) {+ n.castShadow = true;+ n.receiveShadow = false;+ if (n.material && 'envMapIntensity' in n.material) n.material.envMapIntensity = 0.85;+ }+ });+ return gltf.scene;+ });+ _remoteAvatarTemplates.set(url, p);+ return p;+}+function isLoadableAvatarUrl(url) {+ return typeof url === 'string' && url.length > 0 &&+ (url.startsWith('/') || url.startsWith('http://') || url.startsWith('https://'));+}class RemotePlayer {constructor(sessionId, initial) {@@ -1563,6 +1728,9 @@ class RemotePlayer {this._color = initial?.color ?? 0xffffff;this._lastEmoteTs = 0;this._emoting = false;+ this._avatarUrl = initial?.avatar || '';+ this._avatarLoadToken = 0;+ this._root = root;this.rig = new Group();this.rig.add(root);@@ -1577,6 +1745,13 @@ class RemotePlayer {this.anim.crossfadeTo(motionToClipName(this.motion), 0.0);});+ // If this player brought their own avatar / 3D agent, swap the stand-in+ // template for their real model once it loads. The default-template body+ // above keeps them visible meanwhile so nobody pops in late.+ if (isLoadableAvatarUrl(this._avatarUrl) && this._avatarUrl !== resolvedAvatarUrl) {+ this._swapAvatar(this._avatarUrl);+ }+// Floating name tag — rendered as a CSS-styled DOM sprite that we// project onto the avatar's head each frame.this.label = document.createElement('div');@@ -1613,6 +1788,48 @@ class RemotePlayer {this._lastEmoteTs = player.emoteTs;this._playRemoteEmote(player.emote);}+ // Live avatar swap — a player picked a new avatar without rejoining.+ if (player.avatar !== this._avatarUrl && isLoadableAvatarUrl(player.avatar)) {+ this._avatarUrl = player.avatar;+ this._swapAvatar(player.avatar);+ }+ }++ // Replace the visible body with the player's own avatar GLB. Loads (cached)+ // off the main thread; a load token guards against an out-of-order resolve+ // when avatars are swapped faster than the network fetches them.+ async _swapAvatar(url) {+ const token = ++this._avatarLoadToken;+ let templateScene;+ try {+ templateScene = await loadRemoteAvatarTemplate(url);+ } catch (err) {+ console.warn('[walk] remote avatar load failed, keeping stand-in:', url, err?.message ?? err);+ return;+ }+ if (token !== this._avatarLoadToken || !this.rig) return; // superseded or disposed++ const root = cloneSkinnedScene(templateScene);+ root.traverse((n) => { if (n.isMesh) { n.castShadow = true; n.receiveShadow = false; } });+ // Center feet on the rig origin so y=0 is the ground, matching loadAvatar().+ const box = new Box3().setFromObject(root);+ root.position.y -= box.min.y;++ // Tear down the old body + its mixer, then attach a fresh one bound to the+ // new skeleton with the same shared clips.+ try { this.anim.dispose(); } catch {}+ if (this._root) this.rig.remove(this._root);+ this._root = root;+ this.rig.add(root);++ this.anim = new AnimationManager();+ this.anim.attach(root);+ this.anim.setAnimationDefs(animationDefs);+ try {+ await this.anim.loadAll();+ if (token !== this._avatarLoadToken) return;+ this.anim.crossfadeTo(motionToClipName(this.motion), 0.0);+ } catch {}}async _playRemoteEmote(name) {@@ -1666,7 +1883,9 @@ class RemotePlayer {}dispose() {+ this._avatarLoadToken++; // cancel any in-flight avatar swapscene.remove(this.rig);+ this.rig = null;this.anim.dispose();this.label.remove();}@@ -1726,7 +1945,15 @@ function startNet() {const stored = getStoredName();const name = (stored || `guest-${Math.random().toString(36).slice(2, 6)}`).slice(0, 24);if (nameInput && !nameInput.value) nameInput.value = name;- net = new WalkNet({ name });+ net = new WalkNet({+ name,+ avatar: resolvedAvatarUrl,+ agent: COIN_PARAMS.agent,+ coin: COIN_PARAMS.coin,+ coinName: COIN_PARAMS.name,+ coinSymbol: COIN_PARAMS.symbol,+ coinImage: COIN_PARAMS.image,+ });net.on('status', ({ status }) => {netConnected = status === 'online';@@ -1739,6 +1966,7 @@ function startNet() {remotePlayers.set(sessionId, new RemotePlayer(sessionId, {x: player.x, y: player.y, z: player.z, yaw: player.yaw,motion: player.motion, name: player.name, color: player.color,+ avatar: player.avatar, agent: player.agent,}));renderOnlineCount();});@@ -1758,6 +1986,14 @@ function startNet() {renderOnlineCount();}});+ net.on('chat', (msg) => {+ // Our own messages are rendered optimistically on send — skip the echo.+ if (!msg || msg.id === net.mySessionId) return;+ const rp = remotePlayers.get(msg.id);+ const color = rp?._color;+ window._walkChat?.addChatMessage(msg.name || 'guest', msg.text, { color });+ showSpeechBubbleFor(msg.id, msg.text);+ });setupOnlinePill();setOnlineStatus('connecting');@@ -1861,6 +2097,7 @@ function triggerQuickGesture(index) {const emote = EMOTE_CLIPS[index];playEmote(emote.name);setStatus(`Gesture: ${emote.label}`);+ haptics.buzz(5);}// Close gesture palette on click outside@@ -2641,6 +2878,11 @@ loadAvatar()if (cameraMode === 'firstperson') avatar.visible = false;animationManager.attach(avatar);animationManager.crossfadeTo(motionToClipName(currentMotion), 0);+ // Broadcast the new avatar so everyone else in the room re-renders us+ // as our real avatar live, without a rejoin. Keep resolvedAvatarUrl in+ // sync so remote-template caching stays correct.+ resolvedAvatarUrl = url;+ net?.sendAvatar(url, currentAvatarId || '');setStatus('Avatar switched');} catch (err) {setStatus('Failed to load avatar', { error: true });@@ -2690,9 +2932,7 @@ loadAvatar()addChatMessage(name, text);// Show speech bubble above local avatarshowSpeechBubbleFor('local', text);- if (net?.room) {- net.room.send('chat', { text: text.slice(0, 200) });- }+ net?.sendChat(text);});window.addEventListener('keydown', (e) => {@@ -2706,6 +2946,259 @@ loadAvatar()window._walkChat = { addChatMessage };}+// ── Coin community theming (HUD + 3D totem) ──────────────────────────────+// When /walk is entered as a coin community (?coin=<mint>&…), we theme the+// world: a top-center HUD carrying the coin's identity + live trade flow, and+// a 3D totem at world center — a billboarded medallion of the coin over a+// glowing ground ring — so each coin's space looks unmistakably its own.+{+ const COIN_FRONTEND = 'https://pump.fun/coin/';+ const TRADE_POLL_MS = 7000;++ // Per-coin accent hue keeps every community visually distinct without us+ // having to assign palettes by hand.+ function coinAccent(seed) {+ let h = 0;+ for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) >>> 0;+ const hue = h % 360;+ return { css: `hsl(${hue} 85% 62%)`, three: new Color().setHSL(hue / 360, 0.78, 0.6) };+ }++ function initials(symbol, name) {+ const s = (symbol || name || '?').replace(/[^A-Za-z0-9]/g, '');+ return (s.slice(0, 3) || '?').toUpperCase();+ }++ // Circular coin medallion drawn to a canvas → CanvasTexture. Falls back to a+ // tinted disc with the ticker initials when there's no image or it taints+ // the canvas (cross-origin). Returns { texture, paint(img) } so the async+ // image load can repaint once it arrives.+ function makeMedallionTexture(accent) {+ const size = 320;+ const cv = document.createElement('canvas');+ cv.width = cv.height = size;+ const ctx = cv.getContext('2d');+ const tex = new CanvasTexture(cv);+ tex.anisotropy = 4;++ const drawFallback = () => {+ ctx.clearRect(0, 0, size, size);+ const grad = ctx.createLinearGradient(0, 0, size, size);+ grad.addColorStop(0, accent.css);+ grad.addColorStop(1, 'rgba(10,10,18,0.95)');+ ctx.fillStyle = grad;+ ctx.beginPath();+ ctx.arc(size / 2, size / 2, size / 2 - 8, 0, Math.PI * 2);+ ctx.fill();+ ctx.fillStyle = 'rgba(255,255,255,0.95)';+ ctx.font = `700 ${size * 0.32}px system-ui, sans-serif`;+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.fillText(initials(COIN_PARAMS.symbol, COIN_PARAMS.name), size / 2, size / 2 + 4);+ };++ const ring = () => {+ ctx.lineWidth = 14;+ ctx.strokeStyle = accent.css;+ ctx.shadowColor = accent.css;+ ctx.shadowBlur = 22;+ ctx.beginPath();+ ctx.arc(size / 2, size / 2, size / 2 - 9, 0, Math.PI * 2);+ ctx.stroke();+ ctx.shadowBlur = 0;+ };++ drawFallback();+ ring();+ tex.needsUpdate = true;++ if (COIN_PARAMS.image) {+ const img = new Image();+ img.crossOrigin = 'anonymous';+ img.referrerPolicy = 'no-referrer';+ img.onload = () => {+ try {+ ctx.clearRect(0, 0, size, size);+ ctx.save();+ ctx.beginPath();+ ctx.arc(size / 2, size / 2, size / 2 - 12, 0, Math.PI * 2);+ ctx.clip();+ // cover-fit the image into the circle+ const s = Math.max(size / img.width, size / img.height);+ const w = img.width * s, h = img.height * s;+ ctx.drawImage(img, (size - w) / 2, (size - h) / 2, w, h);+ ctx.restore();+ ring();+ tex.needsUpdate = true;+ } catch {+ drawFallback(); ring(); tex.needsUpdate = true;+ }+ };+ img.src = COIN_PARAMS.image;+ }+ return tex;+ }++ // Flat glowing ring laid on the ground around spawn.+ function makeGroundRingTexture(accent) {+ const size = 512;+ const cv = document.createElement('canvas');+ cv.width = cv.height = size;+ const ctx = cv.getContext('2d');+ const c = size / 2;+ for (const [r, a, w] of [[c - 18, 0.85, 10], [c - 60, 0.35, 6], [c - 150, 0.18, 3]]) {+ ctx.beginPath();+ ctx.arc(c, c, r, 0, Math.PI * 2);+ ctx.strokeStyle = accent.css;+ ctx.globalAlpha = a;+ ctx.lineWidth = w;+ ctx.shadowColor = accent.css;+ ctx.shadowBlur = 24;+ ctx.stroke();+ }+ ctx.globalAlpha = 1;+ const tex = new CanvasTexture(cv);+ tex.anisotropy = 4;+ return tex;+ }++ class CoinTotem {+ constructor() {+ const accent = coinAccent(COIN_PARAMS.coin);+ this.group = new Group();++ // Ground ring — flat, additive, slowly spinning.+ this.ringMesh = new Mesh(+ new CircleGeometry(2.6, 64),+ new MeshBasicMaterial({+ map: makeGroundRingTexture(accent),+ transparent: true, depthWrite: false, opacity: 0.9,+ }),+ );+ this.ringMesh.rotation.x = -Math.PI / 2;+ this.ringMesh.position.y = 0.02;+ this.group.add(this.ringMesh);++ // Faint light beam from the ring up to the medallion.+ this.beam = new Mesh(+ new CylinderGeometry(0.04, 0.22, 3.0, 16, 1, true),+ new MeshBasicMaterial({ color: accent.three, transparent: true, opacity: 0.12, depthWrite: false, side: DoubleSide }),+ );+ this.beam.position.y = 1.5;+ this.group.add(this.beam);++ // Billboarded medallion.+ this.medallion = new Mesh(+ new PlaneGeometry(1.5, 1.5),+ new MeshBasicMaterial({ map: makeMedallionTexture(accent), transparent: true, depthWrite: false }),+ );+ this.medallion.position.y = 3.4;+ this.group.add(this.medallion);++ // Stand the totem ahead of the spawn point (players spawn facing it) so+ // it reads as a monument to gather around. The medallion rides high+ // enough to clear the avatar's head in the default follow framing.+ this.group.position.set(0, 0, -7);+ scene.add(this.group);+ this._t = 0;+ }++ update(dt) {+ this._t += dt;+ this.ringMesh.rotation.z += dt * 0.15;+ // Bob the medallion gently and keep it facing the camera.+ this.medallion.position.y = 3.4 + Math.sin(this._t * 1.4) * 0.08;+ this.medallion.quaternion.copy(camera.quaternion);+ }+ }++ if (COIN_PARAMS.coin) {+ coinTotem = new CoinTotem();+ document.title = `${COIN_PARAMS.symbol ? '$' + COIN_PARAMS.symbol : 'Coin'} · three.ws`;+ buildCoinHud();+ }++ // ── Coin HUD (top-center) ───────────────────────────────────────────────+ function buildCoinHud() {+ const accent = coinAccent(COIN_PARAMS.coin);+ const hud = document.createElement('div');+ hud.id = 'walk-coin-hud';+ hud.style.cssText = [+ 'position:fixed', 'z-index:7',+ 'left:50%', 'top:calc(env(safe-area-inset-top, 0) + 56px)',+ 'transform:translateX(-50%)',+ 'display:flex', 'align-items:center', 'gap:10px',+ 'background:rgba(14,14,22,0.74)', `border:1px solid ${accent.css}`,+ 'border-radius:999px', 'padding:6px 14px 6px 7px',+ 'backdrop-filter:blur(12px)', '-webkit-backdrop-filter:blur(12px)',+ 'font-family:system-ui,sans-serif', 'color:#fff',+ 'box-shadow:0 6px 24px rgba(0,0,0,0.35)',+ 'max-width:min(92vw, 460px)',+ ].join(';');++ const imgHtml = COIN_PARAMS.image+ ? `<img src="${escAttr(COIN_PARAMS.image)}" alt="" referrerpolicy="no-referrer" onerror="this.replaceWith(Object.assign(document.createElement('span'),{textContent:'${escAttr(initials(COIN_PARAMS.symbol, COIN_PARAMS.name))}',className:'coin-fallback'}))" style="width:34px;height:34px;border-radius:50%;object-fit:cover;border:1px solid ${accent.css};flex:0 0 34px;background:#0e0e16" />`+ : `<span class="coin-fallback">${esc(initials(COIN_PARAMS.symbol, COIN_PARAMS.name))}</span>`;++ const title = COIN_PARAMS.symbol ? `$${esc(COIN_PARAMS.symbol)}` : 'Coin';+ const sub = COIN_PARAMS.name ? esc(COIN_PARAMS.name) : `${COIN_PARAMS.coin.slice(0, 4)}…${COIN_PARAMS.coin.slice(-4)}`;++ hud.innerHTML = `+ <style>+ #walk-coin-hud .coin-fallback{width:34px;height:34px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:13px;background:${accent.css};color:#0b0b12;flex:0 0 34px}+ #walk-coin-hud a{color:rgba(255,255,255,0.85);text-decoration:none}+ #walk-coin-hud a:hover{color:#fff}+ #walk-coin-hud .coin-meta{display:flex;flex-direction:column;line-height:1.15;min-width:0}+ #walk-coin-hud .coin-title{font-weight:700;font-size:14px;letter-spacing:-0.2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+ #walk-coin-hud .coin-sub{font-size:11px;color:rgba(255,255,255,0.55);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+ #walk-coin-hud .coin-trade{font-size:11px;font-variant-numeric:tabular-nums;padding:2px 8px;border-radius:999px;background:rgba(255,255,255,0.06);white-space:nowrap;opacity:0;transition:opacity .25s}+ #walk-coin-hud .coin-trade.is-live{opacity:1}+ #walk-coin-hud .coin-trade.buy{color:#34d399}+ #walk-coin-hud .coin-trade.sell{color:#f87171}+ #walk-coin-hud .coin-actions{display:flex;gap:8px;align-items:center;margin-left:2px;border-left:1px solid rgba(255,255,255,0.12);padding-left:10px}+ #walk-coin-hud .coin-actions a{font-size:11px;font-weight:600}+ body.is-zen #walk-coin-hud{opacity:0;pointer-events:none}+ </style>+ ${imgHtml}+ <a class="coin-meta" href="${COIN_FRONTEND}${escAttr(COIN_PARAMS.coin)}" target="_blank" rel="noopener" title="Open on pump.fun">+ <span class="coin-title">${title}</span>+ <span class="coin-sub">${sub}</span>+ </a>+ <span class="coin-trade" data-trade></span>+ <span class="coin-actions">+ <a href="/communities" title="Switch community">↩ coins</a>+ </span>`;+ document.body.appendChild(hud);++ // Live trade flow — last on-chain trade for this mint, refreshed on an+ // interval. Real data only: on any failure we leave the chip hidden.+ const tradeEl = hud.querySelector('[data-trade]');+ const url = `/api/pump/coin-trades?mint=${encodeURIComponent(COIN_PARAMS.coin)}&limit=1`;+ let stopped = false;+ async function pollTrade() {+ if (stopped) return;+ try {+ const r = await fetch(url, { headers: { accept: 'application/json' } });+ if (r.ok) {+ const data = await r.json();+ const t = data?.trades?.[0];+ if (t && Number.isFinite(t.sol_amount)) {+ const sol = t.sol_amount >= 1 ? t.sol_amount.toFixed(2) : t.sol_amount.toFixed(3);+ tradeEl.textContent = `${t.is_buy ? '▲' : '▼'} ${sol} SOL`;+ tradeEl.className = `coin-trade is-live ${t.is_buy ? 'buy' : 'sell'}`;+ tradeEl.title = 'Most recent on-chain trade';+ }+ }+ } catch { /* offline / rate-limited — keep last value */ }+ if (!stopped) setTimeout(pollTrade, TRADE_POLL_MS);+ }+ pollTrade();+ window.addEventListener('beforeunload', () => { stopped = true; });+ }++ function escAttr(s) { return String(s).replace(/[<>&"]/g, c => ({ '<': '<', '>': '>', '&': '&', '"': '"' })[c]); }+}+// ── Restore zen preference ───────────────────────────────────────────────// Runs after all UI state is declared. URL param wins, then stored choice.(() => {diff --git a/src/worlds-lobby.js b/src/worlds-lobby.jsnew file mode 100644index 000000000..23e4ffdea--- /dev/null+++ b/src/worlds-lobby.js@@ -0,0 +1,397 @@+// Coin Communities lobby — the front door to three.ws worlds.+//+// Every coin on three.ws is its own 3D world at /walk?coin=<mint>; its+// CoinCommunities community is the live social layer inside. This page does two+// things with zero friction:+// 1. Lets a visitor pick or drop in an avatar / 3D agent (no sign-in) and+// remembers it.+// 2. Lists the live coin-worlds (GET /api/community/worlds) and drops the+// visitor into any of them — or the open mainland — in one click.+//+// Data is real (CoinCommunities via the api/community/* proxy). Every state is+// designed: loading skeletons, empty, error, and the graceful "not configured"+// path where the social layer is offline but worlds are still enterable.++import { AvatarGalleryPicker } from './avatar-gallery-picker.js';++// ── tiny DOM helpers ─────────────────────────────────────────────────────────+const $ = (sel, root = document) => root.querySelector(sel);+const el = (tag, attrs = {}, children = []) => {+ const node = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (k === 'class') node.className = v;+ else if (k === 'html') node.innerHTML = v;+ else if (k === 'text') node.textContent = v;+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);+ else if (v !== false && v != null) node.setAttribute(k, v);+ }+ for (const c of [].concat(children)) {+ if (c == null || c === false) continue;+ node.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);+ }+ return node;+};++const compact = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 });+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++// ── persisted onboarding choice ──────────────────────────────────────────────+const LS = {+ name: 'tws:walkName',+ avatarId: 'tws:worldAvatarId',+ avatarName: 'tws:worldAvatarName',+ avatarUrl: 'tws:worldAvatarUrl',+ avatarThumb: 'tws:worldAvatarThumb',+};+const lsGet = (k) => { try { return localStorage.getItem(k) || ''; } catch { return ''; } };+const lsSet = (k, v) => { try { localStorage.setItem(k, v ?? ''); } catch {} };++// Curated instant avatars (stable demo fixtures — animated rigs first so a+// brand-new visitor can one-click drop in and immediately look alive).+const QUICK_AVATARS = [+ { id: 'avatar_demo_disk_saga', name: 'Saga', tag: 'robot' },+ { id: 'avatar_demo_disk_agent', name: 'Agent', tag: 'soldier' },+ { id: 'avatar_demo_disk_boss', name: 'Boss', tag: 'soldier' },+ { id: 'avatar_demo_disk_cz', name: 'CZ', tag: 'humanoid' },+];++const state = {+ worlds: [],+ worldsStatus: 'loading', // loading | ready | empty | error | unconfigured+ worldsError: '',+ query: '',+ avatar: null, // { id, name, model_url, thumbnail_url }+};++// ── avatar onboarding ────────────────────────────────────────────────────────+function currentAvatar() {+ if (state.avatar) return state.avatar;+ const id = lsGet(LS.avatarId);+ if (id) {+ return {+ id,+ name: lsGet(LS.avatarName) || 'Avatar',+ model_url: lsGet(LS.avatarUrl) || '',+ thumbnail_url: lsGet(LS.avatarThumb) || '',+ };+ }+ return null;+}++function setAvatar(a) {+ state.avatar = a;+ lsSet(LS.avatarId, a?.id || '');+ lsSet(LS.avatarName, a?.name || '');+ lsSet(LS.avatarUrl, a?.model_url || '');+ lsSet(LS.avatarThumb, a?.thumbnail_url || '');+ renderAvatarPanel();+}++async function resolveAvatar(id) {+ const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`, { credentials: 'include' });+ if (!res.ok) throw new Error(`Couldn't load that avatar (${res.status}).`);+ const { avatar } = await res.json();+ return {+ id: avatar.id,+ name: avatar.name || 'Avatar',+ model_url: avatar.model_url || avatar.url || '',+ thumbnail_url: avatar.thumbnail_url || '',+ };+}++function renderAvatarPanel() {+ const host = $('#wl-avatar');+ if (!host) return;+ const a = currentAvatar();+ const nameInput = $('#wl-name');+ host.innerHTML = '';++ // 3D / thumbnail preview of the chosen avatar.+ const preview = el('div', { class: 'wl-avatar-preview' });+ if (a?.model_url && window.customElements?.get('model-viewer')) {+ const mv = document.createElement('model-viewer');+ mv.setAttribute('src', a.model_url);+ mv.setAttribute('camera-orbit', '0deg 90deg 2.4m');+ mv.setAttribute('camera-target', '0m 1m 0m');+ mv.setAttribute('field-of-view', '24deg');+ mv.setAttribute('disable-zoom', '');+ mv.setAttribute('interaction-prompt', 'none');+ mv.setAttribute('autoplay', '');+ mv.setAttribute('shadow-intensity', '0.7');+ mv.setAttribute('exposure', '1');+ mv.style.cssText = 'width:100%;height:100%;--poster-color:transparent;background:transparent';+ preview.appendChild(mv);+ } else if (a?.thumbnail_url) {+ preview.appendChild(el('img', { src: a.thumbnail_url, alt: a.name, loading: 'lazy' }));+ } else {+ preview.appendChild(el('div', { class: 'wl-avatar-ph', 'aria-hidden': 'true', html: PERSON_SVG }));+ }+ host.appendChild(preview);++ const meta = el('div', { class: 'wl-avatar-meta' }, [+ el('div', { class: 'wl-avatar-name', text: a ? a.name : 'No avatar yet' }),+ el('div', { class: 'wl-avatar-sub', text: a ? 'Ready to drop in' : 'Pick one below to get started' }),+ ]);+ host.appendChild(meta);++ if (nameInput && !nameInput.value) {+ nameInput.value = lsGet(LS.name) || `guest-${Math.random().toString(36).slice(2, 6)}`;+ }+}++function buildQuickAvatars() {+ const row = $('#wl-quick');+ if (!row) return;+ for (const q of QUICK_AVATARS) {+ const btn = el('button', {+ class: 'wl-quick-btn', type: 'button', 'data-id': q.id,+ title: `Use ${q.name} (${q.tag})`,+ }, [+ el('span', { class: 'wl-quick-dot', 'aria-hidden': 'true' }),+ el('span', { text: q.name }),+ ]);+ btn.addEventListener('click', async () => {+ row.querySelectorAll('.wl-quick-btn').forEach((b) => b.classList.remove('is-on'));+ btn.classList.add('is-on');+ btn.disabled = true;+ try {+ setAvatar(await resolveAvatar(q.id));+ } catch (err) {+ toast(err.message, 'error');+ } finally {+ btn.disabled = false;+ }+ });+ row.appendChild(btn);+ }+}++function wireAvatarActions() {+ $('#wl-browse')?.addEventListener('click', () => {+ const signedIn = document.cookie.includes('session');+ const picker = new AvatarGalleryPicker({+ source: signedIn ? 'both' : 'public',+ title: 'Choose your avatar or 3D agent',+ ctaLabel: 'Use this avatar',+ showModes: false,+ onSelect: (avatar) => {+ picker.close();+ setAvatar({+ id: avatar.id,+ name: avatar.name || 'Avatar',+ model_url: avatar.model_url || '',+ thumbnail_url: avatar.thumbnail_url || '',+ });+ },+ });+ picker.openModal();+ });++ // Drop in by id / paste — three.ws avatar id or agent avatar id.+ const idForm = $('#wl-id-form');+ idForm?.addEventListener('submit', async (e) => {+ e.preventDefault();+ const raw = $('#wl-id-input')?.value.trim();+ if (!raw) return;+ const id = raw.replace(/^.*\/(avatars?)\//, '').replace(/[?#].*$/, '').trim();+ const btn = $('#wl-id-btn');+ btn?.setAttribute('disabled', 'true');+ try {+ setAvatar(await resolveAvatar(id));+ $('#wl-id-input').value = '';+ toast('Avatar loaded.', 'ok');+ } catch (err) {+ toast(err.message, 'error');+ } finally {+ btn?.removeAttribute('disabled');+ }+ });++ $('#wl-create-link')?.setAttribute('href', '/create');++ const nameInput = $('#wl-name');+ nameInput?.addEventListener('change', () => lsSet(LS.name, nameInput.value.trim().slice(0, 24)));+}++// ── enter a world ────────────────────────────────────────────────────────────+function enterWorld(coin) {+ const a = currentAvatar();+ const name = ($('#wl-name')?.value || lsGet(LS.name) || '').trim().slice(0, 24);+ if (name) lsSet(LS.name, name);+ const params = new URLSearchParams();+ if (coin) params.set('coin', coin);+ if (a?.id) params.set('avatar', a.id);+ if (name) params.set('name', name);+ const qs = params.toString();+ window.location.href = `/walk${qs ? `?${qs}` : ''}`;+}++// ── worlds grid ──────────────────────────────────────────────────────────────+async function loadWorlds() {+ state.worldsStatus = 'loading';+ renderWorlds();+ try {+ const res = await fetch('/api/community/worlds', { headers: { accept: 'application/json' } });+ // 503 = CoinCommunities not configured; 404 = the community proxy isn't+ // deployed on this target yet. Both mean "no live social layer" — degrade+ // to the same graceful state where worlds are still enterable, rather than+ // a hard error.+ if (res.status === 503 || res.status === 404) { state.worldsStatus = 'unconfigured'; renderWorlds(); return; }+ if (!res.ok) throw new Error(`worlds ${res.status}`);+ const body = await res.json();+ const worlds = body?.data?.worlds || [];+ state.worlds = worlds;+ state.worldsStatus = worlds.length ? 'ready' : 'empty';+ } catch (err) {+ state.worldsStatus = 'error';+ state.worldsError = err.message;+ }+ renderWorlds();+}++function worldCard(w) {+ const symbol = w.symbol ? `$${w.symbol}` : `${w.token.slice(0, 4)}…${w.token.slice(-4)}`;+ const card = el('button', { class: 'wl-card', type: 'button', title: `Enter ${symbol}` }, [+ el('div', { class: 'wl-card-art' }, [+ w.image+ ? el('img', { src: w.image, alt: symbol, loading: 'lazy', referrerpolicy: 'no-referrer' })+ : el('div', { class: 'wl-card-art-ph', text: symbol.slice(0, 3) }),+ el('span', { class: 'wl-card-live' }, [el('span', { class: 'wl-live-dot' }), 'live']),+ ]),+ el('div', { class: 'wl-card-body' }, [+ el('div', { class: 'wl-card-sym', text: symbol }),+ el('div', { class: 'wl-card-stats' }, [+ stat(PEOPLE_SVG, w.members, 'members'),+ stat(CHAT_SVG, w.posts, 'posts'),+ stat(HEART_SVG, w.likes, 'likes'),+ ]),+ ]),+ el('span', { class: 'wl-card-enter', text: 'Enter →' }),+ ]);+ card.addEventListener('click', () => enterWorld(w.token));+ return card;+}++function stat(svg, n, label) {+ return el('span', { class: 'wl-stat', title: `${n} ${label}` }, [+ el('span', { class: 'wl-stat-i', 'aria-hidden': 'true', html: svg }),+ el('span', { text: compact.format(n || 0) }),+ ]);+}++function renderWorlds() {+ const host = $('#wl-worlds');+ const count = $('#wl-worlds-count');+ if (!host) return;+ host.innerHTML = '';++ if (state.worldsStatus === 'loading') {+ for (let i = 0; i < 8; i++) host.appendChild(el('div', { class: 'wl-card wl-skel' }));+ if (count) count.textContent = '';+ return;+ }+ if (state.worldsStatus === 'unconfigured') {+ host.appendChild(emptyBlock(+ 'The live community layer is offline',+ 'CoinCommunities isn’t configured on this deployment yet — but worlds are still open. Drop into the mainland, or enter any coin by pasting its mint below.',+ 'Enter the mainland', () => enterWorld(''),+ ));+ host.appendChild(manualMint());+ if (count) count.textContent = '';+ return;+ }+ if (state.worldsStatus === 'error') {+ host.appendChild(emptyBlock(+ 'Couldn’t load worlds',+ state.worldsError || 'Something went wrong fetching live communities.',+ 'Retry', loadWorlds,+ ));+ if (count) count.textContent = '';+ return;+ }+ if (state.worldsStatus === 'empty') {+ host.appendChild(emptyBlock(+ 'No live communities yet',+ 'Be the first — drop into the open mainland world and bring people in.',+ 'Enter the mainland', () => enterWorld(''),+ ));+ host.appendChild(manualMint());+ if (count) count.textContent = '';+ return;+ }++ const q = state.query.toLowerCase();+ const list = state.worlds.filter((w) =>+ !q || (w.symbol || '').toLowerCase().includes(q) || w.token.toLowerCase().includes(q));+ if (count) count.textContent = `${list.length} world${list.length === 1 ? '' : 's'}`;+ if (!list.length) {+ host.appendChild(emptyBlock('No match', `No live world matches “${state.query}”.`, 'Clear', () => {+ state.query = ''; $('#wl-search').value = ''; renderWorlds();+ }));+ return;+ }+ for (const w of list) host.appendChild(worldCard(w));+}++function emptyBlock(title, body, ctaLabel, onCta) {+ return el('div', { class: 'wl-empty' }, [+ el('div', { class: 'wl-empty-icon', 'aria-hidden': 'true', html: GLOBE_SVG }),+ el('h3', { text: title }),+ el('p', { text: body }),+ el('button', { class: 'wl-btn wl-btn-primary', type: 'button', onclick: onCta, text: ctaLabel }),+ ]);+}++function manualMint() {+ const form = el('form', { class: 'wl-mint-form' }, [+ el('input', {+ type: 'text', id: 'wl-mint-input', class: 'wl-input',+ placeholder: 'Paste a coin mint to enter its world…', autocomplete: 'off',+ 'aria-label': 'Coin mint address',+ }),+ el('button', { class: 'wl-btn', type: 'submit', text: 'Enter' }),+ ]);+ form.addEventListener('submit', (e) => {+ e.preventDefault();+ const mint = $('#wl-mint-input').value.trim();+ if (!MINT_RE.test(mint)) { toast('That doesn’t look like a valid mint address.', 'error'); return; }+ enterWorld(mint);+ });+ return form;+}++// ── toast ────────────────────────────────────────────────────────────────────+let toastTimer = null;+function toast(text, kind = 'info') {+ const t = $('#wl-toast');+ if (!t) return;+ t.textContent = text;+ t.dataset.kind = kind;+ t.classList.add('show');+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => t.classList.remove('show'), 3200);+}++// ── icons ────────────────────────────────────────────────────────────────────+const PERSON_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c1.5-4.5 4.5-7 8-7s6.5 2.5 8 7"/></svg>`;+const PEOPLE_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M16 19c0-2.5-2-4.5-4.5-4.5S7 16.5 7 19"/><circle cx="11.5" cy="9" r="3"/><path d="M19 18c0-1.8-1-3.3-2.5-3.9"/></svg>`;+const CHAT_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a8 8 0 0 1-11.5 7.2L4 20l.8-5.5A8 8 0 1 1 21 12Z"/></svg>`;+const HEART_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20s-7-4.3-9.2-8.5C1.3 8.7 2.7 5.5 6 5.5c2 0 3.2 1.3 4 2.5.8-1.2 2-2.5 4-2.5 3.3 0 4.7 3.2 3.2 6C19 15.7 12 20 12 20Z"/></svg>`;+const GLOBE_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c2.5 2.5 2.5 15 0 18M12 3c-2.5 2.5-2.5 15 0 18"/></svg>`;++// ── boot ─────────────────────────────────────────────────────────────────────+export function bootLobby() {+ buildQuickAvatars();+ wireAvatarActions();+ renderAvatarPanel();++ $('#wl-enter-mainland')?.addEventListener('click', () => enterWorld(''));+ const search = $('#wl-search');+ search?.addEventListener('input', () => { state.query = search.value.trim(); renderWorlds(); });++ loadWorlds();+ // Keep the lobby feeling live.+ setInterval(loadWorlds, 30_000);+}++document.addEventListener('DOMContentLoaded', bootLobby);diff --git a/vercel.json b/vercel.jsonindex 212d20f02..7d82e671e 100644--- a/vercel.json+++ b/vercel.json@@ -317,10 +317,18 @@"src": "/xr/?","dest": "/xr.html"},+ {+ "src": "/play/?",+ "dest": "/play.html"+ },{"src": "/walk/?","dest": "/walk.html"},+ {+ "src": "/communities/?",+ "dest": "/communities.html"+ },{"src": "/wk/([A-Za-z0-9_-]+)","dest": "/walk?avatar=$1",@@ -2259,6 +2267,18 @@"src": "/create/selfie/","dest": "/create-selfie.html"},+ {+ "src": "/scan",+ "dest": "/scan.html"+ },+ {+ "src": "/scan/",+ "dest": "/scan.html"+ },+ {+ "src": "/worlds/?",+ "dest": "/worlds.html"+ },{"src": "/create-review","dest": "/create-review.html"diff --git a/vite.config.js b/vite.config.jsindex e9f6f7f17..a125d2497 100644--- a/vite.config.js+++ b/vite.config.js@@ -196,6 +196,8 @@ const appConfig = {start: resolve(__dirname, 'pages/start.html'),create: resolve(__dirname, 'pages/create.html'),'create-selfie': resolve(__dirname, 'pages/create-selfie.html'),+ scan: resolve(__dirname, 'pages/scan.html'),+ worlds: resolve(__dirname, 'pages/worlds.html'),'avatar-studio': resolve(__dirname, 'pages/avatar-studio.html'),'create-review': resolve(__dirname, 'pages/create-review.html'),'import-rpm': resolve(__dirname, 'pages/import-rpm.html'),@@ -236,7 +238,9 @@ const appConfig = {'gallery-picker': resolve(__dirname, 'pages/gallery-picker.html'),xr: resolve(__dirname, 'pages/xr.html'),walk: resolve(__dirname, 'pages/walk.html'),+ communities: resolve(__dirname, 'pages/communities.html'),'walk-embed': resolve(__dirname, 'pages/walk-embed.html'),+ play: resolve(__dirname, 'pages/play.html'),pose: resolve(__dirname, 'pages/pose.html'),club: resolve(__dirname, 'pages/club.html'),skills: resolve(__dirname, 'pages/skills.html'),@@ -409,6 +413,10 @@ const appConfig = {'/create': resolve(root, 'pages/create.html'),'/create/selfie': resolve(root, 'pages/create-selfie.html'),'/create/selfie/': resolve(root, 'pages/create-selfie.html'),+ '/scan': resolve(root, 'pages/scan.html'),+ '/scan/': resolve(root, 'pages/scan.html'),+ '/worlds': resolve(root, 'pages/worlds.html'),+ '/worlds/': resolve(root, 'pages/worlds.html'),'/create/studio': resolve(root, 'pages/avatar-studio.html'),'/create/studio/': resolve(root, 'pages/avatar-studio.html'),'/create-review': resolve(root, 'pages/create-review.html'),@@ -475,6 +483,8 @@ const appConfig = {'/avatar-artifact/': resolve(root, 'pages/avatar-artifact.html'),'/walk': resolve(root, 'pages/walk.html'),'/walk/': resolve(root, 'pages/walk.html'),+ '/play': resolve(root, 'pages/play.html'),+ '/play/': resolve(root, 'pages/play.html'),'/walk-embed': resolve(root, 'pages/walk-embed.html'),'/walk-embed/': resolve(root, 'pages/walk-embed.html'),'/pose': resolve(root, 'pages/pose.html'),