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(multiplayer): walk-net + Fly.io multiplayer server workspace
nirholas781036b08576
diff --git a/multiplayer/.gitignore b/multiplayer/.gitignorenew file mode 100644index 000000000..d17eba831--- /dev/null+++ b/multiplayer/.gitignore@@ -0,0 +1,4 @@+node_modules+*.log+.DS_Store+.fly/diff --git a/multiplayer/Dockerfile b/multiplayer/Dockerfilenew file mode 100644index 000000000..9f8b150ad--- /dev/null+++ b/multiplayer/Dockerfile@@ -0,0 +1,26 @@+# Production image for the three.ws multiplayer Colyseus server.+#+# Build & run locally:+# docker build -t three-ws-multiplayer .+# docker run --rm -p 2567:2567 three-ws-multiplayer+#+# Deploy to Fly.io:+# fly launch --no-deploy # accepts the included fly.toml+# fly deploy++FROM node:22-slim AS deps+WORKDIR /app+COPY package.json package-lock.json* ./+RUN npm install --omit=dev --no-audit --no-fund++FROM node:22-slim AS runtime+WORKDIR /app+ENV NODE_ENV=production+ENV PORT=2567+COPY --from=deps /app/node_modules ./node_modules+COPY package.json ./+COPY src ./src+EXPOSE 2567+HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \+ CMD node -e "require('http').get('http://localhost:'+(process.env.PORT||2567)+'/health', (r) => process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"+CMD ["node", "src/index.js"]diff --git a/multiplayer/README.md b/multiplayer/README.mdnew file mode 100644index 000000000..cf76dec19--- /dev/null+++ b/multiplayer/README.md@@ -0,0 +1,70 @@+# three.ws · multiplayer++Authoritative [Colyseus](https://colyseus.io/) server that powers the `/walk` page on three.ws.++This process runs **outside** the Vercel deploy — Vercel doesn't host long-lived WebSockets, so this server lives next to the static site (Fly.io, Railway, Render, or a small VPS). The client at `three.ws/walk` connects to it over a WebSocket and exchanges player state through the `WalkRoom` defined in [`src/rooms/WalkRoom.js`](src/rooms/WalkRoom.js).++## Run locally++```bash+# From the repo root+npm install # installs this workspace too+npm run dev:multi # boots the Colyseus server on :2567++# Or, in another terminal, both servers together:+npm run dev:walk-all # Vite (:3000) + Colyseus (:2567)+```++The Vite dev page at `http://localhost:3000/walk` will autodiscover the server at `ws://localhost:2567`.++## Configuration (env)++| Var | Default | Purpose |+| --- | --- | --- |+| `PORT` | `2567` | TCP port to bind |+| `HOST` | `0.0.0.0` | Interface to bind |+| `ALLOWED_ORIGINS` | `localhost:3000-3003,three.ws,www.three.ws` | Comma-separated origin allow-list for the WS upgrade. `*.vercel.app` and `*.three.ws` are always allowed so preview deploys connect. |++## Endpoints++| Route | Purpose |+| --- | --- |+| `/health`, `/healthz` | Liveness probe — returns `{ok:true}` |+| `/colyseus` | Admin monitor UI ([@colyseus/monitor](https://docs.colyseus.io/tools/monitor/)) — protect this behind a reverse proxy or basic auth in prod |+| WS upgrade | Colyseus protocol — clients connect with `new Client('ws://host:2567')` |++## Anti-cheat++Every `move` message is validated server-side in [`WalkRoom.js`](src/rooms/WalkRoom.js):++- **Max-step clamp**: positions farther than `1.2 m` from the player's last position are rejected (legit deltas at 15Hz × 4 m/s run speed are ~0.27 m).+- **World bounds**: a 60 m radius around origin; out-of-bounds positions are clamped.+- **Y clamp**: vertical position pinned to `[-10, 10]`.+- **Rate limit**: 30 moves/sec per client window — well above the 15Hz the client sends, so it absorbs jitter without dropping legit traffic.+- **Field types**: every numeric field is `Number.isFinite`-checked; motion strings are validated against an allow-list.++## Deploy to Fly.io++```bash+cd multiplayer+fly launch --no-deploy # reads fly.toml (already in this dir)+fly secrets set ALLOWED_ORIGINS=https://three.ws,https://www.three.ws+fly deploy+```++After deploy, point the client at the new host by adding a meta tag to `walk.html`:++```html+<meta name="walk-server" content="wss://three-ws-multiplayer.fly.dev">+```++## Scaling notes++- A single Node process holds many rooms (each room = one WalkRoom instance).+- Each room caps at 50 clients (`MAX_CLIENTS_PER_ROOM` in [WalkRoom.js](src/rooms/WalkRoom.js)). Colyseus's matchmaker creates a new room when the current one fills.+- Across machines: add [`@colyseus/redis-presence`](https://docs.colyseus.io/scalability/redis-presence/) + a Redis instance so matchmaking is cluster-aware. This is a config-only change to [`src/index.js`](src/index.js); add it when you cross ~200 concurrent players.+- Memory budget: ~5 MB per 50-player room on Node 22. The default Fly VM (256 MB) holds plenty of rooms.++## What the schema looks like on the wire++See [`src/schemas.js`](src/schemas.js). Each `Player` is 8 fields, encoded as a binary delta: only the fields that changed since the last patch are sent. At 15Hz × 50 players × ~24 bytes/player avg = ~18 KB/s outbound per fully-busy room — fine on any VPS.diff --git a/multiplayer/fly.toml b/multiplayer/fly.tomlnew file mode 100644index 000000000..3c47bd8e1--- /dev/null+++ b/multiplayer/fly.toml@@ -0,0 +1,40 @@+# Fly.io deploy config for the three.ws multiplayer server.+#+# After `fly launch --no-deploy` reads this file once, run:+# fly secrets set ALLOWED_ORIGINS=https://three.ws,https://www.three.ws+# fly deploy+#+# To scale rooms across machines, bump `min_machines_running` and use+# Fly's autoscaling. Each Colyseus room is single-process — sharding across+# machines is handled by Colyseus's match-making + `@colyseus/redis-presence`+# (add when you cross ~200 concurrent players).++app = "three-ws-multiplayer"+primary_region = "iad"++[build]+ dockerfile = "Dockerfile"++[env]+ PORT = "2567"+ NODE_ENV = "production"++[http_service]+ internal_port = 2567+ force_https = true+ auto_stop_machines = false+ auto_start_machines = true+ min_machines_running = 1+ processes = ["app"]++ [[http_service.checks]]+ grace_period = "10s"+ interval = "30s"+ method = "GET"+ timeout = "5s"+ path = "/health"++[[vm]]+ cpu_kind = "shared"+ cpus = 1+ memory_mb = 256diff --git a/multiplayer/package.json b/multiplayer/package.jsonnew file mode 100644index 000000000..fc924611d--- /dev/null+++ b/multiplayer/package.json@@ -0,0 +1,22 @@+{+ "name": "@three.ws/multiplayer",+ "version": "0.1.0",+ "private": true,+ "description": "Authoritative Colyseus server backing the /walk page on three.ws — rooms, schema state, anti-cheat clamps.",+ "type": "module",+ "main": "src/index.js",+ "scripts": {+ "start": "node src/index.js",+ "dev": "node --watch src/index.js"+ },+ "engines": {+ "node": ">=20"+ },+ "dependencies": {+ "colyseus": "^0.16.0",+ "@colyseus/core": "^0.16.0",+ "@colyseus/schema": "^3.0.0",+ "@colyseus/ws-transport": "^0.16.0",+ "@colyseus/monitor": "^0.16.0"+ }+}diff --git a/multiplayer/src/index.js b/multiplayer/src/index.jsnew file mode 100644index 000000000..2cf035147--- /dev/null+++ b/multiplayer/src/index.js@@ -0,0 +1,112 @@+// Entry point for the three.ws multiplayer server.+//+// 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.++import http from 'node:http';+import { Server } from '@colyseus/core';+import { WebSocketTransport } from '@colyseus/ws-transport';+import { monitor } from '@colyseus/monitor';++import { WalkRoom } from './rooms/WalkRoom.js';++const PORT = Number(process.env.PORT || 2567);+const HOST = process.env.HOST || '0.0.0.0';+// Origins permitted to upgrade to WebSocket — comma-separated list. Default+// covers local dev + the production three.ws origin. Anything outside this+// set gets a 403 before the WS handshake completes.+const ALLOWED_ORIGINS = (+ process.env.ALLOWED_ORIGINS ||+ 'http://localhost:3000,http://localhost:3001,http://localhost:3002,http://localhost:3003,https://three.ws,https://www.three.ws'+)+ .split(',')+ .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();+});++// 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);+}++const transport = new WebSocketTransport({+ server: httpServer,+ verifyClient(info, next) {+ const origin = info.req.headers.origin;+ if (!origin) return next(true); // native clients / curl probes+ if (ALLOWED_ORIGINS.includes(origin)) return next(true);+ // Allow any Vercel preview deploy that targets the same project — these+ // have origins like https://three-ws-<hash>-<team>.vercel.app. We match+ // by hostname suffix so we don't have to maintain an allow-list per+ // preview URL.+ try {+ const host = new URL(origin).hostname;+ if (host.endsWith('.vercel.app') || host.endsWith('.three.ws')) {+ return next(true);+ }+ } catch {}+ console.warn(`[multiplayer] rejecting origin ${origin}`);+ return next(false, 403, 'origin not allowed');+ },+});++const gameServer = new Server({ transport });+gameServer.define('walk_world', WalkRoom);++gameServer+ .listen(PORT, HOST)+ .then(() => {+ console.log(`[multiplayer] listening on ws://${HOST}:${PORT}`);+ console.log(`[multiplayer] allowed origins: ${ALLOWED_ORIGINS.join(', ')}`);+ })+ .catch((err) => {+ console.error('[multiplayer] failed to start:', err);+ process.exit(1);+ });++// Clean shutdown on SIGTERM/SIGINT so deploys don't drop sessions abruptly.+const shutdown = async (signal) => {+ console.log(`[multiplayer] ${signal} received — shutting down`);+ try {+ await gameServer.gracefullyShutdown(true);+ } catch (err) {+ console.error('[multiplayer] shutdown error:', err);+ }+ process.exit(0);+};+process.on('SIGTERM', () => shutdown('SIGTERM'));+process.on('SIGINT', () => shutdown('SIGINT'));diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsnew file mode 100644index 000000000..6b2269c26Binary files /dev/null and b/multiplayer/src/rooms/WalkRoom.js differdiff --git a/multiplayer/src/schemas.js b/multiplayer/src/schemas.jsnew file mode 100644index 000000000..aaa9e5a11--- /dev/null+++ b/multiplayer/src/schemas.js@@ -0,0 +1,43 @@+// Schema definitions shared between the WalkRoom (server) and the client.+//+// @colyseus/schema uses delta encoding: only fields that changed since the+// last patch are sent over the wire. Keep this schema small and primitive —+// every field here is paid for on every state diff.++import { Schema, MapSchema, defineTypes } from '@colyseus/schema';++export class Player extends Schema {+ constructor() {+ super();+ this.id = '';+ this.name = 'guest';+ this.color = 0xffffff;+ this.x = 0;+ this.y = 0;+ this.z = 0;+ this.yaw = 0;+ this.motion = 'idle'; // 'idle' | 'walk' | 'run'+ this.tsServer = 0; // server-side last-update epoch ms (for interpolation)+ }+}+defineTypes(Player, {+ id: 'string',+ name: 'string',+ color: 'uint32',+ x: 'float32',+ y: 'float32',+ z: 'float32',+ yaw: 'float32',+ motion: 'string',+ tsServer: 'float64',+});++export class WalkState extends Schema {+ constructor() {+ super();+ this.players = new MapSchema();+ }+}+defineTypes(WalkState, {+ players: { map: Player },+});diff --git a/package-lock.json b/package-lock.jsonindex 59765cfdf..e1bf4f5e5 100644--- a/package-lock.json+++ b/package-lock.json@@ -11,7 +11,8 @@"license": "Apache-2.0","workspaces": ["agent-payments-sdk",- "character-studio"+ "character-studio",+ "multiplayer"],"dependencies": {"@avaturn/sdk": "^1.1.4",@@ -54,6 +55,7 @@"bcryptjs": "^2.4.3","bn.js": "^5.2.3","bs58": "^6.0.0",+ "colyseus.js": "^0.16.22","dat.gui": "^0.7.9","ethers": "^6.16.0","express": "^4.22.1",@@ -909,6 +911,20 @@"vite-plugin-compression": "^0.5.1"}},+ "multiplayer": {+ "name": "@three.ws/multiplayer",+ "version": "0.1.0",+ "dependencies": {+ "@colyseus/core": "^0.16.0",+ "@colyseus/monitor": "^0.16.0",+ "@colyseus/schema": "^3.0.0",+ "@colyseus/ws-transport": "^0.16.0",+ "colyseus": "^0.16.0"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/@adobe/css-tools": {"version": "4.4.4","resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.4.tgz",@@ -5008,6 +5024,116 @@"zod": "^3.24.2"}},+ "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"+ },+ "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"+ }+ },+ "node_modules/@colyseus/core/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"+ },+ "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"+ },+ "node_modules/@colyseus/httpie": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/@colyseus/httpie/-/httpie-2.0.1.tgz",+ "integrity": "sha512-JvABMZzPLiyrUsVj3ElXGORRDTu+NKzXHWd1uV1R1SThAKMm06cVW6bOyADARD65bs8JJoHNNbUkW8KoRvRDzA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "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"+ }+ },+ "node_modules/@colyseus/msgpackr": {+ "version": "1.11.2",+ "resolved": "https://registry.npmjs.org/@colyseus/msgpackr/-/msgpackr-1.11.2.tgz",+ "integrity": "sha512-MuwPFhizFKC3zmGfy0fpo+kcnZdNdnQHFVjw81v4WXHCelDeCX8yNRVtuEm8kGlHqq7qiASLC0pu0RPqYOhxXg==",+ "license": "MIT",+ "optionalDependencies": {+ "msgpackr-extract": "^3.0.2"+ }+ },+ "node_modules/@colyseus/schema": {+ "version": "3.0.76",+ "resolved": "https://registry.npmjs.org/@colyseus/schema/-/schema-3.0.76.tgz",+ "integrity": "sha512-i+ceBZyhB7lTn5+BoG/xxYfzW4dKKyLOywsGKVgXHe9fD905AS/Lk180jd1bICEJhebGeiRXEQ2YUPl/xwFg2g==",+ "license": "MIT",+ "bin": {+ "schema-codegen": "bin/schema-codegen",+ "schema-debug": "bin/schema-debug"+ }+ },+ "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"+ }+ },+ "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"+ }+ },+ "node_modules/@colyseus/ws-transport/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": "*"+ }+ },"node_modules/@coral-xyz/anchor": {"version": "0.31.1","resolved": "https://registry.npmjs.org/@coral-xyz/anchor/-/anchor-0.31.1.tgz",@@ -9621,6 +9747,84 @@"node": ">= 18"}},+ "node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.3.tgz",+ "integrity": "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@msgpackr-extract/msgpackr-extract-darwin-x64": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-x64/-/msgpackr-extract-darwin-x64-3.0.3.tgz",+ "integrity": "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm/-/msgpackr-extract-linux-arm-3.0.3.tgz",+ "integrity": "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm64": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm64/-/msgpackr-extract-linux-arm64-3.0.3.tgz",+ "integrity": "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@msgpackr-extract/msgpackr-extract-linux-x64": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-x64/-/msgpackr-extract-linux-x64-3.0.3.tgz",+ "integrity": "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@msgpackr-extract/msgpackr-extract-win32-x64": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-win32-x64/-/msgpackr-extract-win32-x64-3.0.3.tgz",+ "integrity": "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },"node_modules/@napi-rs/wasm-runtime": {"version": "0.2.12","resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz",@@ -18411,6 +18615,10 @@}}},+ "node_modules/@three.ws/multiplayer": {+ "resolved": "multiplayer",+ "link": true+ },"node_modules/@tootallnate/quickjs-emscripten": {"version": "0.23.0","resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz",@@ -25768,6 +25976,43 @@"simple-swizzle": "^0.2.2"}},+ "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"+ }+ },+ "node_modules/colyseus.js": {+ "version": "0.16.22",+ "resolved": "https://registry.npmjs.org/colyseus.js/-/colyseus.js-0.16.22.tgz",+ "integrity": "sha512-xyiajukHvlwOtcziVbXZWmz7yBH3EImovYrGPAe2kVkdubLVYmOjskJuXh2VLlO8XGjyhmNwig9ELz18sTUo9g==",+ "license": "MIT",+ "dependencies": {+ "@colyseus/httpie": "^2.0.0",+ "@colyseus/msgpackr": "^1.11.2",+ "@colyseus/schema": "^3.0.0",+ "tslib": "^2.1.0",+ "ws": "^8.13.0"+ },+ "engines": {+ "node": ">= 12.x"+ },+ "funding": {+ "url": "https://github.com/sponsors/endel"+ }+ },"node_modules/combined-stream": {"version": "1.0.8","resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",@@ -34911,6 +35156,28 @@"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==","license": "MIT"},+ "node_modules/msgpackr-extract": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/msgpackr-extract/-/msgpackr-extract-3.0.3.tgz",+ "integrity": "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA==",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "node-gyp-build-optional-packages": "5.2.2"+ },+ "bin": {+ "download-msgpackr-prebuilds": "bin/download-prebuilds.js"+ },+ "optionalDependencies": {+ "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3",+ "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3",+ "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3",+ "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3",+ "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3",+ "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3"+ }+ },"node_modules/multiformats": {"version": "9.9.0","resolved": "https://registry.npmjs.org/multiformats/-/multiformats-9.9.0.tgz",@@ -35238,6 +35505,21 @@"node-gyp-build-test": "build-test.js"}},+ "node_modules/node-gyp-build-optional-packages": {+ "version": "5.2.2",+ "resolved": "https://registry.npmjs.org/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.2.2.tgz",+ "integrity": "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "detect-libc": "^2.0.1"+ },+ "bin": {+ "node-gyp-build-optional-packages": "bin.js",+ "node-gyp-build-optional-packages-optional": "optional.js",+ "node-gyp-build-optional-packages-test": "build-test.js"+ }+ },"node_modules/node-int64": {"version": "0.4.0","resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",@@ -35251,6 +35533,12 @@"integrity": "sha512-8DY+kFsDkNXy1sJglUfuODx1/opAGJGyrTuFqEoN90oRc2Vk0ZbD4K2qmKXBBEhZQzdKHIVfEJpDU8Ak2NJEvQ==","license": "MIT"},+ "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"+ },"node_modules/node-releases": {"version": "2.0.37","resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.37.tgz",diff --git a/package.json b/package.jsonindex 263d8b8dc..0eb35af2d 100644--- a/package.json+++ b/package.json@@ -24,7 +24,8 @@],"workspaces": ["agent-payments-sdk",- "character-studio"+ "character-studio",+ "multiplayer"],"main": "src/app.js","browserslist": [@@ -42,6 +43,8 @@"scripts": {"postinstall": "npm run build --prefix agent-payments-sdk && node scripts/fix-pump-sdk-esm.mjs","dev": "vite --port 3000",+ "dev:multi": "npm run dev --prefix multiplayer",+ "dev:walk-all": "node scripts/dev-walk-all.mjs","dev:lib": "TARGET=lib vite","build:pages": "node scripts/build-page-index.mjs","prebuild": "node scripts/build-page-index.mjs",@@ -122,6 +125,7 @@"bcryptjs": "^2.4.3","bn.js": "^5.2.3","bs58": "^6.0.0",+ "colyseus.js": "^0.16.22","dat.gui": "^0.7.9","ethers": "^6.16.0","express": "^4.22.1",diff --git a/scripts/dev-walk-all.mjs b/scripts/dev-walk-all.mjsnew file mode 100644index 000000000..738070978--- /dev/null+++ b/scripts/dev-walk-all.mjs@@ -0,0 +1,62 @@+#!/usr/bin/env node+// Run the Vite dev server and the Colyseus multiplayer server side by side+// for /walk development. Both processes share this terminal and shut down+// together on Ctrl+C.+//+// npm run dev:walk-all+//+// Vite picks the first free port from 3000 upward; Colyseus binds 2567 by+// default. The /walk client autodiscovers ws://localhost:2567 in dev (see+// src/walk-net.js), so no environment plumbing is required.++import { spawn } from 'node:child_process';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');++const procs = [];++function start(name, cmd, args, color) {+ const child = spawn(cmd, args, {+ cwd: root,+ stdio: ['ignore', 'pipe', 'pipe'],+ env: process.env,+ });+ const tag = `[${color}m[${name}][0m`;+ const pipe = (stream, target) => {+ let buf = '';+ stream.setEncoding('utf8');+ stream.on('data', (chunk) => {+ buf += chunk;+ const lines = buf.split('\n');+ buf = lines.pop();+ for (const line of lines) target.write(`${tag} ${line}\n`);+ });+ stream.on('end', () => {+ if (buf) target.write(`${tag} ${buf}\n`);+ });+ };+ pipe(child.stdout, process.stdout);+ pipe(child.stderr, process.stderr);+ child.on('exit', (code, signal) => {+ console.log(`${tag} exited code=${code} signal=${signal ?? ''}`);+ shutdown();+ });+ procs.push(child);+ return child;+}++function shutdown() {+ for (const p of procs) {+ if (!p.killed && p.exitCode === null) {+ try { p.kill('SIGTERM'); } catch {}+ }+ }+}++process.on('SIGINT', () => { shutdown(); process.exit(0); });+process.on('SIGTERM', () => { shutdown(); process.exit(0); });++start('vite', 'npm', ['run', 'dev'], '36');+start('multi', 'npm', ['run', 'dev', '--prefix', 'multiplayer'], '35');diff --git a/src/walk-net.js b/src/walk-net.jsnew file mode 100644index 000000000..6eb790088--- /dev/null+++ b/src/walk-net.js@@ -0,0 +1,196 @@+// Multiplayer client for /walk — wraps colyseus.js with a tiny event API+// that walk.js can subscribe to without knowing anything about Colyseus.+//+// Design goals:+// - Graceful single-player fallback. If the server is unreachable, the+// page still works; we surface the state via onStatus so the HUD can+// show "offline".+// - Bounded send rate. The render loop runs at 60+ Hz; we throttle to+// 15Hz outbound, matching the room's patch rate. Anything faster just+// wastes bandwidth.+// - No reconnection storms. On disconnect we attempt one reconnect with+// jittered backoff, then give up until the user clicks the HUD pill+// (handled in walk.js).++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.005; // m — skip send if nothing meaningful changed+const YAW_EPSILON = 0.01; // rad++function defaultServerUrl() {+ // Resolution priority:+ // 1. window.WALK_SERVER_URL (test override)+ // 2. <meta name="walk-server" content="...">+ // 3. Same host on :2567 (dev convenience)+ if (typeof window !== 'undefined' && window.WALK_SERVER_URL) {+ return window.WALK_SERVER_URL;+ }+ if (typeof document !== 'undefined') {+ const meta = document.querySelector('meta[name="walk-server"]');+ const v = meta?.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 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)+ */+ 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.mySessionId = null;+ this._handlers = {+ status: new Set(),+ add: new Set(), // (player, sessionId)+ remove: new Set(), // (sessionId)+ change: new Set(), // (player, sessionId)+ };+ this._lastSent = null; // { x, y, z, yaw, motion } we last broadcast+ this._lastSentAt = 0;+ this._reconnectTimer = null;+ this._destroyed = false;+ }++ on(event, fn) {+ const bucket = this._handlers[event];+ if (!bucket) throw new Error(`WalkNet: 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(`[walk-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.mySessionId = this.room.sessionId;++ // Colyseus 0.16 moved schema callbacks behind getStateCallbacks(room)+ // — the legacy `state.players.onAdd(fn)` form no longer exists.+ const $ = getStateCallbacks(this.room);+ $(this.room.state).players.onAdd((player, sessionId) => {+ this._emit('add', player, sessionId);+ // Per-instance onChange fires on every field delta.+ $(player).onChange(() => this._emit('change', player, sessionId));+ });+ $(this.room.state).players.onRemove((_player, sessionId) => {+ this._emit('remove', sessionId);+ });++ this.room.onLeave((code) => {+ console.log('[walk-net] room.onLeave code=', code);+ this._setStatus('offline');+ if (!this._destroyed && code !== 1000) this._scheduleReconnect();+ });+ this.room.onError((code, message) => {+ console.warn('[walk-net] room.onError', code, message);+ });++ this._setStatus('online');+ } catch (err) {+ console.warn('[walk-net] connect failed:', err?.message ?? err);+ this._setStatus('failed', err?.message ?? String(err));+ // Single retry after ~3s — most failures here are "server not+ // running yet" during local dev. After that we go offline until+ // the user clicks the HUD pill (handled by walk.js).+ this._scheduleReconnect();+ }+ }++ _scheduleReconnect() {+ if (this._reconnectTimer || this._destroyed) return;+ const delay = 3000 + Math.random() * 1500;+ this._reconnectTimer = setTimeout(() => {+ this._reconnectTimer = null;+ if (this._destroyed) return;+ this.connect();+ }, delay);+ }++ /**+ * Send our local state to the server. Throttled to SEND_HZ — call this+ * every frame and it'll do the right thing.+ *+ * @param {{ x:number, y:number, z:number, yaw:number, motion:string }} state+ */+ sendState(state) {+ if (!this.room) return;+ const now = performance.now();+ if (now - this._lastSentAt < SEND_INTERVAL_MS) return;++ // Skip if nothing meaningful changed since the last send.+ if (this._lastSent) {+ const dx = state.x - this._lastSent.x;+ const dy = state.y - this._lastSent.y;+ const dz = state.z - this._lastSent.z;+ const dyaw = state.yaw - this._lastSent.yaw;+ const positionStill = Math.hypot(dx, dy, dz) < POSITION_EPSILON;+ const yawStill = Math.abs(dyaw) < YAW_EPSILON;+ const motionSame = state.motion === this._lastSent.motion;+ if (positionStill && yawStill && motionSame) 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;+ }++ rename(name) {+ this.name = name;+ this.room?.send('rename', { name });+ }++ /** Force a reconnect (e.g. after the user clicks the offline pill). */+ 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/walk.js b/src/walk.jsindex 26ab645c4..4612c451d 100644--- a/src/walk.js+++ b/src/walk.js@@ -30,9 +30,11 @@ import {} from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';import nipplejs from 'nipplejs';import { AnimationManager } from './animation-manager.js';+import { WalkNet } from './walk-net.js';const AVATAR_URL = '/avatars/default.glb';const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';@@ -68,6 +70,8 @@ const video = document.getElementById('walk-camera-feed');const joystickEl = document.getElementById('walk-joystick');const arBtn = document.getElementById('walk-ar-toggle');const statusEl = document.getElementById('walk-status');+const onlinePill = document.getElementById('walk-online');+const onlineCountEl = document.getElementById('walk-online-count');function setStatus(text, { error = false, sticky = false } = {}) {if (!statusEl) return;@@ -250,12 +254,21 @@ let avatarYaw = 0; // current facing (radians); we lerp this toward movement anglet avatarLean = 0; // current torso pitch (radians); lerps toward target leanlet currentMotion = 'idle'; // 'idle' | 'walk' | 'run' — drives clip crossfades+// Cached gltf scene + animation manifest defs, populated by loadAvatar — the+// multiplayer layer reuses both to spawn remote-player avatars without+// re-fetching the .glb or the clip manifest. SkeletonUtils.clone() makes a+// proper deep copy of skinned hierarchies; vanilla object3D.clone() would+// share bones and corrupt the rig.+let avatarTemplate = null;+let animationDefs = null;+async function loadAvatar() {setStatus('loading avatar…', { sticky: true });const loader = new GLTFLoader();const gltf = await loader.loadAsync(AVATAR_URL);avatar = gltf.scene;+ avatarTemplate = gltf.scene;avatar.traverse((n) => {if (n.isMesh) {n.castShadow = true;@@ -294,6 +307,7 @@ async function loadAvatar() {if (needed.length === 0) {throw new Error('Animation manifest missing idle/walking/running clips');}+ animationDefs = needed;animationManager.setAnimationDefs(needed);await animationManager.loadAll();@@ -487,6 +501,19 @@ function tick() {// 3. Tick the animation mixer.animationManager.update(dt);+ // 4. Broadcast our state to the server (throttled inside WalkNet) and+ // advance every remote player's interpolated transform + animation.+ if (net && avatar) {+ net.sendState({+ x: avatarRig.position.x,+ y: avatarRig.position.y,+ z: avatarRig.position.z,+ yaw: avatarYaw,+ motion: currentMotion,+ });+ }+ updateRemotePlayers(dt);+renderer.render(scene, camera);requestAnimationFrame(tick);}@@ -498,10 +525,220 @@ function lerpAngle(a, b, t) {return a + diff * t;}+// ── Multiplayer ───────────────────────────────────────────────────────────+//+// The server is best-effort. /walk works fully as a single-player page if+// the Colyseus server is unreachable — the WalkNet client emits status+// transitions but never blocks the render loop or the local controller.++const REMOTE_LERP = 0.22; // per-frame lerp factor toward the latest server state+const REMOTE_YAW_LERP = 0.18;++/** @type {Map<string, RemotePlayer>} */+const remotePlayers = new Map();++let net = null;+let netConnected = false;++class RemotePlayer {+ constructor(sessionId, initial) {+ this.sessionId = sessionId;++ // Clone the loaded template via SkeletonUtils.clone so the skinned+ // mesh gets its own bone hierarchy. Plain Object3D.clone() would share+ // bones with the local avatar and produce visual chaos.+ const root = cloneSkinnedScene(avatarTemplate);+ root.traverse((n) => {+ if (n.isMesh) {+ n.castShadow = true;+ n.receiveShadow = false;+ // Materials are still shared with the template, which is fine+ // for env intensity, but we tint a hue offset onto the cloned+ // skinned mesh's emissive so each player is visually distinct.+ if (n.material && n.material.color && initial?.color != null) {+ n.material = n.material.clone();+ n.material.emissive = n.material.color.clone();+ n.material.emissive.setHex(initial.color);+ n.material.emissiveIntensity = 0.18;+ }+ }+ });++ this.rig = new Group();+ this.rig.add(root);+ scene.add(this.rig);++ this.anim = new AnimationManager();+ this.anim.attach(root);+ this.anim.setAnimationDefs(animationDefs);+ // Reuse the already-fetched clips on the local manager — load asynchronously+ // so the remote doesn't block on a second manifest fetch.+ this.anim.loadAll().then(() => {+ this.anim.crossfadeTo(motionToClipName(this.motion), 0.0);+ });++ // 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');+ this.label.className = 'walk-remote-label';+ this.label.textContent = initial?.name ?? sessionId.slice(0, 6);+ document.body.appendChild(this.label);++ // Visual state — target (latest server) vs current (interpolated).+ this.targetX = initial?.x ?? 0;+ this.targetY = initial?.y ?? 0;+ this.targetZ = initial?.z ?? 0;+ this.targetYaw = initial?.yaw ?? 0;+ this.motion = initial?.motion ?? 'idle';+ this.currentYaw = this.targetYaw;+ this.rig.position.set(this.targetX, this.targetY, this.targetZ);+ this.rig.quaternion.setFromAxisAngle(new Vector3(0, 1, 0), this.targetYaw);+ }++ applyServerState(player) {+ this.targetX = player.x;+ this.targetY = player.y;+ this.targetZ = player.z;+ this.targetYaw = player.yaw;+ if (player.motion !== this.motion) {+ this.motion = player.motion;+ this.anim.crossfadeTo(motionToClipName(player.motion), 0.18);+ }+ if (this.label.textContent !== player.name && player.name) {+ this.label.textContent = player.name;+ }+ }++ tick(dt) {+ // Position lerp.+ 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;+ // Yaw lerp (shortest arc).+ this.currentYaw = lerpAngle(this.currentYaw, this.targetYaw, REMOTE_YAW_LERP);+ this.rig.quaternion.setFromAxisAngle(new Vector3(0, 1, 0), this.currentYaw);++ this.anim.update(dt);+ this._updateLabel();+ }++ _updateLabel() {+ // Project head world-space → screen-space for the floating name tag.+ const head = _tmpV3;+ head.set(this.rig.position.x, this.rig.position.y + 2.05, this.rig.position.z);+ head.project(camera);+ const onScreen = head.z > -1 && head.z < 1;+ if (!onScreen) {+ this.label.style.display = 'none';+ return;+ }+ const w = renderer.domElement.clientWidth;+ const h = renderer.domElement.clientHeight;+ const x = (head.x * 0.5 + 0.5) * w;+ const y = (-head.y * 0.5 + 0.5) * h;+ this.label.style.display = '';+ this.label.style.transform = `translate(-50%, -100%) translate(${x}px, ${y}px)`;+ }++ dispose() {+ scene.remove(this.rig);+ this.anim.dispose();+ this.label.remove();+ }+}++const _tmpV3 = new Vector3();++function motionToClipName(motion) {+ if (motion === 'run') return CLIP_RUN;+ if (motion === 'walk') return CLIP_WALK;+ return CLIP_IDLE;+}++function updateRemotePlayers(dt) {+ for (const r of remotePlayers.values()) r.tick(dt);+}++function setupOnlinePill() {+ if (!onlinePill) return;+ onlinePill.addEventListener('click', () => {+ if (!net) return;+ if (net.status === 'failed' || net.status === 'offline') {+ net.retry();+ }+ });+}++function renderOnlineCount() {+ if (!onlineCountEl) return;+ // +1 for the local player — they're not in remotePlayers.+ onlineCountEl.textContent = String(remotePlayers.size + (netConnected ? 1 : 0));+}++function setOnlineStatus(status) {+ if (!onlinePill) return;+ onlinePill.dataset.status = status;+ const label = onlinePill.querySelector('[data-label]');+ if (label) {+ label.textContent =+ status === 'online'+ ? 'online'+ : status === 'connecting'+ ? 'connecting…'+ : status === 'failed'+ ? 'offline — tap to retry'+ : status === 'offline'+ ? 'reconnecting…'+ : 'solo';+ }+}++function startNet() {+ if (!avatarTemplate || !animationDefs) return; // wait until loadAvatar finished+ if (net) return;+ const params = new URLSearchParams(location.search);+ const name = (params.get('name') || `guest-${Math.random().toString(36).slice(2, 6)}`).slice(0, 24);+ net = new WalkNet({ name });++ net.on('status', ({ status }) => {+ netConnected = status === 'online';+ setOnlineStatus(status);+ renderOnlineCount();+ });+ net.on('add', (player, sessionId) => {+ if (sessionId === net.mySessionId) return; // skip self+ if (remotePlayers.has(sessionId)) return;+ 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,+ }));+ renderOnlineCount();+ });+ net.on('change', (player, sessionId) => {+ if (sessionId === net.mySessionId) return;+ const r = remotePlayers.get(sessionId);+ if (r) r.applyServerState(player);+ });+ net.on('remove', (sessionId) => {+ const r = remotePlayers.get(sessionId);+ if (r) {+ r.dispose();+ remotePlayers.delete(sessionId);+ renderOnlineCount();+ }+ });++ setupOnlinePill();+ setOnlineStatus('connecting');+ renderOnlineCount();+ net.connect();+}+// ── Boot ──────────────────────────────────────────────────────────────────loadAvatar().then(() => {requestAnimationFrame(tick);+ startNet();}).catch((err) => {console.error('[walk] failed to load avatar:', err);diff --git a/walk.html b/walk.htmlindex a200967c2..db714b76c 100644--- a/walk.html+++ b/walk.html@@ -15,6 +15,15 @@/><meta name="theme-color" content="#000000" />+ <!--+ 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 once the+ multiplayer/ workspace is live (see multiplayer/README.md):+ <meta name="walk-server" content="wss://three-ws-multiplayer.fly.dev">+ -->+ <meta name="walk-server" content="" />+<link rel="shortcut icon" href="/favicon.ico" /><link rel="stylesheet" href="/style.css" /><link rel="stylesheet" href="/footer.css" />@@ -247,6 +256,76 @@@media (hover: hover) and (min-width: 641px) {#walk-joystick { display: none; }}++ /* ── Multiplayer HUD ────────────────────────────────────────────── */+ #walk-online {+ appearance: none;+ border: 1px solid var(--border);+ background: var(--panel);+ color: var(--text);+ font: inherit;+ font-size: 12px;+ font-weight: 500;+ padding: 6px 10px;+ border-radius: 999px;+ cursor: default;+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ display: inline-flex;+ align-items: center;+ gap: 6px;+ transition: background 0.12s ease;+ }+ #walk-online .dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--text-2);+ }+ #walk-online[data-status="online"] .dot {+ background: #34d399;+ box-shadow: 0 0 8px rgba(52, 211, 153, 0.7);+ }+ #walk-online[data-status="connecting"] .dot,+ #walk-online[data-status="offline"] .dot {+ background: #fde047;+ }+ #walk-online[data-status="failed"] {+ cursor: pointer;+ border-color: rgba(248, 113, 113, 0.5);+ }+ #walk-online[data-status="failed"] .dot {+ background: var(--danger);+ }+ #walk-online .count {+ color: var(--text-2);+ font-variant-numeric: tabular-nums;+ min-width: 1ch;+ text-align: right;+ }+ #walk-online[data-status="online"] .count { color: var(--text); }++ /* Floating name tag for remote players — positioned by walk.js+ from world-space → screen-space each frame. Pointer-events+ off so it never blocks the orbit drag. */+ .walk-remote-label {+ position: fixed;+ top: 0; left: 0;+ z-index: 3;+ background: rgba(10, 10, 10, 0.72);+ border: 1px solid var(--border);+ border-radius: 999px;+ padding: 3px 9px;+ font-size: 11px;+ font-weight: 500;+ color: var(--text);+ white-space: nowrap;+ pointer-events: none;+ transform: translate(-50%, -100%);+ backdrop-filter: blur(6px);+ -webkit-backdrop-filter: blur(6px);+ will-change: transform;+ }</style></head><body>@@ -260,6 +339,16 @@<p>Drag to orbit. Joystick or <kbd>WASD</kbd> to move.</p></div><div class="walk-actions">+ <button+ type="button"+ id="walk-online"+ data-status="idle"+ title="Multiplayer presence"+ >+ <span class="dot"></span>+ <span data-label>solo</span>+ <span class="count" id="walk-online-count">1</span>+ </button><buttontype="button"class="walk-btn"