Skip to content

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.

feat(city): add city page and implement city world features

overstepping88adcd6dcfff
diff --git a/pages/city.html b/pages/city.html
new file mode 100644
index 000000000..30f759b3c
--- /dev/null
+++ b/pages/city.html
@@ -0,0 +1,49 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>City · 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="City — an open world on three.ws. Walk, explore, drive." />
+ <meta name="theme-color" content="#060607" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/src/city/city.css" />
+ </head>
+ <body>
+ <div id="city-loading">
+ <div class="city-loading-card">
+ <img src="/three.svg" alt="three.ws" width="38" height="38" />
+ <div class="city-loading-title">CITY</div>
+ <div class="city-loading-sub" id="city-loading-sub">Loading world…</div>
+ <div class="city-boot-bar" role="status" aria-label="Loading">
+ <span id="city-boot-bar-fill"></span>
+ </div>
+ </div>
+ </div>
+
+ <canvas id="city-canvas" tabindex="0"></canvas>
+
+ <div id="city-hud" aria-hidden="true">
+ <div id="city-hud-tl">
+ <img src="/three.svg" alt="three.ws" width="22" height="22" />
+ <span>CITY</span>
+ </div>
+
+ <div id="city-minimap">
+ <canvas id="city-minimap-canvas" width="120" height="120"></canvas>
+ <div id="city-minimap-north">N</div>
+ </div>
+
+ <div id="city-hud-coords" aria-live="off"></div>
+
+ <div id="city-controls-hint">
+ <kbd>WASD</kbd> move &nbsp;
+ <kbd>Shift</kbd> sprint &nbsp;
+ <kbd>Space</kbd> jump &nbsp;
+ <kbd>Drag</kbd> orbit
+ </div>
+ </div>
+
+ <script type="module" src="/src/city/city-world.js"></script>
+ </body>
+</html>
diff --git a/public/login.html b/public/login.html
index f58badee3..e82fb4e15 100644
--- a/public/login.html
+++ b/public/login.html
@@ -15,7 +15,8 @@
type="module"
src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
></script>
- <link rel="stylesheet" href="/wallet-connect.css" />
+ <meta name="wc-project-id" content="e8a3fdf0b2dc66fa96b47582f55ec3d9" />
+ <link rel="stylesheet" href="/wallet-connect.css" />
<link rel="stylesheet" href="/auth.css" />
<link rel="stylesheet" href="/mobile.css" />
<link rel="stylesheet" href="/footer.css" />
diff --git a/public/wallet-login.js b/public/wallet-login.js
index 9f3f77571..949ec4223 100644
--- a/public/wallet-login.js
+++ b/public/wallet-login.js
@@ -33,10 +33,13 @@ function onSuccess(data) {
// ─── EVM wallet button ────────────────────────────────────────────────────────
+const wcProjectId = document.querySelector('meta[name="wc-project-id"]')?.content || null;
+
const evmMount = document.getElementById('wallet-mount');
if (evmMount) {
const evmCtrl = createConnectWalletButton(evmMount, {
verifyUrl: '/api/auth/siwe/verify',
+ wcProjectId,
onSuccess,
});
evmCtrl.addEventListener('change', (e) => {
diff --git a/public/wallet/connect-button.js b/public/wallet/connect-button.js
index 4d70b76b2..247d9190b 100644
--- a/public/wallet/connect-button.js
+++ b/public/wallet/connect-button.js
@@ -44,6 +44,9 @@ export class ConnectWalletController extends EventTarget {
#opts;
#onAccountsChanged;
#onChainChanged;
+ #activeProvider = null;
+ #wcProvider = null;
+ #lastConnectMethod = null;
constructor(opts = {}) {
super();
@@ -55,6 +58,7 @@ export class ConnectWalletController extends EventTarget {
onSuccess: null,
autoDetect: false,
labels: {},
+ wcProjectId: null,
...opts,
};
this.#s = initialState();
@@ -75,6 +79,38 @@ export class ConnectWalletController extends EventTarget {
window.ethereum.on('accountsChanged', this.#onAccountsChanged);
window.ethereum.on('chainChanged', this.#onChainChanged);
}
+
+ this.#tryEagerHydrate();
+ }
+
+ async #tryEagerHydrate() {
+ // Restore an existing WalletConnect session without opening the modal.
+ if (!this.#opts.wcProjectId) return;
+ try {
+ const { initWCProvider } = await import('./wc-provider.js');
+ const wc = await initWCProvider({
+ projectId: this.#opts.wcProjectId,
+ chains: this.#opts.allowedChainIds.filter((id) => id > 0).slice(0, 1),
+ optionalChains: this.#opts.allowedChainIds.filter((id) => id > 0).slice(1),
+ });
+ if (wc.accounts?.length) {
+ wc.on('accountsChanged', this.#onAccountsChanged);
+ wc.on('chainChanged', this.#onChainChanged);
+ this.#wcProvider = wc;
+ this.#activeProvider = wc;
+ this.#lastConnectMethod = 'walletconnect';
+ this.#dispatch({
+ type: 'ACCOUNTS_RESOLVED',
+ address: wc.accounts[0],
+ chainId: wc.chainId,
+ });
+ if (!this.#opts.allowedChainIds.includes(wc.chainId)) {
+ this.#dispatch({ type: 'WRONG_CHAIN' });
+ }
+ }
+ } catch {
+ // No stored WC session — nothing to restore.
+ }
}
get state() {
@@ -89,6 +125,9 @@ export class ConnectWalletController extends EventTarget {
get error() {
return this.#s.error;
}
+ get lastConnectMethod() {
+ return this.#lastConnectMethod;
+ }
#dispatch(action) {
const next = reduce(this.#s, action);
@@ -114,6 +153,45 @@ export class ConnectWalletController extends EventTarget {
const address = await signer.getAddress();
const network = await provider.getNetwork();
const chainId = Number(network.chainId);
+ this.#activeProvider = window.ethereum;
+ this.#lastConnectMethod = 'browser';
+ this.#dispatch({ type: 'ACCOUNTS_RESOLVED', address, chainId });
+
+ if (!this.#opts.allowedChainIds.includes(chainId)) {
+ this.#dispatch({ type: 'WRONG_CHAIN' });
+ await this.#trySwitchChain(provider);
+ }
+ } catch (e) {
+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });
+ }
+ }
+
+ async connectWalletConnect() {
+ if (this.#s.status !== STATES.IDLE) return;
+ if (!this.#opts.wcProjectId) return;
+ this.#dispatch({ type: 'CONNECT' });
+ this.#dispatch({ type: 'HAS_PROVIDER' });
+
+ try {
+ const { initWCProvider } = await import('./wc-provider.js');
+ const wc = await initWCProvider({
+ projectId: this.#opts.wcProjectId,
+ chains: this.#opts.allowedChainIds.filter((id) => id > 0).slice(0, 1),
+ optionalChains: this.#opts.allowedChainIds.filter((id) => id > 0).slice(1),
+ });
+
+ wc.on('accountsChanged', this.#onAccountsChanged);
+ wc.on('chainChanged', this.#onChainChanged);
+ this.#wcProvider = wc;
+ this.#activeProvider = wc;
+ this.#lastConnectMethod = 'walletconnect';
+
+ await wc.connect();
+ const provider = new BrowserProvider(wc);
+ const signer = await provider.getSigner();
+ const address = await signer.getAddress();
+ const network = await provider.getNetwork();
+ const chainId = Number(network.chainId);
this.#dispatch({ type: 'ACCOUNTS_RESOLVED', address, chainId });
if (!this.#opts.allowedChainIds.includes(chainId)) {
@@ -152,7 +230,7 @@ export class ConnectWalletController extends EventTarget {
this.#dispatch({ type: 'SIGN' });
try {
- const provider = new BrowserProvider(window.ethereum);
+ const provider = new BrowserProvider(this.#activeProvider || window.ethereum);
const signer = await provider.getSigner();
const address = await signer.getAddress();
@@ -160,9 +238,6 @@ export class ConnectWalletController extends EventTarget {
if (!nonceRes.ok) throw new Error('Failed to get nonce');
const { nonce, csrf, domain: serverDomain, uri: serverUri } = await nonceRes.json();
- // Prefer server-issued domain/uri so dev frontends proxying /api/*
- // to a different origin still produce messages that match the
- // upstream's domain check.
const domain = serverDomain || location.host;
const uri = serverUri || location.origin;
const issuedAt = new Date().toISOString();
@@ -203,6 +278,12 @@ export class ConnectWalletController extends EventTarget {
window.ethereum.removeListener('accountsChanged', this.#onAccountsChanged);
window.ethereum.removeListener('chainChanged', this.#onChainChanged);
}
+ if (this.#wcProvider) {
+ this.#wcProvider.removeListener('accountsChanged', this.#onAccountsChanged);
+ this.#wcProvider.removeListener('chainChanged', this.#onChainChanged);
+ this.#wcProvider = null;
+ }
+ this.#activeProvider = null;
}
}
@@ -217,10 +298,110 @@ const LABEL_DEFAULTS = {
error: 'Retry',
};
+let _pickerStylesInjected = false;
+
+function ensurePickerStyles() {
+ if (_pickerStylesInjected) return;
+ _pickerStylesInjected = true;
+ const s = document.createElement('style');
+ s.textContent = `
+ .cwb-picker {
+ position: fixed;
+ background: #18181b;
+ border: 1px solid #2d2d32;
+ border-radius: 10px;
+ box-shadow: 0 8px 32px rgba(0,0,0,0.5);
+ overflow: hidden;
+ min-width: 200px;
+ z-index: 9999;
+ }
+ .cwb-pick-item {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ padding: 13px 16px;
+ background: none;
+ border: none;
+ color: #f4f4f5;
+ font-size: 14px;
+ font-family: inherit;
+ cursor: pointer;
+ text-align: left;
+ transition: background 0.12s;
+ white-space: nowrap;
+ }
+ .cwb-pick-item:hover { background: rgba(255,255,255,0.07); }
+ .cwb-pick-item + .cwb-pick-item { border-top: 1px solid #2d2d32; }
+ .cwb-pick-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 24px;
+ height: 24px;
+ border-radius: 6px;
+ flex-shrink: 0;
+ }
+ `;
+ document.head.appendChild(s);
+}
+
+function showWalletPicker(anchorEl, onBrowser, onWC) {
+ document.querySelector('.cwb-picker')?.remove();
+ ensurePickerStyles();
+
+ const picker = document.createElement('div');
+ picker.className = 'cwb-picker';
+
+ const mmBtn = document.createElement('button');
+ mmBtn.type = 'button';
+ mmBtn.className = 'cwb-pick-item';
+ mmBtn.innerHTML = `
+ <svg class="cwb-pick-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect width="24" height="24" rx="6" fill="#E8831D"/>
+ <path d="M20 4L13.3 8.9l1.24-2.93L20 4z" fill="#E2761B" stroke="#E2761B" stroke-width=".1"/>
+ <path d="M4 4l6.64 5-1.18-3L4 4z" fill="#E4761B" stroke="#E4761B" stroke-width=".1"/>
+ </svg>
+ Browser wallet`;
+
+ const wcBtn = document.createElement('button');
+ wcBtn.type = 'button';
+ wcBtn.className = 'cwb-pick-item';
+ wcBtn.innerHTML = `
+ <svg class="cwb-pick-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect width="24" height="24" rx="6" fill="#3B99FC"/>
+ <path d="M7.5 9.5c2.5-2.5 6.5-2.5 9 0l.3.3a.3.3 0 010 .42l-1.03 1.03a.15.15 0 01-.21 0l-.41-.42c-1.74-1.74-4.56-1.74-6.3 0l-.44.44a.15.15 0 01-.21 0L7.17 10.24a.3.3 0 010-.42L7.5 9.5zm11.13 2.12l.92.92a.3.3 0 010 .42l-4.14 4.14a.3.3 0 01-.42 0l-2.94-2.94a.08.08 0 00-.1 0l-2.94 2.94a.3.3 0 01-.42 0L5.45 13a.3.3 0 010-.42l.92-.92a.3.3 0 01.42 0l2.94 2.94c.03.03.08.03.1 0l2.94-2.94a.3.3 0 01.42 0l2.94 2.94c.03.03.08.03.1 0l2.94-2.94a.3.3 0 01.42 0z" fill="white"/>
+ </svg>
+ WalletConnect`;
+
+ picker.appendChild(mmBtn);
+ picker.appendChild(wcBtn);
+ document.body.appendChild(picker);
+
+ const rect = anchorEl.getBoundingClientRect();
+ picker.style.top = `${rect.bottom + 6}px`;
+ picker.style.left = `${rect.left}px`;
+
+ mmBtn.onclick = (e) => { e.stopPropagation(); picker.remove(); onBrowser(); };
+ wcBtn.onclick = (e) => { e.stopPropagation(); picker.remove(); onWC(); };
+
+ const close = (e) => {
+ if (!picker.contains(e.target) && e.target !== anchorEl) {
+ picker.remove();
+ document.removeEventListener('click', close);
+ }
+ };
+ setTimeout(() => document.addEventListener('click', close), 0);
+}
+
export function createConnectWalletButton(mountEl, opts = {}) {
+ mountEl._cwbCtrl?.dispose();
+
const labels = { ...LABEL_DEFAULTS, ...(opts.labels || {}) };
const allowedChainIds = opts.allowedChainIds || DEFAULT_CHAIN_IDS;
- const ctrl = new ConnectWalletController({ ...opts, allowedChainIds });
+ const wcProjectId = opts.wcProjectId || null;
+ const ctrl = new ConnectWalletController({ ...opts, allowedChainIds, wcProjectId });
+ mountEl._cwbCtrl = ctrl;
const btn = document.createElement('button');
btn.type = 'button';
@@ -245,6 +426,8 @@ export function createConnectWalletButton(mountEl, opts = {}) {
: `${short} · ${chainName}`;
} else if (s === STATES.ERROR) {
btn.textContent = labels.error;
+ } else if (s === STATES.NO_PROVIDER && wcProjectId) {
+ btn.textContent = labels.idle || 'Connect wallet';
} else {
btn.textContent = labels[s] || s;
}
@@ -253,7 +436,11 @@ export function createConnectWalletButton(mountEl, opts = {}) {
function updateClickHandler(status) {
btn.onclick = null;
if (status === STATES.NO_PROVIDER) {
- btn.onclick = () => window.open('https://metamask.io', '_blank', 'noopener');
+ if (wcProjectId) {
+ btn.onclick = () => ctrl.connectWalletConnect();
+ } else {
+ btn.onclick = () => window.open('https://metamask.io', '_blank', 'noopener');
+ }
} else if (status === STATES.CONNECTED) {
btn.onclick = () => ctrl.signAndVerify();
} else if (status === STATES.WRONG_CHAIN) {
@@ -261,10 +448,20 @@ export function createConnectWalletButton(mountEl, opts = {}) {
} else if (status === STATES.ERROR) {
btn.onclick = () => {
ctrl.reset();
- ctrl.connect();
+ if (ctrl.lastConnectMethod === 'walletconnect') {
+ ctrl.connectWalletConnect();
+ } else {
+ ctrl.connect();
+ }
};
} else if (status === STATES.IDLE) {
- btn.onclick = () => ctrl.connect();
+ if (wcProjectId) {
+ btn.onclick = window.ethereum
+ ? () => showWalletPicker(btn, () => ctrl.connect(), () => ctrl.connectWalletConnect())
+ : () => ctrl.connectWalletConnect();
+ } else {
+ btn.onclick = () => ctrl.connect();
+ }
}
}
diff --git a/public/wallet/wc-provider.js b/public/wallet/wc-provider.js
new file mode 100644
index 000000000..d89b205a9
--- /dev/null
+++ b/public/wallet/wc-provider.js
@@ -0,0 +1,31 @@
+// CDN-compatible WalletConnect EthereumProvider singleton.
+// Uses esm.sh so this file works outside Vite bundling.
+
+let _singleton = null;
+
+/**
+ * @param {{ projectId: string, chains?: number[], optionalChains?: number[] }} opts
+ */
+export async function initWCProvider({ projectId, chains, optionalChains }) {
+ if (_singleton) return _singleton;
+ const { default: EthereumProvider } = await import(
+ /* webpackIgnore: true */ 'https://esm.sh/@walletconnect/[email protected]'
+ );
+ _singleton = await EthereumProvider.init({
+ projectId,
+ chains: chains?.length ? chains : [1],
+ optionalChains: optionalChains?.length ? optionalChains : [8453, 10, 42161, 11155111, 84532],
+ showQrModal: true,
+ });
+ return _singleton;
+}
+
+export async function disconnectWC() {
+ if (!_singleton) return;
+ try {
+ await _singleton.disconnect();
+ } catch {
+ // session may already be gone
+ }
+ _singleton = null;
+}
diff --git a/src/city/city-camera.js b/src/city/city-camera.js
new file mode 100644
index 000000000..02ae9b001
--- /dev/null
+++ b/src/city/city-camera.js
@@ -0,0 +1,108 @@
+import * as THREE from 'three';
+
+const MIN_PHI = 0.18; // ~10° — low angle
+const MAX_PHI = 1.30; // ~74° — near top-down
+const MIN_DIST = 3;
+const MAX_DIST = 28;
+const LERP_K = 0.12; // camera position lag
+
+export class CityCamera {
+ constructor(camera, canvas) {
+ this._camera = camera;
+ this.theta = 0; // horizontal orbit angle (radians)
+ this.phi = 0.52; // elevation angle from horizontal
+ this.distance = 11; // metres from look-target
+
+ this._target = new THREE.Vector3();
+ this._desired = new THREE.Vector3();
+
+ this._drag = false;
+ this._lastX = 0;
+ this._lastY = 0;
+
+ this._bindInput(canvas);
+ }
+
+ // Horizontal orbit angle — fed to CityPlayer so movement stays camera-relative
+ get yaw() { return this.theta; }
+
+ // Call once per frame before rendering.
+ // playerPos: THREE.Vector3, playerHeight: number (metres)
+ update(playerPos, playerHeight) {
+ // Look at the player's upper body (chest/neck area)
+ this._target.set(playerPos.x, playerPos.y + playerHeight * 0.58, playerPos.z);
+
+ // Spherical offset from target
+ const hDist = this.distance * Math.cos(this.phi);
+ this._desired.set(
+ this._target.x + hDist * Math.sin(this.theta),
+ this._target.y + this.distance * Math.sin(this.phi),
+ this._target.z + hDist * Math.cos(this.theta),
+ );
+
+ this._camera.position.lerp(this._desired, LERP_K);
+ this._camera.lookAt(this._target);
+ }
+
+ // ── Input binding ─────────────────────────────────────────────────────────
+
+ _bindInput(canvas) {
+ this._onMouseDown = (e) => {
+ if (e.button !== 0 && e.button !== 2) return;
+ this._drag = true;
+ this._lastX = e.clientX;
+ this._lastY = e.clientY;
+ };
+ this._onMouseMove = (e) => {
+ if (!this._drag) return;
+ const dx = e.clientX - this._lastX;
+ const dy = e.clientY - this._lastY;
+ this._lastX = e.clientX;
+ this._lastY = e.clientY;
+ this.theta -= dx * 0.0045;
+ this.phi = Math.max(MIN_PHI, Math.min(MAX_PHI, this.phi + dy * 0.0045));
+ };
+ this._onMouseUp = () => { this._drag = false; };
+ this._onWheel = (e) => {
+ this.distance = Math.max(MIN_DIST, Math.min(MAX_DIST, this.distance + e.deltaY * 0.018));
+ };
+
+ // Touch orbit (one finger drag)
+ this._onTouchStart = (e) => {
+ if (e.touches.length !== 1) return;
+ this._drag = true;
+ this._lastX = e.touches[0].clientX;
+ this._lastY = e.touches[0].clientY;
+ };
+ this._onTouchMove = (e) => {
+ if (!this._drag || e.touches.length !== 1) return;
+ const dx = e.touches[0].clientX - this._lastX;
+ const dy = e.touches[0].clientY - this._lastY;
+ this._lastX = e.touches[0].clientX;
+ this._lastY = e.touches[0].clientY;
+ this.theta -= dx * 0.005;
+ this.phi = Math.max(MIN_PHI, Math.min(MAX_PHI, this.phi + dy * 0.005));
+ };
+ this._onTouchEnd = () => { this._drag = false; };
+
+ canvas.addEventListener('mousedown', this._onMouseDown);
+ canvas.addEventListener('wheel', this._onWheel, { passive: true });
+ canvas.addEventListener('touchstart', this._onTouchStart, { passive: true });
+ canvas.addEventListener('touchmove', this._onTouchMove, { passive: true });
+ canvas.addEventListener('touchend', this._onTouchEnd);
+ window.addEventListener('mousemove', this._onMouseMove);
+ window.addEventListener('mouseup', this._onMouseUp);
+
+ this._canvas = canvas;
+ }
+
+ destroy() {
+ this._canvas.removeEventListener('mousedown', this._onMouseDown);
+ this._canvas.removeEventListener('wheel', this._onWheel);
+ this._canvas.removeEventListener('touchstart', this._onTouchStart);
+ this._canvas.removeEventListener('touchmove', this._onTouchMove);
+ this._canvas.removeEventListener('touchend', this._onTouchEnd);
+ window.removeEventListener('mousemove', this._onMouseMove);
+ window.removeEventListener('mouseup', this._onMouseUp);
+ }
+}
diff --git a/src/city/city-map.js b/src/city/city-map.js
new file mode 100644
index 000000000..b85c2fb9c
--- /dev/null
+++ b/src/city/city-map.js
@@ -0,0 +1,327 @@
+import * as THREE from 'three';
+
+// City grid constants (metres)
+export const BLOCK = 56; // building footprint area per block
+export const ROAD = 14; // road width (kerb to kerb + sidewalk)
+export const CELL = BLOCK + ROAD; // 70 — one grid cell
+export const GRID = 8; // 8×8 blocks
+export const CITY_HALF = (GRID * CELL + ROAD) / 2; // 287 — half-extent from origin
+
+// NYC-inspired architectural palette: brick, concrete, glass, stone
+const PALETTE = [
+ 0xc0794a, // terracotta brick
+ 0xb8a888, // limestone
+ 0x4a6e9a, // glass blue
+ 0x9a9898, // concrete gray
+ 0xd4c890, // sandstone cream
+ 0x607878, // weathered dark concrete
+ 0xa06048, // dark brick red
+ 0x7898b8, // steel glass
+ 0xd8ccb8, // light stone
+ 0x506070, // dark glass tower
+ 0xb89870, // warm sandstone
+ 0x88a070, // industrial green-gray
+];
+
+// Deterministic seeded RNG (mulberry32-style)
+function makeRng(seed) {
+ let s = seed ^ 0xdeadbeef;
+ return () => {
+ s = Math.imul(s ^ (s >>> 16), 0x45d9f3b);
+ s = Math.imul(s ^ (s >>> 16), 0x45d9f3b);
+ s ^= s >>> 16;
+ return (s >>> 0) / 0xffffffff;
+ };
+}
+
+// Build the entire city geometry into `scene`.
+// Returns { buildingBoxes } — flat AABB list used for collision.
+export function buildCity(scene) {
+ const r = makeRng(42);
+ const buildingBoxes = [];
+
+ // ── Ground (grass/dirt base beneath everything) ───────────────────────────
+ const groundSize = CITY_HALF * 2 + 600;
+ const groundMesh = new THREE.Mesh(
+ new THREE.PlaneGeometry(groundSize, groundSize),
+ new THREE.MeshStandardMaterial({ color: 0x2a3a28, roughness: 1.0 }),
+ );
+ groundMesh.rotation.x = -Math.PI / 2;
+ groundMesh.receiveShadow = true;
+ scene.add(groundMesh);
+
+ // ── Road surface (one large dark plane) ──────────────────────────────────
+ const roadMesh = new THREE.Mesh(
+ new THREE.PlaneGeometry(CITY_HALF * 2, CITY_HALF * 2),
+ new THREE.MeshStandardMaterial({ color: 0x282830, roughness: 0.92, metalness: 0.05 }),
+ );
+ roadMesh.rotation.x = -Math.PI / 2;
+ roadMesh.position.y = 0.01;
+ roadMesh.receiveShadow = true;
+ scene.add(roadMesh);
+
+ // ── Sidewalk pads (one per block, slightly raised) ────────────────────────
+ const sidewalkMat = new THREE.MeshStandardMaterial({ color: 0x38383e, roughness: 0.9 });
+ const sidewalkGeo = new THREE.PlaneGeometry(BLOCK + 2, BLOCK + 2);
+ for (let bx = 0; bx < GRID; bx++) {
+ for (let bz = 0; bz < GRID; bz++) {
+ const cx = blockCenter(bx);
+ const cz = blockCenter(bz);
+ const pad = new THREE.Mesh(sidewalkGeo, sidewalkMat);
+ pad.rotation.x = -Math.PI / 2;
+ pad.position.set(cx, 0.02, cz);
+ pad.receiveShadow = true;
+ scene.add(pad);
+ }
+ }
+
+ // ── Road centre-line dashes ───────────────────────────────────────────────
+ buildRoadMarkings(scene);
+
+ // ── Collect building instance data grouped by colour ─────────────────────
+ const byColor = new Map(); // paletteIdx → [{cx, cz, w, h, d}]
+ for (let bx = 0; bx < GRID; bx++) {
+ for (let bz = 0; bz < GRID; bz++) {
+ placeBlockBuildings(blockCenter(bx), blockCenter(bz), r, byColor, buildingBoxes);
+ }
+ }
+
+ // ── Window texture (shared emissive canvas — lit offices) ────────────────
+ const WIN_TEX = buildWindowTex();
+ WIN_TEX.wrapS = WIN_TEX.wrapT = THREE.RepeatWrapping;
+ // Repeat of 0.3 ≈ one window every ~3 building units at typical building sizes
+ WIN_TEX.repeat.set(0.3, 0.3);
+
+ // ── Emit one InstancedMesh per colour ─────────────────────────────────────
+ const unitBox = new THREE.BoxGeometry(1, 1, 1);
+ const tm = new THREE.Matrix4();
+ const q = new THREE.Quaternion();
+
+ for (const [palIdx, list] of byColor) {
+ const mat = new THREE.MeshStandardMaterial({
+ color: PALETTE[palIdx],
+ roughness: 0.85,
+ metalness: 0.0,
+ emissiveMap: WIN_TEX,
+ emissive: new THREE.Color(0xfff0c0),
+ emissiveIntensity: 0.55,
+ });
+ const mesh = new THREE.InstancedMesh(unitBox, mat, list.length);
+ mesh.castShadow = true;
+ mesh.receiveShadow = true;
+ list.forEach(({ cx, cz, w, h, d }, i) => {
+ tm.compose(new THREE.Vector3(cx, h / 2, cz), q, new THREE.Vector3(w, h, d));
+ mesh.setMatrixAt(i, tm);
+ });
+ mesh.instanceMatrix.needsUpdate = true;
+ scene.add(mesh);
+ }
+
+ // ── Rooftop caps (single grey, all buildings) ─────────────────────────────
+ const allBuildings = [...byColor.values()].flat();
+ if (allBuildings.length > 0) {
+ const roofMat = new THREE.MeshStandardMaterial({ color: 0x505058, roughness: 0.6, metalness: 0.15 });
+ const roofMesh = new THREE.InstancedMesh(unitBox, roofMat, allBuildings.length);
+ allBuildings.forEach(({ cx, cz, w, h, d }, i) => {
+ tm.compose(new THREE.Vector3(cx, h + 0.25, cz), q, new THREE.Vector3(w + 0.4, 0.5, d + 0.4));
+ roofMesh.setMatrixAt(i, tm);
+ });
+ roofMesh.instanceMatrix.needsUpdate = true;
+ scene.add(roofMesh);
+ }
+
+ // ── Street lights ─────────────────────────────────────────────────────────
+ buildStreetlights(scene);
+
+ return { buildingBoxes };
+}
+
+// Centre coordinate of grid column/row index
+function blockCenter(idx) {
+ return -CITY_HALF + ROAD + BLOCK / 2 + idx * CELL;
+}
+
+// Fill a block with buildings, push instances to byColor, boxes to buildingBoxes
+function placeBlockBuildings(bCX, bCZ, r, byColor, buildingBoxes) {
+ const margin = 4;
+ const inner = BLOCK - margin * 2; // 48m inner area
+ const cols = 2 + Math.floor(r() * 2); // 2 or 3
+ const rows = 2 + Math.floor(r() * 2);
+ const cellW = inner / cols;
+ const cellD = inner / rows;
+
+ for (let ci = 0; ci < cols; ci++) {
+ for (let ri = 0; ri < rows; ri++) {
+ if (r() < 0.12) continue; // occasionally leave a gap
+
+ // Centre of this slot with slight jitter
+ const cx = bCX - inner / 2 + cellW * (ci + 0.5) + (r() - 0.5) * cellW * 0.14;
+ const cz = bCZ - inner / 2 + cellD * (ri + 0.5) + (r() - 0.5) * cellD * 0.14;
+
+ const w = cellW * (0.60 + r() * 0.32);
+ const d = cellD * (0.60 + r() * 0.32);
+ // Height biased toward shorter buildings (urban density mix)
+ const h = Math.pow(r(), 1.7) * 52 + 4;
+
+ const palIdx = Math.floor(r() * PALETTE.length);
+
+ if (!byColor.has(palIdx)) byColor.set(palIdx, []);
+ byColor.get(palIdx).push({ cx, cz, w, h, d });
+
+ buildingBoxes.push({
+ minX: cx - w / 2, maxX: cx + w / 2,
+ minZ: cz - d / 2, maxZ: cz + d / 2,
+ h,
+ });
+ }
+ }
+}
+
+// Yellow dashed centre lines along every road
+function buildRoadMarkings(scene) {
+ const dashMat = new THREE.MeshStandardMaterial({
+ color: 0xeecc00,
+ emissive: 0x443300,
+ emissiveIntensity: 0.15,
+ roughness: 0.9,
+ });
+ // Vertical roads (parallel to Z)
+ for (let i = 0; i <= GRID; i++) {
+ const rx = -CITY_HALF + ROAD / 2 + i * CELL;
+ addDashes(scene, dashMat, rx, true);
+ }
+ // Horizontal roads (parallel to X)
+ for (let i = 0; i <= GRID; i++) {
+ const rz = -CITY_HALF + ROAD / 2 + i * CELL;
+ addDashes(scene, dashMat, rz, false);
+ }
+}
+
+function addDashes(scene, mat, axisVal, alongZ) {
+ const length = CITY_HALF * 2;
+ const dashLen = 5;
+ const dashGap = 5;
+ const count = Math.floor(length / (dashLen + dashGap));
+ // PlaneGeometry is in the XY plane; rotate -90° around X to lay flat on ground
+ const geo = alongZ
+ ? new THREE.PlaneGeometry(0.28, dashLen) // width × length along Z
+ : new THREE.PlaneGeometry(dashLen, 0.28); // length along X × width
+ const mesh = new THREE.InstancedMesh(geo, mat, count);
+ // Rotation matrix: -90° around X lays the plane flat (normal faces +Y)
+ const rot = new THREE.Matrix4().makeRotationX(-Math.PI / 2);
+ const trans = new THREE.Matrix4();
+ const m = new THREE.Matrix4();
+ for (let k = 0; k < count; k++) {
+ const along = -CITY_HALF + k * (dashLen + dashGap) + dashLen / 2;
+ const px = alongZ ? axisVal : along;
+ const pz = alongZ ? along : axisVal;
+ trans.makeTranslation(px, 0.035, pz);
+ m.multiplyMatrices(trans, rot);
+ mesh.setMatrixAt(k, m);
+ }
+ mesh.instanceMatrix.needsUpdate = true;
+ scene.add(mesh);
+}
+
+// Street lights at every road intersection
+function buildStreetlights(scene) {
+ const poleMat = new THREE.MeshStandardMaterial({ color: 0x484854, roughness: 0.6, metalness: 0.5 });
+ const glowMat = new THREE.MeshStandardMaterial({ color: 0xfff0b8, emissive: 0xfff0b8, emissiveIntensity: 2.5 });
+
+ const intersections = (GRID + 1) * (GRID + 1);
+ const poleMesh = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.07, 0.09, 6.5, 6), poleMat, intersections);
+ const glowMesh = new THREE.InstancedMesh(new THREE.SphereGeometry(0.15, 6, 6), glowMat, intersections);
+ poleMesh.castShadow = true;
+
+ const m = new THREE.Matrix4();
+ let idx = 0;
+ for (let bx = 0; bx <= GRID; bx++) {
+ for (let bz = 0; bz <= GRID; bz++) {
+ const x = -CITY_HALF + ROAD / 2 + bx * CELL - 3;
+ const z = -CITY_HALF + ROAD / 2 + bz * CELL - 3;
+ m.makeTranslation(x, 3.25, z);
+ poleMesh.setMatrixAt(idx, m);
+ m.makeTranslation(x, 6.7, z);
+ glowMesh.setMatrixAt(idx, m);
+ idx++;
+ }
+ }
+ poleMesh.instanceMatrix.needsUpdate = true;
+ glowMesh.instanceMatrix.needsUpdate = true;
+ scene.add(poleMesh);
+ scene.add(glowMesh);
+}
+
+// Pre-render a static overhead minimap canvas for the city layout.
+// Returns an HTMLCanvasElement you can drawImage() from every frame.
+export function buildMinimapStatic(buildingBoxes) {
+ const SCALE = 1.8; // pixels per metre
+ const SIZE = Math.ceil(CITY_HALF * 2 * SCALE);
+ const c = document.createElement('canvas');
+ c.width = SIZE; c.height = SIZE;
+ const ctx = c.getContext('2d');
+
+ // Road base
+ ctx.fillStyle = '#18181e';
+ ctx.fillRect(0, 0, SIZE, SIZE);
+
+ // Sidewalk pads
+ ctx.fillStyle = '#2a2a32';
+ for (let bx = 0; bx < GRID; bx++) {
+ for (let bz = 0; bz < GRID; bz++) {
+ const cx = blockCenter(bx);
+ const cz = blockCenter(bz);
+ const sx = (cx - BLOCK / 2 + CITY_HALF) * SCALE;
+ const sz = (cz - BLOCK / 2 + CITY_HALF) * SCALE;
+ ctx.fillRect(sx, sz, BLOCK * SCALE, BLOCK * SCALE);
+ }
+ }
+
+ // Buildings (taller = slightly lighter)
+ for (const b of buildingBoxes) {
+ const brightness = Math.min(1, 0.3 + b.h / 60);
+ ctx.fillStyle = `rgba(${Math.round(80 + brightness * 70)},${Math.round(85 + brightness * 65)},${Math.round(100 + brightness * 60)},0.9)`;
+ const sx = (b.minX + CITY_HALF) * SCALE;
+ const sz = (b.minZ + CITY_HALF) * SCALE;
+ const sw = (b.maxX - b.minX) * SCALE;
+ const sd = (b.maxZ - b.minZ) * SCALE;
+ ctx.fillRect(sx, sz, Math.max(1, sw), Math.max(1, sd));
+ }
+
+ return { canvas: c, scale: SCALE };
+}
+
+// Canvas texture simulating lit/unlit office windows.
+// Tiled via repeat on the building emissive map — warm glow on every face.
+function buildWindowTex() {
+ const COLS = 6, ROWS = 10;
+ const W = 128, H = 200;
+ const c = document.createElement('canvas');
+ c.width = W; c.height = H;
+ const ctx = c.getContext('2d');
+
+ // Dark building face base
+ ctx.fillStyle = '#000';
+ ctx.fillRect(0, 0, W, H);
+
+ const cw = W / COLS, rh = H / ROWS;
+ const pw = cw * 0.56, ph = rh * 0.52;
+ const ox = (cw - pw) / 2, oy = (rh - ph) / 2;
+
+ // Deterministic random for consistent look every load
+ let s = 0xc0ffee;
+ const rand = () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 0xffffffff; };
+
+ for (let col = 0; col < COLS; col++) {
+ for (let row = 0; row < ROWS; row++) {
+ if (rand() > 0.45) { // ~55% of windows lit
+ // Vary between warm (office) and cool (fluorescent) light
+ const warm = rand() > 0.4;
+ ctx.fillStyle = warm ? `rgba(255,225,150,${0.6 + rand() * 0.4})` : `rgba(180,220,255,${0.5 + rand() * 0.4})`;
+ ctx.fillRect(col * cw + ox, row * rh + oy, pw, ph);
+ }
+ }
+ }
+
+ return new THREE.CanvasTexture(c);
+}
diff --git a/src/city/city-player.js b/src/city/city-player.js
new file mode 100644
index 000000000..cf69986fb
--- /dev/null
+++ b/src/city/city-player.js
@@ -0,0 +1,191 @@
+import * as THREE from 'three';
+import {
+ buildAvatar, resolveAvatarUrl, loadManifest, newAnim,
+ CLIP_IDLE, CLIP_WALK,
+} from '../game/avatar-rig.js';
+import { CITY_HALF } from './city-map.js';
+
+const WALK_SPEED = 5; // m/s
+const SPRINT_SPEED = 11; // m/s
+const JUMP_VEL = 9; // m/s initial upward
+const GRAVITY = -22; // m/s²
+const PLAYER_R = 0.42; // collision capsule radius (metres)
+const BOUNDS = CITY_HALF - 6;
+
+export class CityPlayer {
+ constructor(scene) {
+ this._scene = scene;
+
+ // Visual rig — avatar model is a child of this
+ this.rig = new THREE.Group();
+ scene.add(this.rig);
+
+ this.velocity = new THREE.Vector3();
+ this.onGround = false;
+ this.motion = 'idle';
+
+ this._anim = null;
+ this.height = 1.7; // head-anchor height, updated after avatar loads
+
+ // Raw key state
+ this._keys = new Set();
+ // Current horizontal facing angle (radians, Three.js Y-rotation convention)
+ this._yaw = 0;
+
+ this._bindInput();
+ }
+
+ get position() { return this.rig.position; }
+
+ // ── Avatar loading ────────────────────────────────────────────────────────
+
+ async load(avatarInput) {
+ await loadManifest();
+ const url = await resolveAvatarUrl(avatarInput || '');
+ this._anim = newAnim();
+ const { height } = await buildAvatar(this.rig, url, this._anim);
+ this.height = height;
+ return this;
+ }
+
+ // ── Per-frame update ──────────────────────────────────────────────────────
+ // cameraYaw: horizontal angle of the orbiting camera (radians)
+
+ update(dt, buildingBoxes, cameraYaw) {
+ const sprint = this._keys.has('shift');
+ const speed = sprint ? SPRINT_SPEED : WALK_SPEED;
+
+ // Build movement vector in camera space
+ let dx = 0, dz = 0;
+ if (this._keys.has('w') || this._keys.has('arrowup')) { dx -= Math.sin(cameraYaw); dz -= Math.cos(cameraYaw); }
+ if (this._keys.has('s') || this._keys.has('arrowdown')) { dx += Math.sin(cameraYaw); dz += Math.cos(cameraYaw); }
+ if (this._keys.has('a') || this._keys.has('arrowleft')) { dx -= Math.cos(cameraYaw); dz += Math.sin(cameraYaw); }
+ if (this._keys.has('d') || this._keys.has('arrowright')) { dx += Math.cos(cameraYaw); dz -= Math.sin(cameraYaw); }
+
+ const moving = dx !== 0 || dz !== 0;
+ if (moving) {
+ const len = Math.sqrt(dx * dx + dz * dz);
+ dx /= len; dz /= len;
+ this.velocity.x = dx * speed;
+ this.velocity.z = dz * speed;
+ // Face movement direction (atan2 gives angle from +Z axis in XZ plane)
+ this._yaw = Math.atan2(dx, dz);
+ } else {
+ this.velocity.x *= Math.pow(0.05, dt); // quick stop
+ this.velocity.z *= Math.pow(0.05, dt);
+ }
+
+ // Jump
+ if (this._keys.has(' ') && this.onGround) {
+ this.velocity.y = JUMP_VEL;
+ this.onGround = false;
+ }
+
+ // Gravity
+ if (!this.onGround) {
+ this.velocity.y += GRAVITY * dt;
+ }
+
+ // Tentative next position
+ const p = this.rig.position;
+ let nx = p.x + this.velocity.x * dt;
+ let ny = p.y + this.velocity.y * dt;
+ let nz = p.z + this.velocity.z * dt;
+
+ // Building collision (push-out in XZ plane)
+ const resolved = this._resolveBuildings(nx, ny, nz, buildingBoxes);
+ nx = resolved.x; nz = resolved.z;
+
+ // Ground — flat terrain at y = 0
+ if (ny <= 0) { ny = 0; this.velocity.y = 0; this.onGround = true; }
+ else { this.onGround = false; }
+
+ // World bounds
+ nx = Math.max(-BOUNDS, Math.min(BOUNDS, nx));
+ nz = Math.max(-BOUNDS, Math.min(BOUNDS, nz));
+
+ p.set(nx, ny, nz);
+
+ // Smooth rotation toward movement direction
+ if (moving) {
+ let diff = this._yaw - this.rig.rotation.y;
+ while (diff > Math.PI) diff -= Math.PI * 2;
+ while (diff < -Math.PI) diff += Math.PI * 2;
+ this.rig.rotation.y += diff * Math.min(1, dt * 14);
+ }
+
+ // Animation
+ this._updateMotion(sprint, moving);
+ this._anim?.update(dt);
+ }
+
+ // ── Private ───────────────────────────────────────────────────────────────
+
+ _updateMotion(sprint, moving) {
+ if (!this._anim) return;
+ const hSpeed = Math.sqrt(this.velocity.x ** 2 + this.velocity.z ** 2);
+ const next = hSpeed < 0.4 ? 'idle' : (sprint ? 'sprint' : 'walk');
+ if (next === this.motion) return;
+ this.motion = next;
+ const clip = next === 'idle' ? CLIP_IDLE : CLIP_WALK;
+ this._anim.crossfadeTo(clip, 0.2).catch(() => {});
+ }
+
+ _resolveBuildings(nx, ny, nz, boxes) {
+ // Simple capsule vs AABB: treat player as a vertical cylinder of radius PLAYER_R
+ for (const b of boxes) {
+ if (ny > b.h) continue; // stepped over or jumped above
+ // Closest point on box to player centre
+ const cx = Math.max(b.minX, Math.min(b.maxX, nx));
+ const cz = Math.max(b.minZ, Math.min(b.maxZ, nz));
+ const ox = nx - cx;
+ const oz = nz - cz;
+ const dist2 = ox * ox + oz * oz;
+ if (dist2 >= PLAYER_R * PLAYER_R) continue;
+
+ const dist = Math.sqrt(dist2);
+ if (dist < 0.001) {
+ // Dead centre inside box — eject toward nearest face
+ const toLeft = nx - b.minX;
+ const toRight = b.maxX - nx;
+ const toFront = nz - b.minZ;
+ const toBack = b.maxZ - nz;
+ const min = Math.min(toLeft, toRight, toFront, toBack);
+ if (min === toLeft) nx = b.minX - PLAYER_R;
+ else if (min === toRight) nx = b.maxX + PLAYER_R;
+ else if (min === toFront) nz = b.minZ - PLAYER_R;
+ else nz = b.maxZ + PLAYER_R;
+ } else {
+ const push = (PLAYER_R - dist) / dist;
+ nx += ox * push;
+ nz += oz * push;
+ }
+ }
+ return { x: nx, z: nz };
+ }
+
+ _bindInput() {
+ const TRACKED = new Set([
+ 'w','a','s','d',
+ 'arrowup','arrowdown','arrowleft','arrowright',
+ ' ','shift',
+ ]);
+ this._onKeyDown = (e) => {
+ const k = e.key.toLowerCase();
+ if (!TRACKED.has(k)) return;
+ if (k === ' ' || k.startsWith('arrow')) e.preventDefault();
+ this._keys.add(k);
+ };
+ this._onKeyUp = (e) => {
+ this._keys.delete(e.key.toLowerCase());
+ };
+ window.addEventListener('keydown', this._onKeyDown);
+ window.addEventListener('keyup', this._onKeyUp);
+ }
+
+ destroy() {
+ window.removeEventListener('keydown', this._onKeyDown);
+ window.removeEventListener('keyup', this._onKeyUp);
+ this._scene.remove(this.rig);
+ }
+}
diff --git a/src/city/city-world.js b/src/city/city-world.js
new file mode 100644
index 000000000..c36f59e2b
--- /dev/null
+++ b/src/city/city-world.js
@@ -0,0 +1,201 @@
+import * as THREE from 'three';
+import { Sky } from 'three/addons/objects/Sky.js';
+import { buildCity, buildMinimapStatic, CITY_HALF } from './city-map.js';
+import { CityPlayer } from './city-player.js';
+import { CityCamera } from './city-camera.js';
+
+// ── DOM refs ─────────────────────────────────────────────────────────────────
+
+const canvas = document.getElementById('city-canvas');
+const loadingEl = document.getElementById('city-loading');
+const subEl = document.getElementById('city-loading-sub');
+const barEl = document.getElementById('city-boot-bar-fill');
+const hudEl = document.getElementById('city-hud');
+const coordsEl = document.getElementById('city-hud-coords');
+const mmCanvas = document.getElementById('city-minimap-canvas');
+const mmCtx = mmCanvas.getContext('2d');
+
+function progress(pct, label) {
+ if (barEl) barEl.style.width = pct + '%';
+ if (subEl) subEl.textContent = label;
+}
+
+// ── Boot ──────────────────────────────────────────────────────────────────────
+
+async function main() {
+ progress(8, 'Setting up renderer…');
+
+ // Renderer
+ const renderer = new THREE.WebGLRenderer({
+ canvas,
+ antialias: true,
+ powerPreference: 'high-performance',
+ });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ renderer.setSize(window.innerWidth, window.innerHeight);
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 0.92;
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+
+ // Scene
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.Fog(0x9aafbf, 110, 500);
+
+ // Camera
+ const camera = new THREE.PerspectiveCamera(58, window.innerWidth / window.innerHeight, 0.1, 600);
+ camera.position.set(0, 12, 20);
+
+ progress(18, 'Adding lights…');
+
+ // Ambient — generous so shadowed areas stay readable
+ scene.add(new THREE.AmbientLight(0xc0d4e8, 1.4));
+
+ // Sun — warm afternoon angle, less overpowering than midday
+ const sun = new THREE.DirectionalLight(0xffe8c0, 2.0);
+ sun.position.set(60, 80, -50); // slightly behind camera = front-lit scene
+ sun.castShadow = true;
+ sun.shadow.mapSize.set(2048, 2048);
+ sun.shadow.camera.near = 1;
+ sun.shadow.camera.far = 500;
+ sun.shadow.camera.left = -160;
+ sun.shadow.camera.right = 160;
+ sun.shadow.camera.top = 160;
+ sun.shadow.camera.bottom = -160;
+ sun.shadow.bias = -0.0008;
+ scene.add(sun);
+
+ // Secondary fill from the opposite side — kills pitch-black shadows
+ const fill = new THREE.DirectionalLight(0x90b8e0, 0.7);
+ fill.position.set(-60, 50, 60);
+ scene.add(fill);
+
+ // Hemisphere (sky/ground colour fill)
+ scene.add(new THREE.HemisphereLight(0x90b8d8, 0x4a6040, 0.6));
+
+ progress(28, 'Building sky…');
+
+ // Sky dome
+ const sky = new Sky();
+ sky.scale.setScalar(5000);
+ scene.add(sky);
+ const su = sky.material.uniforms;
+ su.turbidity.value = 4.0;
+ su.rayleigh.value = 2.2;
+ su.mieCoefficient.value = 0.006;
+ su.mieDirectionalG.value = 0.9;
+ su.sunPosition.value.set(0.4, 0.35, -0.85).normalize();
+
+ progress(40, 'Building city…');
+
+ const { buildingBoxes } = buildCity(scene);
+
+ progress(62, 'Building minimap…');
+
+ const minimap = buildMinimapStatic(buildingBoxes);
+
+ progress(72, 'Loading avatar…');
+
+ // Player — pick avatar from URL param or localStorage
+ const avatarInput = new URLSearchParams(location.search).get('avatar')
+ || localStorage.getItem('kx-avatar')
+ || '';
+
+ const player = new CityPlayer(scene);
+ await player.load(avatarInput);
+ player.position.set(0, 0, 0);
+
+ progress(92, 'Entering world…');
+
+ // Camera controller (attach after player exists)
+ const cityCamera = new CityCamera(camera, canvas);
+
+ // Block right-click context menu so RMB can orbit
+ canvas.addEventListener('contextmenu', (e) => e.preventDefault());
+
+ // Resize handler
+ window.addEventListener('resize', () => {
+ renderer.setSize(window.innerWidth, window.innerHeight);
+ camera.aspect = window.innerWidth / window.innerHeight;
+ camera.updateProjectionMatrix();
+ });
+
+ // Focus canvas so keyboard input works immediately
+ canvas.focus();
+
+ // ── Reveal ──────────────────────────────────────────────────────────────────
+ progress(100, 'Ready');
+ await delay(180);
+ loadingEl.classList.add('hidden');
+ await delay(480);
+ loadingEl.style.display = 'none';
+ hudEl.style.display = '';
+
+ // ── Game loop ────────────────────────────────────────────────────────────────
+ const clock = new THREE.Clock();
+
+ (function tick() {
+ requestAnimationFrame(tick);
+ const dt = Math.min(clock.getDelta(), 0.05);
+
+ player.update(dt, buildingBoxes, cityCamera.yaw);
+ cityCamera.update(player.position, player.height);
+
+ drawMinimap(mmCtx, player.position, minimap);
+ updateCoords(player.position);
+
+ renderer.render(scene, camera);
+ })();
+}
+
+// ── Minimap ───────────────────────────────────────────────────────────────────
+
+function drawMinimap(ctx, playerPos, minimap) {
+ const W = 120, H = 120;
+ const { canvas: src, scale } = minimap;
+
+ // Player's position in the static minimap image
+ const px = (playerPos.x + CITY_HALF) * scale;
+ const pz = (playerPos.z + CITY_HALF) * scale;
+
+ ctx.clearRect(0, 0, W, H);
+
+ // Clip to circle
+ ctx.save();
+ ctx.beginPath();
+ ctx.arc(W / 2, H / 2, W / 2, 0, Math.PI * 2);
+ ctx.clip();
+
+ // Blit 120×120 region of the static image centred on player
+ ctx.drawImage(src, px - W / 2, pz - H / 2, W, H, 0, 0, W, H);
+
+ ctx.restore();
+
+ // Player dot
+ ctx.fillStyle = 'rgba(255,255,255,0.95)';
+ ctx.beginPath();
+ ctx.arc(W / 2, H / 2, 3, 0, Math.PI * 2);
+ ctx.fill();
+
+ // Heading tick (points up = north on the map)
+ ctx.strokeStyle = 'rgba(255,255,255,0.35)';
+ ctx.lineWidth = 1.5;
+ ctx.beginPath();
+ ctx.moveTo(W / 2, H / 2);
+ ctx.lineTo(W / 2, H / 2 - 10);
+ ctx.stroke();
+}
+
+// ── Coordinate HUD ────────────────────────────────────────────────────────────
+
+function updateCoords(pos) {
+ if (!coordsEl) return;
+ coordsEl.textContent = `${pos.x.toFixed(1)}, ${pos.y.toFixed(1)}, ${pos.z.toFixed(1)}`;
+}
+
+// ── Utility ───────────────────────────────────────────────────────────────────
+
+function delay(ms) { return new Promise((r) => setTimeout(r, ms)); }
+
+main().catch(console.error);
diff --git a/src/city/city.css b/src/city/city.css
new file mode 100644
index 000000000..3bd1f0b68
--- /dev/null
+++ b/src/city/city.css
@@ -0,0 +1,151 @@
+*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
+
+html, body {
+ width: 100%; height: 100%;
+ overflow: hidden;
+ background: #060607;
+ font-family: 'Inter', ui-sans-serif, system-ui, sans-serif;
+ -webkit-font-smoothing: antialiased;
+}
+
+/* ── Canvas ─────────────────────────────────────────────────────────────────── */
+
+#city-canvas {
+ position: fixed; inset: 0;
+ width: 100%; height: 100%;
+ display: block;
+ outline: none;
+ cursor: grab;
+}
+
+#city-canvas:active { cursor: grabbing; }
+
+/* ── Loading screen ─────────────────────────────────────────────────────────── */
+
+#city-loading {
+ position: fixed; inset: 0;
+ display: flex; align-items: center; justify-content: center;
+ background: #060607;
+ z-index: 100;
+ transition: opacity 0.5s ease;
+}
+
+#city-loading.hidden {
+ opacity: 0;
+ pointer-events: none;
+}
+
+.city-loading-card {
+ display: flex; flex-direction: column; align-items: center;
+ gap: 14px;
+}
+
+.city-loading-title {
+ font-size: 11px;
+ font-weight: 700;
+ letter-spacing: 0.3em;
+ color: rgba(255, 255, 255, 0.4);
+ text-transform: uppercase;
+}
+
+.city-loading-sub {
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.25);
+ letter-spacing: 0.06em;
+ min-height: 18px;
+}
+
+.city-boot-bar {
+ width: 160px; height: 2px;
+ background: rgba(255, 255, 255, 0.06);
+ border-radius: 2px;
+ overflow: hidden;
+}
+
+.city-boot-bar span {
+ display: block;
+ height: 100%;
+ width: 0%;
+ background: rgba(255, 255, 255, 0.45);
+ border-radius: 2px;
+ transition: width 0.35s ease;
+}
+
+/* ── HUD ─────────────────────────────────────────────────────────────────────── */
+
+#city-hud {
+ position: fixed; inset: 0;
+ pointer-events: none;
+ z-index: 10;
+ display: none;
+}
+
+/* Top-left logo + label */
+#city-hud-tl {
+ position: absolute;
+ top: 18px; left: 20px;
+ display: flex; align-items: center; gap: 8px;
+ font-size: 11px;
+ font-weight: 700;
+ letter-spacing: 0.25em;
+ color: rgba(255, 255, 255, 0.35);
+ text-transform: uppercase;
+ user-select: none;
+}
+
+/* Bottom-left coordinates */
+#city-hud-coords {
+ position: absolute;
+ bottom: 18px; left: 20px;
+ font-size: 10px;
+ font-family: ui-monospace, 'JetBrains Mono', monospace;
+ color: rgba(255, 255, 255, 0.2);
+ letter-spacing: 0.04em;
+ user-select: none;
+}
+
+/* Bottom-right minimap */
+#city-minimap {
+ position: absolute;
+ bottom: 18px; right: 20px;
+ width: 120px; height: 120px;
+ border-radius: 50%;
+ overflow: hidden;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+}
+
+#city-minimap-canvas {
+ display: block;
+ width: 100%; height: 100%;
+}
+
+#city-minimap-north {
+ position: absolute;
+ top: 5px; left: 50%; transform: translateX(-50%);
+ font-size: 8px;
+ font-weight: 700;
+ letter-spacing: 0.15em;
+ color: rgba(255, 255, 255, 0.25);
+ user-select: none;
+}
+
+/* Top-right controls hint */
+#city-controls-hint {
+ position: absolute;
+ top: 18px; right: 20px;
+ font-size: 10px;
+ color: rgba(255, 255, 255, 0.2);
+ letter-spacing: 0.05em;
+ user-select: none;
+ line-height: 1.6;
+}
+
+#city-controls-hint kbd {
+ font-family: ui-monospace, monospace;
+ font-size: 9px;
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 3px;
+ padding: 1px 4px;
+ margin-right: 2px;
+}
diff --git a/src/wallet/connect-button.js b/src/wallet/connect-button.js
index fcbc14291..be93af05b 100644
--- a/src/wallet/connect-button.js
+++ b/src/wallet/connect-button.js
@@ -71,6 +71,8 @@ export class ConnectWalletController extends EventTarget {
#activeProvider = null;
/** WalletConnect provider instance, kept separately for listener cleanup. */
#wcProvider = null;
+ /** 'browser' | 'walletconnect' | null — set on successful connect, used for error retry. */
+ #lastConnectMethod = null;
/**
* @param {{
@@ -138,14 +140,45 @@ export class ConnectWalletController extends EventTarget {
return;
}
const eager = await eagerConnectWallet();
- if (!eager) return;
- this.#dispatch({
- type: 'ACCOUNTS_RESOLVED',
- address: eager.address,
- chainId: eager.chainId,
- });
- if (!this.#opts.allowedChainIds.includes(eager.chainId)) {
- this.#dispatch({ type: 'WRONG_CHAIN' });
+ if (eager) {
+ this.#dispatch({
+ type: 'ACCOUNTS_RESOLVED',
+ address: eager.address,
+ chainId: eager.chainId,
+ });
+ if (!this.#opts.allowedChainIds.includes(eager.chainId)) {
+ this.#dispatch({ type: 'WRONG_CHAIN' });
+ }
+ return;
+ }
+
+ // Restore an existing WalletConnect session without opening the modal.
+ if (this.#opts.wcProjectId) {
+ try {
+ const { initWCProvider } = await import('./wc-provider.js');
+ const wc = await initWCProvider({
+ projectId: this.#opts.wcProjectId,
+ chains: this.#opts.allowedChainIds.filter((id) => id > 0).slice(0, 1),
+ optionalChains: this.#opts.allowedChainIds.filter((id) => id > 0).slice(1),
+ });
+ if (wc.accounts?.length) {
+ wc.on('accountsChanged', this.#onAccountsChanged);
+ wc.on('chainChanged', this.#onChainChanged);
+ this.#wcProvider = wc;
+ this.#activeProvider = wc;
+ this.#lastConnectMethod = 'walletconnect';
+ this.#dispatch({
+ type: 'ACCOUNTS_RESOLVED',
+ address: wc.accounts[0],
+ chainId: wc.chainId,
+ });
+ if (!this.#opts.allowedChainIds.includes(wc.chainId)) {
+ this.#dispatch({ type: 'WRONG_CHAIN' });
+ }
+ }
+ } catch {
+ // No stored WC session — nothing to restore.
+ }
}
}
@@ -161,6 +194,9 @@ export class ConnectWalletController extends EventTarget {
get error() {
return this.#s.error;
}
+ get lastConnectMethod() {
+ return this.#lastConnectMethod;
+ }
/** @param {{ type: string, [k: string]: any }} action */
#dispatch(action) {
@@ -189,6 +225,7 @@ export class ConnectWalletController extends EventTarget {
const network = await provider.getNetwork();
const chainId = Number(network.chainId);
this.#activeProvider = window.ethereum;
+ this.#lastConnectMethod = 'browser';
this.#dispatch({ type: 'ACCOUNTS_RESOLVED', address, chainId });
if (!this.#opts.allowedChainIds.includes(chainId)) {
@@ -219,6 +256,7 @@ export class ConnectWalletController extends EventTarget {
wc.on('chainChanged', this.#onChainChanged);
this.#wcProvider = wc;
this.#activeProvider = wc;
+ this.#lastConnectMethod = 'walletconnect';
await wc.connect();
const provider = new BrowserProvider(wc);
@@ -505,7 +543,11 @@ export function createConnectWalletButton(mountEl, opts = {}) {
} else if (status === STATES.ERROR) {
btn.onclick = () => {
ctrl.reset();
- ctrl.connect();
+ if (ctrl.lastConnectMethod === 'walletconnect') {
+ ctrl.connectWalletConnect();
+ } else {
+ ctrl.connect();
+ }
};
} else if (status === STATES.IDLE) {
if (wcProjectId) {
diff --git a/vercel.json b/vercel.json
index 2785c2b12..9ced2ea45 100644
--- a/vercel.json
+++ b/vercel.json
@@ -321,6 +321,10 @@
"src": "/xr/?",
"dest": "/xr.html"
},
+ {
+ "src": "/city/?",
+ "dest": "/city.html"
+ },
{
"src": "/play/?",
"dest": "/play.html"
diff --git a/vite.config.js b/vite.config.js
index 0f40ab9ba..37ffb6c01 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -283,6 +283,7 @@ const appConfig = {
walk: resolve(__dirname, 'pages/walk.html'),
communities: resolve(__dirname, 'pages/communities.html'),
'walk-embed': resolve(__dirname, 'pages/walk-embed.html'),
+ city: resolve(__dirname, 'pages/city.html'),
play: resolve(__dirname, 'pages/play.html'),
game: resolve(__dirname, 'pages/game.html'),
pose: resolve(__dirname, 'pages/pose.html'),