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: restructure surfaces, routes, and shared modules

nirholascd6cc321447b
diff --git a/.gitignore b/.gitignore
index 104ea2f98..1ca10e906 100644
--- a/.gitignore
+++ b/.gitignore
@@ -137,3 +137,41 @@ scratch/showcase-before.png
# Local scratch: throwaway scripts, screenshots, verification snippets
scratch/
+docs/3d-generation-api/animation/pre-rig-check-v2-0-20250506.md
+docs/3d-generation-api/animation/retarget.md
+docs/3d-generation-api/animation/rig-v1-0-20240301.md
+docs/3d-generation-api/animation/rig-v2-5-20260210.md
+docs/3d-generation-api/export/conversion.md
+docs/3d-generation-api/file-upload/quick-upload-directly.md
+docs/3d-generation-api/file-upload/upload-in-sts.md
+docs/3d-generation-api/get-started/changelog.md
+docs/3d-generation-api/get-started/errors-and-error-handling.md
+docs/3d-generation-api/get-started/introduction.md
+docs/3d-generation-api/get-started/overview.md
+docs/3d-generation-api/get-started/pricing.md
+docs/3d-generation-api/get-started/quick-start.md
+docs/3d-generation-api/get-started/rate-limits.md
+docs/3d-generation-api/image-generation/advanced-image-generation.md
+docs/3d-generation-api/image-generation/basic-text-to-image.md
+docs/3d-generation-api/image-generation/multiview-image.md
+docs/3d-generation-api/mesh-editing/mesh-completion-v1-0-20250506.md
+docs/3d-generation-api/mesh-editing/mesh-segmentation-v1-0-20250506.md
+docs/3d-generation-api/mesh-editing/smart-low-poly-p-v2-0-20251225.md
+docs/3d-generation-api/model-generation/image-to-model-p1-20260311.md
+docs/3d-generation-api/model-generation/image-to-model-turbo-v1-0-20250506.md
+docs/3d-generation-api/model-generation/image-to-model-v1-4-20240625.md
+docs/3d-generation-api/model-generation/image-to-model-v2-0-v2-5.md
+docs/3d-generation-api/model-generation/image-to-model-v3-0-v3-1.md
+docs/3d-generation-api/model-generation/import-model.md
+docs/3d-generation-api/model-generation/multiview-to-model-p1-20260311.md
+docs/3d-generation-api/model-generation/multiview-to-model-v2-0-v2-5.md
+docs/3d-generation-api/model-generation/multiview-to-model-v3-0-v3-1.md
+docs/3d-generation-api/model-generation/text-to-model-p1-20260311.md
+docs/3d-generation-api/model-generation/text-to-model-turbo-v1-0-20250506.md
+docs/3d-generation-api/model-generation/text-to-model-v1-4-20240625.md
+docs/3d-generation-api/model-generation/text-to-model-v2-0-v2-5.md
+docs/3d-generation-api/model-generation/text-to-model-v3-0-v3-1.md
+docs/3d-generation-api/other/support-faq.md
+docs/3d-generation-api/task-query/get-your-task-result.md
+docs/3d-generation-api/texture/texture-model-v2-5-20250123.md
+docs/3d-generation-api/texture/texture-model-v3-0-20250812.md
diff --git a/api/forge.js b/api/forge.js
new file mode 100644
index 000000000..3019d7efd
--- /dev/null
+++ b/api/forge.js
@@ -0,0 +1,135 @@
+/**
+ * Forge — browser-facing text → 3D model generator.
+ *
+ * POST /api/forge { prompt, aspect_ratio? } → start a job
+ * GET /api/forge?job=<id> → poll a job
+ *
+ * This is the public, auth-free twin of the 3D Studio MCP server
+ * (api/mcp-3d.js): it drives the exact same real pipeline — a flux-schnell
+ * text-to-image pass, then Microsoft TRELLIS mesh reconstruction on Replicate —
+ * but over plain JSON so the /forge page can drive it straight from the
+ * browser. There is no shared MCP/OAuth context here, so requests are rate
+ * limited by client IP using the same generation/status limiters.
+ *
+ * No mock paths: if REPLICATE_API_TOKEN is absent the endpoint returns a clean
+ * 503 with a configuration message and the page renders a designed "not
+ * configured" state — it never fabricates a model.
+ */
+
+import { cors, json, method, readJson, wrap } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { textToImage } from './_mcp3d/text-to-image.js';
+import { createRegenProvider } from './_providers/replicate.js';
+
+const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);
+
+// A Replicate prediction id is a lowercase base32-ish token. Constrain the
+// poll parameter to that shape so we never forward arbitrary strings upstream.
+const JOB_ID_RE = /^[a-z0-9]{16,64}$/;
+
+function unconfigured(res) {
+ return json(res, 503, {
+ error: 'unconfigured',
+ message:
+ 'Text-to-3D generation is not configured on this deployment (REPLICATE_API_TOKEN is missing).',
+ });
+}
+
+async function startJob(req, res) {
+ const ip = clientIp(req);
+ const rl = await limits.mcp3dGenerate(ip);
+ if (!rl.success) {
+ return json(res, 429, {
+ error: 'rate_limited',
+ message: 'Generation limit reached. Try again shortly.',
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+ }
+
+ const body = await readJson(req, 8_000).catch(() => null);
+ const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';
+ if (prompt.length < 3 || prompt.length > 1000) {
+ return json(res, 400, {
+ error: 'invalid_prompt',
+ message: 'Describe one subject in 3–1000 characters.',
+ });
+ }
+ const aspect = VALID_ASPECT.has(body?.aspect_ratio) ? body.aspect_ratio : '1:1';
+
+ let provider;
+ try {
+ provider = createRegenProvider();
+ } catch {
+ return unconfigured(res);
+ }
+
+ try {
+ const { imageUrl, model } = await textToImage(prompt, { aspectRatio: aspect });
+ const job = await provider.submit({
+ mode: 'reconstruct',
+ params: { image: imageUrl, prompt },
+ });
+ return json(res, 200, {
+ job_id: job.extJobId,
+ status: 'queued',
+ prompt,
+ preview_image_url: imageUrl,
+ text_to_image_model: model,
+ eta_seconds: typeof job.eta === 'number' ? job.eta : null,
+ });
+ } catch (err) {
+ if (err?.code === 'unconfigured') return unconfigured(res);
+ return json(res, 502, {
+ error: 'generation_failed',
+ message: err?.message || 'The generator could not start this job.',
+ });
+ }
+}
+
+async function pollJob(req, res, jobId) {
+ if (!JOB_ID_RE.test(jobId)) {
+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });
+ }
+
+ const rl = await limits.mcp3dStatus(clientIp(req));
+ if (!rl.success) {
+ return json(res, 429, {
+ error: 'rate_limited',
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+ }
+
+ let provider;
+ try {
+ provider = createRegenProvider();
+ } catch {
+ return unconfigured(res);
+ }
+
+ const result = await provider.status(jobId);
+ if (result.status === 'done' && result.resultGlbUrl) {
+ return json(res, 200, { job_id: jobId, status: 'done', glb_url: result.resultGlbUrl });
+ }
+ if (result.status === 'failed') {
+ return json(res, 200, {
+ job_id: jobId,
+ status: 'failed',
+ error: result.error || 'Generation failed.',
+ });
+ }
+ return json(res, 200, { job_id: jobId, status: result.status || 'running' });
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (req.method === 'POST') return startJob(req, res);
+
+ const url = new URL(req.url, 'http://localhost');
+ const jobId = (url.searchParams.get('job') || '').trim();
+ if (!jobId) {
+ return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll a job.' });
+ }
+ return pollJob(req, res, jobId);
+});
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index d087fcdd4..9eacddcfd 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -344,6 +344,8 @@ async function handleMine(req, res) {
SELECT ai.id, ai.name, ai.description, ai.category, ai.tags, ai.avatar_id, ai.user_id,
ai.forks_count, ai.views_count, ai.published_at, ai.created_at, ai.skills,
ai.is_published, av.thumbnail_key,
+ av.storage_key AS avatar_storage_key,
+ av.visibility AS avatar_visibility,
ap.amount AS asset_price_amount,
ap.currency_mint AS asset_price_currency_mint,
ap.chain AS asset_price_chain,
@@ -400,6 +402,8 @@ async function handleList(req, res, url) {
SELECT ai.id, ai.name, ai.description, ai.category, ai.tags, ai.avatar_id, ai.user_id,
ai.forks_count, ai.views_count, ai.published_at, ai.created_at, ai.skills,
av.thumbnail_key,
+ av.storage_key AS avatar_storage_key,
+ av.visibility AS avatar_visibility,
ai.meta->'onchain' AS onchain,
ai.meta->'token' AS token,
u.display_name AS author_name,
@@ -445,6 +449,8 @@ async function handleList(req, res, url) {
SELECT ai.id, ai.name, ai.description, ai.category, ai.tags, ai.avatar_id, ai.user_id,
ai.forks_count, ai.views_count, ai.published_at, ai.created_at, ai.skills,
av.thumbnail_key,
+ av.storage_key AS avatar_storage_key,
+ av.visibility AS avatar_visibility,
ai.meta->'onchain' AS onchain,
ai.meta->'token' AS token,
u.display_name AS author_name,
@@ -917,6 +923,8 @@ async function handleSimilar(req, res, id) {
SELECT ai.id, ai.name, ai.description, ai.category, ai.tags, ai.avatar_id, ai.user_id,
ai.forks_count, ai.views_count, ai.published_at, ai.created_at, ai.skills,
av.thumbnail_key,
+ av.storage_key AS avatar_storage_key,
+ av.visibility AS avatar_visibility,
(
(CASE WHEN ai.category = ${base.category} THEN 3 ELSE 0 END)
+ cardinality(ARRAY(SELECT unnest(ai.tags) INTERSECT SELECT unnest(${base.tags}::text[])))
diff --git a/multiplayer/src/cosmetics.js b/multiplayer/src/cosmetics.js
deleted file mode 100644
index 6e4c1380f..000000000
--- a/multiplayer/src/cosmetics.js
+++ /dev/null
@@ -1,194 +0,0 @@
-// Cosmetics shop — the catalog of visual-only looks players buy with gold, and
-// the deterministic rotation that decides which ones are on sale right now.
-//
-// Cosmetics are STRICTLY visual. Nothing here touches combat, stats, movement,
-// or any other gameplay value — a cosmetic only changes how an avatar renders
-// (a body tint, a worn prop, a ground aura). The server owns purchase + rotation
-// authority; the client is sent this catalog so it can render any peer's
-// equipped look, and a live shop snapshot (offers + countdowns) when the shop
-// opens. Pure + dependency-free so the rotation is unit-tested without a room
-// (mirrors quests.js).
-//
-// Visual spec (`visual`), interpreted only by the client cosmetics renderer:
-// { tint: '#rrggbb' } recolour the avatar's body materials
-// { prop: '/path.glb', anchor: 'head' } attach a prop (auto-fitted to the head)
-// { aura: '#rrggbb' } a glowing ring at the avatar's feet
-// A cosmetic may combine fields (e.g. a tint + an aura).
-
-// Rarity tiers, lowest → highest. The colour drives the catalog card accent on
-// the client so rarity reads at a glance; kept here so server + client agree.
-export const RARITIES = {
- common: { label: 'Common', color: '#9aa7b4' },
- uncommon: { label: 'Uncommon', color: '#4fb477' },
- rare: { label: 'Rare', color: '#4a90e2' },
- epic: { label: 'Epic', color: '#b06ff0' },
- legendary: { label: 'Legendary', color: '#f0a23a' },
-};
-
-// The full catalog. `rotation` is one of:
-// 'always' — always on sale (a permanent staple)
-// 'daily' — part of the daily-rotating pool (a subset is offered each UTC day)
-// 'weekly' — part of the weekly-rotating pool (a subset offered each UTC week)
-// Prices are in gold. Ids are stable — never renumber a live cosmetic, since
-// ownership and the equipped selection persist by id (Task 16).
-export const COSMETICS = [
- // ---- Always available (the staples) ----------------------------------
- { id: 'tint-ash', name: 'Ashen Cloak', rarity: 'common', price: 60, rotation: 'always', visual: { tint: '#6b6f76' } },
- { id: 'tint-crimson', name: 'Crimson Dye', rarity: 'common', price: 80, rotation: 'always', visual: { tint: '#c0392b' } },
- { id: 'tint-azure', name: 'Azure Dye', rarity: 'common', price: 80, rotation: 'always', visual: { tint: '#2e86de' } },
- { id: 'hat-beanie', name: 'Wool Beanie', rarity: 'common', price: 120, rotation: 'always', visual: { prop: '/accessories/hat-beanie.glb', anchor: 'head' } },
-
- // ---- Daily rotation pool (DAILY_OFFER_COUNT offered each day) ----------
- { id: 'tint-emerald', name: 'Emerald Dye', rarity: 'uncommon', price: 140, rotation: 'daily', visual: { tint: '#1abc9c' } },
- { id: 'tint-violet', name: 'Violet Dye', rarity: 'uncommon', price: 140, rotation: 'daily', visual: { tint: '#8e44ad' } },
- { id: 'hat-baseball', name: 'Field Cap', rarity: 'uncommon', price: 200, rotation: 'daily', visual: { prop: '/accessories/hat-baseball.glb', anchor: 'head' } },
- { id: 'glasses-round', name: 'Round Specs', rarity: 'uncommon', price: 180, rotation: 'daily', visual: { prop: '/accessories/glasses-round.glb', anchor: 'face' } },
- { id: 'tint-gold', name: 'Gilded Sheen', rarity: 'rare', price: 360, rotation: 'daily', visual: { tint: '#f1c40f' } },
- { id: 'aura-ember', name: 'Ember Aura', rarity: 'rare', price: 420, rotation: 'daily', visual: { aura: '#ff6b35' } },
-
- // ---- Weekly rotation pool (WEEKLY_OFFER_COUNT offered each week) -------
- { id: 'hat-cowboy', name: "Ranger's Hat", rarity: 'rare', price: 480, rotation: 'weekly', visual: { prop: '/accessories/hat-cowboy.glb', anchor: 'head' } },
- { id: 'glasses-shades', name: 'Shades', rarity: 'rare', price: 520, rotation: 'weekly', visual: { prop: '/accessories/glasses-shades.glb', anchor: 'face' } },
- { id: 'aura-frost', name: 'Frost Aura', rarity: 'epic', price: 700, rotation: 'weekly', visual: { aura: '#6bd3ff' } },
- { id: 'aura-radiant', name: 'Radiant Aura', rarity: 'epic', price: 760, rotation: 'weekly', visual: { aura: '#ffe27a', tint: '#fff4cf' } },
- { id: 'aura-void', name: 'Void Aura', rarity: 'legendary', price: 1400, rotation: 'weekly', visual: { aura: '#9b59b6', tint: '#2c2c54' } },
-];
-
-// How many of each rotating pool are on sale at once. Kept below each pool's
-// size so the set genuinely changes from one period to the next.
-export const DAILY_OFFER_COUNT = 3;
-export const WEEKLY_OFFER_COUNT = 2;
-
-const BY_ID = new Map(COSMETICS.map((c) => [c.id, c]));
-const DAILY_POOL = COSMETICS.filter((c) => c.rotation === 'daily').map((c) => c.id);
-const WEEKLY_POOL = COSMETICS.filter((c) => c.rotation === 'weekly').map((c) => c.id);
-const ALWAYS = COSMETICS.filter((c) => c.rotation === 'always').map((c) => c.id);
-
-const DAY_MS = 24 * 60 * 60 * 1000;
-
-export function cosmeticById(id) {
- return BY_ID.get(id) || null;
-}
-
-// A stable 32-bit hash of a string (FNV-1a) — same constant the quest roller
-// uses, so rotations are deterministic across processes and restarts.
-function hashString(s) {
- let h = 0x811c9dc5;
- for (let i = 0; i < s.length; i++) {
- h ^= s.charCodeAt(i);
- h = Math.imul(h, 0x01000193);
- }
- return h >>> 0;
-}
-
-// Epoch ms of the most recent UTC midnight at or before `now`.
-function startOfUtcDay(now) {
- const d = new Date(now);
- return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
-}
-
-// 'YYYY-MM-DD' (UTC) for `now` — the key the daily rotation is seeded with.
-export function dailyKey(now) {
- return new Date(startOfUtcDay(now)).toISOString().slice(0, 10);
-}
-
-// Epoch ms of the next UTC midnight — when the daily set rotates. The client
-// renders a live countdown to this and re-requests the shop when it passes.
-export function nextDailyReset(now) {
- return startOfUtcDay(now) + DAY_MS;
-}
-
-// Epoch ms of UTC Monday 00:00 at or before `now` (ISO week start).
-function startOfUtcWeek(now) {
- const dow = (new Date(now).getUTCDay() + 6) % 7; // Mon=0 … Sun=6
- return startOfUtcDay(now) - dow * DAY_MS;
-}
-
-// Week key — the Monday date string the weekly rotation is seeded with.
-export function weekKey(now) {
- return new Date(startOfUtcWeek(now)).toISOString().slice(0, 10);
-}
-
-// Epoch ms of the next UTC Monday — when the weekly set rotates.
-export function nextWeeklyReset(now) {
- return startOfUtcWeek(now) + 7 * DAY_MS;
-}
-
-// Deterministically pick `count` distinct ids from `pool` for a rotation key.
-// Seeded Fisher–Yates (xorshift32 PRNG) — identical to the daily-quest roller,
-// so a period's offers are fixed and reproducible on every server/restart.
-function rollOffers(pool, key, count) {
- if (count >= pool.length) return [...pool];
- const seed = hashString(key);
- const idx = pool.map((_, i) => i);
- let state = seed || 1;
- const rand = () => {
- state ^= state << 13; state >>>= 0;
- state ^= state >> 17;
- state ^= state << 5; state >>>= 0;
- return state / 0xffffffff;
- };
- for (let i = idx.length - 1; i > 0; i--) {
- const j = Math.floor(rand() * (i + 1));
- [idx[i], idx[j]] = [idx[j], idx[i]];
- }
- return idx.slice(0, count).map((i) => pool[i]);
-}
-
-// The current offer board: which cosmetic ids are buyable right now, split by
-// bucket, plus the epoch-ms moments each rotation next turns over (for the
-// client countdowns). Server-authoritative — derived purely from `now`.
-export function currentOffers(now) {
- return {
- always: [...ALWAYS],
- daily: rollOffers(DAILY_POOL, dailyKey(now), DAILY_OFFER_COUNT),
- weekly: rollOffers(WEEKLY_POOL, weekKey(now), WEEKLY_OFFER_COUNT),
- dailyResetAt: nextDailyReset(now),
- weeklyResetAt: nextWeeklyReset(now),
- };
-}
-
-// Whether a given cosmetic is on sale at `now`. Always-cosmetics are always
-// offered; rotating ones only during their current window. The buy handler
-// gates on this so a client can't purchase something not currently for sale.
-export function isOffered(id, now) {
- const c = BY_ID.get(id);
- if (!c) return false;
- if (c.rotation === 'always') return true;
- const offers = currentOffers(now);
- return c.rotation === 'daily' ? offers.daily.includes(id) : offers.weekly.includes(id);
-}
-
-// Pure purchase rule — the single source of truth for whether a buy is allowed,
-// shared by the server buy handler and its tests. Returns the resolved cosmetic
-// plus an outcome code so the caller can phrase the notice (and compute the gold
-// shortfall) without re-deriving the rules:
-// 'unknown' — no such cosmetic id
-// 'owned' — the player already owns it
-// 'not-offered' — exists but isn't in the current rotation
-// 'poor' — offered + unowned, but the player can't afford it
-// 'ok' — buyable now
-// `owned` may be a Set or an array of ids; `gold` is the player's purse.
-export function evaluatePurchase(gold, owned, id, now) {
- const cosmetic = cosmeticById(id);
- if (!cosmetic) return { ok: false, reason: 'unknown', cosmetic: null };
- const has = owned instanceof Set ? owned.has(id) : Array.isArray(owned) && owned.includes(id);
- if (has) return { ok: false, reason: 'owned', cosmetic };
- if (!isOffered(id, now)) return { ok: false, reason: 'not-offered', cosmetic };
- if ((gold | 0) < cosmetic.price) return { ok: false, reason: 'poor', cosmetic };
- return { ok: true, reason: 'ok', cosmetic };
-}
-
-// The catalog as sent to the client: every cosmetic's id, name, rarity, price,
-// rotation, and visual spec, plus the rarity palette. The client renders peers'
-// equipped looks and the shop/wardrobe entirely from this — no prices or visuals
-// are hard-coded client-side.
-export function clientCatalog() {
- return {
- rarities: RARITIES,
- cosmetics: COSMETICS.map((c) => ({
- id: c.id, name: c.name, rarity: c.rarity, price: c.price,
- rotation: c.rotation, visual: c.visual,
- })),
- };
-}
diff --git a/multiplayer/src/index.js b/multiplayer/src/index.js
index 8f6d11cb1..55ba58827 100644
--- a/multiplayer/src/index.js
+++ b/multiplayer/src/index.js
@@ -15,18 +15,15 @@
import http from 'node:http';
import express from 'express';
-import { Server, matchMaker } from '@colyseus/core';
+import { Server } from '@colyseus/core';
import { WebSocketTransport } from '@colyseus/ws-transport';
import { monitor } from '@colyseus/monitor';
import { WalkRoom } from './rooms/WalkRoom.js';
-import { GameRoom } from './rooms/GameRoom.js';
-import { REALMS } from './rooms/realms.js';
import { blockStore } from './block-store.js';
import { worldPersistence } from './persistence.js';
import { flushAllPlayers } from './playerStore.js';
import { marketplaceStore } from './marketplaceStore.js';
-import { SERVERS } from './servers.js';
import { socialHub } from './social-hub.js';
import { verifyNotifySignature } from './presence-token.js';
@@ -191,129 +188,6 @@ const gameServer = new Server({ transport, ...(driver && { driver }), ...(presen
// to the shared mainland world; a missing tier is the open General world (see
// WalkRoom.onCreate / onAuth / schemas.js).
gameServer.define('walk_world', WalkRoom).filterBy(['coin', 'tier']);
-// One room definition per realm — each is its own instance, so players in
-// different realms never see or affect each other. The realm name is baked into
-// the definition's options and read by GameRoom.onCreate. Mainland/Whisperwood/
-// Pond/Mine are safe; Wilderness is the danger+pvp realm that drops death-bags.
-// Mine is the enclosed cave interior reached through the Mainland mine entrance.
-//
-// Server dimension (Task 23): filterBy(['server']) splits each realm definition
-// into one room per chosen world instance, exactly as walk_world is split by
-// coin/tier above. A joinOrCreate for game_mainland with {server:'s2'} matches
-// only rooms created with server='s2', so the two worlds never merge — players
-// on different servers can't see each other in any realm, chat, or /who. A
-// missing/forged server option collapses to the default instance (see
-// servers.cleanServer / GameRoom.onCreate).
-// One room definition per realm, sourced from REALMS so a newly-defined realm is
-// reachable the moment it's added to realms.js — no separate list to keep in sync.
-for (const realm of Object.keys(REALMS)) {
- gameServer.define(`game_${realm}`, GameRoom, { realm }).filterBy(['server']);
-}
-
-// --- Multi-server discovery (Task 23) --------------------------------------
-// Read-only population the /play login picker consumes from the (different-origin)
-// static site, so it carries permissive CORS. Always live truth — never cached or
-// faked. (Friends presence — "which server+realm a friend is on" — is published by
-// the social hub under the verified account id and read by the authenticated
-// friends API, NOT here; there is no anonymous by-id lookup to scrape.)
-
-// CORS for the public population endpoint. The counts aren't sensitive, so any
-// origin may GET them; no credentials are involved. OPTIONS preflights short-circuit.
-function publicJsonCors(_req, res, next) {
- res.set('Access-Control-Allow-Origin', '*');
- res.set('Access-Control-Allow-Methods', 'GET, OPTIONS');
- res.set('Access-Control-Allow-Headers', 'Content-Type');
- res.set('Cache-Control', 'no-store');
- if (_req.method === 'OPTIONS') return res.status(204).end();
- next();
-}
-
-// Lightweight per-IP rate limit for the public endpoint — a fixed window that
-// clears legitimate picker polling (one every ~10s) with wide headroom but caps a
-// scripted flood. In-process (per instance), which is plenty for a read-only GET.
-const RATE_WINDOW_MS = 10_000;
-const RATE_MAX = 30;
-const _rateBuckets = new Map(); // ip -> { windowStart, count }
-
-// Trusted client-IP resolution. X-Forwarded-For is fully client-controlled when a
-// request reaches the app directly, so keying the limiter on it lets a flood rotate
-// a fresh XFF per request and never hit a bucket. We only trust a forwarded IP from
-// our actual fronting proxy:
-// - Fly.io sets Fly-Client-IP to the real edge client IP (it can't be spoofed
-// past the proxy);
-// - TRUSTED_PROXY_IP_HEADER names any other platform's verified client-IP header
-// (e.g. CF-Connecting-IP, X-Real-IP) for non-Fly deploys.
-// Absent a trusted header we fall back to the raw socket peer, which an attacker
-// can't forge. We deliberately do NOT parse X-Forwarded-For as the access key.
-const TRUSTED_IP_HEADER = (process.env.TRUSTED_PROXY_IP_HEADER || '').trim().toLowerCase();
-function clientIp(req) {
- const fly = req.headers['fly-client-ip'];
- if (typeof fly === 'string' && fly.trim()) return fly.trim();
- if (TRUSTED_IP_HEADER) {
- const h = req.headers[TRUSTED_IP_HEADER];
- const v = Array.isArray(h) ? h[0] : h;
- if (typeof v === 'string' && v.trim()) return v.split(',')[0].trim();
- }
- return req.socket?.remoteAddress || 'unknown';
-}
-
-function rateLimit(req, res, next) {
- const ip = clientIp(req);
- const now = Date.now();
- let b = _rateBuckets.get(ip);
- if (!b || now - b.windowStart > RATE_WINDOW_MS) { b = { windowStart: now, count: 0 }; _rateBuckets.set(ip, b); }
- b.count++;
- if (b.count > RATE_MAX) return res.status(429).json({ error: 'rate_limited' });
- next();
-}
-// Bound the bucket map so a churn of distinct IPs can't grow it without limit.
-setInterval(() => {
- const now = Date.now();
- for (const [ip, b] of _rateBuckets) if (now - b.windowStart > RATE_WINDOW_MS) _rateBuckets.delete(ip);
-}, RATE_WINDOW_MS * 6).unref?.();
-
-// GET /servers — the world-instance roster with REAL live population. Population
-// is the sum of connected clients across every game_* room whose metadata names
-// that server, queried through the matchmaker (so it's correct across all
-// horizontally-scaled instances, not just this process). The most-populated server
-// that isn't near capacity is recommended, so newcomers land where the world feels
-// alive rather than fragmenting into an empty instance — without ever faking a count.
-app.get('/servers', publicJsonCors, rateLimit, async (_req, res) => {
- const counts = Object.fromEntries(SERVERS.map((s) => [s.id, 0]));
- try {
- const rooms = await matchMaker.query({});
- for (const r of rooms) {
- if (typeof r.name !== 'string' || !r.name.startsWith('game_')) continue;
- const sid = r.metadata?.server;
- if (sid && sid in counts) counts[sid] += r.clients || 0;
- }
- } catch (err) {
- console.warn('[multiplayer] /servers query failed:', err?.message);
- return res.status(503).json({ error: 'population_unavailable' });
- }
- // Recommend the fullest server that still has comfortable headroom, so worlds
- // stay lively instead of every newcomer being sent to the emptiest one. Falls
- // back to the least-full server only when all are near capacity. Stable on ties
- // (first in roster order wins) so the suggestion doesn't flicker between polls.
- const SOFT_CAP = 40; // leave room under the 50/room ceiling before steering elsewhere
- let recommended = SERVERS[0]?.id || null;
- let bestLive = -1; // fullest below the soft cap
- let leastFull = Infinity; // fallback when everyone is busy
- for (const s of SERVERS) {
- const n = counts[s.id];
- if (n < SOFT_CAP && n > bestLive) { bestLive = n; recommended = s.id; }
- if (bestLive < 0 && n < leastFull) { leastFull = n; recommended = s.id; }
- }
- res.json({
- servers: SERVERS.map((s) => ({
- id: s.id,
- name: s.name,
- blurb: s.blurb,
- players: counts[s.id],
- recommended: s.id === recommended,
- })),
- });
-});
gameServer
.listen(PORT, HOST)
diff --git a/multiplayer/src/marketplaceStore.js b/multiplayer/src/marketplaceStore.js
deleted file mode 100644
index dfff8ce06..000000000
--- a/multiplayer/src/marketplaceStore.js
+++ /dev/null
@@ -1,222 +0,0 @@
-// MarketplaceStore — durable persistence for the player-to-player marketplace
-// (Task 20): the live listings every player can browse, and the pending payouts
-// owed to sellers who were offline when their goods sold.
-//
-// This is the in-game item economy — distinct from the platform's AGENT
-// marketplace under `api/marketplace*`. Listings here are account-scoped (keyed
-// to a player's stable account id / wallet) and must survive a seller's
-// disconnect, the room emptying, AND a server restart, so a buyer in one realm
-// can purchase goods a seller listed from another realm yesterday.
-//
-// Same two-tier model as block-store.js:
-// 1. In-process memory — the multiplayer server runs as a single always-on
-// instance, so the Maps below already let a listing outlive both the
-// seller's session and the room it was created in.
-// 2. Upstash Redis (REST), used when UPSTASH_REDIS_REST_URL + _TOKEN are set —
-// upgrades durability across restarts/redeploys. Writes are debounced and
-// flushed on shutdown so a busy market doesn't hammer Redis.
-//
-// Escrow lives HERE, not in any inventory: when a player lists, the offered
-// item(s) or gold are removed from them and stored on the listing object. That
-// is the escrow — there is exactly one copy of the goods, so nothing can be
-// listed-and-spent or duplicated. Cancel returns the escrow to the seller; a
-// sale delivers it to the buyer.
-
-const REDIS_URL = process.env.UPSTASH_REDIS_REST_URL || '';
-const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || '';
-const SAVE_DEBOUNCE_MS = 2500;
-const LISTINGS_KEY = 'market:listings';
-const PAYOUTS_KEY = 'market:payouts';
-const SETTLED_KEY = 'market:settled'; // on-chain tx signatures already consumed (replay guard)
-
-let _seq = 0;
-function newId() {
- // Monotonic + time so ids sort by recency and never collide within a process.
- _seq = (_seq + 1) % 0xffffff;
- return `lst_${Date.now().toString(36)}${_seq.toString(36).padStart(4, '0')}`;
-}
-
-class MarketplaceStore {
- constructor() {
- this._listings = new Map(); // id -> listing
- this._payouts = new Map(); // sellerId -> [{ gold, items:[{item,qty}], reason, listingId, ts }]
- this._settled = new Set(); // tx signatures consumed by a token settlement
- this._saveTimer = null;
- this._redis = null;
- this._redisReady = null;
- this._loaded = false;
- this._durable = false;
-
- if (REDIS_URL && REDIS_TOKEN) {
- this._redisReady = import('@upstash/redis')
- .then(async ({ Redis }) => {
- this._redis = new Redis({ url: REDIS_URL, token: REDIS_TOKEN });
- await this._redis.ping();
- this._durable = true;
- await this._hydrate();
- console.log('[marketplace-store] persistence: memory + Upstash Redis (verified)');
- })
- .catch((err) => {
- this._redis = null;
- console.error('[marketplace-store] Redis unreachable — listings are MEMORY-ONLY and will not survive a restart:', err?.message);
- });
- } else {
- console.log('[marketplace-store] persistence: memory-only (set UPSTASH_REDIS_REST_URL/_TOKEN for cross-restart durability)');
- }
- }
-
- get durable() { return this._durable; }
- async ready() { if (this._redisReady) await this._redisReady; }
-
- async _hydrate() {
- if (this._loaded || !this._redis) return;
- try {
- const [rawL, rawP, rawS] = await Promise.all([
- this._redis.get(LISTINGS_KEY),
- this._redis.get(PAYOUTS_KEY),
- this._redis.get(SETTLED_KEY),
- ]);
- const parse = (raw) => (typeof raw === 'string' ? JSON.parse(raw) : raw) || null;
- const L = parse(rawL);
- if (L && typeof L === 'object') for (const v of Object.values(L)) if (v && v.id) this._listings.set(v.id, v);
- const P = parse(rawP);
- if (P && typeof P === 'object') for (const [k, v] of Object.entries(P)) if (Array.isArray(v) && v.length) this._payouts.set(k, v);
- const S = parse(rawS);
- if (Array.isArray(S)) for (const sig of S) if (typeof sig === 'string') this._settled.add(sig);
- } catch (err) {
- console.warn('[marketplace-store] hydrate failed:', err?.message);
- }
- this._loaded = true;
- }
-
- // ---- listings ---------------------------------------------------------
-
- // Active listings, most-recent first. Optionally excluding one seller (so the
- // Buy tab can hide your own goods if desired — the caller decides).
- activeListings() {
- const out = [];
- for (const l of this._listings.values()) if (l.status === 'active') out.push(l);
- out.sort((a, b) => b.createdAt - a.createdAt);
- return out;
- }
-
- listingsBySeller(sellerId) {
- const out = [];
- for (const l of this._listings.values()) if (l.seller === sellerId) out.push(l);
- out.sort((a, b) => b.createdAt - a.createdAt);
- return out;
- }
-
- get(id) { return this._listings.get(id) || null; }
-
- // Create a listing. `escrow` is the goods already removed from the seller:
- // either { item, qty } (gold listing) or { gold } (gold-for-token listing).
- create(listing) {
- const id = newId();
- const rec = { id, ...listing, status: 'active', createdAt: Date.now() };
- this._listings.set(id, rec);
- this._scheduleSave();
- return rec;
- }
-
- update(id, patch) {
- const l = this._listings.get(id);
- if (!l) return null;
- Object.assign(l, patch);
- this._scheduleSave();
- return l;
- }
-
- // Prune sold/cancelled listings older than `maxAgeMs` so the store and the Buy
- // snapshot don't grow without bound. Active listings are never pruned.
- prune(maxAgeMs = 1000 * 60 * 60 * 24 * 7) {
- const cutoff = Date.now() - maxAgeMs;
- let removed = 0;
- for (const [id, l] of this._listings) {
- if (l.status !== 'active' && (l.closedAt || l.createdAt) < cutoff) {
- this._listings.delete(id);
- removed++;
- }
- }
- if (removed) this._scheduleSave();
- return removed;
- }
-
- // ---- pending payouts (offline-seller proceeds) ------------------------
-
- // Queue value owed to a seller who isn't online to receive it now. Drained on
- // their next join. Durable, so owed proceeds survive a restart until claimed.
- enqueuePayout(sellerId, payout) {
- if (!sellerId) return;
- const list = this._payouts.get(sellerId) || [];
- list.push({ ...payout, ts: Date.now() });
- this._payouts.set(sellerId, list);
- this._scheduleSave();
- }
-
- // Take and clear all pending payouts for a seller (called on join). Returns the
- // list; the caller is responsible for actually delivering them.
- drainPayouts(sellerId) {
- const list = this._payouts.get(sellerId);
- if (!list || !list.length) return [];
- this._payouts.delete(sellerId);
- this._scheduleSave();
- return list;
- }
-
- hasPendingPayouts(sellerId) {
- return (this._payouts.get(sellerId)?.length || 0) > 0;
- }
-
- // ---- on-chain replay guard -------------------------------------------
-
- isSettled(txSig) { return this._settled.has(txSig); }
- markSettled(txSig) {
- if (!txSig) return;
- this._settled.add(txSig);
- // Bound the set so a long-lived process doesn't accumulate signatures forever.
- if (this._settled.size > 5000) {
- const first = this._settled.values().next().value;
- this._settled.delete(first);
- }
- this._scheduleSave();
- }
-
- // ---- persistence ------------------------------------------------------
-
- _scheduleSave() {
- if (!this._redis && !this._redisReady) return; // memory-only
- if (this._saveTimer) return;
- const handle = setTimeout(() => { this._saveTimer = null; this.flush(); }, SAVE_DEBOUNCE_MS);
- if (typeof handle.unref === 'function') handle.unref();
- this._saveTimer = handle;
- }
-
- async flush() {
- if (this._saveTimer) { clearTimeout(this._saveTimer); this._saveTimer = null; }
- if (!this._redisReady) return;
- await this._redisReady;
- if (!this._redis) return;
- try {
- await Promise.all([
- this._redis.set(LISTINGS_KEY, JSON.stringify(Object.fromEntries(this._listings))),
- this._redis.set(PAYOUTS_KEY, JSON.stringify(Object.fromEntries(this._payouts))),
- this._redis.set(SETTLED_KEY, JSON.stringify([...this._settled])),
- ]);
- this._durable = true;
- } catch (err) {
- console.error('[marketplace-store] save failed — market durability degraded:', err?.message);
- }
- }
-
- async flushAll() { await this.flush(); }
-}
-
-// One store shared by every GameRoom in the process — that shared memory is
-// exactly what lets a listing outlive its seller's session and its room.
-export const marketplaceStore = new MarketplaceStore();
-
-// Periodically retire long-closed (sold/cancelled) listings so neither the store
-// nor the Buy snapshot grows without bound over a long-lived process. Active
-// listings are never touched. Unref'd so it never keeps the process alive.
-setInterval(() => marketplaceStore.prune(), 1000 * 60 * 60).unref?.();
diff --git a/multiplayer/src/quests.js b/multiplayer/src/quests.js
deleted file mode 100644
index 5c4cca856..000000000
--- a/multiplayer/src/quests.js
+++ /dev/null
@@ -1,201 +0,0 @@
-// Quest engine — the authoritative definitions and helpers behind the Mainland
-// tutorial and the daily-quest rotation. Pure data + pure functions: no Colyseus
-// or network concerns live here, so the GameRoom can drive everything from real
-// action hooks (gather/combat/movement/banking) and this module stays trivially
-// testable and deterministic.
-//
-// Two systems share this file:
-// • Tutorial — a fixed, ordered onboarding (TUTORIAL_STEPS). A fresh account
-// walks it once; completion is persisted so it never replays.
-// • Daily quests — three objectives rolled per account per UTC day from
-// DAILY_POOL. The roll is DETERMINISTIC (hash of playerId + date) so the
-// same player always sees the same set for a given day, a reconnect mid-day
-// never reshuffles their quests, and there is no Math.random to make state
-// unreproducible across a restart.
-//
-// Progress only ever moves from server-validated actions — never from a client
-// claim — so a player cannot spoof a turn-in.
-
-// ---------------------------------------------------------------------------
-// Badges — cosmetic account achievements granted by quests. Surfaced on the
-// player's nameplate and in the quest panel (the in-world "profile").
-// ---------------------------------------------------------------------------
-export const BADGES = {
- newcomer: { id: 'newcomer', label: 'Newcomer', icon: '🎓', desc: 'Finished the Mainland tutorial.' },
- warrior: { id: 'warrior', label: 'Warrior', icon: '⚔️', desc: 'Cleared a combat daily quest.' },
- forager: { id: 'forager', label: 'Forager', icon: '🧺', desc: 'Cleared a gathering daily quest.' },
- fisher: { id: 'fisher', label: 'Fisher', icon: '🎣', desc: 'Cleared a fishing daily quest.' },
- pitcook: { id: 'pitcook', label: 'Pit Cook', icon: '🔥', desc: 'Cleared a cooking daily quest.' },
- builder: { id: 'builder', label: 'Builder', icon: '🔨', desc: 'Placed a firepit in the wild.' },
- devoted: { id: 'devoted', label: 'Devoted', icon: '🌟', desc: 'Cleared every daily quest in one day.' },
-};
-
-// ---------------------------------------------------------------------------
-// Tutorial — ordered steps. Each step advances only when the player performs
-// the real action `kind` `count` times (validated server-side):
-// move → successful tile steps
-// talk → talking to the guide NPC
-// gather → gathering a specific resource item
-// combat → defeating a mob
-// bank → depositing an item at the bank counter
-// `slot` (when present) is the hotbar index the step is teaching the player to
-// equip — the client highlights it.
-// ---------------------------------------------------------------------------
-export const TUTORIAL_STEPS = [
- {
- id: 'move', kind: 'move', count: 8,
- title: 'Find your footing',
- desc: 'Use WASD (or the joystick on touch) to walk. Take a few steps to get your bearings.',
- guide: "Welcome to the Mainland, traveler. First — get a feel for your feet. Walk around a little.",
- },
- {
- id: 'meet', kind: 'talk', count: 1,
- title: 'Meet Aldric',
- desc: 'Walk up to Aldric the Guide by the fountain and talk to him.',
- guide: "Good. I'm Aldric — I keep new arrivals from wandering into an ogre on day one. Let me show you the ropes.",
- },
- {
- id: 'chop', kind: 'gather', item: 'wood', count: 1, slot: 0,
- title: 'Chop a tree',
- desc: 'Equip your axe (hotbar slot 1), then click a tree to walk over and chop it for wood.',
- guide: 'See those trees to the west? Equip your axe — slot 1 — and click one. Bring back some wood.',
- },
- {
- id: 'mine', kind: 'gather', item: 'stone', count: 1, slot: 1,
- title: 'Mine some stone',
- desc: 'Switch to your pickaxe (hotbar slot 2) and click a rock to mine stone.',
- guide: 'Different tools for different jobs. Switch to your pickaxe — slot 2 — and chip at the rocks to the northeast.',
- },
- {
- id: 'fish', kind: 'fish', item: 'fish', count: 1, slot: 2,
- title: 'Cast a line',
- desc: 'Equip your fishing rod (hotbar slot 3) and stand beside the millpond to cast.',
- guide: "Next skill: fishing. Your rod's in slot 3. Walk to the millpond in the southeast and cast — click the water.",
- },
- {
- id: 'fight', kind: 'combat', count: 1, slot: 3,
- title: 'Train your blade',
- desc: 'Equip your sword (hotbar slot 4) and click a training dummy to defeat it.',
- guide: 'Steel next. Equip your sword — slot 4 — and put a training dummy out of its misery. Mind, real beasts hit back.',
- },
- {
- id: 'bank', kind: 'bank', count: 1,
- title: 'Stash your loot',
- desc: 'Stand on the glowing bank counter, open the bank, and deposit an item to keep it safe.',
- guide: 'Carry too much and a death will scatter it. Step onto the bank counter — the gold tiles — and stash something.',
- },
- {
- id: 'report', kind: 'talk', count: 1,
- title: 'Report back',
- desc: 'Return to Aldric to complete your training and claim your reward.',
- guide: "You've got the loop: gather, fight, bank. Come see me to wrap up — there's a reward in it for you.",
- },
-];
-
-// The line Aldric speaks once the tutorial is finished (replay-safe; he keeps
-// pointing the player at the daily board afterward).
-export const GUIDE_DONE = "Training complete. Check the daily board — fresh bounties every day, and they pay. Safe travels.";
-
-export const TUTORIAL_REWARD = { gold: 150, xp: { combat: 60, woodcutting: 60, mining: 60, fishing: 60 }, badge: 'newcomer' };
-
-// ---------------------------------------------------------------------------
-// Daily quests — the pool three are drawn from each day. Every entry is
-// completable on the Mainland realm alone (wood/stone/coal nodes + training
-// dummies), so a rolled set is never impossible to clear here.
-// ---------------------------------------------------------------------------
-export const DAILY_POOL = [
- { id: 'd_wood', type: 'gather', item: 'wood', count: 15, title: 'Lumberjack', desc: 'Chop 15 wood.', reward: { gold: 120, xp: { woodcutting: 160 }, badge: 'forager' } },
- { id: 'd_haul', type: 'gather', item: 'wood', count: 30, title: 'Big Haul', desc: 'Chop 30 wood.', reward: { gold: 260, xp: { woodcutting: 320 } } },
- { id: 'd_stone', type: 'gather', item: 'stone', count: 12, title: 'Stonemason', desc: 'Mine 12 stone.', reward: { gold: 140, xp: { mining: 170 }, badge: 'forager' } },
- { id: 'd_coal', type: 'gather', item: 'coal', count: 6, title: 'Coal Run', desc: 'Mine 6 coal.', reward: { gold: 180, xp: { mining: 200 }, item: { id: 'coal', qty: 3 } } },
- { id: 'd_combat', type: 'combat', count: 8, title: 'Monster Hunter', desc: 'Defeat 8 foes.', reward: { gold: 200, xp: { combat: 240 }, badge: 'warrior' } },
- { id: 'd_train', type: 'combat', count: 3, title: 'Sparring', desc: 'Defeat 3 training dummies.', reward: { gold: 80, xp: { combat: 90 } } },
- { id: 'd_fish', type: 'fish', item: 'fish', count: 5, title: 'Catch of the Day', desc: 'Catch 5 fish at the Pond.', reward: { gold: 130, xp: { fishing: 150 }, badge: 'fisher' } },
- { id: 'd_haul_fish', type: 'fish', item: 'fish', count: 10, title: 'Haul It In', desc: 'Catch 10 fish.', reward: { gold: 220, xp: { fishing: 260 } } },
- { id: 'd_cook', type: 'cook', item: 'cookedFish', count: 5, title: 'Camp Cook', desc: 'Cook 5 fish at the Roast Pit.', reward: { gold: 140, xp: { cooking: 180 }, badge: 'pitcook' } },
- { id: 'd_build', type: 'build', count: 1, title: 'Light a Fire', desc: 'Build a firepit anywhere it is allowed.', reward: { gold: 160, xp: { woodcutting: 80, mining: 80 }, badge: 'builder' } },
-];
-
-export const DAILY_COUNT = 3;
-
-// A stable 32-bit hash of a string (FNV-1a). Deterministic across processes.
-function hashString(s) {
- let h = 0x811c9dc5;
- for (let i = 0; i < s.length; i++) {
- h ^= s.charCodeAt(i);
- h = Math.imul(h, 0x01000193);
- }
- return h >>> 0;
-}
-
-// 'YYYY-MM-DD' in UTC for `now` (epoch ms). The daily boundary is UTC midnight.
-export function dailyKey(now) {
- return new Date(now).toISOString().slice(0, 10);
-}
-
-// Epoch ms of the next UTC midnight after `now` — the moment the current
-// dailies expire and a fresh set rolls. The client renders a live countdown to
-// this and re-requests its quests when it passes.
-export function nextResetAt(now) {
- const d = new Date(now);
- return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 1, 0, 0, 0, 0);
-}
-
-// Deterministically pick DAILY_COUNT distinct quests for (playerId, dateKey).
-// Seeded Fisher–Yates over the pool indices using a hash of playerId+date, so a
-// player's set is fixed for the day and identical on every reconnect/restart.
-export function rollDailies(playerId, dateKey) {
- const seed = hashString(`${playerId}|${dateKey}`);
- const idx = DAILY_POOL.map((_, i) => i);
- // xorshift32 PRNG seeded from the hash — pure, no global RNG.
- let state = seed || 1;
- const rand = () => {
- state ^= state << 13; state >>>= 0;
- state ^= state >> 17;
- state ^= state << 5; state >>>= 0;
- return state / 0xffffffff;
- };
- for (let i = idx.length - 1; i > 0; i--) {
- const j = Math.floor(rand() * (i + 1));
- [idx[i], idx[j]] = [idx[j], idx[i]];
- }
- return idx.slice(0, DAILY_COUNT).map((i) => ({ id: DAILY_POOL[i].id, progress: 0, claimed: false }));
-}
-
-export function dailyDef(id) {
- return DAILY_POOL.find((q) => q.id === id) || null;
-}
-
-// Fresh, never-started quest state for a brand-new account.
-export function freshQuestState(playerId, now) {
- const date = dailyKey(now);
- return {
- tutorial: { step: 0, progress: 0, done: false },
- daily: { date, quests: rollDailies(playerId, date) },
- badges: [],
- };
-}
-
-// Bring a (possibly persisted) quest-state blob up to date: re-roll the dailies
-// if the UTC day has turned over since it was saved, and backfill any missing
-// shape so older/partial saves load cleanly. Mutates and returns `qs`.
-export function normalizeQuestState(qs, playerId, now) {
- if (!qs || typeof qs !== 'object') return freshQuestState(playerId, now);
- if (!qs.tutorial || typeof qs.tutorial !== 'object') qs.tutorial = { step: 0, progress: 0, done: false };
- if (!Array.isArray(qs.badges)) qs.badges = [];
- const date = dailyKey(now);
- if (!qs.daily || qs.daily.date !== date || !Array.isArray(qs.daily.quests)) {
- qs.daily = { date, quests: rollDailies(playerId, date) };
- } else {
- // Drop any quest whose definition no longer exists (pool changed between
- // deploys) so the client never renders an orphan.
- qs.daily.quests = qs.daily.quests.filter((q) => dailyDef(q.id));
- if (!qs.daily.quests.length) qs.daily.quests = rollDailies(playerId, date);
- }
- return qs;
-}
-
-export function currentStep(qs) {
- if (qs.tutorial.done) return null;
- return TUTORIAL_STEPS[qs.tutorial.step] || null;
-}
diff --git a/multiplayer/src/rooms/GameRoom.js b/multiplayer/src/rooms/GameRoom.js
deleted file mode 100644
index 1341b8284..000000000
--- a/multiplayer/src/rooms/GameRoom.js
+++ /dev/null
@@ -1,3322 +0,0 @@
-// GameRoom — authoritative state for a Kintara isometric realm (Mainland).
-//
-// Same philosophy as WalkRoom: the server owns the truth. Clients send intent
-// ('step', 'gather', 'attack', 'invMove', 'equip', 'bankDeposit', ...) and the
-// server validates every one (walkability, adjacency, tool/skill gates, rate
-// limits) before mutating the shared state. A malicious client can desync its
-// own view but can't move through walls, gather depleted nodes, or mint gold.
-//
-// Movement is tile-stepped: the client paths locally and asks to step one tile
-// at a time. The server accepts a step only if the target is in-bounds, within
-// one tile (8-way) of the player's current tile, and walkable. That makes
-// teleport-cheating impossible without a separate max-step heuristic.
-
-import { Room, matchMaker } from '@colyseus/core';
-
-import { GameState, GamePlayer, ResourceNode, Mob, Slot, Tombstone, Structure } from '../schemas/game.js';
-import { REALMS, DEFAULT_REALM, isBlocked, inBounds, realmLayout, fishingSpotNear, portalAt, rollerAt, rollerDelta, inNoPvpZone, wheelLandmark } from './realms.js';
-import { signTransfer, verifyTransfer, consumeTransferNonce } from './realm-transfer.js';
-import { runCommand, commandManifest } from './commands.js';
-import { STACKABLE_ITEMS, isEdible, healValue, scaledHeal, isMount, mountStepMs, rollLoot, itemLabel, clientItemRegistry, cookBurnChance, fishCatchChance, fishDoubleChance } from '../items.js';
-import { cleanAvatarUrl } from '../avatar-url.js';
-import { loadPlayer, savePlayer, hydratePlayer, flushPlayer } from '../playerStore.js';
-import { cleanServer } from '../servers.js';
-import { evictChannel, payoutChannel, TAKEOVER_CLOSE_CODE } from '../presence-keys.js';
-import { socialHub } from '../social-hub.js';
-import { verifyPresenceTicket } from '../presence-token.js';
-import { verifyPlayPass } from '../play-pass.js';
-import { newGuestId, signGuestToken, verifyGuestToken } from '../guest-token.js';
-import { cosmeticById, evaluatePurchase, currentOffers, clientCatalog } from '../cosmetics.js';
-import { marketplaceStore } from '../marketplaceStore.js';
-import {
- TOKEN_SYMBOL, TOKEN_DECIMALS, tokenConfigured, isWalletAddress,
- quoteTokenForUsd, signQuote, verifyQuote, splitAmount, buildSplitTransaction, verifySplitPayment,
- buildSpinPayment, verifySpinPayment,
-} from '../game-token.js';
-import {
- rollSpin, spinSegments, reserveSpin, commitSpin, releaseSpin,
- FREE_SPIN_COOLDOWN_MS, SPIN_MIN_AVG_LEVEL, PAID_SPIN_USD,
-} from '../spin-wheel.js';
-import {
- TUTORIAL_STEPS, TUTORIAL_REWARD, GUIDE_DONE, BADGES, DAILY_POOL,
- dailyDef, nextResetAt, freshQuestState, normalizeQuestState, currentStep,
-} from '../quests.js';
-
-// One GameRoom instance == one realm. The realm is selected by the room
-// definition (`options.realm`, see index.js); every geometry / spawn / flag
-// lookup reads `this.realm`, so the same class serves Mainland, Wilderness,
-// Whisperwood, and Pond. A realm's `danger` flag is what gates death-bag drops
-// (Task 02): dying in a danger realm spills part of your pack into a tombstone.
-
-// Platform entry gate (wallet-first sign-in + game-token balance), mirrored from
-// WalkRoom. When a game token is pinned (PLAY_GATE_MINT, falling back to
-// THREE_MINT) every wallet-shaped join must carry a valid play pass proving the
-// signed-in wallet holds ≥ the floor. An unset mint leaves the gate off, but the
-// account-binding in onAuth still applies (a wallet pid always needs a pass; a
-// guest always needs a server-signed guest token) so the profile account can
-// never be claimed from an unsigned option. Read at boot — gate config is fixed
-// for the process lifetime.
-const PLAY_GATE_MINT = (process.env.PLAY_GATE_MINT || process.env.THREE_MINT || '').trim();
-const PLAY_GATE_MIN = (() => {
- const n = Number(process.env.PLAY_GATE_MIN);
- return Number.isFinite(n) && n > 0 ? n : 1;
-})();
-
-const MAX_CLIENTS_PER_ROOM = 50;
-const PATCH_RATE_MS = 1000 / 15;
-const SIM_TICK_MS = 250; // respawns, healing, death timers
-
-const INV_SIZE = 24;
-const HOTBAR_SIZE = 6;
-const MAX_STACK = 999;
-const BANK_SIZE = 48;
-
-// Marketplace (Task 20). Bounds keep a single listing's numbers sane and stop a
-// player from flooding the board. The treasury cut applies ONLY to token sales
-// (gold sales are fee-free) — 500 bps = 5%, leaving 95% to the seller's wallet.
-const MAX_LISTINGS_PER_SELLER = 20;
-const MARKET_GOLD_MAX = 0xffffffff;
-const MARKET_USD_MIN = 0.01;
-const MARKET_USD_MAX = 100_000;
-const MARKET_TREASURY_BPS = 500;
-
-// Which items stack is owned by the item registry (items.js) so cooking, loot,
-// banking, and the shop all agree. cookedFish + potions land here automatically.
-const STACKABLE = STACKABLE_ITEMS;
-const TOOLS = new Set(['axe', 'pickaxe', 'rod', 'hammer', 'sword']);
-
-// The five trainable skills, broadcast as integer levels on GamePlayer. The
-// order here is the canonical display order the client renders. LEVEL_CAP is the
-// shared ceiling — surfaced to the client so the UI never hard-codes it.
-const SKILLS = ['combat', 'woodcutting', 'mining', 'fishing', 'cooking'];
-const LEVEL_CAP = 99;
-
-// Per-action rate limits (messages/sec) — generous vs. legit play, tight vs.
-// floods. Movement is the hot path so it gets the most headroom. Chat sits low:
-// a few lines a second is plenty for conversation and turns a scripted flood into
-// dropped messages (with feedback — see _handleChat).
-const RATE_LIMITS = { step: 20, gather: 6, attack: 6, fish: 6, cook: 6, consume: 6, ui: 30, chat: 4, mkt: 4, spin: 2 };
-
-// World chat: hard cap on a single message. Longer messages are rejected (not
-// silently truncated) so the sender knows their line didn't go through whole.
-const MAX_CHAT_LEN = 200;
-
-// Gathering: which tool + skill each node kind needs, and what it yields.
-const NODE_RULES = {
- tree: { tool: 'axe', skill: 'woodcutting', item: 'wood', respawnMs: 15000 },
- rock: { tool: 'pickaxe', skill: 'mining', item: 'stone', respawnMs: 18000 },
- coal: { tool: 'pickaxe', skill: 'mining', item: 'coal', respawnMs: 22000 },
-};
-
-const GATHER_COOLDOWN_MS = 900; // time between successful harvests
-const ATTACK_COOLDOWN_MS = 700;
-const COOK_COOLDOWN_MS = 1200; // pace between cook actions
-const COOK_BATCH_MAX = 5; // raw fish processed per cook action (one cooldown)
-const COOK_XP = 12; // cooking XP per fish successfully cooked (burns yield none)
-const CONSUME_COOLDOWN_MS = 1100; // pace between bites — no instant heal-spam
-const FISH_COOLDOWN_MS = 1500; // per-cast reel time — sets casting cadence on the real clock
-// The catch + double-haul curves live in items.js (fishCatchChance/fishDoubleChance)
-// as pure functions, so the odds are unit-tested and shared, not inlined here.
-const RESPAWN_PLAYER_MS = 4000;
-const RESPAWN_MOB_MS = 8000;
-
-// Movement speed is server-authoritative (Task 09). On foot, a player may take a
-// step no more often than every ON_FOOT_STEP_MS; mounts lower this floor via the
-// item registry (items.js `mount.stepMs`), so riding is visibly faster without
-// ever trusting a client-claimed speed.
-const ON_FOOT_STEP_MS = 140;
-
-// Death-bags (danger realms only). A tombstone lives for TOMBSTONE_TTL_MS, then
-// crumbles server-side (and the client view follows). For the first
-// TTL - GRACE window only the owner may loot it; once inside the final
-// TOMBSTONE_GRACE_MS before expiry, anyone standing adjacent may take what's
-// left — a fair "claim it fast or share it" rule.
-const TOMBSTONE_TTL_MS = 120000; // 2 minutes
-const TOMBSTONE_GRACE_MS = 45000; // last 45s: open to anyone adjacent
-const FOUNTAIN_HEAL_PER_TICK = 6; // hp restored per sim tick near the fountain
-const REGEN_PER_TICK = 1; // passive hp regen out of combat
-
-// Mob AI (Task 03): roam, aggro, chase, contact damage. Scans run on the sim
-// tick (SIM_TICK_MS), never the patch rate, so the per-mob player scan stays
-// cheap. Roamers wander near home; `aggro` mobs notice, chase, and hit nearby
-// players, feeding the death/tombstone system. Dummies (roam/aggro both false)
-// stay inert.
-const MOB_AGGRO_RADIUS = 6; // tiles (Chebyshev) within which a hostile mob notices a player
-const MOB_LEASH_RADIUS = 11; // tiles from its home tile a mob will chase before giving up
-const MOB_ROAM_RADIUS = 4; // tiles from home a roamer will wander when idle
-const MOB_MOVE_MS = 600; // minimum wall-clock between a mob's steps (roam + chase)
-const MOB_ROAM_CHANCE = 0.4; // probability an idle roamer takes a step on an eligible tick
-const MOB_ATTACK_COOLDOWN_MS = 1000; // minimum wall-clock between a mob's contact hits
-const MOB_REGEN_PER_TICK = 1; // hp a disengaged, hurt mob recovers per sim tick
-const MOB_BASE_DAMAGE = { goblin: 5, ogre: 9, dummy: 0 }; // contact-damage floor by kind (+0..3 variance)
-
-// Arena rollers (Task 22): how often a moving-floor strip shoves a standing
-// player one tile. Slower than the sim tick so the push reads as a deliberate
-// nudge to learn, not a blur — ~two pushes a second.
-const ROLLER_PUSH_MS = 500;
-
-// Player-built structures (Task 07). `cost` is the EXACT material bill, deducted
-// atomically on placement (no partial spend, no negative balance). `lifetimeMs`
-// 0 == permanent (the shack, a landmark) — a firepit burns out after its window,
-// healing adjacent players like the fountain until it decays. `cap` is how many
-// of that kind one player may own at once; the shack's cap of 1 is enforced
-// within the realm — and since the shack is Whisperwood-only (realms.js), the
-// single Whisperwood room IS the cross-realm scope, so "one per player across
-// realms" holds. `heal` is the per-tick HP a firepit restores to anyone beside it.
-const STRUCTURE_DEFS = {
- firepit: { cost: { stone: 20, coal: 20, wood: 50 }, lifetimeMs: 30000, cap: Infinity, heal: FOUNTAIN_HEAL_PER_TICK },
- shack: { cost: { wood: 500, stone: 200 }, lifetimeMs: 0, cap: 1, heal: 0 },
-};
-
-// XP curve: cumulative XP required for a level. Early levels fly by, later
-// ones grind — matches the guide ("early levels come quickly").
-function levelForXp(xp) {
- // level n requires 50 * n^1.8 cumulative XP. Cap at 99.
- let lvl = 1;
- while (lvl < LEVEL_CAP && xp >= Math.floor(50 * Math.pow(lvl, 1.8))) lvl++;
- return lvl;
-}
-
-// Inverse of levelForXp: the cumulative XP required to *be* at a given level.
-// Level 1 starts at 0; reaching level L needs 50 * (L-1)^1.8 cumulative XP — the
-// same threshold levelForXp compares against. Used to send the client the
-// boundaries of its current level so it can draw an exact progress bar without
-// re-deriving the curve (one source of truth for the formula).
-function xpForLevel(level) {
- const lvl = Math.max(1, Math.min(LEVEL_CAP, level | 0));
- return lvl <= 1 ? 0 : Math.floor(50 * Math.pow(lvl - 1, 1.8));
-}
-
-function clean(str, maxLen) {
- if (typeof str !== 'string') return '';
- // Strip control chars (incl. NUL/escape), collapse whitespace, trim, cap.
- return str.replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, maxLen);
-}
-
-function pickPlayerColor(sessionId) {
- let h = 0;
- for (let i = 0; i < sessionId.length; i++) h = (h * 31 + sessionId.charCodeAt(i)) >>> 0;
- return hslToHex((h % 360) / 360, 0.65, 0.6);
-}
-function hslToHex(h, s, l) {
- const k = (n) => (n + h * 12) % 12;
- const a = s * Math.min(l, 1 - l);
- const f = (n) => Math.round((l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1))) * 255);
- return (f(0) << 16) | (f(8) << 8) | f(4);
-}
-
-export class GameRoom extends Room {
- // Account ownership is proven here, before onJoin, exactly as WalkRoom verifies
- // its play pass. The game profile account key (playerId) — which loads gold,
- // bank, inventory, cosmetics and drives the single-session eviction channel —
- // MUST come only from this verified binding, never from a raw `options.pid`. An
- // unsigned pid set to a victim's wallet/guest id would otherwise hijack their
- // whole saved profile and grief them off their eviction channel.
- //
- // Two proof shapes:
- // • Wallet account — proven by a play pass (ed25519-over-nonce minted by
- // /api/play/verify, sealed with the shared secret). The wallet rides inside
- // the signed pass; we bind it as the account. A wallet-shaped pid presented
- // WITHOUT a matching pass is rejected — never trusted on assertion alone.
- // • Guest account — no wallet to sign, so the server mints the identity: a
- // random guest id in an HMAC-signed token. The client replays the token on
- // reconnect; we verify it and bind the sealed id. A guest with no (or an
- // invalid) token is issued a brand-new id + token here, so a guest id can
- // only ever be used by the socket that holds its signed token.
- // The bound account + (for new guests) the fresh token are stashed on
- // client.userData/auth so onJoin derives playerId from the verified value and
- // hands any new guest token back to the client to persist.
- static onAuth(client, options) {
- // Portal handoff (trusted server-to-server seat reservation). The source room
- // already verified this account and minted a single-use, HMAC-signed transfer
- // carrying it; the reservation can't ride a play pass / guest token, so the
- // account is re-bound from the signed transfer here. Consume the nonce NOW (the
- // earliest trusted point) so a captured transfer can't be replayed to bind a
- // victim's account or restore a carry — and stash the verified result so onJoin
- // applies the carry without re-consuming.
- const transfer = options?.transfer ? verifyTransfer(options.transfer) : null;
- if (transfer && consumeTransferNonce(transfer.jti)) {
- client.userData = {
- ...(client.userData || {}),
- account: transfer.account,
- accountKind: isWalletAddress(transfer.account) ? 'wallet' : 'guest',
- transfer,
- };
- return true;
- }
-
- const pass = verifyPlayPass(options?.playPass);
- if (pass) {
- // A valid play pass: bind its verified wallet as the account. When the gate
- // is pinned, also enforce the mint + balance floor so an off-floor wallet
- // can't ride a pass minted for a different token. Throw (not return false)
- // so a refusal reaches the client as a `play_pass`-prefixed error.
- if (PLAY_GATE_MINT) {
- if (pass.mint !== PLAY_GATE_MINT) throw new Error('play_pass_mismatch');
- if (!(typeof pass.balance === 'number' && pass.balance >= PLAY_GATE_MIN)) {
- throw new Error('play_pass_required');
- }
- }
- client.userData = {
- ...(client.userData || {}),
- account: pass.wallet,
- accountKind: 'wallet',
- playBalance: pass.balance,
- playExp: pass.exp,
- };
- return true;
- }
-
- // No play pass. The platform gate, when pinned, requires one for entry.
- if (PLAY_GATE_MINT) throw new Error('play_pass_required');
-
- // A wallet-shaped pid with no proving pass is a takeover attempt — reject it
- // outright rather than load that wallet's profile on a bare assertion.
- if (isWalletAddress(clean(options?.pid, 80))) throw new Error('play_pass_required');
-
- // Guest path: trust only a server-signed guest token. A valid one re-binds the
- // returning guest's id; anything else (missing/forged/expired) gets a brand-new
- // server-minted id so a guest id can never be claimed by another socket.
- let gid = verifyGuestToken(options?.guestToken);
- let issuedToken = null;
- if (!gid) {
- gid = newGuestId();
- issuedToken = signGuestToken(gid);
- }
- client.userData = {
- ...(client.userData || {}),
- account: gid,
- accountKind: 'guest',
- ...(issuedToken ? { newGuestToken: issuedToken } : {}),
- };
- return true;
- }
-
- constructor() {
- super();
- this.maxClients = MAX_CLIENTS_PER_ROOM;
- // Off-schema, server-only per-player data: XP totals, private bank, and
- // per-action cooldown/rate windows. None of this needs to sync to peers.
- this.priv = new Map(); // sessionId -> { xp, bank: Slot[], cooldowns, rate }
- // Per-session subscription to the account's eviction channel (Task 23
- // single-active-session). sessionId -> { channel, handler }.
- this._evictSubs = new Map();
- // Per-session subscription to the account's marketplace payout channel (Task
- // 20), so a sale settled elsewhere can deliver gold proceeds to this seat.
- // sessionId -> { channel, handler }.
- this._payoutSubs = new Map();
- // Sim-tick counter that paces periodic profile autosaves.
- this._saveTick = 0;
- }
-
- async onCreate(options) {
- // The room definition pins which realm this instance hosts. An unknown or
- // missing name falls back to the default realm so the room never boots into
- // an undefined map.
- const name = REALMS[options?.realm] ? options.realm : DEFAULT_REALM;
- this.realm = REALMS[name];
- // Which world instance this room belongs to (Task 23). filterBy(['server'])
- // in index.js guarantees every client matched here passed the same server
- // option, but we still resolve it defensively so a forged/missing value can
- // never create a room for a non-existent instance.
- this.server = cleanServer(options?.server);
- // Monotonic id sources for tombstones and player-built structures (Task 07)
- // spawned by this room.
- this._tombSeq = 0;
- this._structSeq = 0;
-
- this.setState(new GameState());
- this.state.realm = this.realm.name;
- this.state.server = this.server;
- // Publish (realm, server) onto the room listing so the /servers endpoint can
- // sum live population per instance through the matchmaker — across every
- // horizontally-scaled process, not just this one.
- await this.setMetadata({ realm: this.realm.name, server: this.server });
- this.setPatchRate(PATCH_RATE_MS);
- this.autoDispose = true;
-
- this._seedWorld();
-
- this.onMessage('step', (c, p) => this._handleStep(c, p));
- this.onMessage('gather', (c, p) => this._handleGather(c, p));
- this.onMessage('attack', (c, p) => this._handleAttack(c, p));
- this.onMessage('fish', (c, p) => this._handleFish(c, p));
- this.onMessage('cook', (c, p) => this._handleCook(c, p));
- this.onMessage('consume', (c, p) => this._handleConsume(c, p));
- this.onMessage('invMove', (c, p) => this._handleInvMove(c, p));
- this.onMessage('equip', (c, p) => this._handleEquip(c, p));
- this.onMessage('bankDeposit', (c, p) => this._handleBank(c, p, 'deposit'));
- this.onMessage('bankWithdraw', (c, p) => this._handleBank(c, p, 'withdraw'));
- this.onMessage('bankOpen', (c) => this._sendBank(c));
- this.onMessage('skills', (c) => this._sendSkills(c));
- this.onMessage('tombLoot', (c, p) => this._handleTombLoot(c, p));
- this.onMessage('setAvatar', (c, p) => this._handleAvatar(c, p));
- // Friends presence (Task 15): the client (re)asserts its presence ticket on
- // this channel — used after a portal handoff, where the new room's seat
- // reservation carries no join options, so the ticket can't ride onJoin.
- // Idempotent with the onJoin registration; the verified account id is the
- // trust anchor, never a raw client field.
- this.onMessage('presence', (c, ticket) => {
- const uid = verifyPresenceTicket(ticket);
- if (!uid) return;
- c.userData = { ...(c.userData || {}), accountUid: uid };
- socialHub.register(uid, c, this.realm.name, this.server);
- });
- // Cosmetics shop (Task 21): request the live shop board, buy a cosmetic from
- // the current rotation, and equip/unequip an owned (purchased) cosmetic. All
- // gold + ownership + rotation checks are server-authoritative below.
- this.onMessage('shopOpen', (c) => this._sendShop(c));
- this.onMessage('buyCosmetic', (c, p) => this._handleBuyCosmetic(c, p));
- this.onMessage('equipCosmetic', (c, p) => this._handleEquipCosmetic(c, p));
- this.onMessage('unequipCosmetic', (c) => this._handleUnequipCosmetic(c));
- // Mounts (Task 09): use the active hotbar item (ride a mount), leave the saddle,
- // and a generic slash-command channel (Task 13's chat forwards /dismount here).
- this.onMessage('use', (c, p) => this._handleUse(c, p));
- this.onMessage('dismount', (c) => this._handleDismount(c));
- // Building (Task 07): place a firepit/shack on an adjacent tile, paying its
- // exact material cost. Pickup/lock/unlock are slash-commands routed through
- // the command channel below (their actions live on this room).
- this.onMessage('build', (c, p) => this._handleBuild(c, p));
- // Player-to-player marketplace (Task 20): browse active listings, list your
- // own goods (item-for-gold or gold-for-token), cancel a listing (returns the
- // escrow), buy a gold listing with in-game gold, and the two-step on-chain
- // flow for token listings (quote → settle). Escrow, gold transfers, and the
- // 95/5 token split are all server-authoritative below. Distinct from the
- // platform AGENT marketplace under api/marketplace*.
- this.onMessage('mktOpen', (c) => this._sendMarket(c));
- this.onMessage('mktList', (c, p) => this._handleMarketList(c, p));
- this.onMessage('mktCancel', (c, p) => this._handleMarketCancel(c, p));
- this.onMessage('mktBuyGold', (c, p) => this._handleMarketBuyGold(c, p));
- this.onMessage('mktTokenQuote', (c, p) => this._handleMarketTokenQuote(c, p));
- this.onMessage('mktTokenSettle', (c, p) => this._handleMarketTokenSettle(c, p));
-
- // Wheel of Fortune (Task 19): info/eligibility + free spin (12h cooldown),
- // and the two-step paid spin ($3 in $THREE, 50% burned / 50% to treasury)
- // that settles on-chain before the prize is rolled. The roll is always
- // server-authoritative — the client only animates to the chosen segment.
- this.onMessage('spinInfo', (c) => this._sendSpinInfo(c));
- this.onMessage('spinFree', (c) => this._handleSpinFree(c));
- this.onMessage('spinPaidPrep', (c, p) => this._handleSpinPaidPrep(c, p));
- this.onMessage('spinPaidSettle', (c, p) => this._handleSpinPaidSettle(c, p));
- this.onMessage('command', (c, p) => this._handleCommand(c, p));
- // Quests (tutorial + dailies). The client only ever requests a snapshot,
- // talks to the guide, or asks to turn a finished quest in — all progress is
- // driven from the real action hooks below, never from a client claim.
- this.onMessage('questOpen', (c) => this._sendQuests(c));
- this.onMessage('npcTalk', (c, p) => this._handleNpcTalk(c, p));
- this.onMessage('questTurnIn', (c, p) => this._handleTurnIn(c, p));
- this.onMessage('chat', (c, p) => this._handleChat(c, p));
-
- // Re-check the token gate the same way WalkRoom does: the game server has no
- // RPC, so "still holding the floor" is re-proven by the client minting a fresh
- // play pass before the current one's TTL lapses and reconnecting (onAuth
- // re-validates). To actively evict a wallet that fell below the floor
- // mid-session, sweep once a minute and drop any client whose bound pass has
- // expired without a refresh. Only runs when the gate is pinned.
- if (PLAY_GATE_MINT) {
- this.clock.setInterval(() => {
- const nowS = Date.now() / 1000;
- for (const client of this.clients) {
- const exp = client.userData?.playExp;
- if (typeof exp === 'number' && exp < nowS) {
- try { client.leave(4002, 'play_pass_required'); } catch {}
- }
- }
- }, 60_000);
- }
-
- this.setSimulationInterval(() => this._tick(), SIM_TICK_MS);
- }
-
- _seedWorld() {
- for (const n of this.realm.nodes) {
- const node = new ResourceNode();
- node.id = n.id;
- node.kind = n.kind;
- node.tx = n.tx;
- node.ty = n.ty;
- this.state.nodes.set(n.id, node);
- }
- // Per-mob behaviour + leash anchor, kept off-schema: clients only need the
- // position/hp/aggro that the Mob schema already syncs.
- this._mobAI = new Map();
- for (const m of this.realm.mobs) {
- const mob = new Mob();
- mob.id = m.id;
- mob.kind = m.kind;
- mob.tx = m.tx;
- mob.ty = m.ty;
- mob.hp = mob.maxHp = m.hp;
- this.state.mobs.set(m.id, mob);
- this._mobAI.set(m.id, {
- roam: !!m.roam,
- aggro: !!m.aggro,
- homeTx: m.tx,
- homeTy: m.ty,
- nextMoveAt: 0,
- attackReadyAt: 0,
- });
- }
- }
-
- async onJoin(client, options) {
- const name = clean(options?.name, 24) || `guest-${client.sessionId.slice(0, 4)}`;
- // Stable account key: the VERIFIED account bound in onAuth — a play-pass wallet
- // or a server-signed guest id — never a raw `options.pid`. Tutorial completion,
- // daily assignment, progress, badges, the bank, and the single-session eviction
- // channel all key off it, so trusting it only when proven is what stops another
- // client from loading or evicting a victim's profile. onAuth always populates
- // account; the session id is a last-resort fallback that can never collide.
- const playerId = clean(client.userData?.account, 80) || client.sessionId;
- // Hand a freshly-minted guest token back to the client so it can persist it and
- // re-present it on reconnect to keep this guest's progression. Sent before any
- // other state so the client stores it even if it disconnects early.
- if (client.userData?.newGuestToken) {
- try { client.send('guestToken', { token: client.userData.newGuestToken, account: playerId }); } catch {}
- }
- const now = Date.now();
- // Single active session per account (Task 16 integrity rule, enforced across
- // world instances for Task 23): announce this login on the account's eviction
- // channel BEFORE loading the profile. Any live session of the same account —
- // in any realm, on any server, in any process — persists itself and
- // disconnects in response, so two windows can never both mutate and clobber
- // the one shared profile. In single-instance mode the stale session persists
- // synchronously here, so the load below already sees its latest state.
- this.presence.publish(evictChannel(playerId), { exceptSession: client.sessionId, ts: now });
- // Pull the durable profile into the in-process cache before the synchronous
- // load below (Task 16). A cache hit (a session already live in this process,
- // or a record left warm from a recent visit) returns instantly; a miss — the
- // first join after a restart/redeploy, or a player whose last session was on
- // another instance (Task 23) — fetches it from Redis. Without this, a returning
- // player on a fresh process would look brand-new and be reset to the starter kit.
- await hydratePlayer(playerId);
- const saved = loadPlayer(playerId);
- const quests = normalizeQuestState(saved?.quests, playerId, now) || freshQuestState(playerId, now);
-
- const p = new GamePlayer();
- p.id = client.sessionId;
- p.name = name;
- p.color = pickPlayerColor(client.sessionId);
- p.tx = this.realm.spawn.tx;
- p.ty = this.realm.spawn.ty;
-
- // Fixed-length inventory + hotbar so slot indices are stable drag targets.
- for (let i = 0; i < INV_SIZE; i++) p.inv.push(new Slot());
- for (let i = 0; i < HOTBAR_SIZE; i++) p.hotbar.push(new Slot());
-
- // Starter kit — the four gathering tools + a basic sword, mirroring the
- // guide's tutorial hand-out so a fresh player can exercise the full loop
- // immediately. Tools go straight onto the hotbar.
- const kit = ['axe', 'pickaxe', 'rod', 'sword'];
- for (let i = 0; i < kit.length; i++) {
- p.hotbar[i].item = kit[i];
- p.hotbar[i].qty = 1;
- }
- p.activeSlot = 0;
- // The avatar the player picked on /play (or a create→play handoff) rides in
- // as a join option. Fall back to the persisted avatar URL so a returning
- // player on a new device (or any session that didn't pass options.avatar)
- // is still rendered as their chosen look, not the default capsule.
- p.cosmetic = cleanAvatarUrl(options?.avatar) || cleanAvatarUrl(saved?.profile?.cosmetic) || '';
- p.badges = (quests.badges || []).join(',');
- // Restore the persisted purse + owned/equipped cosmetics (Task 16/21), keyed
- // to the stable account id so a purchase and the look the player chose survive
- // a disconnect/realm transfer. Owned ids are filtered to ones still in the
- // catalogue so a removed cosmetic never lingers; the equipped id must be owned.
- const cos = this._loadCosmetics(saved);
- p.gold = Number.isFinite(saved?.gold) ? Math.min(0xffffffff, Math.max(0, saved.gold | 0)) : 0;
- p.cosmeticId = cos.equipped;
- p.tsServer = now;
- this.state.players.set(client.sessionId, p);
-
- this.priv.set(client.sessionId, {
- playerId,
- // One XP bucket per trainable skill. Levels are broadcast on the schema;
- // raw XP stays server-side and is only ever sent to its owner.
- xp: Object.fromEntries(SKILLS.map((s) => [s, 0])),
- bank: Array.from({ length: BANK_SIZE }, () => ({ item: '', qty: 0 })),
- cooldowns: { gather: 0, attack: 0, fish: 0, cook: 0, consume: 0, step: 0 },
- rate: new Map(),
- quests,
- // Owned shop cosmetics (a Set of catalogue ids) + the equipped id. The
- // equipped id is mirrored onto the synced schema (p.cosmeticId); ownership
- // stays server-side and is only ever sent to its owner via the shop board.
- cosmetics: { owned: cos.owned, equipped: cos.equipped },
- // Wheel of Fortune (Task 19): when this account may next take its free spin.
- // Persisted per account so the 12h cooldown survives a disconnect/realm hop
- // and can't be reset by reconnecting. Paid spins never touch this timer.
- spin: { nextFreeSpinAt: Number.isFinite(saved?.spin?.nextFreeSpinAt) ? saved.spin.nextFreeSpinAt : 0 },
- });
-
- // Arriving through a portal: a signed transfer restores the haul the player
- // carried out of the previous realm and lands them at the portal's exit tile
- // instead of the realm's default spawn. The transfer was verified AND its
- // single-use nonce consumed in onAuth (which also bound the account from it),
- // so we read the already-validated result off client.userData here — a replayed
- // transfer never reaches this point with a fresh nonce, so it can't re-apply a
- // carry and dupe gold/items the player has since banked or spent.
- const transfer = client.userData?.transfer || null;
- if (transfer && transfer.to === this.realm.name) {
- if (transfer.carry) this._applyCarry(p, this.priv.get(client.sessionId), transfer.carry);
- const dtx = transfer.tx | 0, dty = transfer.ty | 0;
- if (inBounds(this.realm, dtx, dty) && !isBlocked(this.realm, dtx, dty)) {
- p.tx = dtx;
- p.ty = dty;
- }
- } else if (saved?.profile) {
- // No in-session carry token — this is a fresh login (first connect, a
- // reconnect, or a switch to another world instance). Restore the
- // account-scoped profile so items, hotbar, bank, skills, and mount are
- // identical regardless of which server the player chose (Task 23). The
- // profile is realm-agnostic; position stays this realm's spawn. Uses the
- // same defensively-bounded applier as portal carries, so a corrupt saved
- // blob can't inject out-of-range items or skill levels.
- this._applyCarry(p, this.priv.get(client.sessionId), saved.profile);
-
- // Resume at the tile the player was standing on when they left — so a
- // player picking up where they left off doesn't wake at the spawn fountain
- // every time. Position is only restored when it's the SAME realm (the
- // client may connect to any realm on re-login); danger realms always spawn
- // at the safe spawn so a disconnecting player isn't born inside a mob.
- if (!this.realm.danger &&
- saved.lastRealm === this.realm.name &&
- Number.isFinite(saved.lastTx) && Number.isFinite(saved.lastTy)) {
- const ltx = saved.lastTx | 0, lty = saved.lastTy | 0;
- if (inBounds(this.realm, ltx, lty) && !isBlocked(this.realm, ltx, lty)) {
- p.tx = ltx;
- p.ty = lty;
- }
- }
-
- // Restore placed structures (Task 07) the player left in this realm.
- // If the room is already live (reconnect), the structures may still be
- // present under the old session id — we hand them off. If the room was
- // freshly created (after room dispose or restart), we re-seed them.
- const savedStructures = saved.structures?.[this.realm.name] || [];
- if (savedStructures.length) this._restoreStructures(client, p, playerId, name, savedStructures);
- }
-
- // Register this session as the account's live presence + subscribe to its
- // eviction channel so a later login elsewhere can take this seat over. The
- // presence row records which server+realm the account is on, which a friends
- // panel (Task 15) reads via GET /presence to show "online on Server 2 ·
- // Mainland". Cleared/transferred on leave (see onLeave).
- const channel = evictChannel(playerId);
- const handler = (msg) => this._onEvict(playerId, msg);
- await this.presence.subscribe(channel, handler);
- this._evictSubs.set(client.sessionId, { channel, handler });
- // Marketplace payout channel (Task 20): a sale settled in another realm/room
- // nudges this seat to drain its durable payout queue, so gold proceeds land
- // live instead of waiting for the next login. Subscribed per-session and torn
- // down on leave alongside the eviction subscription.
- const payChan = payoutChannel(playerId);
- const payHandler = (msg) => {
- this._drainMarketPayouts(client.sessionId);
- // A cross-room sale notice piggybacks on the payout nudge (token sales pay
- // the seller on-chain so there's no payout to drain, but they still deserve
- // a toast). Send it directly if the message carries one.
- if (msg?.notice) {
- const c = this._clientFor(client.sessionId);
- if (c) try { c.send('notice', { kind: 'market', text: msg.notice }); } catch {}
- }
- };
- await this.presence.subscribe(payChan, payHandler);
- this._payoutSubs.set(client.sessionId, { channel: payChan, handler: payHandler });
- // Account-level friends presence (Task 15 + 23). The friends graph keys off
- // the three.ws account id (users.id), carried in verified, spoof-proof form by
- // a presence ticket — never a raw client field. The social hub publishes the
- // account's online status plus which world instance + realm it's on (TTL'd in
- // Redis, refreshed on a heartbeat) so the friends API can show "online ·
- // Server 2 · Mainland" and DM this player live. This is the single presence
- // path — there is no parallel by-playerId registry to scrape or leave stale.
- const accountUid = verifyPresenceTicket(options?.presence);
- if (accountUid) {
- client.userData = { ...(client.userData || {}), accountUid };
- socialHub.register(accountUid, client, this.realm.name, this.server);
- }
-
- // Claim any proceeds owed while this account was offline (gold from sales of
- // its listings). Drains the durable queue and credits the live player.
- this._drainMarketPayouts(client.sessionId);
-
- // Hand the client the full static realm layout (geometry, fountain, bank
- // counter, fishing/cooking tiles, safe camp, portals, and the
- // safe/pvp/danger flags) so it renders exactly the tiles the server treats
- // as solid/interactive — and knows whether this realm drops death-bags.
- // Dynamic objects (nodes, mobs, players, tombstones) arrive via synced
- // schema state instead. The build catalogue (which structures this realm
- // permits, with their authoritative costs) rides along so the client's build
- // menu + affordability never drift from the server (Task 07).
- const layout = realmLayout(this.realm);
- layout.buildCatalog = this._buildCatalog();
- client.send('realm', layout);
- // Item catalogue (icons, labels, mount tuning) so the hotbar can label items and
- // the scene can render the right steed. Static — sent once per join.
- client.send('items', clientItemRegistry());
- // Cosmetics catalogue (Task 21): id → name, rarity, price, rotation, and the
- // visual spec. Static, sent once per join so the client can render any peer's
- // equipped cosmetic immediately; the live shop board (offers + countdowns +
- // owned + gold) is fetched on demand via 'shopOpen'.
- client.send('cosmetics', clientCatalog());
- // Slash-command manifest (Task 13) so the chat input can autocomplete and
- // describe commands as the player types '/'. Generated from the same
- // registry that powers /help and the router, so the hint never drifts.
- client.send('commands', commandManifest());
- // Hand over the player's quest state (tutorial step, today's dailies +
- // progress, reset countdown, earned badges) so the quest panel and the
- // guide's "!"/"?" marker render immediately on entry.
- this._sendQuests(client);
-
- console.log(`[${this.realm.name} ${this.roomId}] +join ${name} (n=${this.state.players.size})`);
- }
-
- async onLeave(client) {
- const sid = client.sessionId;
- const priv = this.priv.get(sid);
- // A portal handoff reserved a seat in the destination room and sent the client
- // the token. If the client disconnects before consuming it, clear the flag so
- // the slot can't be stuck. (The destination seat expires on its own TTL.)
- if (priv) priv.transferring = false;
- // An evicted session already persisted itself synchronously inside _onEvict;
- // persisting again here would write a now-stale snapshot over whatever the
- // new session has since done, so skip it. A normal leave persists as usual.
- if (!priv?._evicted) {
- this._persistPlayer(sid);
- // Force the final state to durable storage now rather than waiting on the
- // debounce timer (Task 16): a clean disconnect must not lose the last few
- // seconds if the process is torn down before the timer fires. No-op when
- // Redis isn't configured. The evicted path is skipped — its successor
- // session owns the record now and flushes on its own.
- if (priv?.playerId) await flushPlayer(priv.playerId);
- }
-
- // Drop the account's eviction subscription and clear its presence row — but
- // only if the row is still OURS. A takeover overwrites the row with the new
- // session's id on its own join, and that newer session must not be erased by
- // the old one's delayed disconnect.
- const sub = this._evictSubs.get(sid);
- if (sub) {
- try { this.presence.unsubscribe(sub.channel, sub.handler); } catch {}
- this._evictSubs.delete(sid);
- }
- const paySub = this._payoutSubs.get(sid);
- if (paySub) {
- try { this.presence.unsubscribe(paySub.channel, paySub.handler); } catch {}
- this._payoutSubs.delete(sid);
- }
-
- // Clear account-level friends presence when this account's last socket here
- // leaves; the social hub keeps it online if another tab/realm is still open.
- if (client.userData?.accountUid) socialHub.unregister(client.userData.accountUid, client);
-
- this.state.players.delete(sid);
- this.priv.delete(sid);
- }
-
- // React to another login of the same account (published on its eviction channel
- // from onJoin). Enforces one active session per account across all realms and
- // world instances: persist the stale local session NOW (so the new session loads
- // the latest profile) and disconnect it with the takeover code, after telling it
- // why so the client shows a "signed in elsewhere" screen instead of reconnecting.
- _onEvict(playerId, msg) {
- const except = msg?.exceptSession || '';
- for (const [sid, priv] of this.priv) {
- if (priv.playerId !== playerId || sid === except || priv._evicted) continue;
- this._persistPlayer(sid);
- priv._evicted = true; // suppress the duplicate persist in onLeave
- const c = this._clientFor(sid);
- if (c) {
- try { c.send('takeover', { reason: 'signed-in-elsewhere' }); } catch {}
- try { c.leave(TAKEOVER_CLOSE_CODE); } catch {}
- }
- }
- }
-
- async onDispose() {
- // Belt-and-suspenders (Task 16): a normal dispose follows every client's
- // onLeave (which already persisted + flushed), but a forced teardown can skip
- // those — so persist and flush any session still resident before the room is
- // gone. Mirrors WalkRoom awaiting blockStore.flush on dispose.
- const ids = new Set();
- for (const [sid, priv] of this.priv) {
- if (priv?._evicted || !priv?.playerId) continue;
- this._persistPlayer(sid);
- ids.add(priv.playerId);
- }
- await Promise.allSettled([...ids].map((pid) => flushPlayer(pid)));
- console.log(`[${this.realm.name} ${this.roomId}] disposed`);
- }
-
- // ----- movement --------------------------------------------------------
-
- _handleStep(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p || p.dead) return;
- // A portal handshake is in flight — the client is about to leave for the
- // destination realm. Freeze further movement so a queued step can't trigger
- // a second transfer (or move the soon-to-be-snapshotted player off the tile).
- if (this.priv.get(client.sessionId)?.transferring) return;
- if (!this._rateOk(client.sessionId, 'step')) return;
- if (!payload || typeof payload !== 'object') return;
-
- const tx = payload.tx | 0;
- const ty = payload.ty | 0;
- if (!Number.isFinite(payload.tx) || !Number.isFinite(payload.ty)) return;
-
- // One tile, 8-way, no teleporting through anything.
- const dx = Math.abs(tx - p.tx);
- const dy = Math.abs(ty - p.ty);
- if (dx > 1 || dy > 1 || (dx === 0 && dy === 0)) return;
- if (!this._isWalkable(tx, ty)) return;
- // Don't allow cutting a diagonal between two blocked corners.
- if (dx === 1 && dy === 1 && (!this._isWalkable(tx, p.ty) && !this._isWalkable(p.tx, ty))) return;
-
- // Server-enforced step floor (Task 09): on foot you step no faster than
- // ON_FOOT_STEP_MS; a mount lowers the floor (items.js) for visibly faster but
- // still authoritative travel. Early steps are dropped and the client self-paces
- // to match, so a client claiming mount speed without a mount gains nothing.
- const sPriv = this.priv.get(client.sessionId);
- const sNow = Date.now();
- const stepFloor = p.mounted ? (mountStepMs(p.mount) || ON_FOOT_STEP_MS) : ON_FOOT_STEP_MS;
- if (sPriv && sNow < (sPriv.cooldowns.step || 0)) return;
- if (sPriv) sPriv.cooldowns.step = sNow + stepFloor;
-
- p.tx = tx;
- p.ty = ty;
- if (typeof payload.yaw === 'number' && Number.isFinite(payload.yaw)) p.yaw = payload.yaw;
- p.motion = 'walk';
- p.tsServer = Date.now();
- // Tutorial: the very first step is simply learning to walk.
- this._questProgress(client, { kind: 'move', n: 1 });
-
- // Stepping onto a portal tile carries the player to its destination realm.
- // Each realm is its own room instance, so the move is a seat reservation in
- // the destination room plus a signed snapshot of everything the player is
- // carrying — the client tears down this seat and joins the other room.
- const portal = portalAt(this.realm, tx, ty);
- if (portal) {
- // Combat-LEVEL gate (Task 11): a gated portal (e.g. the northern cave)
- // refuses entry until the player's combat level meets the threshold. The
- // player keeps standing on the tile — no transfer, no bounce — and is told
- // what they need. Server-authoritative: a client can't forge its way past.
- if (portal.gate && !this._meetsGate(p, portal.gate)) {
- client.send('notice', { kind: 'portal', text: `You need Combat ${portal.gate.combat} to enter here (you're ${this._combatLevel(p)}).` });
- return;
- }
- this._beginTransfer(client, p, portal);
- }
- }
-
- // ----- realm traversal -------------------------------------------------
-
- // Reserve a seat in the destination realm and hand the client a transfer it
- // can consume. The player's full carry (inventory, hotbar, bank, gold, skills,
- // hp, mount) rides in an HMAC-signed token so the destination room can restore
- // it without trusting the client — a forged or replayed carry is rejected there.
- async _beginTransfer(client, p, portal) {
- const priv = this.priv.get(client.sessionId);
- if (!priv || priv.transferring) return;
- const dest = REALMS[portal.to] ? portal.to : DEFAULT_REALM;
- const destRealm = REALMS[dest];
- const tx = Number.isFinite(portal.toTx) ? portal.toTx : destRealm.spawn.tx;
- const ty = Number.isFinite(portal.toTy) ? portal.toTy : destRealm.spawn.ty;
- priv.transferring = true;
- const token = signTransfer({ to: dest, tx, ty, carry: this._snapshotCarry(client, p), account: priv.playerId });
- try {
- const reservation = await matchMaker.joinOrCreate(`game_${dest}`, {
- name: p.name,
- avatar: p.cosmetic,
- transfer: token,
- });
- // Persist quests now so the destination room (which reloads them by pid)
- // sees the same progress this room had at the moment of the step.
- this._persistPlayer(client.sessionId);
- client.send('portal', { to: dest, reservation });
- } catch (err) {
- priv.transferring = false;
- console.error(`[${this.realm.name} ${this.roomId}] portal → ${dest} failed:`, err?.message ?? err);
- client.send('notice', { kind: 'portal', text: 'The way is blocked right now. Try again.' });
- }
- }
-
- // Snapshot everything a player carries between realms. Quests persist by pid
- // (reloaded in the destination's onJoin), so only the in-memory haul rides here.
- _snapshotCarry(client, p) {
- return this._serializeProfile(p, this.priv.get(client.sessionId));
- }
-
- // The account-scoped, realm-agnostic profile: inventory, hotbar, bank, gold,
- // skills (raw XP), vitals, and mount. Used both as the portal carry payload and
- // as the persisted profile blob (Task 16/23) — one serializer so the two never
- // drift, and so switching world instances restores exactly what a portal would.
- _serializeProfile(p, priv) {
- const slots = (arr) => arr.map((s) => ({ item: s.item, qty: s.qty }));
- return {
- inv: slots(p.inv),
- hotbar: slots(p.hotbar),
- activeSlot: p.activeSlot,
- bank: (priv?.bank || []).map((s) => ({ item: s.item, qty: s.qty })),
- gold: p.gold,
- hp: p.hp,
- maxHp: p.maxHp,
- xp: { ...(priv?.xp || {}) },
- mounted: !!p.mounted,
- mount: p.mount || '',
- // Avatar GLB URL — persisted so the player's look survives on a device that
- // never stored it locally. Validated on restore (same rules as join time).
- cosmetic: p.cosmetic || '',
- };
- }
-
- // Restore a verified carry onto a freshly-joined player in the destination room.
- // Slot arrays are rebuilt defensively (the token is signed, but we still bound
- // indices and quantities so a malformed-but-signed payload can't corrupt state).
- _applyCarry(p, priv, carry) {
- const fill = (target, src, size) => {
- for (let i = 0; i < size; i++) {
- const s = src && src[i];
- const item = s && typeof s.item === 'string' ? s.item : '';
- target[i].item = item;
- target[i].qty = item && Number.isFinite(s.qty) ? Math.max(0, Math.min(999, s.qty | 0)) : 0;
- }
- };
- fill(p.inv, carry.inv, INV_SIZE);
- fill(p.hotbar, carry.hotbar, HOTBAR_SIZE);
- if (Number.isFinite(carry.activeSlot)) {
- p.activeSlot = Math.max(-1, Math.min(HOTBAR_SIZE - 1, carry.activeSlot | 0));
- }
- if (priv) {
- for (let i = 0; i < BANK_SIZE; i++) {
- const s = carry.bank && carry.bank[i];
- const item = s && typeof s.item === 'string' ? s.item : '';
- priv.bank[i] = { item, qty: item && Number.isFinite(s.qty) ? Math.max(0, Math.min(999, s.qty | 0)) : 0 };
- }
- if (carry.xp && typeof carry.xp === 'object') {
- for (const skill of SKILLS) {
- const v = Number.isFinite(carry.xp[skill]) ? Math.max(0, carry.xp[skill]) : 0;
- priv.xp[skill] = v;
- p[skill] = levelForXp(v);
- }
- }
- }
- if (Number.isFinite(carry.gold)) p.gold = Math.max(0, Math.min(0xffffffff, carry.gold | 0));
- if (Number.isFinite(carry.maxHp) && carry.maxHp > 0) p.maxHp = carry.maxHp | 0;
- if (Number.isFinite(carry.hp)) p.hp = Math.max(0, Math.min(p.maxHp, carry.hp | 0));
- if (carry.mounted && typeof carry.mount === 'string' && carry.mount) {
- p.mounted = true;
- p.mount = carry.mount;
- }
- // Avatar GLB URL — restored from persisted profile on fresh login (not from a
- // portal carry, where the client already re-sends it as an option). Validated
- // through the same allow-list as join-time so a saved URL that has since been
- // removed from the allow-list doesn't persist to peers.
- if (typeof carry.cosmetic === 'string' && carry.cosmetic) {
- const validated = cleanAvatarUrl(carry.cosmetic);
- if (validated) p.cosmetic = validated;
- }
- }
-
- _isWalkable(tx, ty) {
- if (!inBounds(this.realm, tx, ty)) return false;
- if (isBlocked(this.realm, tx, ty)) return false;
- // Fixed NPCs occupy their tile; players stand adjacent to talk.
- for (const n of this.realm.npcs || []) {
- if (n.tx === tx && n.ty === ty) return false;
- }
- // Non-depleted resource nodes occupy their tile.
- for (const [, n] of this.state.nodes) {
- if (!n.depleted && n.tx === tx && n.ty === ty) return false;
- }
- // Living mobs occupy their tile.
- for (const [, m] of this.state.mobs) {
- if (!m.dead && m.tx === tx && m.ty === ty) return false;
- }
- // Player-built structures are solid — you stand beside a firepit/shack,
- // never on it (Task 07), exactly like the fountain.
- for (const [, s] of this.state.structures) {
- if (s.tx === tx && s.ty === ty) return false;
- }
- return true;
- }
-
- // ----- gathering -------------------------------------------------------
-
- _handleGather(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p || p.dead) return;
- // Mounted players ride; they can't swing a tool. Dismount to harvest. (Combat
- // stays allowed while mounted — cavalry can fight.)
- if (p.mounted) { client.send('notice', { kind: 'mount', text: 'Dismount before you gather.' }); return; }
- if (!this._rateOk(client.sessionId, 'gather')) return;
- const node = this.state.nodes.get(String(payload?.id ?? ''));
- if (!node || node.depleted) return;
-
- const priv = this.priv.get(client.sessionId);
- const now = Date.now();
- if (now < priv.cooldowns.gather) return;
-
- if (!this._adjacent(p, node)) return;
-
- const rule = NODE_RULES[node.kind];
- if (!rule) return;
-
- // Must have the right tool equipped on the active hotbar slot.
- const active = p.hotbar[p.activeSlot];
- if (!active || active.item !== rule.tool) {
- client.send('notice', { kind: 'tool', text: `Equip a ${rule.tool} to gather this.` });
- return;
- }
-
- // Award the resource. _addItem returns the quantity that DIDN'T fit, so a
- // nonzero leftover on a single item means the backpack is full.
- const leftover = this._addItem(p, rule.item, 1);
- if (leftover >= 1) {
- client.send('notice', { kind: 'full', text: 'Your inventory is full.' });
- return;
- }
- let bonusCoal = false;
- if (node.kind === 'rock' && Math.random() < 0.15) { this._addItem(p, 'coal', 1); bonusCoal = true; }
-
- this._grantXp(client, p, rule.skill, 8 + Math.floor(Math.random() * 5));
- node.depleted = true;
- node.respawnAt = now + rule.respawnMs;
- priv.cooldowns.gather = now + GATHER_COOLDOWN_MS;
- p.tsServer = now;
- // Quest progress: the resource just harvested (plus any bonus coal from a
- // rock) counts toward gathering tutorial steps and dailies.
- this._questProgress(client, { kind: 'gather', item: rule.item, n: 1 });
- if (bonusCoal) this._questProgress(client, { kind: 'gather', item: 'coal', n: 1 });
- }
-
- // ----- fishing ---------------------------------------------------------
-
- // Cast a line. Validates (alive, rod equipped, beside fishable water, off
- // cooldown, room in the pack) then rolls a catch against fishing skill + spot
- // quality. Every cast — hit or miss — arms the per-cast cooldown so casting
- // has cadence on the real clock; the client renders the line/bobber while the
- // authoritative result rides back as a notice.
- _handleFish(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p || p.dead) return;
- if (!this._rateOk(client.sessionId, 'fish')) return;
- if (p.mounted) { client.send('notice', { kind: 'mount', text: 'Dismount before you fish.' }); return; }
-
- const priv = this.priv.get(client.sessionId);
- const now = Date.now();
- if (now < priv.cooldowns.fish) return; // still reeling in the previous cast
-
- // Need the rod on the active hotbar slot.
- const active = p.hotbar[p.activeSlot];
- if (!active || active.item !== 'rod') {
- client.send('notice', { kind: 'tool', text: 'Equip a fishing rod to cast.' });
- return;
- }
-
- // Need fishable water within one tile (8-way, including the player's tile).
- const spot = fishingSpotNear(this.realm, p.tx, p.ty);
- if (!spot) {
- client.send('notice', { kind: 'fish', text: 'Move next to the water to cast.' });
- return;
- }
-
- // Don't let a catch evaporate: reject the cast up front when there's no room
- // for even one fish — same notice the gather path uses.
- if (!this._hasRoomFor(p, 'fish')) {
- client.send('notice', { kind: 'full', text: 'Your inventory is full.' });
- return;
- }
-
- // Arm the cadence on the real cooldown clock (no fake timers).
- priv.cooldowns.fish = now + FISH_COOLDOWN_MS;
-
- const lvl = p.fishing;
- const quality = spot.quality || 1;
- const chance = fishCatchChance(lvl, quality);
-
- if (Math.random() < chance) {
- // Yield: usually one fish, with a skill/quality-scaled shot at a double haul.
- const want = 1 + (Math.random() < fishDoubleChance(lvl, quality) ? 1 : 0);
- const leftover = this._addItem(p, 'fish', want);
- const caught = want - leftover;
- if (caught <= 0) {
- // Pack filled between the room check and now — be honest, no phantom catch.
- client.send('notice', { kind: 'full', text: 'Your inventory is full.' });
- p.tsServer = now;
- return;
- }
- // XP scales gently with level + quality so richer water trains faster.
- const xp = Math.round((10 + Math.floor(Math.random() * 6) + lvl * 0.3) * quality) * caught;
- this._grantXp(client, p, 'fishing', xp);
- this._questProgress(client, { kind: 'fish', item: 'fish', n: caught });
- client.send('notice', { kind: 'fish', text: caught > 1 ? `Caught ${caught} fish!` : 'Caught a fish.' });
- } else {
- // A miss still teaches the cast — a small XP trickle keeps progression smooth.
- this._grantXp(client, p, 'fishing', 2);
- client.send('notice', { kind: 'fish', text: 'The fish got away.' });
- }
- p.tsServer = now;
- }
-
- // Is there room in the backpack for at least one of `item`? For stackables, an
- // empty slot OR a non-full existing stack counts; otherwise an empty slot.
- _hasRoomFor(p, item) {
- if (STACKABLE.has(item)) {
- for (const s of p.inv) {
- if (!s.item) return true;
- if (s.item === item && s.qty < MAX_STACK) return true;
- }
- return false;
- }
- return p.inv.some((s) => !s.item);
- }
-
- // ----- cooking & consumables -------------------------------------------
-
- // Cook raw fish into cooked fish at a Roast Pit. Validates the player is
- // alive, standing on/next to a cooking tile of THIS realm, and actually holds
- // raw fish; then converts up to a small batch in one action (one cooldown).
- // Low cooking levels burn some fish — the raw fish is consumed with no result
- // and the player is told honestly; burns grant no XP. Never loses or dupes an
- // item: the cooked result is reserved (pack space checked) before the raw fish
- // is spent.
- _handleCook(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p || p.dead) return;
- if (!this._rateOk(client.sessionId, 'cook')) return;
- if (p.mounted) { client.send('notice', { kind: 'mount', text: 'Dismount before you cook.' }); return; }
-
- const priv = this.priv.get(client.sessionId);
- const now = Date.now();
- if (now < priv.cooldowns.cook) return;
-
- if (!this._atCookingSpot(p)) {
- client.send('notice', { kind: 'cook', text: 'Stand by the Roast Pit to cook.' });
- return;
- }
-
- const fish = this._findItemSlot(p, 'fish');
- if (!fish) {
- client.send('notice', { kind: 'cook', text: 'You have no raw fish to cook.' });
- return;
- }
-
- const want = Math.max(1, Math.min(COOK_BATCH_MAX, payload?.qty | 0 || 1));
- const level = p.cooking;
- let cooked = 0;
- let burned = 0;
- for (let i = 0; i < want; i++) {
- const slot = fish.slot;
- if (slot.item !== 'fish' || slot.qty <= 0) break; // stack exhausted
- if (Math.random() < cookBurnChance(level)) {
- // Burned: the raw fish is gone, nothing to store, no XP.
- slot.qty -= 1;
- if (slot.qty === 0) slot.item = '';
- burned++;
- continue;
- }
- // Success: reserve pack space for the cooked fish BEFORE spending the raw
- // one. If the pack is full, stop the batch with no item lost.
- const leftover = this._addItem(p, 'cookedFish', 1);
- if (leftover >= 1) {
- if (cooked === 0 && burned === 0) {
- client.send('notice', { kind: 'full', text: 'Your inventory is full.' });
- return;
- }
- break;
- }
- slot.qty -= 1;
- if (slot.qty === 0) slot.item = '';
- this._grantXp(client, p, 'cooking', COOK_XP);
- cooked++;
- }
-
- if (cooked === 0 && burned === 0) return;
- priv.cooldowns.cook = now + COOK_COOLDOWN_MS;
- p.tsServer = now;
-
- if (cooked > 0) this._questProgress(client, { kind: 'cook', item: 'cookedFish', n: cooked });
-
- // Honest result: report exactly what the fire produced.
- const parts = [];
- if (cooked) parts.push(`Cooked ${cooked} fish`);
- if (burned) parts.push(`burned ${burned}`);
- client.send('cooked', { cooked, burned, level: p.cooking });
- client.send('notice', { kind: cooked ? 'cook' : 'burn', text: `${parts.join(', ')}.` });
- }
-
- // Eat an edible item (cooked fish, potions) from a referenced inv/hotbar slot
- // to restore HP. Server-authoritative: validates the slot really holds an
- // edible item, refuses at full health (so food is never silently wasted),
- // heals up to maxHp (never over), consumes one from the stack, and applies a
- // short cooldown. Works from both the backpack and the hotbar.
- _handleConsume(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p || p.dead) return;
- if (!this._rateOk(client.sessionId, 'consume')) return;
-
- const priv = this.priv.get(client.sessionId);
- const now = Date.now();
- if (now < priv.cooldowns.consume) return;
-
- const ref = this._resolveSlot(p, payload?.slot);
- if (!ref) return;
- const slot = ref.slot;
- if (!slot.item || !isEdible(slot.item)) {
- client.send('notice', { kind: 'eat', text: 'That can’t be eaten.' });
- return;
- }
- if (p.hp >= p.maxHp) {
- client.send('notice', { kind: 'eat', text: 'You’re already at full health.' });
- return;
- }
-
- const before = p.hp;
- p.hp = Math.min(p.maxHp, p.hp + scaledHeal(slot.item, p.cooking));
- const gained = p.hp - before;
- slot.qty -= 1;
- if (slot.qty === 0) slot.item = '';
- priv.cooldowns.consume = now + CONSUME_COOLDOWN_MS;
- p.tsServer = now;
- client.send('notice', { kind: 'eat', text: `+${gained} HP.` });
- }
-
- // True if the player is on or directly adjacent to any cooking tile (the Roast
- // Pit) of the current realm — you stand by the fire, not necessarily on it.
- _atCookingSpot(p) {
- const tiles = this.realm.cooking || [];
- for (const t of tiles) {
- if (Math.abs(p.tx - t.tx) <= 1 && Math.abs(p.ty - t.ty) <= 1) return true;
- }
- return false;
- }
-
- // Find a live slot holding `item`: the active hotbar slot first (what you're
- // "holding"), then the rest of the hotbar, then the backpack. Null if none.
- _findItemSlot(p, item) {
- const active = p.hotbar[p.activeSlot];
- if (active && active.item === item && active.qty > 0) return { slot: active };
- for (const s of p.hotbar) if (s.item === item && s.qty > 0) return { slot: s };
- for (const s of p.inv) if (s.item === item && s.qty > 0) return { slot: s };
- return null;
- }
-
- // ----- combat ----------------------------------------------------------
-
- _handleAttack(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p || p.dead) return;
- if (!this._rateOk(client.sessionId, 'attack')) return;
- const targetId = String(payload?.id ?? '');
- const mob = this.state.mobs.get(targetId);
- // No mob with that id → maybe it's another player. PvP rides the same 'attack'
- // intent + cooldown; the dedicated handler enforces this realm's PvP rules.
- if (!mob) {
- const victim = this.state.players.get(targetId);
- if (victim && victim !== p) this._attackPlayer(client, p, victim);
- return;
- }
- if (mob.dead) return;
-
- const priv = this.priv.get(client.sessionId);
- const now = Date.now();
- if (now < priv.cooldowns.attack) return;
- if (!this._adjacent(p, mob)) return;
-
- // Damage scales with combat level; a sword on the active slot adds a flat
- // bonus. Small variance keeps fights from feeling mechanical.
- const hasSword = p.hotbar[p.activeSlot]?.item === 'sword';
- const base = 4 + Math.floor(p.combat * 0.8) + (hasSword ? 6 : 0);
- const dmg = base + Math.floor(Math.random() * 4);
- mob.hp = Math.max(0, mob.hp - dmg);
- mob.hitTs = now;
- priv.cooldowns.attack = now + ATTACK_COOLDOWN_MS;
-
- if (mob.hp === 0) {
- mob.dead = true;
- mob.respawnAt = now + RESPAWN_MOB_MS;
- const reward = 5 + Math.floor(Math.random() * 6);
- p.gold = Math.min(0xffffffff, p.gold + reward);
- this._grantXp(client, p, 'combat', 14 + Math.floor(Math.random() * 8));
- client.send('notice', { kind: 'kill', text: `Defeated ${mob.kind} (+${reward}g).` });
- // Task 09: roll the mob's loot table — materials and, rarely, a ridable mount.
- this._awardLoot(client, p, mob);
- // Quest progress: a defeated foe counts toward combat tutorial + dailies.
- this._questProgress(client, { kind: 'combat', n: 1 });
- }
- p.tsServer = now;
- }
-
- // ----- player vs player (Task 04 rules, enforced for the wild realms + Arena) ----
-
- // Strike another player. Server-authoritative and gated by the realm's rules:
- // PvP must be ON, neither fighter may stand in a PvP-immune tile (a wilderness
- // safe camp or an Arena spectator stand), and the attacker must be adjacent and
- // off cooldown. Damage flows through the shared _damagePlayer funnel, so a fatal
- // blow drops a death-bag in danger realms (the wilds) and is a clean, item-safe
- // knockout in the Arena (danger:false). On a kill the victor takes combat XP and
- // a small bounty.
- _attackPlayer(client, attacker, victim) {
- if (!this.realm.pvp) {
- client.send('notice', { kind: 'pvp', text: 'This is a peaceful realm — you can’t attack other players here.' });
- return;
- }
- if (victim.dead) return;
- // A spectator stand / safe camp shields BOTH sides: you can't be hit while in
- // one, and you can't reach out of the floor to hit someone standing in it.
- if (inNoPvpZone(this.realm, attacker.tx, attacker.ty)) {
- client.send('notice', { kind: 'pvp', text: 'Step out of the safe zone to fight.' });
- return;
- }
- if (inNoPvpZone(this.realm, victim.tx, victim.ty)) {
- client.send('notice', { kind: 'pvp', text: `${victim.name} is in a safe zone.` });
- return;
- }
-
- const priv = this.priv.get(client.sessionId);
- const now = Date.now();
- if (now < priv.cooldowns.attack) return;
- if (!this._adjacent(attacker, victim)) return;
-
- const hasSword = attacker.hotbar[attacker.activeSlot]?.item === 'sword';
- const base = 4 + Math.floor(attacker.combat * 0.8) + (hasSword ? 6 : 0);
- const dmg = base + Math.floor(Math.random() * 4);
- priv.cooldowns.attack = now + ATTACK_COOLDOWN_MS;
-
- const fatal = this._damagePlayer(victim, dmg, { by: attacker.id, byName: attacker.name });
- attacker.tsServer = now;
- if (fatal) {
- const bounty = 8 + Math.floor(Math.random() * 8);
- attacker.gold = Math.min(0xffffffff, attacker.gold + bounty);
- this._grantXp(client, attacker, 'combat', 18 + Math.floor(Math.random() * 10));
- client.send('notice', { kind: 'kill', text: `You defeated ${victim.name} (+${bounty}g).` });
- this._questProgress(client, { kind: 'combat', n: 1 });
- }
- }
-
- // ----- mounts & loot ---------------------------------------------------
-
- // Roll a slain mob's loot table and hand the killer their winnings. Mounts are
- // rare; everything else is gathered material. Items go to the pack (mounts prefer
- // a free HOTBAR slot so they're immediately rideable); anything that doesn't fit
- // spills into a ground bag on the mob's tile instead of vanishing — loot is never
- // silently lost on a full pack.
- _awardLoot(client, p, mob) {
- const drops = rollLoot(mob.kind);
- if (!drops.length) return;
- const spoils = []; // non-mount lines for the loot toast
- const overflow = []; // Slots that didn't fit anywhere → ground bag
- let mount = null; // { label, bagged } when a mount drops
- for (const d of drops) {
- const left = this._giveLoot(p, d.item, d.qty);
- const got = d.qty - left;
- if (isMount(d.item)) {
- if (got > 0 || left > 0) mount = { label: itemLabel(d.item), bagged: left > 0 };
- } else if (got > 0) {
- spoils.push(got > 1 ? `${got}× ${itemLabel(d.item)}` : itemLabel(d.item));
- }
- if (left > 0) overflow.push(new Slot(d.item, left));
- }
- if (overflow.length) this._spawnLootBag(p, mob.tx, mob.ty, overflow);
-
- if (mount) {
- const where = mount.bagged ? 'It dropped into the bag at your feet.' : 'It’s on your hotbar — ride out!';
- client.send('notice', { kind: 'mount', text: `The ${mob.kind} dropped a ${mount.label}! ${where}` });
- }
- if (spoils.length) client.send('notice', { kind: 'loot', text: `Looted ${spoils.join(', ')}.` });
- if (overflow.length && !(mount && mount.bagged)) {
- client.send('notice', { kind: 'full', text: 'Pack full — extra loot waits in a bag at your feet.' });
- }
- }
-
- // Give looted items to a player. Mounts are seated on a free HOTBAR slot first
- // (there is no inv→hotbar mover yet, and a mount you can't reach is useless),
- // then the backpack; everything else goes straight to the backpack. Returns the
- // quantity that didn't fit anywhere.
- _giveLoot(p, item, qty) {
- if (isMount(item)) {
- let placed = 0;
- for (const s of p.hotbar) {
- if (placed >= qty) break;
- if (!s.item) { s.item = item; s.qty = 1; placed++; }
- }
- if (placed >= qty) return 0;
- return this._addItem(p, item, qty - placed);
- }
- return this._addItem(p, item, qty);
- }
-
- // Spill overflow loot into a ground bag on (tx,ty) owned by the killer — the same
- // Tombstone vessel + tombLoot recovery path used by death-bags, so loot never
- // vanishes on a full pack and the client renders/recovers it identically.
- _spawnLootBag(p, tx, ty, slots) {
- const now = Date.now();
- const bag = new Tombstone();
- bag.id = `loot_${this.realm.name}_${p.id}_${++this._tombSeq}`;
- bag.owner = p.id;
- bag.ownerName = p.name;
- bag.tx = tx;
- bag.ty = ty;
- bag.expiresAt = now + TOMBSTONE_TTL_MS;
- for (const s of slots) bag.items.push(s);
- this.state.tombstones.set(bag.id, bag);
- return bag.items.length;
- }
-
- // Use the active hotbar item (or an explicit slot). Today that rides a mount; the
- // registry decides what "use" means per item, so future usable items slot in here
- // without a new intent. A stray click on a non-usable item is a harmless no-op.
- _handleUse(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p || p.dead) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- let i = p.activeSlot;
- if (payload && Number.isInteger(payload.slot)) i = payload.slot | 0;
- if (i < 0 || i >= HOTBAR_SIZE) return;
- const slot = p.hotbar[i];
- if (!slot || !slot.item) return;
- if (isMount(slot.item)) {
- p.activeSlot = i; // hold the reins
- this._mount(client, p, slot.item);
- }
- }
-
- // Mount up: flip to the faster server-enforced cadence and record the steed so
- // peers render it. Re-mounting the same steed is a no-op; swapping steeds just
- // changes which creature you ride.
- _mount(client, p, item) {
- if (p.mounted && p.mount === item) return;
- p.mounted = true;
- p.mount = item;
- p.tsServer = Date.now();
- client.send('notice', { kind: 'mount', text: `Mounted your ${itemLabel(item)}.` });
- }
-
- // Leave the saddle, back to on-foot speed. Idempotent and friendly when already
- // on foot. Routed to by the 'dismount' intent and the /dismount command.
- _handleDismount(client) {
- const p = this.state.players.get(client.sessionId);
- if (!p) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- if (!p.mounted) { client.send('notice', { kind: 'mount', text: 'You’re not mounted.' }); return; }
- const was = p.mount;
- p.mounted = false;
- p.mount = '';
- p.tsServer = Date.now();
- client.send('notice', { kind: 'mount', text: `Dismounted your ${itemLabel(was)}.` });
- }
-
- // ----- world chat ------------------------------------------------------
-
- // Realm-wide chat. This room IS one realm, so a broadcast reaches exactly the
- // players who can see each other — chat never leaks across realms/instances.
- // Leading-'/' messages are handed to the command router instead of broadcast
- // (Task 13); everything else is sanitized, length-capped, rate-limited, and
- // echoed to everyone (the sender included, so their own line is driven by the
- // same authoritative event their peers receive).
- _handleChat(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p) return;
- const now = Date.now();
- // Sanitize up front (strip control chars, collapse whitespace, trim). Cap
- // generously here so we can still measure "too long" against MAX_CHAT_LEN
- // rather than silently truncating to it.
- const text = clean(payload?.text, 2000);
- if (!text) return;
-
- // Slash-commands bypass chat entirely — the command router has its own
- // validation and rate limit, so route before charging a chat token.
- if (text[0] === '/') { this._handleCommand(client, { text }); return; }
-
- // Flood control. Tell the sender (throttled, so a flood can't be amplified
- // into a flood of error replies) instead of dropping silently.
- if (!this._rateOk(client.sessionId, 'chat')) {
- const priv = this.priv.get(client.sessionId);
- if (priv && now - (priv.chatNoticeAt || 0) > 1500) {
- priv.chatNoticeAt = now;
- client.send('chat', { system: true, kind: 'error', text: 'You’re sending messages too fast.', ts: now });
- }
- return;
- }
-
- // Length cap — reject rather than truncate so nothing is sent half-said.
- if (text.length > MAX_CHAT_LEN) {
- client.send('chat', { system: true, kind: 'error', text: `Message too long. Keep it under ${MAX_CHAT_LEN} characters.`, ts: now });
- return;
- }
-
- this.broadcast('chat', { id: client.sessionId, name: p.name, text, ts: now });
- }
-
- // Slash-command channel. Task 13's chat forwards any leading-'/' message here; the
- // game HUD also calls it directly. Handles /dismount and /mount today; unknown
- // commands get an honest reply rather than silence.
- _handleCommand(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- const text = clean(payload?.text, 64);
- const cmd = text.replace(/^\//, '').split(/\s+/)[0].toLowerCase();
-
- // /mount needs the hotbar + item registry, so it stays inline; every other
- // command is dispatched through the Task 13 registry — the single source of
- // truth for /help, /who, /pickup, /lock, /unlock, /dismount.
- if (cmd === 'mount') {
- const slot = p.hotbar[p.activeSlot];
- if (slot && isMount(slot.item)) this._mount(client, p, slot.item);
- else client.send('notice', { kind: 'mount', text: 'Select a mount on your hotbar first.' });
- return;
- }
-
- const reply = runCommand({ room: this, client, player: p }, text);
- // Command replies render as system chat lines — distinct from player chat —
- // so multi-line output (/help, /who) stays readable instead of flashing past
- // as a toast. A null reply means the handler already answered (e.g. /dismount).
- if (reply && reply.text) {
- client.send('chat', { system: true, kind: reply.kind || 'system', text: reply.text, ts: Date.now() });
- }
- }
-
- // ----- building (Task 07: firepit / shack) -----------------------------
-
- // The structures this realm permits, each with its authoritative cost + lifetime,
- // sent to the client on join so the build menu and ghost validity mirror the
- // server exactly. `cap` 0 means unlimited (the client renders no cap note).
- _buildCatalog() {
- const out = {};
- for (const kind of this.realm.structures || []) {
- const def = STRUCTURE_DEFS[kind];
- if (def) out[kind] = { cost: { ...def.cost }, lifetimeMs: def.lifetimeMs, cap: Number.isFinite(def.cap) ? def.cap : 0 };
- }
- return out;
- }
-
- // Place a structure on an adjacent tile, paying its EXACT material cost. The
- // server is the sole authority: it re-validates the realm rules, the target
- // tile, the per-player cap, and the full material bill, and deducts atomically
- // (the cost is checked payable before a single item is spent) so there is no
- // free build and no negative balance. A firepit gets an `expiresAt`; a shack is
- // permanent. The client's build-mode ghost mirrors these gates for instant
- // feedback, but a forged 'build' that skips them gets nothing here.
- _handleBuild(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p || p.dead) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- // You build with your hands, not from the saddle — mirrors the gather gate.
- if (p.mounted) { client.send('notice', { kind: 'build', text: 'Dismount before you build.' }); return; }
- if (!payload || typeof payload !== 'object') return;
-
- const kind = String(payload.kind ?? '');
- const def = STRUCTURE_DEFS[kind];
- if (!def) return;
-
- // Realm rules (Task 01): the realm must permit this structure kind. Shacks
- // are Whisperwood-only; firepits are allowed wherever building makes sense.
- if (!(this.realm.structures || []).includes(kind)) {
- client.send('notice', { kind: 'build', text: `You can’t build a ${kind} here.` });
- return;
- }
-
- if (!Number.isFinite(payload.tx) || !Number.isFinite(payload.ty)) return;
- const tx = payload.tx | 0;
- const ty = payload.ty | 0;
-
- // Must sit on a tile right next to the builder (8-way) — never under them.
- const dx = Math.abs(tx - p.tx);
- const dy = Math.abs(ty - p.ty);
- if (dx === 0 && dy === 0) { client.send('notice', { kind: 'build', text: 'Step back a tile to place it.' }); return; }
- if (dx > 1 || dy > 1) { client.send('notice', { kind: 'build', text: 'Build on a tile right beside you.' }); return; }
-
- // The tile must be free and buildable: walkable (so not blocked, not on a
- // node/mob/another structure) and clear of portals, the bank counter, the
- // fountain, fishing/cooking spots, and any standing player.
- if (!this._isBuildable(tx, ty)) { client.send('notice', { kind: 'build', text: 'You can’t build there.' }); return; }
-
- // Per-player cap (shack: one). Counted on the live structure map.
- if (Number.isFinite(def.cap)) {
- let owned = 0;
- for (const [, s] of this.state.structures) {
- if (s.kind === kind && this._ownedBy(s, priv.playerId)) owned++;
- }
- if (owned >= def.cap) {
- client.send('notice', { kind: 'build', text: `You can only have ${def.cap} ${kind}${def.cap === 1 ? '' : 's'} — pick it up first.` });
- return;
- }
- }
-
- // Exact material cost — verify the whole bill is payable before spending any
- // of it, then deduct atomically.
- if (!this._canAfford(p, def.cost)) {
- client.send('notice', { kind: 'build', text: `Need ${this._missingCost(p, def.cost)} to build a ${kind}.` });
- return;
- }
- this._spendCost(p, def.cost);
-
- const now = Date.now();
- const s = new Structure();
- s.id = `st_${this.realm.name}_${p.id}_${++this._structSeq}`;
- s.kind = kind;
- // Store the stable account id on a server-only property so ownership
- // survives reconnects (a new session gets a new p.id). s.owner stays the
- // session id that the schema broadcasts to peers for client-side UI rendering.
- s._ownerPlayerId = priv.playerId;
- s.owner = p.id;
- s.ownerName = p.name;
- s.tx = tx;
- s.ty = ty;
- s.expiresAt = def.lifetimeMs ? now + def.lifetimeMs : 0;
- s.locked = false;
- this.state.structures.set(s.id, s);
- p.tsServer = now;
- client.send('notice', { kind: 'build', text: `Built a ${kind}.` });
- // Quest progress: placing any structure counts toward the build daily.
- this._questProgress(client, { kind: 'build', item: kind, n: 1 });
- }
-
- // A tile is buildable when it's walkable (bounds + not blocked + no node/mob/
- // structure on it) AND clear of the interactive/landmark tiles a structure
- // must never cover or block: portals, the bank counter, the fountain, and the
- // fishing/cooking spots — plus any tile a player is currently standing on.
- _isBuildable(tx, ty) {
- if (!this._isWalkable(tx, ty)) return false;
- for (const [, pl] of this.state.players) {
- if (!pl.dead && pl.tx === tx && pl.ty === ty) return false;
- }
- if (portalAt(this.realm, tx, ty)) return false;
- if ((this.realm.bankZone || []).some((t) => t.tx === tx && t.ty === ty)) return false;
- const f = this.realm.fountain;
- if (f && f.tx === tx && f.ty === ty) return false;
- for (const sp of this.realm.fishing || []) if (sp.tx === tx && sp.ty === ty) return false;
- for (const ck of this.realm.cooking || []) if (ck.tx === tx && ck.ty === ty) return false;
- return true;
- }
-
- // Total quantity of `item` the player holds across backpack + hotbar — materials
- // usually live in the backpack, but count both so a stack dragged to the hotbar
- // still pays.
- _countMaterial(p, item) {
- let n = 0;
- for (const s of p.inv) if (s.item === item) n += s.qty;
- for (const s of p.hotbar) if (s.item === item) n += s.qty;
- return n;
- }
-
- _canAfford(p, cost) {
- for (const [item, qty] of Object.entries(cost)) {
- if (this._countMaterial(p, item) < qty) return false;
- }
- return true;
- }
-
- // A human-readable summary of what the player is short for `cost` — drives the
- // honest "Need 200 more wood" notice.
- _missingCost(p, cost) {
- const parts = [];
- for (const [item, qty] of Object.entries(cost)) {
- const short = qty - this._countMaterial(p, item);
- if (short > 0) parts.push(`${short} more ${itemLabel(item)}`);
- }
- return parts.join(', ');
- }
-
- // Atomically remove a paid cost from the pack (backpack first, then hotbar),
- // emptying slots as they zero out. Only ever called after _canAfford passes, so
- // it never under-pays or drives a slot negative.
- _spendCost(p, cost) {
- for (const [item, qty] of Object.entries(cost)) {
- let left = qty;
- for (const arr of [p.inv, p.hotbar]) {
- for (const s of arr) {
- if (left <= 0) break;
- if (s.item !== item) continue;
- const take = Math.min(s.qty, left);
- s.qty -= take;
- left -= take;
- if (s.qty === 0) s.item = '';
- }
- }
- }
- }
-
- // Restore a player's placed structures from their persisted profile into the
- // live room state. Handles two cases:
- // a) Room still live (reconnect): the structure is already in state.structures
- // under the OLD session id — update owner to the new session so pickup/lock
- // work again. Skipped if another player's structure now occupies that tile.
- // b) Room freshly created (after dispose or restart): re-seed the structure;
- // skip any tile that's now blocked (another player's structure placed first).
- // Expired firepits are silently dropped rather than resurrected.
- _restoreStructures(client, p, playerId, playerName, savedStructures) {
- const now = Date.now();
- for (const sv of savedStructures) {
- if (sv.expiresAt && sv.expiresAt <= now) continue; // firepit expired — gone
- const tx = sv.tx | 0, ty = sv.ty | 0;
-
- // Case (a): structure still in this live room under the old session id.
- let found = false;
- for (const [, s] of this.state.structures) {
- if (s.tx === tx && s.ty === ty && s.kind === sv.kind &&
- (s._ownerPlayerId === playerId || s.owner === client.sessionId)) {
- s.owner = client.sessionId; // hand off to new session
- s._ownerPlayerId = playerId;
- found = true;
- break;
- }
- }
- if (found) continue;
-
- // Case (b): re-seed. Check tile is clear (bounds, walkable, no other structure).
- if (!inBounds(this.realm, tx, ty) || isBlocked(this.realm, tx, ty)) continue;
- let blocked = false;
- for (const [, s] of this.state.structures) {
- if (s.tx === tx && s.ty === ty) { blocked = true; break; }
- }
- if (blocked) continue;
-
- const s = new Structure();
- s.id = `st_restore_${this.realm.name}_${client.sessionId}_${++this._structSeq}`;
- s.kind = sv.kind;
- s._ownerPlayerId = playerId;
- s.owner = client.sessionId;
- s.ownerName = playerName;
- s.tx = tx;
- s.ty = ty;
- s.expiresAt = sv.expiresAt || 0;
- s.locked = !!sv.locked;
- this.state.structures.set(s.id, s);
- }
- }
-
- // ----- structure actions (firepit/shack; invoked by /pickup /lock /unlock) ----
- // These operate on real synced state.structures and never throw on the empty
- // case: with no structure placed they honestly report "nothing placed". Only the
- // owner can act, and only on a structure beside them.
-
- pickupStructure(p) {
- const priv = this.priv.get(p.id);
- const owned = [];
- for (const [, s] of this.state.structures) if (this._ownedBy(s, priv?.playerId || p.id)) owned.push(s);
- if (!owned.length) return { text: 'You have not placed a firepit or shack to pick up.', kind: 'error' };
- const near = owned.filter((s) => this._adjacent(p, s)).sort((a, b) => this._d2(p, a) - this._d2(p, b));
- if (!near.length) {
- const where = owned.map((s) => ` • ${s.kind} at (${s.tx}, ${s.ty})`).join('\n');
- return { text: `Stand next to one of your structures to pick it up:\n${where}`, kind: 'info' };
- }
- const s = near[0];
- if (s.locked) return { text: `Your ${s.kind} is locked — /unlock it first.`, kind: 'error' };
- this.state.structures.delete(s.id);
- return { text: `Picked up your ${s.kind}.`, kind: 'info' };
- }
-
- setStructureLock(p, locked) {
- const priv = this.priv.get(p.id);
- let target = null;
- for (const [, s] of this.state.structures) {
- if (this._ownedBy(s, priv?.playerId || p.id) && this._adjacent(p, s) &&
- (!target || this._d2(p, s) < this._d2(p, target))) target = s;
- }
- if (!target) return { text: `Stand next to your own firepit or shack to ${locked ? 'lock' : 'unlock'} it.`, kind: 'error' };
- if (target.locked === locked) return { text: `Your ${target.kind} is already ${locked ? 'locked' : 'unlocked'}.`, kind: 'info' };
- target.locked = locked;
- const k = target.kind.charAt(0).toUpperCase() + target.kind.slice(1);
- return { text: `${k} ${locked ? 'locked' : 'unlocked'}.`, kind: 'info' };
- }
-
- // A structure is "owned by" an account when _ownerPlayerId (stable account id
- // stored at build time) or the legacy session-id owner field matches. The stable
- // id is preferred; the fallback keeps pre-fix structures accessible.
- _ownedBy(s, playerId) {
- return (s._ownerPlayerId || s.owner) === playerId;
- }
-
- // Squared tile distance — cheap "nearest" ordering, no sqrt.
- _d2(a, b) { const dx = a.tx - b.tx, dy = a.ty - b.ty; return dx * dx + dy * dy; }
-
- // ----- death & tombstones ----------------------------------------------
-
- // Single funnel for all damage to a player (mob contact in Task 03, PvP in
- // Task 04, environment, …). Clamps HP at 0 and, when it lands the killing
- // blow, routes through _killPlayer so death/tombstone/respawn happen in
- // exactly one place. Returns true if the hit was fatal. `opts.byName` (and
- // `opts.by`) label the cause for the death notice.
- _damagePlayer(p, amount, opts = {}) {
- if (!p || p.dead) return false;
- const dmg = Math.max(0, Math.floor(amount));
- if (dmg <= 0) return false;
- p.hp = Math.max(0, p.hp - dmg);
- p.tsServer = Date.now();
- if (p.hp === 0) {
- this._killPlayer(p, opts);
- return true;
- }
- return false;
- }
-
- // Kill a player: freeze them, schedule a respawn, and — only in a danger
- // realm — spill the droppable part of their pack into a tombstone on the tile
- // they fell. Idempotent: a second call on an already-dead player is a no-op.
- _killPlayer(p, opts = {}) {
- if (!p || p.dead) return;
- const now = Date.now();
- p.dead = true;
- // Task 09: auto-dismount on death — no keeping the saddle through a respawn.
- if (p.mounted) { p.mounted = false; p.mount = ''; }
- p.motion = 'idle';
- p.hp = 0;
- p.respawnAt = now + RESPAWN_PLAYER_MS;
-
- let droppedCount = 0;
- if (this.realm.danger) droppedCount = this._dropTombstone(p, now);
-
- const client = this._clientFor(p.id);
- client?.send('died', {
- realm: this.realm.name,
- danger: !!this.realm.danger,
- respawnAt: p.respawnAt,
- dropped: droppedCount,
- byName: opts.byName || '',
- });
- p.tsServer = now;
- }
-
- // Drop rule (deterministic & fair): you KEEP your tools (axe/pickaxe/rod/
- // hammer/sword) wherever they sit — losing the means to recover would be
- // punishing and grief-prone — and you DROP everything else (gathered
- // resources, food, and any other non-tool item) from BOTH the backpack and
- // the hotbar into the bag. Gold is a currency, not an inventory item, so it
- // is never dropped. Returns the number of slots that landed in the tombstone.
- _dropTombstone(p, now) {
- const tomb = new Tombstone();
- tomb.id = `tomb_${this.realm.name}_${p.id}_${++this._tombSeq}`;
- tomb.owner = p.id;
- tomb.ownerName = p.name;
- tomb.tx = p.tx;
- tomb.ty = p.ty;
- tomb.expiresAt = now + TOMBSTONE_TTL_MS;
-
- for (const slot of [...p.inv, ...p.hotbar]) {
- if (!slot.item || TOOLS.has(slot.item)) continue;
- tomb.items.push(new Slot(slot.item, slot.qty));
- slot.item = '';
- slot.qty = 0;
- }
-
- if (tomb.items.length === 0) return 0; // nothing droppable — no empty bag
- this.state.tombstones.set(tomb.id, tomb);
- return tomb.items.length;
- }
-
- // Recover a tombstone's contents. Must be adjacent. Ownership holds for the
- // first part of the bag's life; once inside the final grace window before
- // expiry, anyone adjacent may loot. Items flow back through _addItem so a full
- // pack leaves the remainder in the bag (no duplication, no loss). An emptied
- // bag is removed immediately.
- _handleTombLoot(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p || p.dead) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- const tomb = this.state.tombstones.get(String(payload?.id ?? ''));
- if (!tomb) return;
-
- if (!this._adjacent(p, tomb)) {
- client.send('notice', { kind: 'tomb', text: 'Walk up to the bag to loot it.' });
- return;
- }
-
- const now = Date.now();
- const isOwner = tomb.owner === p.id;
- const isPublic = now > tomb.expiresAt - TOMBSTONE_GRACE_MS;
- if (!isOwner && !isPublic) {
- client.send('notice', { kind: 'tomb', text: `This bag belongs to ${tomb.ownerName || 'someone'}.` });
- return;
- }
-
- // Pull each slot back into the pack; whatever doesn't fit stays in the bag.
- let taken = 0;
- for (const s of tomb.items) {
- if (!s.item || s.qty <= 0) continue;
- const before = s.qty;
- const leftover = this._addItem(p, s.item, s.qty);
- taken += before - leftover;
- s.qty = leftover;
- if (leftover === 0) s.item = '';
- }
-
- // Compact emptied slots; remove the bag entirely once nothing remains.
- for (let i = tomb.items.length - 1; i >= 0; i--) {
- if (!tomb.items[i].item) tomb.items.splice(i, 1);
- }
- if (tomb.items.length === 0) {
- this.state.tombstones.delete(tomb.id);
- client.send('notice', { kind: 'tomb', text: isOwner ? 'Recovered your belongings.' : 'Looted the bag.' });
- } else if (taken > 0) {
- client.send('notice', { kind: 'full', text: 'Pack full — some items remain in the bag.' });
- } else {
- client.send('notice', { kind: 'full', text: 'Your pack is full.' });
- }
- p.tsServer = now;
- }
-
- _clientFor(sessionId) {
- return this.clients?.find?.((c) => c.sessionId === sessionId) || null;
- }
-
- // ----- quests: tutorial + dailies --------------------------------------
-
- // Talk to a fixed NPC. Validates the player stands adjacent to it, advances a
- // tutorial 'talk' step if that's what's next, and replies with a fresh quest
- // snapshot (the guide's current line travels in it) flagged so the client
- // opens the dialog.
- _handleNpcTalk(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p || p.dead) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- const npc = (this.realm.npcs || []).find((n) => n.id === String(payload?.id ?? ''));
- if (!npc) return;
- if (!this._adjacent(p, npc)) {
- client.send('notice', { kind: 'npc', text: `Walk up to ${npc.name} to talk.` });
- return;
- }
- // A talk only advances the tutorial when the next step IS a talk step;
- // otherwise it just opens the dialog (the snapshot already carries the line).
- this._questProgress(client, { kind: 'talk', n: 1 });
- this._sendQuests(client, { npc: npc.id });
- }
-
- // Drive all quest progress from a real, server-validated action. `ev` is
- // { kind, item?, n }. Advances the current tutorial step when it matches, and
- // every matching un-claimed daily. Persists + re-sends the snapshot on change.
- // Progress NEVER originates from a client claim — only from these hooks.
- _questProgress(client, ev) {
- const priv = this.priv.get(client.sessionId);
- const p = this.state.players.get(client.sessionId);
- if (!priv || !p || !priv.quests) return;
- const now = Date.now();
- const qs = normalizeQuestState(priv.quests, priv.playerId, now);
- const n = Math.max(1, ev.n | 0 || 1);
- let changed = false;
-
- // --- tutorial: only the current step, only if its kind (and item) match ---
- const step = currentStep(qs);
- if (step && step.kind === ev.kind && (step.item ? step.item === ev.item : true)) {
- qs.tutorial.progress = Math.min(step.count, qs.tutorial.progress + n);
- changed = true;
- if (qs.tutorial.progress >= step.count) {
- qs.tutorial.step += 1;
- qs.tutorial.progress = 0;
- if (qs.tutorial.step >= TUTORIAL_STEPS.length) {
- qs.tutorial.done = true;
- this._grantQuestReward(client, p, qs, TUTORIAL_REWARD, 'Training complete');
- } else {
- const next = TUTORIAL_STEPS[qs.tutorial.step];
- client.send('notice', { kind: 'quest', text: `Next: ${next.title}.` });
- }
- }
- }
-
- // --- dailies: every matching un-claimed quest advances together ---
- if (ev.kind === 'gather' || ev.kind === 'combat' || ev.kind === 'fish' || ev.kind === 'cook' || ev.kind === 'build') {
- for (const q of qs.daily.quests) {
- if (q.claimed) continue;
- const def = dailyDef(q.id);
- if (!def || def.type !== ev.kind) continue;
- if (def.item && def.item !== ev.item) continue;
- const before = q.progress;
- q.progress = Math.min(def.count, q.progress + n);
- if (q.progress !== before) {
- changed = true;
- if (before < def.count && q.progress >= def.count) {
- client.send('notice', { kind: 'quest', text: `Daily ready: ${def.title} — turn it in for your reward.` });
- }
- }
- }
- }
-
- if (changed) {
- p.badges = (qs.badges || []).join(',');
- this._persistPlayer(client.sessionId);
- this._sendQuests(client);
- }
- }
-
- // Claim a finished daily. Server-authoritative: refuses unless the TRACKED
- // progress meets the target and it isn't already claimed — a forged turn-in
- // for an unfinished quest does nothing. Awards 'devoted' once the whole board
- // is cleared for the day.
- _handleTurnIn(client, payload) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv || !priv.quests) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- const qs = normalizeQuestState(priv.quests, priv.playerId, Date.now());
- const q = qs.daily.quests.find((x) => x.id === String(payload?.id ?? ''));
- const def = q && dailyDef(q.id);
- if (!q || !def) return;
- if (q.claimed) { this._sendQuests(client); return; }
- if (q.progress < def.count) {
- client.send('notice', { kind: 'quest', text: `${def.title} isn't finished yet.` });
- return;
- }
- q.claimed = true;
- this._grantQuestReward(client, p, qs, def.reward, def.title);
- if (qs.daily.quests.every((x) => x.claimed)) this._awardBadge(client, p, qs, 'devoted');
- p.badges = (qs.badges || []).join(',');
- this._persistPlayer(client.sessionId);
- this._sendQuests(client);
- }
-
- // Apply a reward bundle (gold / XP / item / badge) and announce it. An item
- // reward that doesn't fit the pack spills into the bank so a reward is never
- // silently lost.
- _grantQuestReward(client, p, qs, reward, label) {
- if (!reward) return;
- const bits = [];
- if (reward.gold) { p.gold = Math.min(0xffffffff, p.gold + reward.gold); bits.push(`+${reward.gold}g`); }
- if (reward.xp) {
- for (const [skill, amt] of Object.entries(reward.xp)) {
- this._grantXp(client, p, skill, amt);
- bits.push(`+${amt} ${skill} xp`);
- }
- }
- if (reward.item) {
- const left = this._addItem(p, reward.item.id, reward.item.qty);
- if (left > 0) this._bankAdd(this.priv.get(client.sessionId).bank, reward.item.id, left);
- bits.push(`+${reward.item.qty} ${reward.item.id}`);
- }
- if (reward.badge) this._awardBadge(client, p, qs, reward.badge);
- if (bits.length) client.send('notice', { kind: 'reward', text: `${label}: ${bits.join(', ')}.` });
- }
-
- _awardBadge(client, p, qs, id) {
- if (!BADGES[id] || qs.badges.includes(id)) return;
- qs.badges.push(id);
- p.badges = qs.badges.join(',');
- client.send('notice', { kind: 'badge', text: `Badge earned: ${BADGES[id].icon} ${BADGES[id].label}.` });
- }
-
- // Send the requesting player their full quest snapshot: tutorial step (or
- // done), today's dailies with live progress + reward previews, the next-reset
- // timestamp for a real countdown, earned badges, and the guide's current line.
- // `opts.npc` set => the client opens the NPC dialog on this snapshot.
- _sendQuests(client, opts = {}) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv || !priv.quests) return;
- const now = Date.now();
- const qs = normalizeQuestState(priv.quests, priv.playerId, now);
- const badgeStr = (qs.badges || []).join(',');
- if (p.badges !== badgeStr) p.badges = badgeStr; // keep the synced field honest
-
- const step = currentStep(qs);
- const tutorial = qs.tutorial.done
- ? { done: true, total: TUTORIAL_STEPS.length }
- : {
- done: false,
- stepIndex: qs.tutorial.step,
- total: TUTORIAL_STEPS.length,
- progress: qs.tutorial.progress,
- step: step && {
- id: step.id, kind: step.kind, count: step.count, item: step.item || '',
- slot: typeof step.slot === 'number' ? step.slot : -1, title: step.title, desc: step.desc,
- },
- };
-
- const daily = {
- date: qs.daily.date,
- resetAt: nextResetAt(now),
- quests: qs.daily.quests.map((q) => {
- const def = dailyDef(q.id) || {};
- return {
- id: q.id, type: def.type, item: def.item || '', count: def.count || 0,
- title: def.title || q.id, desc: def.desc || '',
- progress: Math.min(q.progress, def.count || q.progress), claimed: !!q.claimed,
- reward: this._rewardPreview(def.reward),
- };
- }),
- };
-
- const badges = (qs.badges || []).map((id) => BADGES[id]).filter(Boolean);
- const guide = qs.tutorial.done ? GUIDE_DONE : (step?.guide || '');
-
- client.send('quests', { tutorial, daily, badges, guide, npc: opts.npc || '' });
- }
-
- // Compact, client-renderable reward summary (no server-only detail).
- _rewardPreview(reward) {
- if (!reward) return {};
- const out = {};
- if (reward.gold) out.gold = reward.gold;
- if (reward.xp) out.xp = reward.xp;
- if (reward.item) out.item = { id: reward.item.id, qty: reward.item.qty };
- if (reward.badge && BADGES[reward.badge]) {
- out.badge = { id: reward.badge, icon: BADGES[reward.badge].icon, label: BADGES[reward.badge].label };
- }
- return out;
- }
-
- // Persist the player's cross-session state through the Task 16 save interface,
- // keyed by the stable account id. Read-merge-write so we only ever own the
- // slices we manage (quests, gold, cosmetics) and never clobber other fields a
- // future system persists. Gold + owned/equipped cosmetics ride here so a
- // purchase and the look the player chose survive a disconnect/realm transfer.
- _persistPlayer(sessionId) {
- const priv = this.priv.get(sessionId);
- if (!priv || !priv.playerId) return;
- const p = this.state.players.get(sessionId);
- const prev = loadPlayer(priv.playerId) || {};
- const next = { ...prev };
- if (priv.quests) next.quests = priv.quests;
- if (p) {
- next.gold = p.gold;
- next.name = p.name;
- // Full account-scoped profile (Task 16/23): inventory, hotbar, bank,
- // skills, mount, and avatar URL so the same account loads identical
- // progression on any world instance.
- next.profile = this._serializeProfile(p, priv);
- // Last realm + tile — so a reconnecting player resumes in place rather
- // than waking at the fountain. Danger-realm positions are still saved;
- // onJoin skips restoring them so the player spawns safely instead.
- next.lastRealm = this.realm.name;
- next.lastTx = p.tx;
- next.lastTy = p.ty;
- // Placed structures (Task 07) keyed by realm so a shack in Whisperwood
- // and a firepit in Mainland both survive. Each realm's list overwrites the
- // previous save for that realm only; structures in other realms are unchanged.
- const myStructures = [];
- for (const [, s] of this.state.structures) {
- if (this._ownedBy(s, priv.playerId)) {
- myStructures.push({ kind: s.kind, tx: s.tx, ty: s.ty, expiresAt: s.expiresAt, locked: s.locked });
- }
- }
- next.structures = { ...(prev.structures || {}), [this.realm.name]: myStructures };
- }
- if (priv.cosmetics) {
- next.cosmetics = { owned: [...priv.cosmetics.owned], equipped: priv.cosmetics.equipped };
- }
- if (priv.spin) next.spin = { nextFreeSpinAt: priv.spin.nextFreeSpinAt || 0 };
- savePlayer(priv.playerId, next);
- }
-
- // ----- cosmetics shop (Task 21) ----------------------------------------
-
- // Rebuild a player's owned/equipped cosmetics from a persisted save, dropping
- // any id no longer in the catalogue (so a removed cosmetic never lingers) and
- // guaranteeing the equipped id is one the player actually owns.
- _loadCosmetics(saved) {
- const ownedIds = Array.isArray(saved?.cosmetics?.owned) ? saved.cosmetics.owned : [];
- const owned = new Set(ownedIds.filter((id) => cosmeticById(id)));
- const wanted = saved?.cosmetics?.equipped || '';
- const equipped = owned.has(wanted) ? wanted : '';
- return { owned, equipped };
- }
-
- // Send the requesting player the live shop board: the full catalogue, which
- // ids are on sale right now (split daily/weekly/always), the next-rotation
- // timestamps for real countdowns, the ids they already own, their equipped id,
- // and their current gold. Everything the shop + wardrobe render from.
- // Client 'shopOpen' request — rate-limited like any UI fetch, then emits the
- // board. The post-mutation refreshes (after buy/equip/unequip) go through
- // _emitShop directly: they are server-initiated, not client requests, so they
- // must never be dropped by the rate limiter or the UI would show stale state.
- _sendShop(client) {
- if (!this._rateOk(client.sessionId, 'ui')) return;
- this._emitShop(client);
- }
-
- _emitShop(client) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv || !priv.cosmetics) return;
- client.send('shop', {
- offers: currentOffers(Date.now()),
- owned: [...priv.cosmetics.owned],
- equipped: priv.cosmetics.equipped,
- gold: p.gold,
- });
- }
-
- // Buy a cosmetic: it must exist, be on sale in the current rotation, not be
- // already owned, and the player must have the gold. On success we debit gold,
- // grant permanent ownership, persist, and refresh the board. Every failure
- // path returns a clear notice instead of silently no-op'ing.
- _handleBuyCosmetic(client, payload) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv || !priv.cosmetics) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- const id = String(payload?.id ?? '');
- // Single source of truth for the buy rules (shared with cosmetics.test.js).
- const { ok, reason, cosmetic } = evaluatePurchase(p.gold, priv.cosmetics.owned, id, Date.now());
- if (!ok) {
- const name = cosmetic?.name || 'cosmetic';
- const text = reason === 'unknown' ? 'That cosmetic doesn’t exist.'
- : reason === 'owned' ? `You already own the ${name}.`
- : reason === 'not-offered' ? `The ${name} isn’t on sale right now.`
- : `Need ${cosmetic.price - p.gold} more gold for the ${name}.`;
- client.send('notice', { kind: 'shop', text });
- return;
- }
- p.gold -= cosmetic.price;
- priv.cosmetics.owned.add(id);
- p.tsServer = Date.now();
- this._persistPlayer(client.sessionId);
- client.send('notice', { kind: 'shop', text: `Bought the ${cosmetic.name}!` });
- this._emitShop(client);
- }
-
- // Equip an owned cosmetic — sets the synced cosmeticId so every peer renders
- // the new look, persists the choice, and refreshes the board. Equipping is
- // purely visual: it never touches gold, stats, inventory, or any gameplay
- // value. You can only equip a cosmetic you actually own.
- _handleEquipCosmetic(client, payload) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv || !priv.cosmetics) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- const id = String(payload?.id ?? '');
- if (!priv.cosmetics.owned.has(id)) {
- client.send('notice', { kind: 'shop', text: 'You don’t own that cosmetic.' });
- return;
- }
- if (priv.cosmetics.equipped === id) return;
- priv.cosmetics.equipped = id;
- p.cosmeticId = id;
- p.tsServer = Date.now();
- this._persistPlayer(client.sessionId);
- client.send('notice', { kind: 'shop', text: `Equipped the ${cosmeticById(id)?.name || 'cosmetic'}.` });
- this._emitShop(client);
- }
-
- // Revert to the default look — clears the equipped cosmetic. Always allowed
- // (no-op if nothing is equipped) and, like equipping, strictly visual.
- _handleUnequipCosmetic(client) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv || !priv.cosmetics) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- if (!priv.cosmetics.equipped) return;
- priv.cosmetics.equipped = '';
- p.cosmeticId = '';
- p.tsServer = Date.now();
- this._persistPlayer(client.sessionId);
- client.send('notice', { kind: 'shop', text: 'Reverted to your default look.' });
- this._emitShop(client);
- }
-
- // ----- marketplace (Task 20) -------------------------------------------
- //
- // A global, account-scoped player-to-player market backed by marketplaceStore
- // (durable, process-wide) so a buyer in any realm can purchase goods a seller
- // listed from anywhere. Two listing types:
- // • gold — an item stack for in-game gold; seller gets the full
- // amount, no fee. Buyer pays gold, receives the item.
- // • goldForToken — in-game gold priced in USD, paid on-chain with $THREE.
- // 95% of the token goes to the seller's wallet, 5% to the
- // treasury; the buyer receives the escrowed gold once the
- // payment is verified on-chain.
- // The offered goods are escrowed on the listing the moment it's created — they
- // leave the seller's inventory/purse immediately — so nothing can be listed and
- // spent twice. Cancel returns the escrow; a sale delivers it to the buyer.
-
- // Send the requesting player the live market board: every active listing, their
- // own listings (any status), and the token-payment capability flags the Sell
- // tab needs to decide whether goldForToken listings are offerable.
- _sendMarket(client) {
- const priv = this.priv.get(client.sessionId);
- if (!priv) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- const me = priv.playerId;
- client.send('market', {
- listings: marketplaceStore.activeListings().map((l) => this._marketView(l, me)),
- mine: marketplaceStore.listingsBySeller(me).map((l) => this._marketView(l, me)),
- token: { enabled: tokenConfigured(), symbol: TOKEN_SYMBOL, decimals: TOKEN_DECIMALS, treasuryBps: MARKET_TREASURY_BPS },
- canToken: isWalletAddress(me),
- });
- }
-
- // A client-safe projection of a listing. The seller's account id is never sent —
- // only their display name — and `mine` lets the UI badge/disable a viewer's own
- // listings on the Buy tab.
- _marketView(l, viewerId) {
- const v = {
- id: l.id,
- type: l.type,
- seller: l.sellerName || 'Trader',
- mine: l.seller === viewerId,
- status: l.status,
- createdAt: l.createdAt,
- };
- if (l.type === 'gold') { v.item = l.item; v.qty = l.qty; v.priceGold = l.priceGold; }
- else { v.goldAmount = l.goldAmount; v.priceUsd = l.priceUsd; }
- if (l.status !== 'active') { v.buyer = l.buyerName || null; v.closedAt = l.closedAt || null; }
- return v;
- }
-
- // Create a listing, escrowing the offered goods out of the seller immediately.
- _handleMarketList(client, payload) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv) return;
- if (!this._rateOk(client.sessionId, 'mkt')) return;
- const type = payload?.type === 'goldForToken' ? 'goldForToken' : 'gold';
-
- const activeCount = marketplaceStore.listingsBySeller(priv.playerId).filter((l) => l.status === 'active').length;
- if (activeCount >= MAX_LISTINGS_PER_SELLER) {
- client.send('notice', { kind: 'market', text: `You can have at most ${MAX_LISTINGS_PER_SELLER} active listings.` });
- return;
- }
-
- if (type === 'gold') {
- const item = typeof payload?.item === 'string' ? payload.item : '';
- const qty = Math.max(1, Math.min(MAX_STACK, payload?.qty | 0));
- const priceGold = Math.max(1, Math.min(MARKET_GOLD_MAX, payload?.priceGold | 0));
- if (!item || !Number.isFinite(payload?.qty) || !Number.isFinite(payload?.priceGold)) {
- client.send('notice', { kind: 'market', text: 'Pick an item, amount, and price.' });
- return;
- }
- // Escrow: pull the exact quantity out of the backpack. If the player doesn't
- // actually hold it, _removeInvItem returns what it could remove — we restore
- // it and refuse, so a listing can never escrow goods that weren't there.
- const removed = this._removeInvItem(p, item, qty);
- if (removed < qty) {
- if (removed > 0) this._addItem(p, item, removed); // put back the partial pull
- client.send('notice', { kind: 'market', text: `You don't have ${qty} ${itemLabel(item)} to list.` });
- return;
- }
- const rec = marketplaceStore.create({
- seller: priv.playerId, sellerName: p.name, type: 'gold',
- item, qty, priceGold,
- });
- p.tsServer = Date.now();
- this._persistPlayer(client.sessionId);
- client.send('notice', { kind: 'market', text: `Listed ${qty}× ${itemLabel(item)} for ${priceGold} gold.` });
- this._broadcastMarketDirty();
- this._sendMarket(client);
- return;
- }
-
- // goldForToken — list in-game gold priced in USD, settled on-chain in $THREE.
- if (!tokenConfigured()) {
- client.send('notice', { kind: 'market', text: 'Token sales are unavailable right now.' });
- return;
- }
- if (!isWalletAddress(priv.playerId)) {
- client.send('notice', { kind: 'market', text: 'Connect a wallet to sell gold for tokens.' });
- return;
- }
- const goldAmount = Math.max(1, Math.min(MARKET_GOLD_MAX, payload?.goldAmount | 0));
- const priceUsd = Number(payload?.priceUsd);
- if (!Number.isFinite(payload?.goldAmount) || !Number.isFinite(priceUsd) || priceUsd < MARKET_USD_MIN || priceUsd > MARKET_USD_MAX) {
- client.send('notice', { kind: 'market', text: `Set a gold amount and a USD price ($${MARKET_USD_MIN}–$${MARKET_USD_MAX}).` });
- return;
- }
- if (p.gold < goldAmount) {
- client.send('notice', { kind: 'market', text: `You only have ${p.gold} gold to list.` });
- return;
- }
- // Escrow the gold out of the purse now.
- p.gold -= goldAmount;
- const rec = marketplaceStore.create({
- seller: priv.playerId, sellerName: p.name, type: 'goldForToken',
- goldAmount, priceUsd: Math.round(priceUsd * 100) / 100, sellerWallet: priv.playerId,
- });
- p.tsServer = Date.now();
- this._persistPlayer(client.sessionId);
- client.send('notice', { kind: 'market', text: `Listed ${goldAmount} gold for $${rec.priceUsd} in ${TOKEN_SYMBOL}.` });
- this._broadcastMarketDirty();
- this._sendMarket(client);
- }
-
- // Cancel a listing you own and reclaim the escrow. Active listings only.
- _handleMarketCancel(client, payload) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv) return;
- if (!this._rateOk(client.sessionId, 'mkt')) return;
- const l = marketplaceStore.get(String(payload?.id ?? ''));
- if (!l || l.seller !== priv.playerId) { client.send('notice', { kind: 'market', text: 'Listing not found.' }); return; }
- if (l.status !== 'active') { client.send('notice', { kind: 'market', text: 'That listing is no longer active.' }); return; }
-
- marketplaceStore.update(l.id, { status: 'cancelled', closedAt: Date.now() });
- if (l.type === 'gold') {
- this._deliverItemsTo(p, priv, l.item, l.qty);
- client.send('notice', { kind: 'market', text: `Cancelled — ${l.qty}× ${itemLabel(l.item)} returned.` });
- } else {
- p.gold = Math.min(MARKET_GOLD_MAX, p.gold + l.goldAmount);
- client.send('notice', { kind: 'market', text: `Cancelled — ${l.goldAmount} gold returned.` });
- }
- p.tsServer = Date.now();
- this._persistPlayer(client.sessionId);
- this._broadcastMarketDirty();
- this._sendMarket(client);
- }
-
- // Buy a gold listing with in-game gold: debit the buyer, deliver the escrowed
- // item, and credit the seller the full price (no fee). Synchronous, so the
- // check-and-claim is atomic — two buyers can't both win the same listing.
- _handleMarketBuyGold(client, payload) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv) return;
- if (!this._rateOk(client.sessionId, 'mkt')) return;
- const l = marketplaceStore.get(String(payload?.id ?? ''));
- if (!l || l.type !== 'gold') { client.send('notice', { kind: 'market', text: 'Listing not found.' }); return; }
- if (l.status !== 'active') { client.send('notice', { kind: 'market', text: 'That listing was just taken.' }); return; }
- if (l.seller === priv.playerId) { client.send('notice', { kind: 'market', text: "You can't buy your own listing." }); return; }
- if (p.gold < l.priceGold) {
- client.send('notice', { kind: 'market', text: `Need ${l.priceGold - p.gold} more gold.` });
- return;
- }
- // Claim the listing before mutating balances so a duplicate buy that slips in
- // finds it already sold.
- marketplaceStore.update(l.id, { status: 'sold', buyer: priv.playerId, buyerName: p.name, closedAt: Date.now() });
- p.gold -= l.priceGold;
- this._deliverItemsTo(p, priv, l.item, l.qty);
- // Pay the seller their gold wherever they are (or queue it durably if offline).
- this._payGoldTo(l.seller, l.priceGold, `Sold ${l.qty}× ${itemLabel(l.item)}`);
- p.tsServer = Date.now();
- this._persistPlayer(client.sessionId);
- client.send('notice', { kind: 'market', text: `Bought ${l.qty}× ${itemLabel(l.item)} for ${l.priceGold} gold.` });
- // Notify the seller immediately if they're online in ANY realm.
- this._notifySellerSold(l.seller, `${p.name} bought your ${l.qty}× ${itemLabel(l.item)} for ${l.priceGold} gold.`);
- this._broadcastMarketDirty();
- this._sendMarket(client);
- }
-
- // Step 1 of an on-chain token purchase: quote the live $THREE amount for the
- // listing's USD price, build the unsigned split transaction (95% seller wallet
- // / 5% treasury) the buyer signs, and hand back a signed quote that binds the
- // amounts + recipients so the client can't tamper before settling.
- async _handleMarketTokenQuote(client, payload) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv) return;
- if (!this._rateOk(client.sessionId, 'mkt')) return;
- const id = String(payload?.id ?? '');
- // Every rejection clears the client's per-listing "Preparing…" spinner.
- const fail = (text) => { client.send('notice', { kind: 'market', text }); client.send('marketBuyFail', { id }); };
- if (!tokenConfigured()) { fail('Token payments are unavailable.'); return; }
- const buyerWallet = priv.playerId;
- if (!isWalletAddress(buyerWallet)) { fail('Connect a Solana wallet to pay with tokens.'); return; }
- const l = marketplaceStore.get(id);
- if (!l || l.type !== 'goldForToken' || l.status !== 'active') { fail('That listing is no longer available.'); return; }
- if (l.seller === buyerWallet) { fail("You can't buy your own listing."); return; }
-
- const quote = await quoteTokenForUsd(l.priceUsd);
- if (!quote) { fail('Live price unavailable — try again in a moment.'); return; }
- // Re-check the listing survived the awaited quote (it could have been bought
- // or cancelled while we fetched the price).
- const still = marketplaceStore.get(l.id);
- if (!still || still.status !== 'active') { fail('That listing is no longer available.'); return; }
-
- const { seller: sellerRaw, treasury: treasuryRaw } = splitAmount(quote.raw, MARKET_TREASURY_BPS);
- let txB64;
- try {
- txB64 = await buildSplitTransaction({
- buyerWallet, sellerWallet: l.sellerWallet,
- sellerRaw: sellerRaw.toString(), treasuryRaw: treasuryRaw.toString(),
- });
- } catch (err) {
- console.warn('[market] build split tx failed:', err?.message);
- fail('Could not prepare the payment. Try again.');
- return;
- }
- const signed = signQuote({
- listingId: l.id, buyer: buyerWallet, sellerWallet: l.sellerWallet,
- usd: l.priceUsd, total: quote.raw.toString(), sellerRaw: sellerRaw.toString(), treasuryRaw: treasuryRaw.toString(),
- });
- client.send('marketQuote', {
- id: l.id,
- tx: txB64,
- quote: signed,
- symbol: TOKEN_SYMBOL,
- decimals: TOKEN_DECIMALS,
- tokenAmount: quote.raw.toString(),
- sellerAmount: sellerRaw.toString(),
- treasuryAmount: treasuryRaw.toString(),
- priceUsd: l.priceUsd,
- goldAmount: l.goldAmount,
- ttlMs: 90_000,
- });
- }
-
- // Step 2: the buyer has broadcast the signed transaction. Verify it on-chain
- // (both legs landed at the right destinations for the quoted amounts), then
- // release the escrowed gold to the buyer. The seller was paid directly in the
- // transaction. Goods are NEVER released before the payment verifies.
- async _handleMarketTokenSettle(client, payload) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv) return;
- if (!this._rateOk(client.sessionId, 'mkt')) return;
- const q = verifyQuote(payload?.quote);
- const failId = q?.listingId || String(payload?.id ?? '');
- const fail = (text) => { client.send('notice', { kind: 'market', text }); client.send('marketBuyFail', { id: failId }); };
- if (!q) { fail('Your quote expired — get a fresh one.'); return; }
- if (q.buyer !== priv.playerId) { fail('That quote was issued to a different wallet.'); return; }
- const txSig = typeof payload?.txSig === 'string' ? payload.txSig.trim() : '';
- if (!txSig) { fail('Missing transaction signature.'); return; }
- if (marketplaceStore.isSettled(txSig)) { fail('That payment was already settled.'); return; }
-
- const l = marketplaceStore.get(q.listingId);
- if (!l || l.type !== 'goldForToken' || l.sellerWallet !== q.sellerWallet) { fail('That listing is no longer available.'); return; }
- if (l.status !== 'active') { fail('That listing is no longer available.'); return; }
- // Claim it synchronously before the async verify so a second settle can't
- // double-release the same gold. Reverted to active if verification fails.
- marketplaceStore.update(l.id, { status: 'settling' });
-
- const verify = await verifySplitPayment({
- txSig, sellerWallet: q.sellerWallet, sellerRaw: q.sellerRaw, treasuryRaw: q.treasuryRaw,
- });
- const current = marketplaceStore.get(l.id);
- if (!current || current.status !== 'settling') {
- // Cancelled/evicted out from under us mid-verify — don't release.
- fail('That listing is no longer available.');
- return;
- }
- if (!verify.ok) {
- marketplaceStore.update(l.id, { status: 'active' });
- const why = verify.reason === 'not_found' ? 'Payment not found on-chain yet — wait for confirmation and retry.'
- : verify.reason?.includes('underpaid') ? 'The payment amount did not match the quote.'
- : 'Could not verify the payment. No gold was released.';
- fail(why);
- return;
- }
- // Verified. Consume the signature, close the listing, deliver the gold.
- marketplaceStore.markSettled(txSig);
- marketplaceStore.update(l.id, { status: 'sold', buyer: priv.playerId, buyerName: p.name, txSig, closedAt: Date.now() });
- p.gold = Math.min(MARKET_GOLD_MAX, p.gold + l.goldAmount);
- p.tsServer = Date.now();
- this._persistPlayer(client.sessionId);
- client.send('marketSettled', { id: l.id, goldAmount: l.goldAmount, txSig });
- client.send('notice', { kind: 'market', text: `Paid — received ${l.goldAmount} gold.` });
- // Notify the seller that their listing sold and they were paid on-chain.
- this._notifySellerSold(l.seller, `Your ${l.goldAmount} gold listing sold to ${p.name} — ${TOKEN_SYMBOL} paid to your wallet.`);
- this._broadcastMarketDirty();
- this._sendMarket(client);
- }
-
- // ----- Wheel of Fortune (Task 19) --------------------------------------
- //
- // A 20-segment prize wheel by the Mainland casino. One free spin per account
- // every 12h, plus unlimited paid spins ($3 in $THREE, 50% burned / 50% to
- // treasury, settled on-chain). The SERVER rolls every outcome (spin-wheel.js);
- // the client only animates to the chosen segment. Spinning needs an average
- // skill level of SPIN_MIN_AVG_LEVEL and standing at the wheel.
-
- // True when the player stands on a tile adjacent (8-way) to the realm's wheel
- // landmark — the same "be at the counter" rule banking uses, so a client can't
- // spin from across the map.
- _atWheel(p) {
- const w = wheelLandmark(this.realm);
- return !!w && Math.abs(p.tx - w.tx) <= 1 && Math.abs(p.ty - w.ty) <= 1;
- }
-
- // Full spin gate (free + paid prep): the realm has a wheel, the player is at
- // it, and their average level qualifies. Returns a reason code, or null when
- // allowed. The level gate can never regress (levels only climb), so settle
- // re-checks level only — a player who paid then got nudged off the tile still
- // gets their spin.
- _spinBlockReason(p) {
- if (!wheelLandmark(this.realm)) return 'no_wheel';
- if (!this._atWheel(p)) return 'not_at_wheel';
- if (this._averageLevel(p) < SPIN_MIN_AVG_LEVEL) return 'level';
- return null;
- }
-
- // Tell the client exactly why a spin was refused, always with the fields its
- // designed states need (current/required level, free-spin countdown).
- _sendSpinDenied(client, p, priv, mode, reason) {
- client.send('spinDenied', {
- mode,
- reason,
- avgLevel: Math.round(this._averageLevel(p) * 10) / 10,
- minLevel: SPIN_MIN_AVG_LEVEL,
- nextFreeSpinAt: priv.spin.nextFreeSpinAt || 0,
- now: Date.now(),
- });
- }
-
- // Snapshot for the spinner UI: the authoritative segment table (with honest
- // odds), the player's standing against the level gate, the free-spin countdown,
- // and whether a paid spin is available (token configured + wallet connected).
- _sendSpinInfo(client) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv) return;
- if (!this._rateOk(client.sessionId, 'spin')) return;
- const avg = this._averageLevel(p);
- client.send('spinInfo', {
- segments: spinSegments(),
- avgLevel: Math.round(avg * 10) / 10,
- minLevel: SPIN_MIN_AVG_LEVEL,
- eligible: avg >= SPIN_MIN_AVG_LEVEL,
- atWheel: this._atWheel(p),
- nextFreeSpinAt: priv.spin.nextFreeSpinAt || 0,
- now: Date.now(),
- costUsd: PAID_SPIN_USD,
- symbol: TOKEN_SYMBOL,
- paidAvailable: tokenConfigured() && isWalletAddress(priv.playerId),
- });
- }
-
- // Roll one prize and grant it. Gold lands in the purse; items go to the
- // backpack and any overflow spills into a ground bag at the player's feet (the
- // same vessel mob loot uses), so a prize is never silently lost on a full pack.
- // Returns the server-decided segment + what actually landed for the client.
- _rollAndAward(client, p) {
- const roll = rollSpin();
- let awardedGold = 0, awardedQty = 0, overflow = 0;
- if (roll.kind === 'gold') {
- const before = p.gold;
- p.gold = Math.min(0xffffffff, p.gold + roll.gold);
- awardedGold = p.gold - before;
- } else {
- const left = this._addItem(p, roll.item, roll.qty);
- awardedQty = roll.qty - left;
- if (left > 0) { this._spawnLootBag(p, p.tx, p.ty, [new Slot(roll.item, left)]); overflow = left; }
- }
- p.tsServer = Date.now();
- const tail = overflow > 0 ? ` — ${overflow} waited in a bag at your feet (pack full)` : '';
- client.send('notice', { kind: 'spin', text: `The wheel landed on ${roll.label}!${tail}` });
- return {
- index: roll.index, kind: roll.kind, item: roll.item, qty: roll.qty, gold: roll.gold,
- label: roll.label, awardedGold, awardedQty, overflow,
- };
- }
-
- // Free spin: gated by level + wheel proximity + the persisted 12h cooldown.
- // The timer is consumed before the roll so the spin can't be repeated, and the
- // new nextFreeSpinAt is persisted + returned for the client's live countdown.
- _handleSpinFree(client) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv) return;
- if (!this._rateOk(client.sessionId, 'spin')) return;
- const reason = this._spinBlockReason(p);
- if (reason) { this._sendSpinDenied(client, p, priv, 'free', reason); return; }
- const now = Date.now();
- if (now < (priv.spin.nextFreeSpinAt || 0)) {
- this._sendSpinDenied(client, p, priv, 'free', 'cooldown');
- return;
- }
- priv.spin.nextFreeSpinAt = now + FREE_SPIN_COOLDOWN_MS;
- const result = this._rollAndAward(client, p);
- this._persistPlayer(client.sessionId);
- client.send('spinResult', { mode: 'free', ...result, nextFreeSpinAt: priv.spin.nextFreeSpinAt, now: Date.now() });
- }
-
- // Paid spin, step 1: price $3 in $THREE, build the 50/50 burn/treasury split
- // transaction the wallet signs, and hand back a signed quote binding the
- // amounts + destinations. No prize is rolled here — only after the payment
- // verifies at settle. Gated identically to a free spin so an ineligible player
- // can't even start paying.
- async _handleSpinPaidPrep(client) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv) return;
- if (!this._rateOk(client.sessionId, 'spin')) return;
- const reason = this._spinBlockReason(p);
- if (reason) { this._sendSpinDenied(client, p, priv, 'paid', reason); return; }
- if (!tokenConfigured()) { client.send('spinDenied', { mode: 'paid', reason: 'token_unavailable' }); return; }
- const buyerWallet = priv.playerId;
- if (!isWalletAddress(buyerWallet)) { client.send('spinDenied', { mode: 'paid', reason: 'no_wallet' }); return; }
- let prep;
- try {
- prep = await buildSpinPayment({ buyerWallet, usd: PAID_SPIN_USD });
- } catch (err) {
- console.warn('[spin] build payment failed:', err?.message);
- client.send('spinDenied', { mode: 'paid', reason: 'build_failed' });
- return;
- }
- if (!prep) { client.send('spinDenied', { mode: 'paid', reason: 'price_unavailable' }); return; }
- client.send('spinPrep', {
- tx: prep.txBase64,
- quote: prep.quoteToken,
- symbol: TOKEN_SYMBOL,
- decimals: TOKEN_DECIMALS,
- costUsd: PAID_SPIN_USD,
- tokenAmount: prep.quote.total,
- tokens: prep.quote.tokens,
- priceUsd: prep.quote.priceUsd,
- burnAmount: prep.quote.burnRaw,
- treasuryAmount: prep.quote.treasuryRaw,
- ttlMs: (prep.quote.ttlSeconds || 90) * 1000,
- });
- }
-
- // Paid spin, step 2: the wallet broadcast the signed transaction. Verify it
- // on-chain (both the burn and treasury legs landed, memo matches the quote),
- // reject replays, THEN roll + award. The free-spin timer is never touched.
- async _handleSpinPaidSettle(client, payload) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv) return;
- if (!this._rateOk(client.sessionId, 'spin')) return;
- // Level can't regress mid-flow, so re-checking it (not wheel proximity) at
- // settle keeps a paid spin valid even if the player drifted off the tile
- // while approving in their wallet — they already committed real funds.
- if (this._averageLevel(p) < SPIN_MIN_AVG_LEVEL) { this._sendSpinDenied(client, p, priv, 'paid', 'level'); return; }
- const buyerWallet = priv.playerId;
- const txSig = typeof payload?.txSig === 'string' ? payload.txSig.trim() : '';
- if (!txSig) { client.send('spinDenied', { mode: 'paid', reason: 'no_signature' }); return; }
- // Atomically claim this signature before the async RPC round-trip. If two
- // concurrent settles of the same sig both reached here, only one gets true —
- // the other sees a reservation in flight and is rejected immediately, closing
- // the TOCTOU window that existed with a plain is-settled check + later mark.
- if (!reserveSpin(txSig)) {
- client.send('spinDenied', { mode: 'paid', reason: 'already_settled' });
- return;
- }
-
- const verify = await verifySpinPayment({ quoteToken: payload?.quote, txSig, buyerWallet });
- if (!verify.ok) {
- // Release the reservation so an honest retry (e.g. tx not yet confirmed)
- // can claim it later — the payment hasn't been spent and no prize was rolled.
- releaseSpin(txSig);
- const why = verify.reason === 'not_found' ? 'not_found'
- : verify.reason?.includes('underpaid') ? 'underpaid'
- : verify.reason === 'bad_quote' ? 'quote_expired'
- : 'verify_failed';
- client.send('spinDenied', { mode: 'paid', reason: why });
- return;
- }
- // Verification passed — permanently commit so this sig can never roll again,
- // then award. Order matters: commit first, award second, persist third.
- commitSpin(txSig);
- const result = this._rollAndAward(client, p);
- this._persistPlayer(client.sessionId);
- client.send('spinResult', { mode: 'paid', ...result, txSig, nextFreeSpinAt: priv.spin.nextFreeSpinAt || 0, now: Date.now() });
- }
-
- // Credit a seller their gold proceeds. If they're online (in this room or any
- // other), the durable payout we enqueue is drained immediately via a presence
- // nudge; if they're offline it waits in the queue until their next login. Either
- // way the queue is the single source of truth, so delivery is exactly-once.
- _payGoldTo(sellerId, gold, reason) {
- marketplaceStore.enqueuePayout(sellerId, { gold, reason });
- try { this.presence.publish(payoutChannel(sellerId), { ts: Date.now() }); } catch {}
- // Fast path: if the seller is in THIS room, draining now avoids a round-trip
- // through pub/sub (and covers presence backends that don't echo to the
- // publishing process).
- for (const [sid, pr] of this.priv) {
- if (pr.playerId === sellerId) { this._drainMarketPayouts(sid); break; }
- }
- }
-
- // Deliver all queued marketplace proceeds for a session's account: gold into the
- // purse, items into the backpack (overflow to the bank, then re-queued if even
- // the bank is full so nothing is ever lost). Atomic drain — whether triggered by
- // a login or a live nudge, each payout is applied exactly once.
- _drainMarketPayouts(sessionId) {
- const p = this.state.players.get(sessionId);
- const priv = this.priv.get(sessionId);
- if (!p || !priv) return;
- const payouts = marketplaceStore.drainPayouts(priv.playerId);
- if (!payouts.length) return;
- let goldGained = 0;
- const itemsGained = [];
- for (const po of payouts) {
- if (po.gold) {
- const before = p.gold;
- p.gold = Math.min(MARKET_GOLD_MAX, p.gold + (po.gold | 0));
- goldGained += p.gold - before;
- }
- if (Array.isArray(po.items)) {
- for (const it of po.items) {
- if (it && it.item && it.qty > 0) {
- // Use the no-nudge delivery so a bank-full re-queue doesn't loop.
- const left = this._stowItem(p, priv, it.item, it.qty);
- const placed = it.qty - left;
- if (placed > 0) itemsGained.push({ item: it.item, qty: placed });
- if (left > 0) marketplaceStore.enqueuePayout(priv.playerId, { items: [{ item: it.item, qty: left }], reason: 'overflow' });
- }
- }
- }
- }
- p.tsServer = Date.now();
- this._persistPlayer(sessionId);
- const c = this._clientFor(sessionId);
- if (c && (goldGained > 0 || itemsGained.length)) {
- c.send('marketPayout', { gold: goldGained, items: itemsGained });
- }
- }
-
- // Tell every client in this room their open market panel is stale so it
- // refetches. Cross-room/realm panels refresh on their own open + poll; this just
- // keeps same-room browsers live as listings appear and sell.
- _broadcastMarketDirty() {
- this.broadcast('marketDirty', {});
- }
-
- // Notify a seller that one of their listings sold. If they're in THIS room, send
- // the notice directly and push a fresh market board so "My Listings" updates live.
- // If they're in a different room, the pub/sub payout nudge already woke them up;
- // we additionally send a presence-channel notice so any realm can reach them.
- _notifySellerSold(sellerId, text) {
- if (!sellerId) return;
- // Try the fast path: seller is in this very room.
- for (const [sid, pr] of this.priv) {
- if (pr.playerId !== sellerId) continue;
- const c = this._clientFor(sid);
- if (c) {
- c.send('notice', { kind: 'market', text });
- this._sendMarket(c);
- }
- return;
- }
- // Seller is online in another realm — publish a cross-room notification.
- // The channel name mirrors evictChannel; the other room's payout subscriber
- // already wakes them for gold delivery. For token sales (no payout queue)
- // we publish on the payout channel anyway so they receive a notice toast.
- try { this.presence.publish(payoutChannel(sellerId), { ts: Date.now(), notice: text }); } catch {}
- }
-
- // ----- marketplace item helpers ----------------------------------------
-
- // Remove up to `qty` of `item` from the backpack, emptying slots as they drain.
- // Returns the quantity actually removed (< qty if the player didn't have enough).
- _removeInvItem(p, item, qty) {
- let need = qty;
- for (const s of p.inv) {
- if (need <= 0) break;
- if (s.item !== item) continue;
- const take = Math.min(s.qty, need);
- s.qty -= take;
- need -= take;
- if (s.qty <= 0) { s.item = ''; s.qty = 0; }
- }
- return qty - need;
- }
-
- // Place items into the backpack, overflowing to the bank, returning whatever
- // still didn't fit. No side effects beyond inventory/bank — used by the payout
- // drainer where re-queueing (not a nudge) handles a true overflow.
- _stowItem(p, priv, item, qty) {
- let left = this._addItem(p, item, qty);
- if (left > 0 && priv?.bank) left = this._bankAdd(priv.bank, item, left);
- return left;
- }
-
- // Deliver listing escrow back to a player on cancel / to a buyer on a gold sale:
- // backpack first, then bank, then a durable payout so a full inventory never
- // destroys the goods.
- _deliverItemsTo(p, priv, item, qty) {
- const left = this._stowItem(p, priv, item, qty);
- if (left > 0) {
- marketplaceStore.enqueuePayout(priv.playerId, { items: [{ item, qty: left }], reason: 'overflow' });
- const c = this._clientFor(p.id);
- if (c) c.send('notice', { kind: 'market', text: `${left}× ${itemLabel(item)} saved — your bags are full; claim it when you have room.` });
- }
- }
-
- // ----- inventory / hotbar ----------------------------------------------
-
- _handleInvMove(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p) return;
- if (this.priv.get(client.sessionId)?.transferring) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- const from = this._resolveSlot(p, payload?.from);
- const to = this._resolveSlot(p, payload?.to);
- if (!from || !to) return;
- // Swap (or merge stacks of the same stackable item).
- const a = from.slot;
- const b = to.slot;
- if (a === b) return;
- if (a.item && a.item === b.item && STACKABLE.has(a.item)) {
- const room = MAX_STACK - b.qty;
- const moved = Math.min(room, a.qty);
- b.qty += moved;
- a.qty -= moved;
- if (a.qty === 0) a.item = '';
- } else {
- const ti = b.item, tq = b.qty;
- b.item = a.item; b.qty = a.qty;
- a.item = ti; a.qty = tq;
- }
- p.tsServer = Date.now();
- }
-
- _handleEquip(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p) return;
- if (this.priv.get(client.sessionId)?.transferring) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- const i = payload?.slot | 0;
- if (i < -1 || i >= HOTBAR_SIZE) return;
- p.activeSlot = i;
- p.tsServer = Date.now();
- }
-
- // `ref` is { zone: 'inv'|'hotbar', i } — resolves to the live Slot object.
- _resolveSlot(p, ref) {
- if (!ref || typeof ref !== 'object') return null;
- const i = ref.i | 0;
- if (ref.zone === 'inv' && i >= 0 && i < INV_SIZE) return { slot: p.inv[i] };
- if (ref.zone === 'hotbar' && i >= 0 && i < HOTBAR_SIZE) return { slot: p.hotbar[i] };
- return null;
- }
-
- // ----- banking ---------------------------------------------------------
-
- _handleBank(client, payload, dir) {
- const p = this.state.players.get(client.sessionId);
- if (!p) return;
- if (this.priv.get(client.sessionId)?.transferring) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- // Must be standing on a bank-counter tile.
- if (!this.realm.bankZone.some((t) => t.tx === p.tx && t.ty === p.ty)) {
- client.send('notice', { kind: 'bank', text: 'Stand at the bank counter to use storage.' });
- return;
- }
- const priv = this.priv.get(client.sessionId);
- const i = payload?.i | 0;
- const qty = Math.max(1, payload?.qty | 0 || 1);
-
- if (dir === 'deposit') {
- if (i < 0 || i >= INV_SIZE) return;
- const slot = p.inv[i];
- if (!slot.item) return;
- const move = Math.min(qty, slot.qty);
- const left = this._bankAdd(priv.bank, slot.item, move);
- const deposited = move - left;
- slot.qty -= deposited;
- if (slot.qty === 0) slot.item = '';
- // Tutorial: stashing an item teaches the bank. Only count a real deposit.
- if (deposited > 0) this._questProgress(client, { kind: 'bank', n: 1 });
- } else {
- if (i < 0 || i >= BANK_SIZE) return;
- const bslot = priv.bank[i];
- if (!bslot.item) return;
- const move = Math.min(qty, bslot.qty);
- const left = this._addItem(p, bslot.item, move);
- const withdrawn = move - left;
- bslot.qty -= withdrawn;
- if (bslot.qty === 0) bslot.item = '';
- }
- p.tsServer = Date.now();
- this._sendBank(client);
- }
-
- _sendBank(client) {
- const priv = this.priv.get(client.sessionId);
- if (!priv) return;
- client.send('bank', { slots: priv.bank });
- }
-
- // Swap avatar mid-session (e.g. a guest avatar finishing its background upload
- // on /play, or a player changing look without rejoining). Rate-limited as a UI
- // action and host-validated like the join-time avatar.
- _handleAvatar(client, payload) {
- const p = this.state.players.get(client.sessionId);
- if (!p) return;
- if (!this._rateOk(client.sessionId, 'ui')) return;
- const url = cleanAvatarUrl(payload?.avatar);
- if (url) p.cosmetic = url;
- }
-
- _bankAdd(bank, item, qty) {
- let left = qty;
- if (STACKABLE.has(item)) {
- for (const s of bank) {
- if (left <= 0) break;
- if (s.item === item && s.qty < MAX_STACK) {
- const room = MAX_STACK - s.qty;
- const m = Math.min(room, left);
- s.qty += m; left -= m;
- }
- }
- }
- while (left > 0) {
- const empty = bank.find((s) => !s.item);
- if (!empty) break;
- const m = STACKABLE.has(item) ? Math.min(MAX_STACK, left) : 1;
- empty.item = item; empty.qty = m; left -= m;
- }
- return left;
- }
-
- // ----- shared helpers --------------------------------------------------
-
- // Add an item to the player's backpack. Returns the leftover quantity that
- // didn't fit (0 means everything was stored).
- _addItem(p, item, qty) {
- let left = qty;
- if (STACKABLE.has(item)) {
- for (const s of p.inv) {
- if (left <= 0) break;
- if (s.item === item && s.qty < MAX_STACK) {
- const room = MAX_STACK - s.qty;
- const m = Math.min(room, left);
- s.qty += m; left -= m;
- }
- }
- while (left > 0) {
- const empty = p.inv.find((s) => !s.item);
- if (!empty) break;
- const m = Math.min(MAX_STACK, left);
- empty.item = item; empty.qty = m; left -= m;
- }
- } else {
- while (left > 0) {
- const empty = p.inv.find((s) => !s.item);
- if (!empty) break;
- empty.item = item; empty.qty = 1; left -= 1;
- }
- }
- return left;
- }
-
- _grantXp(client, p, skill, amount) {
- const priv = this.priv.get(client.sessionId);
- if (!priv) return;
- priv.xp[skill] = (priv.xp[skill] || 0) + amount;
- const xp = priv.xp[skill];
- const lvl = levelForXp(xp);
- // Tell the earner immediately: how much they got, their new cumulative XP,
- // and the current level boundaries so the client can delta-patch its bar
- // without a round-trip 'skills' request. Raw XP stays private (never in schema).
- const maxed = lvl >= LEVEL_CAP;
- client.send('xpgain', {
- skill,
- amount,
- xp,
- level: lvl,
- levelXp: xpForLevel(lvl),
- nextXp: maxed ? null : xpForLevel(lvl + 1),
- });
- // XP only accumulates, so a changed level is always a level-up.
- if (lvl > p[skill]) {
- p[skill] = lvl;
- client.send('levelup', { skill, level: lvl });
- }
- }
-
- // Reply to a 'skills' request with the requesting player's own XP detail: per
- // skill, the level plus the cumulative XP boundaries of the current level so
- // the client can draw an exact progress bar. Raw XP is never broadcast to
- // peers — it only ever travels back to its owner here.
- _sendSkills(client) {
- const p = this.state.players.get(client.sessionId);
- const priv = this.priv.get(client.sessionId);
- if (!p || !priv) return;
- const skills = {};
- for (const skill of SKILLS) {
- const level = p[skill];
- const xp = priv.xp[skill] || 0;
- const floorXp = xpForLevel(level);
- const maxed = level >= LEVEL_CAP;
- skills[skill] = {
- level,
- xp,
- levelXp: floorXp, // cumulative XP at the start of the current level
- nextXp: maxed ? null : xpForLevel(level + 1), // cumulative XP for next level
- };
- }
- client.send('skills', {
- cap: LEVEL_CAP,
- skills,
- total: this._totalLevel(p),
- average: this._averageLevel(p),
- });
- }
-
- // Authoritative average skill level — the mean of all five skill levels.
- // Returned precisely (a float) so callers choose their own rounding: a gate
- // can floor it (e.g. `Math.floor(avg) >= 20`) while the UI shows one decimal.
- // Reused by Task 19's spin gate and any future average-level content gate.
- _averageLevel(p) {
- return this._totalLevel(p) / SKILLS.length;
- }
-
- _totalLevel(p) {
- let sum = 0;
- for (const s of SKILLS) sum += p[s];
- return sum;
- }
-
- // Authoritative combat level — the input every combat-level gate reads (Task 11).
- // Combat is its own trainable skill here, so the combat level IS that level; the
- // helper keeps the gate logic from reaching into the schema field directly, so a
- // future composite combat formula can change in exactly one place.
- _combatLevel(p) {
- return p.combat;
- }
-
- // Does the player clear a portal's gate? Today the only gate kind is a combat
- // floor; an unknown/empty gate never blocks (fail-open on shape, never on level).
- _meetsGate(p, gate) {
- if (!gate) return true;
- if (Number.isFinite(gate.combat) && this._combatLevel(p) < gate.combat) return false;
- return true;
- }
-
- _adjacent(p, obj) {
- return Math.abs(p.tx - obj.tx) <= 1 && Math.abs(p.ty - obj.ty) <= 1;
- }
-
- _rateOk(sessionId, action) {
- const priv = this.priv.get(sessionId);
- if (!priv) return false;
- const limit = RATE_LIMITS[action] || 10;
- const now = Date.now();
- let bucket = priv.rate.get(action);
- if (!bucket || now - bucket.windowStart > 1000) {
- bucket = { windowStart: now, count: 0 };
- priv.rate.set(action, bucket);
- }
- bucket.count++;
- return bucket.count <= limit;
- }
-
- // ----- simulation tick -------------------------------------------------
-
- _tick() {
- const now = Date.now();
-
- // Periodic profile autosave (Task 16/23). Most saves ride real events
- // (quest progress, gold/cosmetic changes, portal/leave), but a player who
- // only fishes or cooks could go a while without one — so flush every live
- // session about every 20s. Cheap (a few small objects into the store) and it
- // bounds how much progress a hard crash could cost. The leave/eviction paths
- // still save synchronously for the common case.
- if (++this._saveTick >= 80) {
- this._saveTick = 0;
- for (const sid of this.priv.keys()) this._persistPlayer(sid);
- }
-
- // Resource + mob respawns.
- for (const [, n] of this.state.nodes) {
- if (n.depleted && now >= n.respawnAt) {
- n.depleted = false;
- n.respawnAt = 0;
- }
- }
- for (const [, m] of this.state.mobs) {
- if (m.dead && now >= m.respawnAt) {
- m.dead = false;
- m.hp = m.maxHp;
- m.respawnAt = 0;
- // Respawn back at the home tile, disengaged — never re-materialize
- // mid-chase wherever it happened to fall.
- const ai = this._mobAI?.get(m.id);
- if (ai) { m.tx = ai.homeTx; m.ty = ai.homeTy; ai.nextMoveAt = 0; ai.attackReadyAt = 0; }
- m.aggroId = '';
- }
- }
-
- // Expire crumbled death-bags.
- for (const [id, t] of this.state.tombstones) {
- if (now >= t.expiresAt) this.state.tombstones.delete(id);
- }
-
- // Player-built structures (Task 07): decay first, so a firepit never heals on
- // the same tick it burns out, then collect the live firepits for the heal pass.
- const firepits = [];
- for (const [id, s] of this.state.structures) {
- if (s.expiresAt && now >= s.expiresAt) { this.state.structures.delete(id); continue; }
- if (s.kind === 'firepit') firepits.push(s);
- }
-
- // Player healing + respawn — keyed to THIS realm's spawn/fountain, plus any
- // player-built firepit a player is standing beside.
- const fountain = this.realm.fountain;
- for (const [, p] of this.state.players) {
- if (p.dead) {
- if (now >= p.respawnAt) {
- p.dead = false;
- p.hp = p.maxHp;
- p.motion = 'idle';
- p.tx = this.realm.spawn.tx;
- p.ty = this.realm.spawn.ty;
- p.tsServer = now;
- }
- continue;
- }
- if (p.hp < p.maxHp) {
- const nearFountain =
- !!fountain && Math.abs(p.tx - fountain.tx) <= 3 && Math.abs(p.ty - fountain.ty) <= 3;
- // A firepit heals players directly adjacent to it (8-way), at the
- // fountain's rate — a portable campfire heal.
- const nearFire = firepits.some((s) => Math.abs(p.tx - s.tx) <= 1 && Math.abs(p.ty - s.ty) <= 1);
- p.hp = Math.min(p.maxHp, p.hp + (nearFountain || nearFire ? FOUNTAIN_HEAL_PER_TICK : REGEN_PER_TICK));
- }
- }
-
- // Mob AI: roamers wander, hostiles acquire/chase/hit nearby players. Runs on
- // the sim tick so the player scan never touches the patch rate.
- this._mobTick(now);
-
- // Moving floor (Arena rollers): on its own slower cadence, shove every living
- // player who is standing on a roller one tile in the strip's direction. The
- // push is server-authoritative and respects walkability — it never moves a
- // player through a wall, onto a node/mob, off the map, or onto a portal tile
- // (rollers carry you around the floor; they never trigger a realm transfer).
- if (this.realm.rollers && now - (this._rollerAt || 0) >= ROLLER_PUSH_MS) {
- this._rollerAt = now;
- this._rollPlayers(now);
- }
- }
-
- // One roller push pass. Each player's destination is resolved against THIS
- // tick's occupancy, so two players can't be shoved onto the same tile in a way
- // that desyncs from walkability — the second simply isn't moved this push.
- _rollPlayers(now) {
- for (const [sid, p] of this.state.players) {
- if (p.dead) continue;
- if (this.priv.get(sid)?.transferring) continue;
- const roller = rollerAt(this.realm, p.tx, p.ty);
- if (!roller) continue;
- const [dx, dy] = rollerDelta(roller.dir);
- if (!dx && !dy) continue;
- const nx = p.tx + dx, ny = p.ty + dy;
- if (!this._isWalkable(nx, ny)) continue; // pushed against a wall/occupant — hold position
- if (portalAt(this.realm, nx, ny)) continue; // never roll a player through a portal
- p.tx = nx;
- p.ty = ny;
- p.motion = 'walk';
- p.tsServer = now;
- }
- }
-
- // ----- mob AI (Task 03) ------------------------------------------------
-
- // Chebyshev (king-move) tile distance — matches 8-way movement.
- _cheb(a, b) { return Math.max(Math.abs(a.tx - b.tx), Math.abs(a.ty - b.ty)); }
-
- // Contact damage a mob deals, by kind, with a little variance.
- _mobDamage(kind) {
- const base = MOB_BASE_DAMAGE[kind] ?? 4;
- return base <= 0 ? 0 : base + Math.floor(Math.random() * 4);
- }
-
- // Can a mob legally stand on (tx, ty)? Same walkability as players (bounds,
- // blocked, nodes, living mobs, structures, npcs) plus: never inside a safe
- // camp / seating, never on a portal tile, never on top of a living player
- // (mobs attack from an adjacent tile).
- _mobCanStand(tx, ty) {
- if (!this._isWalkable(tx, ty)) return false;
- if (inNoPvpZone(this.realm, tx, ty)) return false;
- if (portalAt(this.realm, tx, ty)) return false;
- for (const [, pl] of this.state.players) {
- if (!pl.dead && pl.tx === tx && pl.ty === ty) return false;
- }
- return true;
- }
-
- // One greedy 8-way step toward (gx, gy), routing around obstacles and never
- // stepping beyond the leash radius from home. Returns true if the mob moved.
- _stepMobToward(mob, gx, gy, ai) {
- const dx = Math.sign(gx - mob.tx);
- const dy = Math.sign(gy - mob.ty);
- if (!dx && !dy) return false;
- // Candidate steps, best-first: straight toward, then single-axis, then the
- // two perpendicular slides that round a corner.
- const cands = [];
- if (dx && dy) cands.push([dx, dy]);
- if (dx) cands.push([dx, 0]);
- if (dy) cands.push([0, dy]);
- if (dx && dy) { cands.push([dx, -dy]); cands.push([-dx, dy]); }
- else if (dx) { cands.push([dx, 1]); cands.push([dx, -1]); }
- else { cands.push([1, dy]); cands.push([-1, dy]); }
- const home = { tx: ai.homeTx, ty: ai.homeTy };
- for (const [sx, sy] of cands) {
- const nx = mob.tx + sx, ny = mob.ty + sy;
- if (this._cheb({ tx: nx, ty: ny }, home) > MOB_LEASH_RADIUS) continue;
- // No diagonal corner-cut between two blocked tiles (mirrors the player rule).
- if (sx !== 0 && sy !== 0 && !this._isWalkable(mob.tx + sx, mob.ty) && !this._isWalkable(mob.tx, mob.ty + sy)) continue;
- if (!this._mobCanStand(nx, ny)) continue;
- mob.tx = nx; mob.ty = ny;
- return true;
- }
- return false;
- }
-
- // One random step to an adjacent walkable tile within the roam radius of home.
- _stepMobRandom(mob, ai) {
- const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]];
- const home = { tx: ai.homeTx, ty: ai.homeTy };
- const start = Math.floor(Math.random() * dirs.length);
- for (let i = 0; i < dirs.length; i++) {
- const [sx, sy] = dirs[(start + i) % dirs.length];
- const nx = mob.tx + sx, ny = mob.ty + sy;
- if (this._cheb({ tx: nx, ty: ny }, home) > MOB_ROAM_RADIUS) continue;
- if (sx !== 0 && sy !== 0 && !this._isWalkable(mob.tx + sx, mob.ty) && !this._isWalkable(mob.tx, mob.ty + sy)) continue;
- if (!this._mobCanStand(nx, ny)) continue;
- mob.tx = nx; mob.ty = ny;
- return true;
- }
- return false;
- }
-
- // Server-authoritative mob simulation. Acquisition/validation runs every sim
- // tick; movement + attacks are gated to MOB_MOVE_MS / MOB_ATTACK_COOLDOWN_MS so
- // the motion reads deliberately and CPU stays bounded.
- _mobTick(now) {
- if (!this._mobAI || this._mobAI.size === 0) return;
- const home = (ai) => ({ tx: ai.homeTx, ty: ai.homeTy });
- for (const [, mob] of this.state.mobs) {
- if (mob.dead) continue;
- const ai = this._mobAI.get(mob.id);
- if (!ai || (!ai.roam && !ai.aggro)) continue; // inert dummies never move
-
- // Slow regen while disengaged so a mob you fled from recovers.
- if (!mob.aggroId && mob.hp < mob.maxHp) {
- mob.hp = Math.min(mob.maxHp, mob.hp + MOB_REGEN_PER_TICK);
- }
-
- // Validate the current target; drop it if it died, left, reached a safe
- // zone, or pulled the mob past its leash.
- let target = mob.aggroId ? this.state.players.get(mob.aggroId) : null;
- if (target) {
- const drop =
- target.dead ||
- this.priv.get(mob.aggroId)?.transferring ||
- inNoPvpZone(this.realm, target.tx, target.ty) ||
- this._cheb(mob, home(ai)) > MOB_LEASH_RADIUS ||
- this._cheb(mob, target) > MOB_AGGRO_RADIUS + 3;
- if (drop) { target = null; mob.aggroId = ''; }
- }
-
- // Acquire the nearest eligible player when idle and still near home.
- if (!target && ai.aggro && this._cheb(mob, home(ai)) <= MOB_LEASH_RADIUS) {
- let bestSid = '', bestDist = Infinity;
- for (const [sid, p] of this.state.players) {
- if (p.dead) continue;
- if (this.priv.get(sid)?.transferring) continue;
- if (inNoPvpZone(this.realm, p.tx, p.ty)) continue;
- const d = this._cheb(mob, p);
- if (d <= MOB_AGGRO_RADIUS && d < bestDist) { bestDist = d; bestSid = sid; }
- }
- if (bestSid) { mob.aggroId = bestSid; target = this.state.players.get(bestSid); }
- }
-
- if (now < ai.nextMoveAt) continue; // pace movement/attacks
-
- if (target) {
- if (this._adjacent(mob, target)) {
- if (now >= ai.attackReadyAt) {
- ai.attackReadyAt = now + MOB_ATTACK_COOLDOWN_MS;
- const dmg = this._mobDamage(mob.kind);
- const fatal = this._damagePlayer(target, dmg, { by: mob.id, byName: mob.kind });
- // Tell the victim's client so it can flash + float a damage number.
- const c = this._clientFor(mob.aggroId);
- if (c) { try { c.send('hit', { byKind: mob.kind, dmg, hp: target.hp, fatal }); } catch {} }
- }
- } else {
- this._stepMobToward(mob, target.tx, target.ty, ai);
- }
- ai.nextMoveAt = now + MOB_MOVE_MS;
- continue;
- }
-
- // No target: walk home if displaced, otherwise wander (roamers only).
- if (this._cheb(mob, home(ai)) > 1) {
- this._stepMobToward(mob, ai.homeTx, ai.homeTy, ai);
- } else if (ai.roam && Math.random() < MOB_ROAM_CHANCE) {
- this._stepMobRandom(mob, ai);
- }
- ai.nextMoveAt = now + MOB_MOVE_MS;
- }
- }
-}
diff --git a/multiplayer/src/rooms/commands.js b/multiplayer/src/rooms/commands.js
deleted file mode 100644
index caffe11c3..000000000
--- a/multiplayer/src/rooms/commands.js
+++ /dev/null
@@ -1,173 +0,0 @@
-// Chat slash-command registry + router (Task 13).
-//
-// Single source of truth for the documented player commands. GameRoom._handleChat
-// forwards any chat line that begins with '/' to runCommand(), which parses the
-// command + args, resolves the name (or an alias), validates it exists, and
-// dispatches to its handler — returning a result the caller sees as a system
-// message. Unknown commands return a helpful error with a "did you mean" hint.
-//
-// /help is GENERATED from this registry, so it can never drift from the real
-// command set. /who reads the live realm roster (state.players). The stateful
-// actions (pickup/lock/unlock/dismount) live on the GameRoom because they mutate
-// synced state; the registry invokes them through ctx.room so the room stays the
-// single authority over mutation.
-//
-// ctx = { room, client, player }
-// handler(ctx, args) -> { text, kind } | string | null
-// null → the handler already sent its own reply (e.g. /dismount's notice);
-// the router sends nothing further.
-// kind → styles the client bubble: 'info' (default) | 'error' | 'help' | 'who'.
-
-export const COMMANDS = [
- {
- name: 'help',
- aliases: ['commands', 'h', '?'],
- args: '',
- desc: 'List the commands you can use',
- run: () => ({ text: formatHelp(), kind: 'help' }),
- },
- {
- name: 'who',
- aliases: ['players', 'online'],
- args: '',
- desc: 'List the players in your realm',
- run: (ctx) => ({ text: formatWho(ctx), kind: 'who' }),
- },
- {
- name: 'pickup',
- aliases: ['take'],
- args: '',
- desc: 'Pick up your firepit or shack you are standing beside',
- run: (ctx) => ctx.room.pickupStructure(ctx.player),
- },
- {
- name: 'lock',
- aliases: [],
- args: '',
- desc: 'Lock the structure beside you against stray clicks',
- run: (ctx) => ctx.room.setStructureLock(ctx.player, true),
- },
- {
- name: 'unlock',
- aliases: [],
- args: '',
- desc: 'Unlock the structure beside you',
- run: (ctx) => ctx.room.setStructureLock(ctx.player, false),
- },
- {
- name: 'dismount',
- aliases: ['unmount'],
- args: '',
- desc: 'Climb down from your mount',
- // Reuse the room's dismount action (shared with the dismount button); it
- // sends its own notice, so the router adds no second reply.
- run: (ctx) => { ctx.room._handleDismount(ctx.client); return null; },
- },
-];
-
-// Client-facing manifest of the registry: just the data the chat autocomplete
-// needs (signature + aliases + description), never the server-side `run`
-// handlers. Sent once on join so the client hint list is the SAME source of
-// truth as /help — it can never drift from the real command set.
-export function commandManifest() {
- return COMMANDS.map((c) => ({
- name: c.name,
- args: c.args || '',
- aliases: c.aliases.slice(),
- desc: c.desc,
- }));
-}
-
-// Resolve a name or alias (case-insensitive) to its command, or null.
-function resolve(name) {
- const n = String(name || '').toLowerCase();
- return COMMANDS.find((c) => c.name === n || c.aliases.includes(n)) || null;
-}
-
-// Nearest command for a "did you mean" hint on a typo. Small registry, so a plain
-// Levenshtein over the names is more than fast enough.
-function suggest(name) {
- const n = String(name || '').toLowerCase();
- let best = null, bestD = Infinity;
- for (const c of COMMANDS) {
- const d = editDistance(n, c.name);
- if (d < bestD) { bestD = d; best = c.name; }
- }
- return best && bestD <= Math.max(2, Math.ceil(best.length / 2)) ? best : null;
-}
-
-function editDistance(a, b) {
- const m = a.length, n = b.length;
- const row = Array.from({ length: n + 1 }, (_, i) => i);
- for (let i = 1; i <= m; i++) {
- let prev = row[0];
- row[0] = i;
- for (let j = 1; j <= n; j++) {
- const tmp = row[j];
- row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
- prev = tmp;
- }
- }
- return row[n];
-}
-
-// Build /help from the registry so it always matches the real command set. Names
-// are padded to a common width so the descriptions line up as a scannable column.
-function formatHelp() {
- const width = COMMANDS.reduce((w, c) => Math.max(w, c.name.length + (c.args ? c.args.length + 1 : 0)), 0);
- const lines = COMMANDS.map((c) => {
- const sig = '/' + c.name + (c.args ? ' ' + c.args : '');
- return ' ' + sig.padEnd(width + 1) + ' ' + c.desc;
- });
- return 'Commands\n' + lines.join('\n');
-}
-
-// /who — real realm occupancy. Each GameRoom is a single realm, so state.players
-// IS the realm roster. The caller is marked and the list is sorted for stability.
-function formatWho(ctx) {
- const realm = cap(ctx.room.state.realm || 'realm');
- const rows = [];
- for (const [id, p] of ctx.room.state.players) {
- rows.push({ name: p.name || 'guest', me: id === ctx.client.sessionId });
- }
- rows.sort((a, b) => (a.me === b.me ? a.name.localeCompare(b.name) : a.me ? -1 : 1));
- const n = rows.length;
- const head = `${n} ${n === 1 ? 'player' : 'players'} in ${realm}`;
- const list = rows.map((r) => ' • ' + r.name + (r.me ? ' (you)' : '')).join('\n');
- return head + (list ? '\n' + list : '');
-}
-
-function cap(s) {
- return String(s || '').replace(/^\w/, (m) => m.toUpperCase());
-}
-
-// Parse + dispatch a raw chat line beginning with '/'. The room has already
-// rate-limited and looked up the player. Returns { text, kind } for the caller to
-// ship as a system message, or null when the handler already replied itself.
-export function runCommand(ctx, raw) {
- const without = String(raw || '').trim().replace(/^\//, '');
- const parts = without.split(/\s+/).filter(Boolean);
- const name = (parts.shift() || '').toLowerCase();
-
- if (!name) return { text: 'Type a command after the slash — try /help.', kind: 'error' };
-
- const cmd = resolve(name);
- if (!cmd) {
- const hint = suggest(name);
- return {
- text: `Unknown command /${name}.` + (hint ? ` Did you mean /${hint}?` : '') + ' Type /help for the list.',
- kind: 'error',
- };
- }
-
- let result;
- try {
- result = cmd.run(ctx, parts);
- } catch (err) {
- console.error(`[commands] /${cmd.name} threw:`, err);
- return { text: `Something went wrong running /${cmd.name}.`, kind: 'error' };
- }
- if (result == null) return null; // handler replied itself
- if (typeof result === 'string') return { text: result, kind: 'info' };
- return { text: String(result.text ?? ''), kind: result.kind || 'info' };
-}
diff --git a/multiplayer/src/rooms/realm-transfer.js b/multiplayer/src/rooms/realm-transfer.js
deleted file mode 100644
index 991d25eb0..000000000
--- a/multiplayer/src/rooms/realm-transfer.js
+++ /dev/null
@@ -1,160 +0,0 @@
-// Realm-transfer tokens — the trust boundary for portal traversal.
-//
-// When a player steps onto a portal, the source GameRoom snapshots their full
-// state (inventory, hotbar, bank, gold, skills, hp, cosmetic) and reserves a
-// seat in the destination realm room. The snapshot can't ride along as plain
-// join options: a client could call client.joinOrCreate('game', { realm, carry })
-// directly and mint gold or items out of thin air. So we seal the snapshot into
-// an HMAC-SHA256 token here — identical construction to holder-pass.js — and the
-// destination room refuses any carry that isn't signed with the shared secret.
-//
-// The token is short-lived (TTL below): a transfer is consumed within a couple
-// of network round-trips, so a long window only widens the replay surface (e.g.
-// banking a token at high gold, spending, then replaying to restore it).
-
-import crypto from 'node:crypto';
-
-const DEV_SECRET = 'three-ws-realm-transfer-dev-secret';
-const TTL_SECONDS = 60; // a transfer is consumed in milliseconds; 60s covers any reconnect hiccup
-
-let _warned = false;
-function secret() {
- // Prefer a dedicated secret, but fall back to the holder-pass secret so a
- // single env var secures both gates in the common single-secret deployment.
- const s = process.env.REALM_TRANSFER_SECRET || process.env.HOLDER_PASS_SECRET;
- if (s) return s;
- if (process.env.NODE_ENV === 'production') {
- throw new Error(
- '[realm-transfer] REALM_TRANSFER_SECRET (or HOLDER_PASS_SECRET) is required in production — ' +
- 'refusing to sign transfers with the dev secret.',
- );
- }
- if (!_warned) {
- _warned = true;
- console.warn(
- '[realm-transfer] no REALM_TRANSFER_SECRET/HOLDER_PASS_SECRET set — using the insecure dev secret. ' +
- 'Set one in production or portal carries can be forged.',
- );
- }
- return DEV_SECRET;
-}
-
-function b64url(buf) {
- return Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
-}
-function b64urlDecode(str) {
- return Buffer.from(str.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
-}
-function hmac(body) {
- return b64url(crypto.createHmac('sha256', secret()).update(body).digest());
-}
-function safeEqual(a, b) {
- const ba = Buffer.from(a);
- const bb = Buffer.from(b);
- if (ba.length !== bb.length) return false;
- return crypto.timingSafeEqual(ba, bb);
-}
-
-// Single-use guard. A transfer token seals a full carry snapshot (gold, items,
-// bank, skills) and is otherwise replayable for its whole TTL — letting a player
-// transfer at high gold, spend/bank it, then replay the same token to restore the
-// snapshot and dupe the difference. So every token carries a random nonce (`jti`)
-// and the destination room consumes it on arrival; a nonce seen twice is rejected.
-// This shared map is the single source of truth across every room in the process
-// (a portal handoff lands in a different GameRoom instance), mirroring the
-// spin-wheel/marketplace replay guards. Entries are swept after a TTL beyond the
-// token window so the set never grows unbounded. (Horizontal scale would back this
-// with the same Redis the presence/profile layers use; the interface is unchanged.)
-const _consumedNonces = new Map(); // jti -> consumedAt (ms)
-const NONCE_TTL_MS = (TTL_SECONDS + 30) * 1000; // cover the token window + clock skew
-
-/**
- * Atomically consume a transfer nonce. Returns true the first time a given nonce
- * is presented (the carry may be applied) and false on every subsequent attempt
- * within the TTL (a replay — the carry must be ignored). Synchronous, so two joins
- * racing the same token can't both win. A falsy nonce is rejected outright so an
- * old token minted before nonces existed can never apply a carry.
- * @param {unknown} jti
- * @returns {boolean}
- */
-export function consumeTransferNonce(jti) {
- if (typeof jti !== 'string' || !jti) return false;
- const now = Date.now();
- const prev = _consumedNonces.get(jti);
- if (prev !== undefined && now - prev <= NONCE_TTL_MS) return false; // already used
- _consumedNonces.set(jti, now);
- return true;
-}
-
-// Sweep expired nonces so a long-lived process doesn't accumulate them forever.
-setInterval(() => {
- const now = Date.now();
- for (const [jti, at] of _consumedNonces) if (now - at > NONCE_TTL_MS) _consumedNonces.delete(jti);
-}, NONCE_TTL_MS).unref?.();
-
-/**
- * Seal a portal transfer into a signed token.
- * @param {{ to: string, tx: number, ty: number, carry: object, account: string }} payload
- * @returns {string} `${base64url(body)}.${signature}`
- */
-export function signTransfer(payload) {
- const now = Math.floor(Date.now() / 1000);
- const body = b64url(
- JSON.stringify({
- to: payload.to,
- tx: payload.tx,
- ty: payload.ty,
- carry: payload.carry,
- // The verified account that minted this transfer (a play-pass wallet or a
- // server-signed guest id). A portal handoff is a trusted server-to-server
- // seat reservation that carries no play pass / guest token, so the
- // destination room's onAuth re-binds the account from this signed field —
- // the only path by which an account is trusted without a fresh pass/token.
- account: payload.account,
- // Random single-use id so the destination room can reject a replayed token
- // even within its TTL. Bound to the signature, so it can't be swapped.
- jti: crypto.randomBytes(16).toString('hex'),
- iat: now,
- exp: now + TTL_SECONDS,
- }),
- );
- return `${body}.${hmac(body)}`;
-}
-
-/**
- * Verify a transfer token and return its payload, or null if missing, malformed,
- * tampered with, or expired.
- * @param {unknown} token
- * @returns {{ to: string, tx: number, ty: number, carry: object, iat: number, exp: number } | null}
- */
-export function verifyTransfer(token) {
- if (typeof token !== 'string' || token.length < 16 || token.length > 65536) return null;
- const dot = token.indexOf('.');
- if (dot <= 0) return null;
- const body = token.slice(0, dot);
- const sig = token.slice(dot + 1);
- if (!safeEqual(sig, hmac(body))) return null;
-
- let payload;
- try {
- payload = JSON.parse(b64urlDecode(body));
- } catch {
- return null;
- }
- if (!payload || typeof payload !== 'object') return null;
- if (typeof payload.to !== 'string' || !payload.to) return null;
- if (!Number.isFinite(payload.tx) || !Number.isFinite(payload.ty)) return null;
- if (!payload.carry || typeof payload.carry !== 'object') return null;
- // Every legitimate token carries a single-use nonce; its absence means a forged
- // or pre-nonce token, which must not be honoured.
- if (typeof payload.jti !== 'string' || !payload.jti) return null;
- // The minting account rides along so the destination can re-bind it across the
- // passless handoff; require it so an old/forged token can't land account-less.
- if (typeof payload.account !== 'string' || !payload.account) return null;
-
- const now = Date.now() / 1000;
- if (typeof payload.exp !== 'number' || payload.exp < now) return null;
- if (typeof payload.iat !== 'number' || payload.iat > now + 60) return null;
- if (payload.exp - payload.iat > TTL_SECONDS + 5) return null;
- return payload;
-}
diff --git a/multiplayer/src/rooms/realms.js b/multiplayer/src/rooms/realms.js
deleted file mode 100644
index 218a76ee4..000000000
--- a/multiplayer/src/rooms/realms.js
+++ /dev/null
@@ -1,600 +0,0 @@
-// Realm definitions — the authoritative maps the GameRoom validates against.
-// The client renders the SAME data (sent on join), so the visual world and the
-// walkable world never drift apart. Coordinates are tile indices.
-//
-// Every realm shares one shape:
-// { name, grid, spawn:{tx,ty}, safe:bool, pvp:bool, danger:bool,
-// blocked:[{x0,y0,x1,y1}], water:[{x0,y0,x1,y1}], bankZone:[{tx,ty}],
-// fountain:{tx,ty}|null, nodes:[{id,kind,tx,ty}],
-// mobs:[{id,kind,tx,ty,hp,roam,aggro}], fishing:[{tx,ty,quality}],
-// cooking:[{tx,ty}], safeCamp:{x0,y0,x1,y1}|null,
-// structures:['firepit'|'shack'], portals:[{x0,y0,x1,y1,to,toTx,toTy}] }
-//
-// `structures` lists which player-built structure kinds this realm permits. A
-// firepit (temporary healing) is allowed wherever building makes sense; the
-// shack (permanent landmark) is Whisperwood-only by design.
-//
-// `water` rects are a visual subset of `blocked` (non-walkable, rendered as
-// water on the client). `fishing` tiles are walkable shore spots beside water,
-// each carrying a `quality` multiplier that scales catch rate + yield.
-//
-// `danger` realms drop a tombstone on death. `pvp` realms allow player combat
-// outside any safeCamp. Resource node ids must be unique WITHIN a realm.
-//
-// A few realms carry extra fields beyond the shared shape:
-// • `cave: true` — render as an enclosed cavern (dark rock) not open sky.
-// • `ring: {x0,y0,x1,y1}`— a practice boxing ring: a walkable, purely-cosmetic
-// platform (no death risk) drawn with ropes + posts.
-// • `seating: [{x0,y0,x1,y1}]` — spectator stands: walkable NO-PvP zones (like a
-// mobile safeCamp) so onlookers aren't dragged into a fight.
-// • `rollers: [{x0,y0,x1,y1,dir}]` — moving-floor strips. On the sim tick the
-// server pushes any player standing on one tile in `dir`
-// ('n'|'s'|'e'|'w'), respecting walkability — learn-the-
-// flow movement, never a teleport.
-// A portal may carry `gate: { combat }` — entry is refused until the player's
-// combat level meets the threshold (the server checks it before the handoff).
-
-function nodesFrom(coords, kind, prefix) {
- return coords.map(([tx, ty], i) => ({ id: `${prefix}${i}`, kind, tx, ty }));
-}
-function tiles(coords) {
- return coords.map(([tx, ty]) => ({ tx, ty }));
-}
-// Fishing shore spots with a per-tile catch-quality multiplier (1 = average).
-// Higher quality = better catch rate and a higher chance of a double haul.
-function fishSpots(coords, quality = 1) {
- return coords.map(([tx, ty]) => ({ tx, ty, quality }));
-}
-
-// ---------------------------------------------------------------- Mainland
-const MAINLAND = {
- name: 'mainland',
- grid: 48,
- spawn: { tx: 24, ty: 30 },
- safe: true, pvp: false, danger: false,
- blocked: [
- { x0: 8, y0: 8, x1: 12, y1: 11 }, // bank building
- { x0: 23, y0: 23, x1: 24, y1: 24 }, // fountain
- { x0: 31, y0: 38, x1: 34, y1: 41 }, // the millpond (water — also in `water` below)
- { x0: 27, y0: 13, x1: 30, y1: 15 }, // Fortune's Folly casino (landmark — see `landmarks`)
- { x0: 28, y0: 17, x1: 28, y1: 17 }, // the Wheel of Fortune (interactable — players stand adjacent)
- ],
- water: [
- { x0: 31, y0: 38, x1: 34, y1: 41 }, // the millpond, fishable from its banks
- ],
- fountain: { tx: 23, ty: 23 },
- bankZone: tiles([[8, 12], [9, 12], [10, 12], [11, 12], [12, 12]]),
- // Fixed, interactable characters. Aldric the Guide stands just off the spawn
- // and drives the tutorial + daily-quest turn-ins. NPCs occupy their tile
- // (players stand adjacent to talk), validated like resource nodes.
- npcs: [
- { id: 'aldric', name: 'Aldric the Guide', kind: 'guide', tx: 26, ty: 29 },
- ],
- // Fixed world landmarks (Task 19). A `casino` is a decorative building (its
- // footprint is in `blocked` above); a `wheel` is interactable — the client
- // renders it, a click walks the player adjacent, and standing beside it opens
- // the Wheel of Fortune. The wheel's own tile is blocked so players approach it
- // from an adjacent tile, exactly like the bank counter or an NPC.
- landmarks: [
- { id: 'fortunes-folly', kind: 'casino', tx: 28, ty: 14, label: "Fortune's Folly" },
- { id: 'wheel', kind: 'wheel', tx: 28, ty: 17, label: 'Wheel of Fortune' },
- ],
- nodes: [
- ...nodesFrom([[12, 28], [14, 30], [16, 29], [13, 33], [15, 35], [11, 31], [18, 34], [20, 30],
- [17, 37], [19, 38], [10, 36], [22, 36], [8, 30], [9, 33], [21, 40], [13, 40]], 'tree', 't'),
- ...nodesFrom([[34, 14], [36, 16], [38, 13], [40, 15], [35, 18], [39, 18], [42, 12], [33, 16]], 'rock', 'r'),
- ...nodesFrom([[37, 20], [41, 20], [34, 21], [39, 22]], 'coal', 'c'),
- ],
- mobs: [
- { id: 'd0', kind: 'dummy', tx: 36, ty: 34, hp: 50, roam: false, aggro: false },
- { id: 'd1', kind: 'dummy', tx: 38, ty: 34, hp: 50, roam: false, aggro: false },
- { id: 'd2', kind: 'dummy', tx: 37, ty: 36, hp: 50, roam: false, aggro: false },
- // Loot mobs (Task 09): a docile monster glade in the SE so mounts are
- // obtainable on the hub today. roam/aggro stay false — even once mob AI
- // (Task 03) lands, these stand their ground and never harass the safe town.
- { id: 'gm0', kind: 'goblin', tx: 41, ty: 32, hp: 34, roam: false, aggro: false },
- { id: 'gm1', kind: 'goblin', tx: 44, ty: 34, hp: 34, roam: false, aggro: false },
- { id: 'gm2', kind: 'goblin', tx: 42, ty: 38, hp: 34, roam: false, aggro: false },
- { id: 'om0', kind: 'ogre', tx: 44, ty: 39, hp: 80, roam: false, aggro: false },
- ],
- // Millpond banks — a calm starter spot (average quality) so a fresh player can
- // learn the cast on the Mainland before the richer realms open up.
- fishing: fishSpots([
- [30, 38], [30, 39], [30, 40], [30, 41], // west bank
- [35, 38], [35, 39], [35, 40], [35, 41], // east bank
- [31, 37], [32, 37], [33, 37], [34, 37], // north bank
- [31, 42], [32, 42], [33, 42], [34, 42], // south bank
- ], 1.0),
- cooking: [],
- safeCamp: null,
- // The Arena plaza: a practice boxing ring (cosmetic, walkable, zero death risk
- // since the Mainland is `safe`) beside the portal into the full Arena. A fresh
- // fighter can learn footwork in the ring before stepping through to real PvP.
- ring: { x0: 6, y0: 16, x1: 10, y1: 20 },
- structures: ['firepit'],
- portals: [
- { x0: 23, y0: 0, x1: 25, y1: 0, to: 'wilderness', toTx: 20, toTy: 36 }, // north → wilderness safe camp
- { x0: 23, y0: 47, x1: 25, y1: 47, to: 'whisperwood', toTx: 20, toTy: 2 }, // south → whisperwood
- { x0: 47, y0: 23, x1: 47, y1: 25, to: 'pond', toTx: 2, toTy: 18 }, // east → pond
- // Mine entrance — a cave mouth cut into the rocky NE hills, just north of
- // the surface ore field. Steps down into the enclosed `mine` interior; the
- // mine's return portal lands the player back at (43,11), a tile clear of
- // this rect so they don't immediately bounce back in.
- { x0: 43, y0: 9, x1: 44, y1: 9, to: 'mine', toTx: 16, toTy: 28 }, // NE → mine interior
- // Arena gate — a stone archway on the plaza just north-west of the ring. Steps
- // into the dedicated PvP Arena; its return strip lands the player at (12,21),
- // a tile clear of this rect (and beside the ring) so they don't bounce back in.
- { x0: 12, y0: 14, x1: 13, y1: 14, to: 'arena', toTx: 14, toTy: 24 }, // plaza → arena
- ],
-};
-
-// ---------------------------------------------------------------- Wilderness
-const WILDERNESS = {
- name: 'wilderness',
- grid: 40,
- spawn: { tx: 20, ty: 36 },
- safe: false, pvp: true, danger: true,
- blocked: [],
- water: [],
- fountain: null,
- bankZone: [],
- nodes: [
- ...nodesFrom([[10, 20], [14, 16], [26, 18], [30, 22], [8, 12], [32, 14], [18, 10], [22, 24]], 'tree', 't'),
- ...nodesFrom([[12, 8], [28, 8], [34, 20], [6, 24], [16, 6]], 'rock', 'r'),
- ...nodesFrom([[24, 6], [30, 10], [9, 17]], 'coal', 'c'),
- ],
- mobs: [
- { id: 'g0', kind: 'goblin', tx: 14, ty: 22, hp: 34, roam: true, aggro: true },
- { id: 'g1', kind: 'goblin', tx: 24, ty: 20, hp: 34, roam: true, aggro: true },
- { id: 'g2', kind: 'goblin', tx: 18, ty: 14, hp: 34, roam: true, aggro: true },
- { id: 'g3', kind: 'goblin', tx: 30, ty: 16, hp: 34, roam: true, aggro: true },
- { id: 'o0', kind: 'ogre', tx: 20, ty: 8, hp: 80, roam: true, aggro: true },
- ],
- fishing: [],
- cooking: [],
- // southern fenced safe camp: no PvP, mobs won't enter.
- safeCamp: { x0: 14, y0: 32, x1: 26, y1: 39 },
- structures: ['firepit'],
- portals: [
- { x0: 19, y0: 39, x1: 21, y1: 39, to: 'mainland', toTx: 24, toTy: 2 }, // south → mainland
- // North trail into the smaller, fully-PvP Wilderness North (no safe camp up
- // there). Lands at its southern return tile.
- { x0: 19, y0: 0, x1: 21, y1: 0, to: 'wilderness_north', toTx: 16, toTy: 28 }, // north → wilderness north
- // East trail into the full-size Wilderness East. Lands just inside its west edge.
- { x0: 39, y0: 18, x1: 39, y1: 20, to: 'wilderness_east', toTx: 2, toTy: 19 }, // east → wilderness east
- ],
-};
-
-// ---------------------------------------------------------------- Whisperwood
-const WHISPERWOOD = {
- name: 'whisperwood',
- grid: 40,
- spawn: { tx: 20, ty: 3 },
- safe: true, pvp: false, danger: false,
- blocked: [
- { x0: 20, y0: 18, x1: 21, y1: 18 }, // forest pool (north)
- { x0: 10, y0: 35, x1: 11, y1: 35 }, // brook (southwest)
- { x0: 30, y0: 36, x1: 31, y1: 36 }, // brook (southeast)
- ],
- water: [
- { x0: 20, y0: 18, x1: 21, y1: 18 },
- { x0: 10, y0: 35, x1: 11, y1: 35 },
- { x0: 30, y0: 36, x1: 31, y1: 36 },
- ],
- fountain: null,
- bankZone: [],
- nodes: [
- ...nodesFrom([[8, 10], [10, 14], [12, 9], [14, 16], [16, 12], [9, 20], [13, 24], [17, 22],
- [24, 10], [28, 14], [26, 20], [30, 18], [22, 26], [32, 24], [11, 30], [27, 28], [19, 32], [23, 34]], 'tree', 't'),
- ...nodesFrom([[34, 10], [6, 26], [35, 30], [7, 33]], 'rock', 'r'),
- ],
- mobs: [],
- // Shaded woodland pools — modest quality vs. the open pond.
- fishing: fishSpots([[20, 17], [21, 17], [19, 19], [22, 19], [10, 34], [11, 34], [30, 35], [31, 35]], 0.9),
- cooking: [],
- safeCamp: null,
- structures: ['firepit', 'shack'],
- portals: [
- { x0: 19, y0: 0, x1: 21, y1: 0, to: 'mainland', toTx: 24, toTy: 45 }, // north → mainland
- ],
-};
-
-// ---------------------------------------------------------------- Pond
-const POND = {
- name: 'pond',
- grid: 36,
- spawn: { tx: 3, ty: 18 },
- safe: true, pvp: false, danger: false,
- blocked: [
- { x0: 14, y0: 12, x1: 22, y1: 22 }, // the large pond (water, non-walkable)
- ],
- water: [
- { x0: 14, y0: 12, x1: 22, y1: 22 }, // open water — the richest fishing in the world
- ],
- fountain: null,
- bankZone: [],
- nodes: [
- ...nodesFrom([[6, 6], [9, 9], [27, 8], [30, 12], [7, 26], [28, 26], [11, 29], [25, 30]], 'tree', 't'),
- ],
- mobs: [],
- // fishable shoreline around the open pond — deep water, the best yields anywhere.
- fishing: fishSpots([
- [13, 14], [13, 16], [13, 18], [13, 20], [23, 14], [23, 16], [23, 18], [23, 20],
- [15, 11], [17, 11], [19, 11], [21, 11], [15, 23], [17, 23], [19, 23], [21, 23],
- ], 1.3),
- cooking: tiles([[10, 18], [11, 18], [10, 19], [11, 19]]), // the Roast Pit
- safeCamp: null,
- structures: ['firepit'],
- portals: [
- { x0: 0, y0: 17, x1: 0, y1: 19, to: 'mainland', toTx: 45, toTy: 24 }, // west → mainland
- // A narrow trail off the pond's quiet north shore crosses into the perils of
- // Wilderness East — leaving the safe pond for a full PvP+danger realm. Lands at
- // its southern edge.
- { x0: 17, y0: 0, x1: 19, y1: 0, to: 'wilderness_east', toTx: 19, toTy: 37 }, // north → wilderness east
- ],
-};
-
-// ---------------------------------------------------------------- Mine
-// An enclosed cave interior reached through the Mainland mine entrance. It is a
-// Mainland-side resource area, so it is `safe` (no PvP, no death-bags) — a place
-// to mine in peace. There is no bank or fountain down here; you carry your haul
-// back up to the Mainland bank. The edge is fully walled; thin interior ridges
-// and pillars split it into an upper and a lower chamber joined by three gaps,
-// giving the space a cave read without trapping any node. The mine is a markedly
-// better mining spot than the surface by DENSITY: ~27 rock + ~12 coal nodes
-// versus the Mainland's 8 + 4. Respawn timers stay the shared defaults
-// (NODE_RULES in GameRoom), so the edge is "more to mine, less waiting" rather
-// than faster individual nodes — better without trivializing progression.
-const MINE = {
- name: 'mine',
- grid: 32,
- cave: true, // enclosed interior — rendered as a dark cavern, like the wilderness cave
- spawn: { tx: 16, ty: 28 }, // just inside the entrance, on the central corridor
- safe: true, pvp: false, danger: false,
- blocked: [
- // Cave shell — a one-tile rock wall around the whole interior, with a
- // three-tile gap at the bottom (x15..17) for the entrance/return opening.
- { x0: 0, y0: 0, x1: 31, y1: 0 }, // north wall
- { x0: 0, y0: 1, x1: 0, y1: 31 }, // west wall
- { x0: 31, y0: 1, x1: 31, y1: 31 }, // east wall
- { x0: 1, y0: 31, x1: 14, y1: 31 }, // south wall (west of the mouth)
- { x0: 18, y0: 31, x1: 30, y1: 31 }, // south wall (east of the mouth)
- // Central ridge dividing the upper and lower chambers, broken by three
- // gaps (x1..3 left, x14..17 centre, x28..30 right) so both chambers and
- // the entrance corridor stay connected.
- { x0: 4, y0: 11, x1: 13, y1: 12 },
- { x0: 18, y0: 11, x1: 27, y1: 12 },
- // Pillars in the lower chamber — cover to mine around.
- { x0: 8, y0: 19, x1: 9, y1: 21 },
- { x0: 22, y0: 19, x1: 23, y1: 21 },
- // Short stubs in the upper chamber for a rougher cave outline.
- { x0: 13, y0: 4, x1: 13, y1: 6 },
- { x0: 19, y0: 4, x1: 19, y1: 6 },
- ],
- water: [],
- fountain: null,
- bankZone: [],
- nodes: [
- // Upper chamber.
- ...nodesFrom([[3, 3], [6, 2], [9, 4], [12, 3], [15, 3], [21, 3], [24, 2], [28, 4],
- [5, 7], [10, 8], [25, 7], [29, 8]], 'rock', 'r'),
- ...nodesFrom([[7, 5], [18, 4], [27, 5], [14, 8]], 'coal', 'cu'),
- // Lower chamber.
- ...nodesFrom([[3, 14], [6, 16], [11, 14], [14, 15], [19, 14], [24, 15], [28, 16],
- [4, 24], [12, 25], [20, 24], [26, 25], [8, 27], [24, 27], [3, 29], [29, 28]], 'rock', 'rl'),
- ...nodesFrom([[5, 18], [12, 20], [18, 18], [21, 20], [27, 21], [9, 25], [17, 22], [25, 28]], 'coal', 'cl'),
- ],
- mobs: [],
- fishing: [],
- cooking: [],
- safeCamp: null,
- structures: [], // a working mine, not a campsite — no player building down here
- portals: [
- // Return to the Mainland mine entrance. Lands at (43,11), a tile clear of
- // the Mainland entrance rect (y=9) so stepping out doesn't bounce back in.
- { x0: 15, y0: 31, x1: 17, y1: 31, to: 'mainland', toTx: 43, toTy: 11 },
- ],
-};
-
-// ---------------------------------------------------------------- Wilderness North
-// A smaller, harsher spur reached from the top of the main Wilderness. The whole
-// map is PvP — there is NO safe camp anywhere up here. Mob density is lower than
-// the main Wilderness (fewer foes, but nowhere to catch your breath). At the far
-// north a crag-flanked cave mouth holds a combat-LEVEL-GATED passage: only a
-// hardened fighter (combat ≥ the portal's gate) may step through into the cave.
-const WILDERNESS_NORTH = {
- name: 'wilderness_north',
- grid: 32,
- spawn: { tx: 16, ty: 28 }, // southern return tile, just inside the trail from the main Wilderness
- safe: false, pvp: true, danger: true,
- blocked: [
- // Crags flanking the northern cave mouth — they frame the gated passage at
- // x15..16 and read the far north as a rocky dead-end but for the cave.
- { x0: 8, y0: 0, x1: 14, y1: 1 },
- { x0: 17, y0: 0, x1: 23, y1: 1 },
- ],
- water: [],
- fountain: null,
- bankZone: [],
- nodes: [
- ...nodesFrom([[9, 12], [22, 10], [6, 20], [25, 18]], 'tree', 't'),
- ...nodesFrom([[12, 6], [20, 6], [7, 8]], 'rock', 'r'),
- ...nodesFrom([[15, 8]], 'coal', 'c'),
- ],
- // Lower density than the main Wilderness (5 mobs): two goblins and a lone ogre.
- mobs: [
- { id: 'g0', kind: 'goblin', tx: 12, ty: 16, hp: 34, roam: true, aggro: true },
- { id: 'g1', kind: 'goblin', tx: 22, ty: 14, hp: 34, roam: true, aggro: true },
- { id: 'o0', kind: 'ogre', tx: 16, ty: 10, hp: 80, roam: true, aggro: true },
- ],
- fishing: [],
- cooking: [],
- safeCamp: null, // no refuge — PvP across the whole map
- structures: ['firepit'],
- portals: [
- { x0: 15, y0: 31, x1: 17, y1: 31, to: 'wilderness', toTx: 20, toTy: 2 }, // south → main Wilderness top
- // The gated cave mouth. Entry needs combat ≥ 20; the server refuses an
- // under-level step with a notice and the player simply stays put.
- { x0: 15, y0: 0, x1: 16, y1: 0, to: 'wilderness_cave', toTx: 14, toTy: 24, gate: { combat: 20 } }, // far north → cave (gated)
- ],
-};
-
-// ---------------------------------------------------------------- Wilderness Cave
-// The level-gated cavern beyond the northern gate — its own enclosed instance.
-// Reaching it at all means you cleared the combat gate, so the danger is steep:
-// trolls and ogres prowl a rich ore seam. PvP + danger like the open wilds, but
-// underground (rendered as a dark cavern). A single passage south returns to
-// Wilderness North.
-const WILDERNESS_CAVE = {
- name: 'wilderness_cave',
- grid: 28,
- cave: true,
- spawn: { tx: 14, ty: 24 }, // arrival tile, just north of the return passage
- safe: false, pvp: true, danger: true,
- blocked: [
- // Cave shell — a one-tile rock wall around the whole interior.
- { x0: 0, y0: 0, x1: 27, y1: 0 },
- { x0: 0, y0: 1, x1: 0, y1: 27 },
- { x0: 27, y0: 1, x1: 27, y1: 27 },
- { x0: 1, y0: 27, x1: 26, y1: 27 },
- // Central ridge splitting upper/lower chambers, broken by a centre gap (x11..16).
- { x0: 4, y0: 12, x1: 10, y1: 13 },
- { x0: 17, y0: 12, x1: 23, y1: 13 },
- // Pillars — cover to fight and mine around.
- { x0: 7, y0: 18, x1: 8, y1: 19 },
- { x0: 19, y0: 18, x1: 20, y1: 19 },
- ],
- water: [],
- fountain: null,
- bankZone: [],
- nodes: [
- ...nodesFrom([[3, 3], [7, 2], [12, 3], [16, 3], [21, 2], [24, 4], [5, 8], [22, 8], [10, 9], [18, 9]], 'rock', 'r'),
- ...nodesFrom([[9, 4], [14, 6], [19, 5], [4, 22], [23, 22], [13, 16]], 'coal', 'c'),
- ],
- // Steep: two ogres, a troll, and a pair of goblins. All roam + aggro.
- mobs: [
- { id: 'tr0', kind: 'troll', tx: 14, ty: 8, hp: 140, roam: true, aggro: true },
- { id: 'o0', kind: 'ogre', tx: 6, ty: 6, hp: 80, roam: true, aggro: true },
- { id: 'o1', kind: 'ogre', tx: 22, ty: 16, hp: 80, roam: true, aggro: true },
- { id: 'g0', kind: 'goblin', tx: 9, ty: 20, hp: 34, roam: true, aggro: true },
- { id: 'g1', kind: 'goblin', tx: 18, ty: 22, hp: 34, roam: true, aggro: true },
- ],
- fishing: [],
- cooking: [],
- safeCamp: null,
- structures: [],
- portals: [
- { x0: 13, y0: 26, x1: 15, y1: 26, to: 'wilderness_north', toTx: 15, toTy: 2 }, // south passage → Wilderness North
- ],
-};
-
-// ---------------------------------------------------------------- Wilderness East
-// A full-size wild expanse east of the main Wilderness, also reachable off the
-// Pond's north shore. PvP + danger like the Wilderness, with the same kind of
-// roaming foes and scattered resources, but no safe camp — the whole map is open.
-const WILDERNESS_EAST = {
- name: 'wilderness_east',
- grid: 40,
- spawn: { tx: 4, ty: 20 },
- safe: false, pvp: true, danger: true,
- blocked: [],
- water: [],
- fountain: null,
- bankZone: [],
- nodes: [
- ...nodesFrom([[10, 8], [16, 12], [24, 10], [30, 16], [8, 24], [34, 26], [20, 30], [28, 34], [14, 34]], 'tree', 't'),
- ...nodesFrom([[12, 18], [26, 22], [33, 12], [9, 32], [22, 6]], 'rock', 'r'),
- ...nodesFrom([[18, 24], [31, 30], [15, 6]], 'coal', 'c'),
- ],
- mobs: [
- { id: 'g0', kind: 'goblin', tx: 14, ty: 16, hp: 34, roam: true, aggro: true },
- { id: 'g1', kind: 'goblin', tx: 26, ty: 14, hp: 34, roam: true, aggro: true },
- { id: 'g2', kind: 'goblin', tx: 20, ty: 26, hp: 34, roam: true, aggro: true },
- { id: 'g3', kind: 'goblin', tx: 32, ty: 22, hp: 34, roam: true, aggro: true },
- { id: 'o0', kind: 'ogre', tx: 22, ty: 18, hp: 80, roam: true, aggro: true },
- ],
- fishing: [],
- cooking: [],
- safeCamp: null,
- structures: ['firepit'],
- portals: [
- { x0: 0, y0: 18, x1: 0, y1: 20, to: 'wilderness', toTx: 37, toTy: 19 }, // west → main Wilderness east edge
- { x0: 17, y0: 39, x1: 19, y1: 39, to: 'pond', toTx: 18, toTy: 2 }, // south → Pond north shore
- ],
-};
-
-// ---------------------------------------------------------------- Arena
-// A dedicated PvP scene reached from the Mainland plaza. PvP is on, but it is NOT
-// a `danger` realm — death here costs no items (a sporting bout, not the wilds);
-// you simply respawn at the south gate. The floor carries moving ROLLERS that
-// shove a standing fighter one tile per push in their direction — read the flow,
-// use it, or get walked into your opponent's reach. SEATING along both flanks is a
-// no-PvP spectator zone. A south strip returns to the Mainland plaza.
-const ARENA = {
- name: 'arena',
- grid: 28,
- spawn: { tx: 14, ty: 24 }, // south gate, on the return strip's doorstep
- safe: false, pvp: true, danger: false,
- blocked: [
- // Arena bowl wall — a solid ring around the whole floor (the south return
- // strip is an interior portal tile, so no gap is needed in the wall).
- { x0: 0, y0: 0, x1: 27, y1: 0 },
- { x0: 0, y0: 1, x1: 0, y1: 27 },
- { x0: 27, y0: 1, x1: 27, y1: 27 },
- { x0: 0, y0: 27, x1: 27, y1: 27 },
- ],
- water: [],
- fountain: null,
- bankZone: [],
- nodes: [],
- mobs: [],
- fishing: [],
- cooking: [],
- safeCamp: null,
- structures: [],
- // Spectator stands down the east and west flanks — walkable, but no PvP can be
- // dealt to or from anyone standing in them (enforced server-side alongside safeCamp).
- seating: [
- { x0: 1, y0: 6, x1: 3, y1: 21 },
- { x0: 24, y0: 6, x1: 26, y1: 21 },
- ],
- // A closed clockwise loop of moving floor — 34 tiles, no gaps at the corners.
- // Each corner tile is owned by the strip that needs to push TOWARD the next
- // strip, so a fighter circling the belt stays on it indefinitely:
- //
- // (8,10) east ──────────────► (18,10)
- // ↑ ↓ right col south y10→15
- // (8,11→16) (19,10→16)
- // left col north ↓ (19,16) bot belt west starts here
- // (8,16) ◄───────────── (9,16)
- //
- // Transition points:
- // (18,10) east → (19,10) right col south ✓
- // (19,15) south → (19,16) bot belt west ✓
- // (9,16) west → (8,16) left col north ✓
- // (8,11) north → (8,10) top belt east ✓
- rollers: [
- { x0: 8, y0: 10, x1: 18, y1: 10, dir: 'e' }, // top belt x8→18
- { x0: 19, y0: 10, x1: 19, y1: 15, dir: 's' }, // right col y10→15 (owns top-right corner)
- { x0: 9, y0: 16, x1: 19, y1: 16, dir: 'w' }, // bottom belt x9→19 (owns bot-right corner)
- { x0: 8, y0: 11, x1: 8, y1: 16, dir: 'n' }, // left col y11→16 (owns bot-left corner)
- ],
- portals: [
- { x0: 12, y0: 26, x1: 15, y1: 26, to: 'mainland', toTx: 12, toTy: 21 }, // south strip → Mainland plaza
- ],
-};
-
-export const REALMS = {
- mainland: MAINLAND,
- wilderness: WILDERNESS,
- whisperwood: WHISPERWOOD,
- pond: POND,
- mine: MINE,
- wilderness_north: WILDERNESS_NORTH,
- wilderness_cave: WILDERNESS_CAVE,
- wilderness_east: WILDERNESS_EAST,
- arena: ARENA,
-};
-
-export const DEFAULT_REALM = 'mainland';
-
-export function inBounds(realm, tx, ty) {
- return tx >= 0 && ty >= 0 && tx < realm.grid && ty < realm.grid;
-}
-
-export function isBlocked(realm, tx, ty) {
- for (const r of realm.blocked) {
- if (tx >= r.x0 && tx <= r.x1 && ty >= r.y0 && ty <= r.y1) return true;
- }
- return false;
-}
-
-export function portalAt(realm, tx, ty) {
- for (const p of realm.portals) {
- if (tx >= p.x0 && tx <= p.x1 && ty >= p.y0 && ty <= p.y1) return p;
- }
- return null;
-}
-
-export function inRect(rect, tx, ty) {
- return rect && tx >= rect.x0 && tx <= rect.x1 && ty >= rect.y0 && ty <= rect.y1;
-}
-
-// The realm's spin-wheel landmark (Task 19), or null if this realm has none.
-// The GameRoom uses its tile for the "stand adjacent to spin" check.
-export function wheelLandmark(realm) {
- return (realm.landmarks || []).find((l) => l.kind === 'wheel') || null;
-}
-
-export function inAnyRect(rects, tx, ty) {
- if (!rects) return false;
- for (const r of rects) if (inRect(r, tx, ty)) return true;
- return false;
-}
-
-// Unit tile delta for a roller's push direction. Unknown directions don't move.
-const ROLLER_DELTA = { n: [0, -1], s: [0, 1], e: [1, 0], w: [-1, 0] };
-export function rollerDelta(dir) {
- return ROLLER_DELTA[dir] || [0, 0];
-}
-
-// The roller whose footprint covers (tx,ty), or null. The first match wins where
-// strips overlap, so a corner belongs to whichever strip is listed first.
-export function rollerAt(realm, tx, ty) {
- for (const r of realm.rollers || []) {
- if (inRect(r, tx, ty)) return r;
- }
- return null;
-}
-
-// True if (tx,ty) is a PvP-immune tile of this realm: inside the safe camp or any
-// spectator-seating stand. Combat to/from such a tile is refused server-side.
-export function inNoPvpZone(realm, tx, ty) {
- return inRect(realm.safeCamp, tx, ty) || inAnyRect(realm.seating, tx, ty);
-}
-
-// The best fishing spot within one tile (8-way, including the player's own tile)
-// of (tx,ty), or null if there's no fishable water in reach. "Best" = highest
-// quality, so standing where two spots overlap rewards the richer water.
-export function fishingSpotNear(realm, tx, ty) {
- let best = null;
- for (const f of realm.fishing) {
- if (Math.abs(f.tx - tx) <= 1 && Math.abs(f.ty - ty) <= 1) {
- if (!best || (f.quality || 1) > (best.quality || 1)) best = f;
- }
- }
- return best;
-}
-
-// Serializable layout sent to the client on join (static geometry only;
-// dynamic objects sync via schema state).
-export function realmLayout(realm) {
- return {
- name: realm.name,
- grid: realm.grid,
- spawn: realm.spawn,
- fountain: realm.fountain,
- blocked: realm.blocked,
- water: realm.water || [],
- bankZone: realm.bankZone,
- fishing: realm.fishing,
- cooking: realm.cooking,
- safeCamp: realm.safeCamp,
- npcs: (realm.npcs || []).map((n) => ({ id: n.id, name: n.name, kind: n.kind, tx: n.tx, ty: n.ty })),
- landmarks: (realm.landmarks || []).map((l) => ({ id: l.id, kind: l.kind, tx: l.tx, ty: l.ty, label: l.label })),
- structures: realm.structures || [],
- // Portals carry their combat gate (if any) so the client can label a locked
- // gate and pre-warn before a wasted walk. toTx/toTy stay server-only.
- portals: realm.portals.map((p) => ({ x0: p.x0, y0: p.y0, x1: p.x1, y1: p.y1, to: p.to, gate: p.gate || null })),
- // Distinguishing scenery for the new realms — all optional, absent on the
- // classic four: an enclosed cave look, the practice boxing ring, spectator
- // stands, and the moving-floor rollers (with direction) the Arena renders.
- cave: !!realm.cave,
- ring: realm.ring || null,
- seating: realm.seating || [],
- rollers: (realm.rollers || []).map((r) => ({ x0: r.x0, y0: r.y0, x1: r.x1, y1: r.y1, dir: r.dir })),
- safe: realm.safe,
- pvp: realm.pvp,
- danger: realm.danger,
- };
-}
diff --git a/multiplayer/src/schemas/game.js b/multiplayer/src/schemas/game.js
deleted file mode 100644
index bdda07236..000000000
--- a/multiplayer/src/schemas/game.js
+++ /dev/null
@@ -1,251 +0,0 @@
-// Game schema — authoritative state for the Kintara isometric MMO realm.
-//
-// Mirrors the design notes in the player guide: a tile world where players
-// gather resources, manage an inventory + hotbar, fight, bank items, and earn
-// gold. Like schemas.js (the /walk experience), every field here is paid for
-// on each delta patch, so we keep types primitive and the shapes flat.
-//
-// @colyseus/schema sends only the fields that changed since the last patch,
-// so large-but-stable structures (a 24-slot inventory) are cheap once synced.
-
-import { Schema, MapSchema, ArraySchema, defineTypes } from '@colyseus/schema';
-
-// ---------------------------------------------------------------------------
-// Inventory
-// ---------------------------------------------------------------------------
-
-// A single inventory / hotbar / bank slot. `item` is '' for an empty slot.
-// `qty` stacks up to 999 for stackable items (wood, stone, coal, fish, gold);
-// tools (axe, pickaxe, rod, hammer, sword) are non-stackable (qty stays 1).
-export class Slot extends Schema {
- constructor(item = '', qty = 0) {
- super();
- this.item = item;
- this.qty = qty;
- }
-}
-defineTypes(Slot, { item: 'string', qty: 'uint16' });
-
-// ---------------------------------------------------------------------------
-// Player
-// ---------------------------------------------------------------------------
-
-export class GamePlayer extends Schema {
- constructor() {
- super();
- this.id = '';
- this.name = 'guest';
- this.color = 0xffffff;
-
- // Tile position (grid coordinates) + a render-facing yaw for facing.
- this.tx = 0;
- this.ty = 0;
- this.yaw = 0;
- this.motion = 'idle'; // 'idle' | 'walk'
-
- // Vitals + currency.
- this.hp = 100;
- this.maxHp = 100;
- this.gold = 0;
- this.dead = false;
- this.respawnAt = 0; // epoch ms the player can act again after dying
-
- // Skills (levels). XP is tracked server-side off-schema; only the level
- // is broadcast since that's all clients render.
- this.combat = 1;
- this.woodcutting = 1;
- this.mining = 1;
- this.fishing = 1;
- this.cooking = 1;
- this.cosmetic = ''; // base avatar URL (the player's chosen model; '' = default)
- // Equipped shop cosmetic id (Task 21), '' = none. Strictly visual: the client
- // layers this look (tint / worn prop / aura) over the base avatar. Synced so
- // every peer renders the player's equipped cosmetic. Server-authoritative —
- // only set after a validated purchase + equip, never from a raw client claim.
- this.cosmeticId = '';
- // Quest-awarded badges, as a comma-separated list of badge ids. Synced so
- // every peer renders the achievement on the player's nameplate (the
- // in-world "profile"). Server-authoritative — only the quest engine writes it.
- this.badges = '';
-
- // 24-slot backpack + 6 hotbar slots. Fixed length so indices are stable
- // references the client can drag between.
- this.inv = new ArraySchema();
- this.hotbar = new ArraySchema();
- this.activeSlot = -1; // index into hotbar; -1 = nothing equipped
-
- // Mount state. `mounted` flips locomotion to the faster cadence the server
- // enforces; `mount` is the registry id of the steed being ridden ('' = on
- // foot) so peers render the right creature underneath the avatar.
- this.mounted = false;
- this.mount = '';
-
- this.tsServer = 0;
- }
-}
-defineTypes(GamePlayer, {
- id: 'string',
- name: 'string',
- color: 'uint32',
- tx: 'int16',
- ty: 'int16',
- yaw: 'float32',
- motion: 'string',
- hp: 'int16',
- maxHp: 'int16',
- gold: 'uint32',
- dead: 'boolean',
- respawnAt: 'float64',
- combat: 'uint16',
- woodcutting: 'uint16',
- mining: 'uint16',
- fishing: 'uint16',
- cooking: 'uint16',
- cosmetic: 'string',
- cosmeticId: 'string',
- badges: 'string',
- inv: [Slot],
- hotbar: [Slot],
- activeSlot: 'int8',
- mounted: 'boolean',
- mount: 'string',
- tsServer: 'float64',
-});
-
-// ---------------------------------------------------------------------------
-// World objects
-// ---------------------------------------------------------------------------
-
-// A harvestable node (tree, rock, coal). When `depleted` it renders as a stump
-// and respawns at `respawnAt`. `kind` drives which tool + skill applies.
-export class ResourceNode extends Schema {
- constructor() {
- super();
- this.id = '';
- this.kind = 'tree'; // 'tree' | 'rock' | 'coal'
- this.tx = 0;
- this.ty = 0;
- this.depleted = false;
- this.respawnAt = 0; // epoch ms it comes back
- }
-}
-defineTypes(ResourceNode, {
- id: 'string',
- kind: 'string',
- tx: 'int16',
- ty: 'int16',
- depleted: 'boolean',
- respawnAt: 'float64',
-});
-
-// A combat target — training dummy (static) or a roaming/aggressive mob.
-export class Mob extends Schema {
- constructor() {
- super();
- this.id = '';
- this.kind = 'dummy';
- this.tx = 0;
- this.ty = 0;
- this.hp = 50;
- this.maxHp = 50;
- this.dead = false;
- this.respawnAt = 0;
- this.hitTs = 0; // epoch ms of last hit, for client flash
- this.aggroId = ''; // session id of the player this mob is chasing ('' = none)
- }
-}
-defineTypes(Mob, {
- id: 'string',
- kind: 'string',
- tx: 'int16',
- ty: 'int16',
- hp: 'int16',
- maxHp: 'int16',
- dead: 'boolean',
- respawnAt: 'float64',
- hitTs: 'float64',
- aggroId: 'string',
-});
-
-// A death-drop bag left where a player died in a danger realm. Holds the items
-// that fell out of the inventory; the owner (and, after a grace window, anyone)
-// can recover them before it expires.
-export class Tombstone extends Schema {
- constructor() {
- super();
- this.id = '';
- this.owner = '';
- this.ownerName = '';
- this.tx = 0;
- this.ty = 0;
- this.items = new ArraySchema();
- this.expiresAt = 0;
- }
-}
-defineTypes(Tombstone, {
- id: 'string',
- owner: 'string',
- ownerName: 'string',
- tx: 'int16',
- ty: 'int16',
- items: [Slot],
- expiresAt: 'float64',
-});
-
-// A player-placed structure occupying a single tile. `firepit` heals players who
-// stand adjacent (like the fountain) and decays at `expiresAt`; `shack` is a
-// permanent landmark (`expiresAt === 0`) until its owner picks it up. `locked`
-// makes a structure ignore stray pickup/interaction clicks. Like the fountain,
-// a structure's tile is solid — players cannot walk onto it.
-export class Structure extends Schema {
- constructor() {
- super();
- this.id = '';
- this.kind = 'firepit'; // 'firepit' | 'shack'
- this.owner = ''; // session id of the placer
- this.ownerName = '';
- this.tx = 0;
- this.ty = 0;
- this.expiresAt = 0; // epoch ms it decays; 0 = permanent
- this.locked = false;
- }
-}
-defineTypes(Structure, {
- id: 'string',
- kind: 'string',
- owner: 'string',
- ownerName: 'string',
- tx: 'int16',
- ty: 'int16',
- expiresAt: 'float64',
- locked: 'boolean',
-});
-
-// ---------------------------------------------------------------------------
-// Root state
-// ---------------------------------------------------------------------------
-
-export class GameState extends Schema {
- constructor() {
- super();
- this.realm = 'mainland';
- // World instance id this room belongs to (Task 23). Synced so the client
- // can label the HUD with the server it actually landed on, confirming the
- // login pick rather than trusting its own local choice.
- this.server = 's1';
- this.players = new MapSchema();
- this.nodes = new MapSchema();
- this.mobs = new MapSchema();
- this.tombstones = new MapSchema();
- this.structures = new MapSchema();
- }
-}
-defineTypes(GameState, {
- realm: 'string',
- server: 'string',
- players: { map: GamePlayer },
- nodes: { map: ResourceNode },
- mobs: { map: Mob },
- tombstones: { map: Tombstone },
- structures: { map: Structure },
-});
diff --git a/multiplayer/src/servers.js b/multiplayer/src/servers.js
deleted file mode 100644
index 553ef7145..000000000
--- a/multiplayer/src/servers.js
+++ /dev/null
@@ -1,53 +0,0 @@
-// World instances ("servers") — Task 23.
-//
-// The platform runs N independent world instances on one host. A player picks
-// one at login; each (realm, server) pair is its own Colyseus room (see the
-// filterBy(['server']) in index.js), so two players on different servers never
-// share a realm room, chat, or /who roster. Progression is account-scoped
-// (playerStore), so the SAME account sees identical items/gold/skills on either
-// server — only presence/visibility is isolated, never the profile.
-//
-// The roster is configurable without a code change via the GAME_SERVERS env:
-// GAME_SERVERS="s1:Server 1:The original world.,s2:Server 2:A fresh start."
-// Each entry is `id:name:blurb` (blurb optional). Ids are matched verbatim as a
-// join option, so keep them short, stable, and url-safe — they never change once
-// players have progressed, because the profile is shared anyway but the choice
-// is remembered per browser.
-
-const ID_RE = /^[a-z0-9][a-z0-9_-]{0,15}$/;
-
-function parseEnv(raw) {
- if (typeof raw !== 'string' || !raw.trim()) return null;
- const out = [];
- const seen = new Set();
- for (const part of raw.split(',')) {
- const [id, name, ...rest] = part.split(':').map((s) => s.trim());
- if (!ID_RE.test(id) || seen.has(id)) continue;
- seen.add(id);
- out.push({ id, name: name || id, blurb: rest.join(':') || '' });
- }
- return out.length ? out : null;
-}
-
-// Default roster: two independent worlds on the same host, exactly as the world
-// guide describes ("Server 1" / "Server 2").
-const DEFAULT_SERVERS = [
- { id: 's1', name: 'Server 1', blurb: 'The original world. Most players are here.' },
- { id: 's2', name: 'Server 2', blurb: 'A second, fully independent world.' },
-];
-
-export const SERVERS = parseEnv(process.env.GAME_SERVERS) || DEFAULT_SERVERS;
-export const SERVER_IDS = new Set(SERVERS.map((s) => s.id));
-export const DEFAULT_SERVER = SERVERS[0].id;
-
-// Resolve a client-supplied server id to a real instance, falling back to the
-// default so a missing/forged value can never land a player in a non-existent
-// world. Mirrors WalkRoom.cleanCoin / cleanTier's "unknown collapses to default"
-// contract.
-export function cleanServer(v) {
- return typeof v === 'string' && SERVER_IDS.has(v) ? v : DEFAULT_SERVER;
-}
-
-export function serverName(id) {
- return SERVERS.find((s) => s.id === id)?.name || id;
-}
diff --git a/multiplayer/src/spin-wheel.js b/multiplayer/src/spin-wheel.js
deleted file mode 100644
index 4c80143d6..000000000
--- a/multiplayer/src/spin-wheel.js
+++ /dev/null
@@ -1,159 +0,0 @@
-// Wheel of Fortune — the authoritative prize table for the Mainland casino spin
-// (Task 19).
-//
-// The SERVER owns the outcome. The 20 segments and their weights live here and
-// nowhere else; both the free spin and the paid spin roll through `rollSpin()`,
-// and the client only ever receives the chosen index to animate toward — it
-// never decides a prize. The display list (`spinSegments()`) is the same table
-// with weights surfaced as honest odds, so the wheel the player sees is exactly
-// the wheel the server rolls.
-//
-// Distribution: gold is the jackpot at a true 1/20 (the gold leg's weight is
-// 1/20 of the total). The remaining 19 segments pay wood, stone, or coal in
-// varying amounts, weighted so small hauls are common and big ones are rare.
-
-import crypto from 'node:crypto';
-
-// Each segment is { kind:'gold'|'item', item?, qty?, gold?, weight }. Order here
-// is the order around the wheel (index 0 at the top, clockwise). Weights sum to
-// 100, with the single gold leg at weight 5 → exactly P(gold) = 5/100 = 1/20.
-const SEGMENTS = [
- { kind: 'gold', gold: 200, weight: 5 }, // 0 — jackpot, ~1/20
- { kind: 'item', item: 'wood', qty: 5, weight: 12 },
- { kind: 'item', item: 'coal', qty: 6, weight: 6 },
- { kind: 'item', item: 'stone', qty: 10, weight: 9 },
- { kind: 'item', item: 'wood', qty: 25, weight: 4 },
- { kind: 'item', item: 'coal', qty: 3, weight: 9 },
- { kind: 'item', item: 'stone', qty: 5, weight: 11 },
- { kind: 'item', item: 'wood', qty: 50, weight: 2 },
- { kind: 'item', item: 'coal', qty: 15, weight: 3 },
- { kind: 'item', item: 'stone', qty: 25, weight: 4 },
- { kind: 'item', item: 'wood', qty: 10, weight: 10 },
- { kind: 'item', item: 'coal', qty: 25, weight: 2 },
- { kind: 'item', item: 'stone', qty: 15, weight: 6 },
- { kind: 'item', item: 'wood', qty: 15, weight: 7 },
- { kind: 'item', item: 'coal', qty: 10, weight: 4 },
- { kind: 'item', item: 'stone', qty: 50, weight: 2 },
- { kind: 'item', item: 'wood', qty: 100, weight: 1 }, // wood jackpot
- { kind: 'item', item: 'coal', qty: 40, weight: 1 },
- { kind: 'item', item: 'stone', qty: 80, weight: 1 },
- { kind: 'item', item: 'coal', qty: 60, weight: 1 }, // coal jackpot
-];
-
-const TOTAL_WEIGHT = SEGMENTS.reduce((s, seg) => s + seg.weight, 0);
-
-const ITEM_LABEL = { wood: 'Wood', stone: 'Stone', coal: 'Coal' };
-
-// Human-readable label for a segment, computed once so the client and any toast
-// describe a prize identically. "200 Gold", "25 Wood", …
-function segmentLabel(seg) {
- if (seg.kind === 'gold') return `${seg.gold} Gold`;
- return `${seg.qty} ${ITEM_LABEL[seg.item] || seg.item}`;
-}
-
-/**
- * The wheel as the client should render it: one entry per segment in wheel
- * order, with the prize, a label, and the segment's true probability (odds are
- * shown openly — the wheel isn't a black box). No secret state; safe to send.
- * @returns {{ index:number, kind:string, item:string|null, qty:number|null,
- * gold:number|null, label:string, oddsPct:number }[]}
- */
-export function spinSegments() {
- return SEGMENTS.map((seg, index) => ({
- index,
- kind: seg.kind,
- item: seg.kind === 'item' ? seg.item : null,
- qty: seg.kind === 'item' ? seg.qty : null,
- gold: seg.kind === 'gold' ? seg.gold : null,
- label: segmentLabel(seg),
- oddsPct: Math.round((seg.weight / TOTAL_WEIGHT) * 1000) / 10,
- }));
-}
-
-/**
- * Roll one outcome using a cryptographically strong weighted draw. Returns the
- * winning segment index plus its reward, normalized to { gold } or { item, qty }.
- * This is the only place a spin's prize is decided.
- * @returns {{ index:number, kind:string, item:string|null, qty:number, gold:number, label:string }}
- */
-export function rollSpin() {
- // randomInt is uniform over [0, TOTAL_WEIGHT) with no modulo bias.
- let roll = crypto.randomInt(0, TOTAL_WEIGHT);
- let index = 0;
- for (let i = 0; i < SEGMENTS.length; i++) {
- if (roll < SEGMENTS[i].weight) { index = i; break; }
- roll -= SEGMENTS[i].weight;
- }
- const seg = SEGMENTS[index];
- return {
- index,
- kind: seg.kind,
- item: seg.kind === 'item' ? seg.item : null,
- qty: seg.kind === 'item' ? seg.qty : 0,
- gold: seg.kind === 'gold' ? seg.gold : 0,
- label: segmentLabel(seg),
- };
-}
-
-export const SEGMENT_COUNT = SEGMENTS.length;
-// 12h between free spins, tracked per account in the persisted profile.
-export const FREE_SPIN_COOLDOWN_MS = 12 * 60 * 60 * 1000;
-// Minimum average skill level required to spin (free or paid).
-export const SPIN_MIN_AVG_LEVEL = 5;
-// USD cost of one paid spin, settled in $THREE (50% burned / 50% to treasury).
-export const PAID_SPIN_USD = 3;
-
-// --- paid-spin replay guard (process-wide) ---------------------------------
-//
-// A settled payment signature must roll at most one prize, ever. Rooms are
-// independent objects, so an in-room set wouldn't stop a player from settling
-// the same signature again after a portal handoff to another realm. This shared
-// map is the single source of truth across every room in the process; entries
-// are swept after a TTL well beyond the 90s quote window so it never grows
-// unbounded. (Horizontal scale would back this with the same Redis the
-// presence/profile layers use; the interface stays identical.)
-// A signature is 'reserved' the instant a settle begins and 'settled' once it
-// awards. Because settlement awaits an RPC round-trip, two concurrent settles of
-// the same signature must not BOTH pass a check-then-act guard and double-roll
-// one payment — so reserveSpin() is the atomic claim taken synchronously before
-// the await. A failed verification releases the claim (so an honest retry of a
-// not-yet-confirmed tx can proceed); a successful one commits it permanently.
-const _spinSigs = new Map(); // txSig -> { state:'reserved'|'settled', at }
-const SETTLED_TTL_MS = 60 * 60 * 1000;
-
-function _live(txSig) {
- const e = _spinSigs.get(txSig);
- if (!e) return null;
- if (Date.now() - e.at > SETTLED_TTL_MS) { _spinSigs.delete(txSig); return null; }
- return e;
-}
-
-// Atomically claim a signature for settlement. Returns false if it is already
-// reserved (a settle in flight) or settled (already rolled). Synchronous — no
-// await between the read and the write — so it is a true mutual-exclusion gate.
-export function reserveSpin(txSig) {
- if (_live(txSig)) return false;
- _spinSigs.set(txSig, { state: 'reserved', at: Date.now() });
- return true;
-}
-
-// Promote a reservation to settled (the prize was awarded). Permanent within TTL.
-export function commitSpin(txSig) {
- _spinSigs.set(txSig, { state: 'settled', at: Date.now() });
-}
-
-// Drop a reservation that didn't settle (verification failed) so an honest retry
-// of the same — now-confirmed — transaction can claim it. A no-op once settled.
-export function releaseSpin(txSig) {
- const e = _spinSigs.get(txSig);
- if (e && e.state === 'reserved') _spinSigs.delete(txSig);
-}
-
-export function isSpinSettled(txSig) {
- return _live(txSig)?.state === 'settled';
-}
-
-setInterval(() => {
- const now = Date.now();
- for (const [sig, e] of _spinSigs) if (now - e.at > SETTLED_TTL_MS) _spinSigs.delete(sig);
-}, 10 * 60 * 1000).unref?.();
diff --git a/pages/forge.html b/pages/forge.html
new file mode 100644
index 000000000..88cfac1cb
--- /dev/null
+++ b/pages/forge.html
@@ -0,0 +1,516 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Forge · Text → 3D · three.ws</title>
+ <meta
+ name="description"
+ content="Type a description, get a textured 3D model. Forge turns a text prompt into an interactive GLB you can orbit, inspect in AR, and download."
+ />
+ <meta property="og:title" content="Forge — Text to 3D · three.ws" />
+ <meta
+ property="og:description"
+ content="Describe an object, watch it become an interactive 3D model. Real generation, real GLB, downloadable."
+ />
+ <meta property="og:type" content="website" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="preconnect" href="https://ajax.googleapis.com" />
+ <script
+ type="module"
+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
+ ></script>
+ <style>
+ .forge-main {
+ max-width: 1180px;
+ margin: 0 auto;
+ padding: var(--space-xl) var(--space-md) var(--space-2xl);
+ }
+ .forge-head {
+ text-align: center;
+ margin-bottom: var(--space-xl);
+ }
+ .forge-eyebrow {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.45rem;
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ padding: 0.3rem 0.7rem;
+ }
+ .forge-eyebrow::before {
+ content: '';
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--success);
+ box-shadow: 0 0 8px var(--success);
+ }
+ .forge-head h1 {
+ font-family: var(--font-display);
+ font-size: clamp(2rem, 5vw, var(--text-2xl));
+ line-height: var(--leading-tight);
+ margin: var(--space-md) 0 var(--space-xs);
+ }
+ .forge-head p {
+ color: var(--ink-dim);
+ max-width: 46ch;
+ margin: 0 auto;
+ line-height: var(--leading-normal);
+ }
+
+ /* Composer ---------------------------------------------------- */
+ .composer {
+ background: var(--surface-glass);
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-lg);
+ padding: var(--space-md);
+ box-shadow: 0 24px 60px -30px rgba(0, 0, 0, 0.8);
+ }
+ .composer textarea {
+ width: 100%;
+ min-height: 86px;
+ resize: vertical;
+ background: transparent;
+ border: none;
+ outline: none;
+ color: var(--ink);
+ font-family: var(--font-body);
+ font-size: var(--text-lg);
+ line-height: var(--leading-normal);
+ }
+ .composer textarea::placeholder {
+ color: var(--ink-dim);
+ }
+ .composer-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ margin-top: var(--space-sm);
+ padding-top: var(--space-sm);
+ border-top: 1px solid var(--stroke);
+ flex-wrap: wrap;
+ }
+ .aspect {
+ display: inline-flex;
+ gap: 2px;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ padding: 2px;
+ }
+ .aspect button {
+ background: transparent;
+ border: none;
+ color: var(--ink-dim);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ padding: 0.32rem 0.55rem;
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+ }
+ .aspect button:hover {
+ color: var(--ink);
+ }
+ .aspect button[aria-pressed='true'] {
+ background: var(--surface-3);
+ color: var(--ink);
+ }
+ .aspect button:focus-visible,
+ .chip:focus-visible,
+ .btn:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-family: var(--font-display);
+ font-weight: 600;
+ font-size: var(--text-base);
+ color: #0b0b0f;
+ background: var(--accent);
+ border: 1px solid var(--accent);
+ border-radius: var(--radius-md);
+ padding: 0.6rem 1.2rem;
+ cursor: pointer;
+ transition: transform 0.12s ease, opacity 0.15s, box-shadow 0.15s;
+ }
+ .btn:hover {
+ box-shadow: 0 0 0 4px var(--accent-soft);
+ }
+ .btn:active {
+ transform: translateY(1px);
+ }
+ .btn[disabled] {
+ opacity: 0.45;
+ cursor: not-allowed;
+ }
+ .btn-ghost {
+ background: transparent;
+ color: var(--ink);
+ border: 1px solid var(--stroke-strong);
+ }
+ .btn-ghost:hover {
+ background: var(--surface-2);
+ box-shadow: none;
+ }
+
+ /* Example chips ------------------------------------------------ */
+ .chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-xs);
+ justify-content: center;
+ margin-top: var(--space-md);
+ }
+ .chip {
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ padding: 0.4rem 0.85rem;
+ cursor: pointer;
+ transition: color 0.15s, border-color 0.15s, background 0.15s;
+ }
+ .chip:hover {
+ color: var(--ink);
+ border-color: var(--stroke-strong);
+ background: var(--surface-2);
+ }
+
+ /* Workspace / states ------------------------------------------ */
+ .stage {
+ margin-top: var(--space-xl);
+ min-height: 320px;
+ }
+ .panel {
+ background: var(--surface-glass);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ overflow: hidden;
+ }
+ .is-hidden {
+ display: none !important;
+ }
+
+ /* Generating state */
+ .gen {
+ display: grid;
+ grid-template-columns: 1fr 1.1fr;
+ gap: var(--space-md);
+ padding: var(--space-md);
+ }
+ @media (max-width: 720px) {
+ .gen {
+ grid-template-columns: 1fr;
+ }
+ .composer-row {
+ justify-content: stretch;
+ }
+ .composer-row .btn {
+ width: 100%;
+ justify-content: center;
+ }
+ }
+ .gen-preview {
+ position: relative;
+ aspect-ratio: 1 / 1;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ overflow: hidden;
+ display: grid;
+ place-items: center;
+ }
+ .gen-preview img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .gen-preview .shimmer {
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(
+ 100deg,
+ transparent 20%,
+ rgba(255, 255, 255, 0.06) 50%,
+ transparent 80%
+ );
+ background-size: 200% 100%;
+ animation: shimmer 1.4s linear infinite;
+ }
+ @keyframes shimmer {
+ to {
+ background-position: -200% 0;
+ }
+ }
+ .gen-steps {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ gap: var(--space-sm);
+ }
+ .step {
+ display: flex;
+ align-items: center;
+ gap: 0.7rem;
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ }
+ .step .dot {
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ border: 2px solid var(--stroke-strong);
+ flex: none;
+ }
+ .step[data-state='active'] {
+ color: var(--ink);
+ }
+ .step[data-state='active'] .dot {
+ border-color: var(--accent);
+ border-top-color: transparent;
+ animation: spin 0.8s linear infinite;
+ }
+ .step[data-state='done'] {
+ color: var(--ink);
+ }
+ .step[data-state='done'] .dot {
+ background: var(--success);
+ border-color: var(--success);
+ }
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ .gen-meta {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ margin-top: var(--space-xs);
+ }
+
+ /* Result state */
+ .result model-viewer {
+ width: 100%;
+ height: min(60vh, 560px);
+ background: radial-gradient(120% 120% at 50% 0%, #15161d 0%, #0a0b10 70%);
+ --poster-color: transparent;
+ }
+ .result-bar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ padding: var(--space-sm) var(--space-md);
+ border-top: 1px solid var(--stroke);
+ flex-wrap: wrap;
+ }
+ .result-bar .label {
+ font-size: var(--text-sm);
+ color: var(--ink-dim);
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .result-bar .actions {
+ display: flex;
+ gap: var(--space-xs);
+ flex: none;
+ }
+
+ /* Empty + error + unconfigured */
+ .notice {
+ padding: var(--space-2xl) var(--space-lg);
+ text-align: center;
+ color: var(--ink-dim);
+ }
+ .notice h3 {
+ color: var(--ink);
+ font-family: var(--font-display);
+ margin: 0 0 var(--space-xs);
+ }
+ .notice p {
+ max-width: 48ch;
+ margin: 0 auto;
+ line-height: var(--leading-normal);
+ }
+ .notice .glyph {
+ font-size: 2.4rem;
+ opacity: 0.5;
+ display: block;
+ margin-bottom: var(--space-sm);
+ }
+ .notice.error h3 {
+ color: var(--danger);
+ }
+ .notice .actions {
+ margin-top: var(--space-md);
+ display: inline-flex;
+ gap: var(--space-xs);
+ }
+ .hint-foot {
+ text-align: center;
+ color: var(--ink-dim);
+ font-size: var(--text-xs);
+ margin-top: var(--space-lg);
+ line-height: var(--leading-normal);
+ }
+ .hint-foot a {
+ color: var(--ink);
+ }
+ </style>
+ </head>
+ <body>
+ <div id="nav-container"></div>
+
+ <main class="forge-main">
+ <header class="forge-head">
+ <span class="forge-eyebrow">Text → 3D · live</span>
+ <h1>Forge a 3D model from words</h1>
+ <p>
+ Describe one object clearly. Forge paints a reference image, then reconstructs a
+ textured mesh you can orbit, view in AR, and download as GLB.
+ </p>
+ </header>
+
+ <form class="composer" id="composer" autocomplete="off">
+ <label for="prompt" class="is-hidden">Describe the object to generate</label>
+ <textarea
+ id="prompt"
+ name="prompt"
+ maxlength="1000"
+ placeholder="a worn leather armchair, studio lighting, plain background"
+ aria-describedby="prompt-hint"
+ ></textarea>
+ <div class="composer-row">
+ <div
+ class="aspect"
+ role="group"
+ aria-label="Reference image aspect ratio"
+ id="aspect"
+ >
+ <button type="button" data-aspect="1:1" aria-pressed="true">1:1</button>
+ <button type="button" data-aspect="4:3" aria-pressed="false">4:3</button>
+ <button type="button" data-aspect="3:4" aria-pressed="false">3:4</button>
+ <button type="button" data-aspect="16:9" aria-pressed="false">16:9</button>
+ </div>
+ <button class="btn" id="generate" type="submit">
+ <span id="generate-label">Generate</span>
+ </button>
+ </div>
+ </form>
+
+ <div class="chips" id="examples" aria-label="Example prompts">
+ <button class="chip" type="button">a low-poly red fox, sitting</button>
+ <button class="chip" type="button">a sci-fi combat helmet, brushed metal</button>
+ <button class="chip" type="button">a potted monstera plant</button>
+ <button class="chip" type="button">a vintage film camera</button>
+ <button class="chip" type="button">a glazed ceramic teapot</button>
+ </div>
+
+ <section class="stage" id="stage" aria-live="polite">
+ <!-- Empty / idle -->
+ <div class="panel notice" id="state-empty">
+ <span class="glyph" aria-hidden="true">◳</span>
+ <h3>Nothing forged yet</h3>
+ <p>
+ Type a description above or tap an example. Generation runs a fast image pass,
+ then a mesh reconstruction — usually 30–90 seconds.
+ </p>
+ </div>
+
+ <!-- Generating -->
+ <div class="panel gen is-hidden" id="state-generating">
+ <div class="gen-preview" id="gen-preview">
+ <div class="shimmer" aria-hidden="true"></div>
+ </div>
+ <div class="gen-steps">
+ <div class="step" id="step-image" data-state="active">
+ <span class="dot" aria-hidden="true"></span>
+ <span>Painting reference image</span>
+ </div>
+ <div class="step" id="step-mesh" data-state="pending">
+ <span class="dot" aria-hidden="true"></span>
+ <span>Reconstructing textured mesh</span>
+ </div>
+ <div class="step" id="step-finish" data-state="pending">
+ <span class="dot" aria-hidden="true"></span>
+ <span>Finalizing GLB</span>
+ </div>
+ <div class="gen-meta" id="gen-meta">Elapsed 0s</div>
+ <div style="margin-top: var(--space-sm)">
+ <button class="btn btn-ghost" type="button" id="cancel">Cancel</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Result -->
+ <div class="panel result is-hidden" id="state-result">
+ <model-viewer
+ id="viewer"
+ camera-controls
+ auto-rotate
+ auto-rotate-delay="0"
+ rotation-per-second="18deg"
+ shadow-intensity="1"
+ exposure="1"
+ ar
+ ar-modes="webxr scene-viewer quick-look"
+ interaction-prompt="none"
+ alt="Generated 3D model"
+ ></model-viewer>
+ <div class="result-bar">
+ <span class="label" id="result-label"></span>
+ <div class="actions">
+ <a class="btn btn-ghost" id="download" download>Download GLB</a>
+ <button class="btn" type="button" id="again">Make another</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Error -->
+ <div class="panel notice error is-hidden" id="state-error">
+ <span class="glyph" aria-hidden="true">⚠</span>
+ <h3>Generation failed</h3>
+ <p id="error-message">Something went wrong. Try a simpler, single-subject prompt.</p>
+ <div class="actions">
+ <button class="btn" type="button" id="retry">Try again</button>
+ </div>
+ </div>
+
+ <!-- Unconfigured -->
+ <div class="panel notice is-hidden" id="state-unconfigured">
+ <span class="glyph" aria-hidden="true">◌</span>
+ <h3>Generator not configured</h3>
+ <p>
+ Text-to-3D needs a Replicate API token on this deployment. Once
+ <code>REPLICATE_API_TOKEN</code> is set, Forge runs the full flux → TRELLIS
+ pipeline with no further changes.
+ </p>
+ </div>
+ </section>
+
+ <p class="hint-foot">
+ Powered by flux-schnell + Microsoft TRELLIS on Replicate. Best results come from one
+ clearly described subject. The same pipeline is available to agents over MCP at
+ <a href="/docs">/api/mcp-3d</a>.
+ </p>
+ </main>
+
+ <script src="/nav.js" defer></script>
+ <script type="module" src="/src/forge.js"></script>
+ </body>
+</html>
diff --git a/pages/game.html b/pages/game.html
deleted file mode 100644
index 66cf1b13f..000000000
--- a/pages/game.html
+++ /dev/null
@@ -1,338 +0,0 @@
-<!doctype html>
-<html lang="en">
- <head>
- <meta charset="utf-8" />
- <title>Adventure · 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="Adventure mode on three.ws — an isometric MMO. Gather wood and ore, fight, level up your skills, bank your loot, and explore a shared world with players worldwide."
- />
- <meta name="theme-color" content="#0d1420" />
-
- <!--
- Multiplayer server URL — the deployed Colyseus host (Cloud Run).
- Local dev ignores this and uses ws://localhost:2567 automatically
- (see defaultServerUrl in src/game/game-net.js), so
- `npm run dev:walk-all` works out of the box.
- -->
- <meta
- name="game-server"
- content="wss://three-ws-multiplayer-93741856042.us-central1.run.app"
- />
-
- <link rel="shortcut icon" href="/favicon.ico" />
-
- <meta property="og:type" content="website" />
- <meta property="og:site_name" content="three.ws" />
- <meta property="og:title" content="Adventure · three.ws" />
- <meta
- property="og:description"
- content="An isometric MMO on three.ws — gather, fight, level up, and explore a shared world."
- />
- <meta property="og:url" content="https://three.ws/game" />
-
- <link rel="stylesheet" href="/src/game/iso-game.css" />
- </head>
- <body>
- <canvas id="kg-canvas"></canvas>
-
- <!-- Portal fade overlay — covers the screen during realm handoffs -->
- <div id="kg-portal-fade" aria-hidden="true"></div>
-
- <!-- Projected nameplates layer -->
- <div id="kg-labels"></div>
-
- <!-- In-world HUD -->
- <header id="kg-topbar" hidden>
- <span id="kg-realm">Mainland</span>
- <span id="kg-server" class="kg-server-chip" hidden></span>
- <span class="kg-stat">online <b id="kg-online">0</b></span>
- <button
- id="kg-skills-btn"
- class="kg-hud-btn"
- type="button"
- aria-haspopup="dialog"
- aria-expanded="false"
- aria-controls="kg-skills"
- title="Skills (K)"
- >
- <svg class="kg-hud-ico" viewBox="0 0 24 24" aria-hidden="true">
- <path d="M4 19V9m5 10V5m5 14v-7m5 7V11" />
- </svg>
- <span>Skills</span>
- </button>
- <span id="kg-status" data-status="connecting">connecting</span>
- </header>
-
- <!-- Skills panel — per-skill level, XP-to-next, and the cap. Populated live
- from the server's 'skills' reply; updates on every 'levelup'. -->
- <aside
- id="kg-skills"
- class="kg-skills"
- hidden
- role="dialog"
- aria-label="Skills"
- aria-modal="false"
- >
- <header class="kg-skills-head">
- <h2 class="kg-skills-title">Skills</h2>
- <button
- id="kg-skills-close"
- class="kg-skills-close"
- type="button"
- aria-label="Close skills"
- >
- <svg viewBox="0 0 24 24" aria-hidden="true">
- <path d="M6 6l12 12M18 6L6 18" />
- </svg>
- </button>
- </header>
- <div class="kg-skills-summary">
- <div class="kg-skills-sum">
- <span class="kg-skills-sum-val" id="kg-skills-total">—</span>
- <span class="kg-skills-sum-lbl">Total level</span>
- </div>
- <div class="kg-skills-sum">
- <span class="kg-skills-sum-val" id="kg-skills-avg">—</span>
- <span class="kg-skills-sum-lbl">Average</span>
- </div>
- </div>
- <ul id="kg-skills-list" class="kg-skills-list" aria-busy="true">
- <li class="kg-skills-loading">Loading your progress…</li>
- </ul>
- <p class="kg-skills-foot">
- Level cap <b id="kg-skills-cap">99</b> · earn XP by gathering and fighting.
- </p>
- </aside>
-
- <!-- Level-up celebrations (real server 'levelup' events) -->
- <div id="kg-levelups" aria-live="polite"></div>
-
- <!-- XP drop chips — "+N XP" floaters on every gain, earner only -->
- <div id="kg-xpdrops" aria-hidden="true"></div>
-
- <!-- World chat — per-realm. Focus with C (or Enter); send with Enter; Esc to
- close. Collapsed by default so it never blocks the world; clicking a
- sender name opens a Mute menu, and the Muted button lists who's hidden. -->
- <section id="kg-chat" class="kg-chat" hidden aria-label="World chat">
- <header class="kg-chat-head">
- <span class="kg-chat-title">Chat</span>
- <button
- id="kg-chat-muted-btn"
- class="kg-chat-muted-btn"
- type="button"
- aria-haspopup="dialog"
- aria-expanded="false"
- aria-controls="kg-chat-muted"
- title="Muted players"
- >
- Muted <b id="kg-chat-muted-n">0</b>
- </button>
- </header>
- <div
- id="kg-chat-log"
- class="kg-chat-log"
- role="log"
- aria-live="polite"
- aria-label="Chat messages"
- ></div>
- <form id="kg-chat-form" class="kg-chat-form" autocomplete="off">
- <!-- Slash-command autocomplete: populated from the server command
- manifest as the player types '/'. role=listbox for screen readers;
- the input owns it via aria-controls / aria-activedescendant. -->
- <ul
- id="kg-chat-hint"
- class="kg-chat-hint"
- role="listbox"
- aria-label="Command suggestions"
- hidden
- ></ul>
- <input
- id="kg-chat-input"
- class="kg-chat-input"
- type="text"
- maxlength="200"
- autocomplete="off"
- role="combobox"
- aria-expanded="false"
- aria-autocomplete="list"
- aria-controls="kg-chat-hint"
- aria-label="Type a message"
- placeholder="Press Enter to chat…"
- />
- <span id="kg-chat-counter" class="kg-chat-counter" aria-live="polite" aria-atomic="true"></span>
- </form>
- <!-- Muted-players view (toggled by the Muted button) -->
- <div
- id="kg-chat-muted"
- class="kg-chat-muted"
- hidden
- role="dialog"
- aria-label="Muted players"
- ></div>
- </section>
-
- <div id="kg-toasts"></div>
- <div id="kg-joystick"></div>
-
- <!-- Mount status — shown only while riding (Task 09). Names the steed and
- lets you dismount; the hotbar and /dismount work too. -->
- <div id="kg-mount" class="kg-mount" hidden>
- <span class="kg-mount-ico" aria-hidden="true">🐎</span>
- <span class="kg-mount-txt">Riding <b id="kg-mount-name">mount</b></span>
- <button id="kg-dismount" class="kg-mount-btn" type="button" aria-label="Dismount">Dismount</button>
- </div>
-
- <!-- Contextual world actions. Shown only when the action is actually
- available (near a Roast Pit with raw fish; hurt while carrying food);
- see _updateActions in src/game/iso-game.js. -->
- <div id="kg-actions" hidden>
- <button
- id="kg-cook"
- class="kg-action kg-action--cook"
- type="button"
- hidden
- aria-label="Cook raw fish at the Roast Pit"
- >
- <i class="kg-action-dot" aria-hidden="true"></i
- ><span class="kg-action-lbl">Cook fish</span>
- </button>
- <button
- id="kg-eat"
- class="kg-action kg-action--eat"
- type="button"
- hidden
- aria-label="Eat food to restore health"
- >
- <i class="kg-action-dot" aria-hidden="true"></i
- ><span class="kg-action-lbl">Eat</span>
- </button>
- <button
- id="kg-cast"
- class="kg-action kg-action--cast"
- type="button"
- hidden
- aria-label="Cast a fishing line into the water"
- >
- <i class="kg-action-dot" aria-hidden="true"></i
- ><span class="kg-action-lbl">Cast line</span>
- </button>
- <button
- id="kg-pickup"
- class="kg-action kg-action--pickup"
- type="button"
- hidden
- aria-label="Pick up your structure"
- >
- <i class="kg-action-dot" aria-hidden="true"></i
- ><span class="kg-action-lbl">Pick up</span>
- </button>
- </div>
-
- <!-- Death-bag recovery panel — opens when you tap an adjacent tombstone.
- Lists the bag's contents (or a designed empty state), a live expiry
- countdown, and a Take-all button (re-loots once the pack has room). -->
- <aside id="kg-tomb-panel" class="kg-tomb-panel" hidden role="dialog" aria-label="Death-bag">
- <header class="kg-tomb-head">
- <span class="kg-tomb-owner" id="kg-tomb-owner">Bag</span>
- <span class="kg-tomb-ttl" id="kg-tomb-ttl"></span>
- <button
- id="kg-tomb-close"
- class="kg-tomb-close"
- type="button"
- aria-label="Close bag"
- >
- <svg viewBox="0 0 24 24" aria-hidden="true">
- <path d="M6 6l12 12M18 6L6 18" />
- </svg>
- </button>
- </header>
- <div id="kg-tomb-items" class="kg-tomb-items"></div>
- <button id="kg-tomb-take" class="kg-tomb-take" type="button">Take all</button>
- </aside>
-
- <!-- Respawn overlay — shown while dead, with a real countdown to the synced
- respawn deadline. Pointer-transparent so it never blocks the world. -->
- <div id="kg-death" class="kg-death" hidden aria-live="assertive">
- <div class="kg-death-card">
- <div class="kg-death-eyebrow">You died</div>
- <p class="kg-death-msg" id="kg-death-msg">You died.</p>
- <div class="kg-death-count" id="kg-death-count">Respawning…</div>
- </div>
- </div>
-
- <div id="kg-hint" hidden>
- <kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> move · drag to rotate · scroll to zoom
- · tap the water to fish · tap a bag to loot · <kbd>K</kbd> skills · <kbd>C</kbd> chat
- </div>
-
- <!-- Start overlay -->
- <div id="kg-start" class="kg-overlay" hidden>
- <div class="kg-card">
- <div class="kg-eyebrow">three.ws · adventure</div>
- <h1 class="kg-title">Enter the world</h1>
- <p class="kg-sub">
- Gather, fight, and level up across a shared isometric realm. Pick a name and
- drop in.
- </p>
- <label class="kg-field">
- <input
- id="kg-name"
- type="text"
- maxlength="24"
- autocomplete="off"
- aria-label="Display name"
- placeholder="guest"
- />
- </label>
- <!-- World-instance picker (Task 23). Real per-server population is
- fetched live from the multiplayer host's /servers endpoint and
- rendered into #kg-servers-list by _initServerPicker in iso-game.js.
- Items, gold, and skills are shared across servers; only who you see
- differs. -->
- <fieldset id="kg-servers" class="kg-servers" aria-label="Choose a server">
- <legend class="kg-servers-legend">Choose a server</legend>
- <div
- id="kg-servers-list"
- class="kg-servers-list"
- role="radiogroup"
- aria-label="World instances"
- aria-busy="true"
- >
- <div class="kg-servers-loading">Finding worlds…</div>
- </div>
- <p class="kg-servers-note">
- Items, gold, and skills are shared across servers — you’ll only see other players on the
- one you pick.
- </p>
- </fieldset>
- <button id="kg-start-btn" class="kg-btn" type="button">Enter world</button>
- <div class="kg-feats">
- <span class="kg-feat">Woodcutting</span>
- <span class="kg-feat">Mining</span>
- <span class="kg-feat">Combat</span>
- <span class="kg-feat">Banking</span>
- </div>
- </div>
- </div>
-
- <!-- Offline overlay -->
- <div id="kg-offline" class="kg-overlay" hidden>
- <div class="kg-card">
- <div class="kg-eyebrow">three.ws · adventure</div>
- <h1 class="kg-title">Disconnected</h1>
- <p class="kg-sub" id="kg-offline-msg">Couldn’t reach the game server.</p>
- <button id="kg-retry" class="kg-btn" type="button">Reconnect</button>
- </div>
- </div>
-
- <script type="module" src="/src/game/iso-game.js"></script>
- <!-- Controls layer (Task 12): hotbar number keys, panel toggles, rebindable keybindings. -->
- <script type="module" src="/src/game/iso-controls.js"></script>
- <script src="/brand.js" defer></script>
-</body>
-</html>
diff --git a/pages/home.html b/pages/home.html
index f528951f3..797d20f32 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -5,11 +5,29 @@
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>three.ws — The 3D Agent Layer of the Internet</title>
<meta name="description" content="Create a 3D AI agent from a selfie in 60 seconds. Embed it anywhere with two lines of HTML. Charge per chat with x402. The 3D agent layer of the internet." />
+ <link rel="canonical" href="https://three.ws/" />
+ <meta name="theme-color" content="#050505" />
+ <meta name="color-scheme" content="dark" />
+ <!-- Open Graph -->
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/" />
<meta property="og:title" content="three.ws — The 3D Agent Layer of the Internet" />
<meta property="og:description" content="Create, embed, and monetize living 3D AI agents. One tag. Any site. Voice, memory, payments, and on-chain identity included." />
- <meta property="og:image" content="/og-image.png" />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta property="og:image:alt" content="three.ws — living 3D AI agents you can embed anywhere" />
+ <!-- Twitter -->
<meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:creator" content="@trythreews" />
+ <meta name="twitter:title" content="three.ws — The 3D Agent Layer of the Internet" />
+ <meta name="twitter:description" content="Create, embed, and monetize living 3D AI agents. One tag. Any site. Voice, memory, payments, and on-chain identity included." />
+ <meta name="twitter:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:image:alt" content="three.ws — living 3D AI agents you can embed anywhere" />
<link rel="icon" href="/favicon.ico" />
+ <link rel="apple-touch-icon" href="/pwa-192x192.png" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter+Tight:wght@400;500;600;700&family=Inter:wght@400;450;500;550;600&family=JetBrains+Mono:wght@400;500;700&display=swap" />
@@ -46,6 +64,17 @@
a { color: inherit; text-decoration: none; }
button { font-family: inherit; cursor: pointer; }
::selection { background: var(--text); color: var(--bg); }
+ main#main-content { display: block; outline: none; }
+ .skip-link {
+ position: fixed; top: 12px; left: 12px; z-index: 1000;
+ transform: translateY(-150%);
+ padding: 10px 16px; border-radius: 8px;
+ background: var(--text); color: var(--bg);
+ font-family: var(--font-mono); font-size: 13px; font-weight: 600;
+ text-decoration: none; box-shadow: 0 8px 24px rgba(0,0,0,0.5);
+ transition: transform 0.18s ease;
+ }
+ .skip-link:focus-visible { transform: translateY(0); outline: 2px solid var(--accent); outline-offset: 2px; }
.wrap-1280 { max-width: 1280px; margin: 0 auto; padding-left: 32px; padding-right: 32px; }
.wrap-1440 { max-width: 1440px; margin: 0 auto; padding-left: 32px; padding-right: 32px; }
@media (max-width: 720px) { .wrap-1280, .wrap-1440 { padding-left: 20px; padding-right: 20px; } }
@@ -1992,33 +2021,9 @@
transition: stroke-dashoffset 1.7s cubic-bezier(.4,0,.2,1);
stroke-dashoffset: 0;
}
- .door-earn-stream {
- position: absolute; top: 12px; left: 12px; right: 12px;
- display: flex; flex-direction: column; gap: 6px; align-items: flex-start;
- pointer-events: none;
- }
- .earn-tick {
- display: inline-flex; align-items: center; gap: 6px;
- padding: 4px 9px; border-radius: 6px; white-space: nowrap;
- background: rgba(5,5,5,0.7); backdrop-filter: blur(8px);
- border: 1px solid var(--hairline-strong);
- font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.03em;
- color: var(--text-3);
- animation: earnTickIn 0.5s cubic-bezier(.2,.7,.3,1) both;
- }
- .earn-tick b { color: var(--green); font-weight: 600; }
- .earn-tick.out { animation: earnTickOut 0.42s ease forwards; }
- @keyframes earnTickIn {
- from { opacity: 0; transform: translateY(-7px); }
- to { opacity: 1; transform: translateY(0); }
- }
- @keyframes earnTickOut {
- to { opacity: 0; transform: translateY(-9px); }
- }
@media (prefers-reduced-motion: reduce) {
.door-earn-line { transition: none; stroke-dashoffset: 0; }
.door-earn-area { transition: none; opacity: 1; }
- .earn-tick { animation: none; }
}
.bento-screenshot { position: relative; }
.bento-agent { position: absolute; inset: 0; }
@@ -2389,6 +2394,7 @@
.mktplace-more{flex-shrink:0;width:52px;height:52px;border-radius:10px;border:1px dashed var(--hairline-strong);display:flex;align-items:center;justify-content:center;font-family:var(--font-mono);font-size:18px;color:var(--text-4);cursor:pointer;transition:border-color .15s,color .15s;text-decoration:none}
.mktplace-more:hover{border-color:var(--text-3);color:var(--text-2)}
.analytics-demo{display:flex;flex-direction:column;gap:10px;--spark:#34d399;--spark-deep:#10b981}
+ .analytics-example-tag{align-self:flex-start;font-family:var(--font-mono);font-size:9px;letter-spacing:.12em;text-transform:uppercase;color:var(--text-4);border:1px solid var(--hairline);border-radius:5px;padding:2px 7px}
.analytics-counters{display:flex;gap:16px}
.analytics-counter{display:flex;flex-direction:column;gap:1px}
.analytics-val{font-family:var(--font-display);font-size:18px;font-weight:600;color:var(--text);font-variant-numeric:tabular-nums;letter-spacing:-0.02em}
@@ -2414,6 +2420,8 @@
</head>
<body>
+<a class="skip-link" href="#main-content">Skip to content</a>
+
<!-- ── NAV ──────────────────────────────────────────────────────── -->
<header class="nav">
<div class="nav-inner">
@@ -2680,6 +2688,7 @@
</script>
<!-- ── HERO ─────────────────────────────────────────────────────── -->
+<main id="main-content" tabindex="-1">
<section class="hero">
<div class="hero-text">
<div class="eyebrow">Open beta · live now</div>
@@ -2970,11 +2979,10 @@
<path class="door-earn-area" d="M0,158 L32,150 L64,140 L96,134 L128,120 L160,112 L192,92 L224,86 L256,66 L288,50 L320,38 L320,180 L0,180 Z" fill="url(#earnFill)"/>
<path class="door-earn-line" d="M0,158 L32,150 L64,140 L96,134 L128,120 L160,112 L192,92 L224,86 L256,66 L288,50 L320,38"/>
</svg>
- <div class="door-earn-stream" id="door-earn-stream" aria-hidden="true"></div>
</div>
<div class="door-earn-overlay">
<div class="door-earn-val" id="door-earn-val">$0.00</div>
- <div class="door-earn-lbl">USDC earned</div>
+ <div class="door-earn-lbl">example earnings · USDC</div>
</div>
</div>
<h3>Charge per chat. Keep everything.</h3>
@@ -3395,6 +3403,7 @@
<p class="bento-title">Track everything</p>
<p class="bento-desc">Conversations, revenue, engagement, retention — all in real-time. See which skills earn the most.</p>
<div class="bento-interact analytics-demo" id="analytics-demo">
+ <div class="analytics-example-tag" aria-hidden="true">Example dashboard</div>
<div class="analytics-counters">
<div class="analytics-counter"><span class="analytics-val" id="an-convos">0</span><span class="analytics-lbl">convos</span></div>
<div class="analytics-counter"><span class="analytics-val" id="an-revenue">$0</span><span class="analytics-lbl">revenue</span></div>
@@ -3481,12 +3490,12 @@
</div>
</div>
<div class="feat-visual">
- <div class="feat-visual-label">Earnings · last 24 hours</div>
+ <div class="feat-visual-label">Earnings dashboard · example</div>
<div class="feat-visual-inner">
<div style="display:flex;justify-content:space-between;align-items:baseline;">
<div>
<div style="font-family:var(--font-display);font-size:36px;font-weight:600;letter-spacing:-0.025em;color:var(--green)">$847.50</div>
- <div style="font-family:var(--font-mono);font-size:11px;letter-spacing:0.15em;text-transform:uppercase;color:var(--text-3);margin-top:4px">Total earned · USDC</div>
+ <div style="font-family:var(--font-mono);font-size:11px;letter-spacing:0.15em;text-transform:uppercase;color:var(--text-3);margin-top:4px">Example earnings · USDC</div>
</div>
<div style="text-align:right">
<div style="font-family:var(--font-display);font-size:20px;font-weight:600;color:var(--text)">312</div>
@@ -3865,6 +3874,8 @@
</div>
</section>
+</main>
+
<!-- ── FOOTER ─────────────────────────────────────────────────────── -->
<footer>
<div class="wrap-1280">
@@ -3904,7 +3915,8 @@
<div class="foot-col-h">Company</div>
<a href="/blog">Blog</a>
<a href="/community">Community</a>
- <a href="https://github.com/nirholas/three.ws">GitHub</a>
+ <a href="https://x.com/trythreews" target="_blank" rel="noopener noreferrer">X / Twitter</a>
+ <a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="mailto:[email protected]">Contact</a>
</div>
<div class="foot-col">
@@ -5131,51 +5143,31 @@
});
}
- // Earn door ticker
+ // Earn door — one-time count-up reveal of an illustrative example figure.
+ // The number is labeled "example earnings" in the markup; it is not live
+ // platform data (real earnings live behind auth on /dashboard/monetize).
var earnVal = document.getElementById('door-earn-val');
var earnViz = document.getElementById('door-earn-viz');
- var earnStream = document.getElementById('door-earn-stream');
if (earnVal) {
var started = false;
+ var reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ var EARN_EXAMPLE = 128.40;
var earnObs = new IntersectionObserver(function(entries) {
if (!entries[0].isIntersecting || started) return;
started = true; earnObs.disconnect();
if (earnViz) earnViz.classList.add('is-live');
- var val = 0, target = 847.5;
+ if (reduceMotion) {
+ earnVal.textContent = '$' + EARN_EXAMPLE.toFixed(2);
+ return;
+ }
+ var val = 0;
(function tick() {
- val += (target - val) * 0.025;
- if (val >= target - 0.01) val = target;
+ val += (EARN_EXAMPLE - val) * 0.025;
+ if (val >= EARN_EXAMPLE - 0.01) val = EARN_EXAMPLE;
earnVal.textContent = '$' + val.toFixed(2);
- if (val < target) requestAnimationFrame(tick);
+ if (val < EARN_EXAMPLE) requestAnimationFrame(tick);
})();
-
- var reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
- if (earnStream && !reduceMotion) {
- var EARN_EVENTS = [
- { label: 'chat', amt: 0.05 },
- { label: 'voice', amt: 0.12 },
- { label: 'skill', amt: 0.25 },
- { label: 'chat', amt: 0.05 },
- { label: 'memory', amt: 0.08 }
- ];
- var ei = 0;
- function pushEarnTick() {
- var ev = EARN_EVENTS[ei++ % EARN_EVENTS.length];
- var row = document.createElement('div');
- row.className = 'earn-tick';
- row.innerHTML = '+&nbsp;<b>$' + ev.amt.toFixed(2) + '</b>&nbsp;&middot;&nbsp;' + ev.label;
- earnStream.prepend(row);
- var live = earnStream.querySelectorAll('.earn-tick:not(.out)');
- if (live.length > 3) {
- var oldest = live[live.length - 1];
- oldest.classList.add('out');
- oldest.addEventListener('animationend', function() { oldest.remove(); }, { once: true });
- }
- }
- pushEarnTick();
- setInterval(pushEarnTick, 2200);
- }
}, { threshold: 0.35 });
earnObs.observe(earnVal);
}
@@ -5813,30 +5805,31 @@
+ '<circle class="spark-dot" cx="' + last.x.toFixed(1) + '" cy="' + last.y.toFixed(1) + '" r="2.5"/>';
}
+ // Counters reveal a fixed set of example figures (the widget is labeled
+ // "example" in the markup). These are illustrative of the analytics
+ // dashboard — not live platform data — so no random "live" simulation.
var animated = false;
+ var targets = { convos: 1247, revenue: 847.5, retention: 68 };
+ function setCounters(convos, revenue, retention) {
+ convosEl.textContent = Math.round(convos).toLocaleString();
+ revenueEl.textContent = '$' + revenue.toFixed(0);
+ retentionEl.textContent = Math.round(retention) + '%';
+ }
function animateCounters() {
if (animated) return;
animated = true;
- var targets = { convos: 1247, revenue: 847.5, retention: 68 };
+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
+ setCounters(targets.convos, targets.revenue, targets.retention);
+ return;
+ }
var start = performance.now();
var dur = 1200;
(function tick(now) {
var p = Math.min((now - start) / dur, 1);
var e = 1 - Math.pow(1 - p, 3);
- convosEl.textContent = Math.round(targets.convos * e).toLocaleString();
- revenueEl.textContent = '$' + (targets.revenue * e).toFixed(0);
- retentionEl.textContent = Math.round(targets.retention * e) + '%';
+ setCounters(targets.convos * e, targets.revenue * e, targets.retention * e);
if (p < 1) requestAnimationFrame(tick);
})(start);
-
- // Live tick
- setInterval(function() {
- var newPt = dataPoints[dataPoints.length - 1] + Math.round((Math.random() - 0.3) * 8);
- dataPoints.push(Math.max(5, newPt));
- if (dataPoints.length > 30) dataPoints.shift();
- maxVal = Math.max.apply(null, dataPoints);
- buildPath();
- }, 2000);
}
buildPath();
diff --git a/public/login.html b/public/login.html
index 4595cb16b..e194d606a 100644
--- a/public/login.html
+++ b/public/login.html
@@ -868,7 +868,7 @@
const agent = await createAgentUI({
canvas: document.getElementById('avatar-canvas'),
- clips: ['idle', 'walk', 'lookdown', 'covereyes', 'reaction', 'silly', 'defeated', 'angry', 'facepalm'],
+ clips: ['idle', 'walk', 'covereyes', 'reaction', 'silly', 'defeated', 'angry', 'facepalm'],
subclips: {
covereyes: { start: 0, end: 48, fps: 30 },
},
@@ -881,20 +881,27 @@
agent.standOn(avatarWrap, { anchor: 'bottom-center', offsetY: -50 });
});
- emailInput.addEventListener('focus', () => {
- agent.play('lookdown', { loop: true });
- });
- emailInput.addEventListener('blur', () => {
- agent.play('idle', { loop: true });
- });
+ // The avatar shields its eyes whenever the user is typing a
+ // credential — email or password — so it never "peeks" at what
+ // you enter. It stays covered while focus moves between the two
+ // fields (or to the password show/hide toggle) and only relaxes
+ // back to idle once you leave the credential inputs entirely.
+ const credentialFields = [emailInput, passwordInput];
- passwordInput.addEventListener('focus', () => {
+ function coverEyes() {
+ if (agent.currentClip === 'covereyes') return;
agent.play('covereyes', { loop: false, hold: true });
agent.faceFront();
- });
- passwordInput.addEventListener('blur', (e) => {
- if (e.relatedTarget && e.relatedTarget.closest('.password-wrap')) return;
+ }
+ function uncoverEyes(e) {
+ const to = e.relatedTarget;
+ if (to && (credentialFields.includes(to) || to.closest?.('.password-wrap'))) return;
agent.play('idle', { loop: true });
+ }
+
+ credentialFields.forEach((field) => {
+ field.addEventListener('focus', coverEyes);
+ field.addEventListener('blur', uncoverEyes);
});
const pickFail = agent.pickFrom(['reaction', 'defeated', 'angry', 'facepalm']);
diff --git a/public/nav.css b/public/nav.css
index 8b3f668e3..df823f14d 100644
--- a/public/nav.css
+++ b/public/nav.css
@@ -132,7 +132,20 @@
.nav-grp.open .nav-pop {
opacity: 1; transform: translateY(0) scale(1); pointer-events: auto;
}
-.nav-pop.wide { grid-template-columns: 1fr 1fr; min-width: 540px; }
+/* Labs mega menu — categorized columns, right-anchored (it's the last group). */
+.nav-pop.mega {
+ left: auto; right: 0;
+ transform-origin: top right;
+ min-width: 632px;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 2px 6px; padding: 8px;
+}
+.nav-col { display: flex; flex-direction: column; gap: 1px; min-width: 0; }
+.nav-col-h {
+ font-family: var(--nv-font-mono); font-size: 10px;
+ text-transform: uppercase; letter-spacing: 0.14em;
+ color: var(--nv-text-4); padding: 9px 12px 5px;
+}
.nav-mi {
display: block; padding: 9px 12px; border-radius: 9px;
transition: background 0.12s;
diff --git a/public/nav.html b/public/nav.html
index e33015e96..decfa575e 100644
--- a/public/nav.html
+++ b/public/nav.html
@@ -9,7 +9,8 @@
<button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false">Build<span class="nav-caret" aria-hidden="true">▾</span></button>
<div class="nav-pop" role="menu" aria-label="Build">
<a class="nav-mi" href="/create" role="menuitem"><span class="nav-mi-t">Create agent</span><span class="nav-mi-d">Avatar + brain wizard</span></a>
- <a class="nav-mi" href="/create/selfie" role="menuitem"><span class="nav-mi-t">Selfie to avatar <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">One photo → rigged 3D avatar</span></a>
+ <a class="nav-mi" href="/create/selfie" role="menuitem"><span class="nav-mi-t">Selfie to avatar</span><span class="nav-mi-d">One photo → rigged 3D avatar</span></a>
+ <a class="nav-mi" href="/forge" role="menuitem"><span class="nav-mi-t">Text to 3D <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Describe an object → textured GLB</span></a>
<a class="nav-mi" href="/play" role="menuitem"><span class="nav-mi-t">Worlds <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Every coin is a 3D world — drop in &amp; hang out</span></a>
<a class="nav-mi" href="/app" role="menuitem"><span class="nav-mi-t">Viewer</span><span class="nav-mi-d">Drag-and-drop GLB</span></a>
<a class="nav-mi" href="/playground" role="menuitem"><span class="nav-mi-t">Playground</span><span class="nav-mi-d">Viewer + environment + embed code</span></a>
@@ -49,42 +50,50 @@
<a class="nav-mi" href="/tutorials" role="menuitem"><span class="nav-mi-t">Tutorials</span><span class="nav-mi-d">Step-by-step guides</span></a>
<a class="nav-mi" href="/brain" role="menuitem"><span class="nav-mi-t">Brain <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Claude · GPT · DeepSeek · Qwen · Llama</span></a>
<a class="nav-mi" href="/chat" role="menuitem"><span class="nav-mi-t">Chat</span><span class="nav-mi-d">Talk to your agent</span></a>
- <a class="nav-mi" href="/pay" role="menuitem"><span class="nav-mi-t">Pay <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Agent payments — x402 + USDC</span></a>
+ <a class="nav-mi" href="/pay" role="menuitem"><span class="nav-mi-t">Pay</span><span class="nav-mi-d">Agent payments — x402 + USDC</span></a>
<a class="nav-mi" href="/docs#solana" role="menuitem"><span class="nav-mi-t">Solana SDK</span><span class="nav-mi-d">Attestations + agent-kit</span></a>
</div>
</div>
<div class="nav-grp">
<button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false">Labs<span class="nav-pill-sm" aria-hidden="true">Beta</span><span class="nav-caret" aria-hidden="true">▾</span></button>
- <div class="nav-pop wide" role="menu" aria-label="Labs">
+ <div class="nav-pop mega" role="menu" aria-label="Labs">
<div class="nav-pop-note">Experimental features — actively iterating. Expect rough edges.</div>
- <a class="nav-mi" href="/launchpad" role="menuitem"><span class="nav-mi-t">Launchpad Studio <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Build a 3D launchpad · token · concierge</span></a>
- <a class="nav-mi" href="/lipsync" role="menuitem"><span class="nav-mi-t">Lipsync <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">TTS or mic → in-browser viseme → mouth</span></a>
- <a class="nav-mi" href="/mocap-studio" role="menuitem"><span class="nav-mi-t">Mocap Studio <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Record face → save clip → replay</span></a>
- <a class="nav-mi" href="/pose" role="menuitem"><span class="nav-mi-t">Pose Studio</span><span class="nav-mi-d">Click-to-pose mannequin + export PNG</span></a>
- <a class="nav-mi" href="/overlay-control" role="menuitem"><span class="nav-mi-t">OBS Overlay</span><span class="nav-mi-d">Stream deck — emote hotkeys, mic</span></a>
- <a class="nav-mi" href="/walk" role="menuitem"><span class="nav-mi-t">Walk <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Walk your avatar — multiplayer + AR</span></a>
- <a class="nav-mi" href="/xr" role="menuitem"><span class="nav-mi-t">XR <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Place your avatar in the real world</span></a>
- <a class="nav-mi" href="/gmgn" role="menuitem"><span class="nav-mi-t">GMGN Smart Money <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Agent narrates smart wallet signals</span></a>
- <a class="nav-mi" href="/pumpfun" role="menuitem"><span class="nav-mi-t">Pump.fun stream</span><span class="nav-mi-d">Mint agent tokens</span></a>
- <a class="nav-mi" href="/pump-live" role="menuitem"><span class="nav-mi-t">Live launches</span><span class="nav-mi-d">Real-time mint feed</span></a>
- <a class="nav-mi" href="/pump-dashboard" role="menuitem"><span class="nav-mi-t">Pump Dashboard</span><span class="nav-mi-d">Watches · scanner · quotes</span></a>
- <a class="nav-mi" href="/pump-visualizer" role="menuitem"><span class="nav-mi-t">Pump Visualizer</span><span class="nav-mi-d">3D view of trending tokens</span></a>
- <a class="nav-mi" href="/three-live" role="menuitem"><span class="nav-mi-t">$THREE Live <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Protocol pulse — live trades in 3D</span></a>
- <a class="nav-mi" href="/strategy-lab" role="menuitem"><span class="nav-mi-t">Strategy Lab</span><span class="nav-mi-d">DCA + subscriptions</span></a>
- <a class="nav-mi" href="/club" role="menuitem"><span class="nav-mi-t">Pole Club <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">x402 micro-tip demo — $0.001 / dance</span></a>
- <a class="nav-mi" href="/shopper" role="menuitem"><span class="nav-mi-t">Endpoint Shopper <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">AI chains x402 endpoints to answer a task</span></a>
- <a class="nav-mi" href="/tutor" role="menuitem"><span class="nav-mi-t">Pay-As-You-Learn Tutor <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">$0.01 per answer in USDC over x402</span></a>
- <a class="nav-mi" href="/fact-checker" role="menuitem"><span class="nav-mi-t">Fact Checker <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">$0.10 per claim — cited verdict + attestation</span></a>
- <a class="nav-mi" href="/arbitrage" role="menuitem"><span class="nav-mi-t">x402 Arbitrage <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Cheapest endpoint per capability, live</span></a>
- <a class="nav-mi" href="/providers" role="menuitem"><span class="nav-mi-t">x402 Providers <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Operator profiles for the paid API catalog</span></a>
- <a class="nav-mi" href="/unstoppable" role="menuitem"><span class="nav-mi-t">Unstoppable Agent <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Self-funding agent dashboard, live</span></a>
- <a class="nav-mi" href="/rider" role="menuitem"><span class="nav-mi-t">Rider (VR)</span><span class="nav-mi-d">Open-source VR music visualization</span></a>
- <a class="nav-mi" href="/forever" role="menuitem"><span class="nav-mi-t">Forever</span><span class="nav-mi-d">Etch a message into Bitcoin — forever</span></a>
- <a class="nav-mi" href="/eth-vanity" role="menuitem"><span class="nav-mi-t">ETH vanity (CREATE2)</span><span class="nav-mi-d">Grind a smart-contract address</span></a>
- <a class="nav-mi" href="/vanity-wallet" role="menuitem"><span class="nav-mi-t">Vanity wallet</span><span class="nav-mi-d">Grind a Solana address</span></a>
+ <div class="nav-col" role="group" aria-label="Avatar &amp; Motion">
+ <div class="nav-col-h">Avatar &amp; Motion</div>
+ <a class="nav-mi" href="/lipsync" role="menuitem"><span class="nav-mi-t">Lipsync</span><span class="nav-mi-d">TTS or mic → in-browser viseme → mouth</span></a>
+ <a class="nav-mi" href="/mocap-studio" role="menuitem"><span class="nav-mi-t">Mocap Studio</span><span class="nav-mi-d">Record face → save clip → replay</span></a>
+ <a class="nav-mi" href="/pose" role="menuitem"><span class="nav-mi-t">Pose Studio</span><span class="nav-mi-d">Click-to-pose mannequin + export PNG</span></a>
+ <a class="nav-mi" href="/overlay-control" role="menuitem"><span class="nav-mi-t">OBS Overlay</span><span class="nav-mi-d">Stream deck — emote hotkeys, mic</span></a>
+ <a class="nav-mi" href="/walk" role="menuitem"><span class="nav-mi-t">Walk</span><span class="nav-mi-d">Walk your avatar — multiplayer + AR</span></a>
+ <a class="nav-mi" href="/xr" role="menuitem"><span class="nav-mi-t">XR</span><span class="nav-mi-d">Place your avatar in the real world</span></a>
+ <a class="nav-mi" href="/rider" role="menuitem"><span class="nav-mi-t">Rider (VR)</span><span class="nav-mi-d">Open-source VR music visualization</span></a>
+ </div>
+ <div class="nav-col" role="group" aria-label="Markets &amp; Pump">
+ <div class="nav-col-h">Markets &amp; Pump</div>
+ <a class="nav-mi" href="/launchpad" role="menuitem"><span class="nav-mi-t">Launchpad Studio</span><span class="nav-mi-d">Build a 3D launchpad · token · concierge</span></a>
+ <a class="nav-mi" href="/gmgn" role="menuitem"><span class="nav-mi-t">GMGN Smart Money</span><span class="nav-mi-d">Agent narrates smart wallet signals</span></a>
+ <a class="nav-mi" href="/pumpfun" role="menuitem"><span class="nav-mi-t">Pump.fun stream</span><span class="nav-mi-d">Mint agent tokens</span></a>
+ <a class="nav-mi" href="/pump-live" role="menuitem"><span class="nav-mi-t">Live launches</span><span class="nav-mi-d">Real-time mint feed</span></a>
+ <a class="nav-mi" href="/pump-dashboard" role="menuitem"><span class="nav-mi-t">Pump Dashboard</span><span class="nav-mi-d">Watches · scanner · quotes</span></a>
+ <a class="nav-mi" href="/pump-visualizer" role="menuitem"><span class="nav-mi-t">Pump Visualizer</span><span class="nav-mi-d">3D view of trending tokens</span></a>
+ <a class="nav-mi" href="/three-live" role="menuitem"><span class="nav-mi-t">$THREE Live <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Protocol pulse — live trades in 3D</span></a>
+ <a class="nav-mi" href="/strategy-lab" role="menuitem"><span class="nav-mi-t">Strategy Lab</span><span class="nav-mi-d">DCA + subscriptions</span></a>
+ </div>
+ <div class="nav-col" role="group" aria-label="x402 &amp; Onchain">
+ <div class="nav-col-h">x402 &amp; Onchain</div>
+ <a class="nav-mi" href="/club" role="menuitem"><span class="nav-mi-t">Pole Club</span><span class="nav-mi-d">x402 micro-tip demo — $0.001 / dance</span></a>
+ <a class="nav-mi" href="/shopper" role="menuitem"><span class="nav-mi-t">Endpoint Shopper</span><span class="nav-mi-d">AI chains x402 endpoints to answer a task</span></a>
+ <a class="nav-mi" href="/tutor" role="menuitem"><span class="nav-mi-t">Pay-As-You-Learn Tutor</span><span class="nav-mi-d">$0.01 per answer in USDC over x402</span></a>
+ <a class="nav-mi" href="/fact-checker" role="menuitem"><span class="nav-mi-t">Fact Checker</span><span class="nav-mi-d">$0.10 per claim — cited verdict + attestation</span></a>
+ <a class="nav-mi" href="/arbitrage" role="menuitem"><span class="nav-mi-t">x402 Arbitrage</span><span class="nav-mi-d">Cheapest endpoint per capability, live</span></a>
+ <a class="nav-mi" href="/providers" role="menuitem"><span class="nav-mi-t">x402 Providers</span><span class="nav-mi-d">Operator profiles for the paid API catalog</span></a>
+ <a class="nav-mi" href="/unstoppable" role="menuitem"><span class="nav-mi-t">Unstoppable Agent</span><span class="nav-mi-d">Self-funding agent dashboard, live</span></a>
+ <a class="nav-mi" href="/forever" role="menuitem"><span class="nav-mi-t">Forever</span><span class="nav-mi-d">Etch a message into Bitcoin — forever</span></a>
+ <a class="nav-mi" href="/eth-vanity" role="menuitem"><span class="nav-mi-t">ETH vanity (CREATE2)</span><span class="nav-mi-d">Grind a smart-contract address</span></a>
+ <a class="nav-mi" href="/vanity-wallet" role="menuitem"><span class="nav-mi-t">Vanity wallet</span><span class="nav-mi-d">Grind a Solana address</span></a>
+ </div>
</div>
</div>
- <a href="/pricing">Pricing</a>
</nav>
<div class="nav-end">
<button type="button" class="nav-walk-toggle" id="home-nav-walk" aria-pressed="false" aria-label="Walk with me — toggle the avatar companion" title="Walk with me">
@@ -104,9 +113,11 @@
<div class="dr-h">Build</div>
<a href="/create">Create agent</a>
<a href="/create/selfie">Selfie to avatar</a>
+ <a href="/forge">Text to 3D</a>
<a href="/play">Worlds</a>
<a href="/app">Viewer</a>
<a href="/playground">Playground</a>
+ <a href="/validation">glTF Validator</a>
<a href="/voice">Voice Lab</a>
<div class="dr-h">Discover</div>
<a href="/features">Features</a>
@@ -123,22 +134,33 @@
<a href="/studio">Widget Studio</a>
<a href="/embed.html">Embed editor</a>
<a href="/avatar-sdk">Avatar SDK</a>
+ <a href="/docs#embedding">Embed docs</a>
+ <a href="/docs#web-component">&lt;agent-3d&gt;</a>
<div class="dr-h">Learn</div>
<a href="/docs">Docs</a>
<a href="/tutorials">Tutorials</a>
<a href="/brain">Brain</a>
<a href="/chat">Chat</a>
<a href="/pay">Pay</a>
- <div class="dr-h">Labs · Beta</div>
- <a href="/launchpad">Launchpad Studio</a>
+ <a href="/docs#solana">Solana SDK</a>
+ <div class="dr-h">Labs · Avatar &amp; Motion</div>
<a href="/lipsync">Lipsync</a>
<a href="/mocap-studio">Mocap Studio</a>
<a href="/pose">Pose Studio</a>
+ <a href="/overlay-control">OBS Overlay</a>
<a href="/walk">Walk</a>
<a href="/xr">XR</a>
+ <a href="/rider">Rider (VR)</a>
+ <div class="dr-h">Labs · Markets &amp; Pump</div>
+ <a href="/launchpad">Launchpad Studio</a>
<a href="/gmgn">GMGN Smart Money</a>
<a href="/pumpfun">Pump.fun stream</a>
+ <a href="/pump-live">Live launches</a>
+ <a href="/pump-dashboard">Pump Dashboard</a>
+ <a href="/pump-visualizer">Pump Visualizer</a>
<a href="/three-live">$THREE Live</a>
+ <a href="/strategy-lab">Strategy Lab</a>
+ <div class="dr-h">Labs · x402 &amp; Onchain</div>
<a href="/club">Pole Club</a>
<a href="/shopper">Endpoint Shopper</a>
<a href="/tutor">Pay-As-You-Learn Tutor</a>
@@ -146,10 +168,10 @@
<a href="/arbitrage">x402 Arbitrage</a>
<a href="/providers">x402 Providers</a>
<a href="/unstoppable">Unstoppable Agent</a>
- <a href="/rider">Rider (VR)</a>
<a href="/forever">Forever</a>
+ <a href="/eth-vanity">ETH vanity (CREATE2)</a>
+ <a href="/vanity-wallet">Vanity wallet</a>
<div class="dr-h">More</div>
- <a href="/pricing">Pricing</a>
<a href="/my-agents" id="home-nav-drawer-my-agents" hidden>My Agents</a>
<div class="sep"></div>
<a href="/login" id="home-nav-drawer-cta">Sign in</a>
diff --git a/scripts/test-tombstone.mjs b/scripts/test-tombstone.mjs
deleted file mode 100644
index 286051135..000000000
--- a/scripts/test-tombstone.mjs
+++ /dev/null
@@ -1,238 +0,0 @@
-// Verifies Task 02 (player death & tombstone death-bags) server logic directly
-// against GameRoom's real methods — no mocks of the logic, only thin stubs for
-// the Colyseus transport (client.send / this.clients) that the methods touch.
-//
-// We drive _killPlayer / _damagePlayer / _handleTombLoot / _tick exactly as the
-// live room would and assert the invariants from the task's Definition of Done:
-// • danger realm drops a tombstone with the right items; safe realm does not
-// • tools are kept, non-tool items dropped, gold untouched
-// • ownership holds until the grace window, then anyone adjacent may loot
-// • adjacency is enforced
-// • inventory math is exact (no duplication, no loss) including a full pack
-// • expired bags vanish in the sim tick; respawn returns to the realm spawn
-//
-// Run: node scripts/test-tombstone.mjs
-
-import { GameRoom } from '../multiplayer/src/rooms/GameRoom.js';
-import { REALMS } from '../multiplayer/src/rooms/realms.js';
-import { GameState, GamePlayer, Slot } from '../multiplayer/src/schemas/game.js';
-
-const INV_SIZE = 24;
-const HOTBAR_SIZE = 6;
-const TTL = 120000;
-const GRACE = 45000;
-
-let passed = 0;
-let failed = 0;
-function ok(cond, label) {
- if (cond) { passed++; console.log(` ✓ ${label}`); }
- else { failed++; console.error(` ✗ ${label}`); }
-}
-function eq(a, b, label) { ok(a === b, `${label} (got ${a}, want ${b})`); }
-
-// Build a GameRoom without running Colyseus' lifecycle: we only need its
-// methods + a state container + the priv/clients maps the methods read.
-function makeRoom(realmName) {
- const room = Object.create(GameRoom.prototype);
- room.realm = REALMS[realmName];
- room.state = new GameState();
- room.state.realm = realmName;
- room.priv = new Map();
- room.clients = [];
- room._tombSeq = 0;
- return room;
-}
-
-function addPlayer(room, id, name, tx, ty) {
- const p = new GamePlayer();
- p.id = id; p.name = name; p.tx = tx; p.ty = ty;
- p.hp = p.maxHp = 100; p.gold = 1234;
- for (let i = 0; i < INV_SIZE; i++) p.inv.push(new Slot());
- for (let i = 0; i < HOTBAR_SIZE; i++) p.hotbar.push(new Slot());
- room.state.players.set(id, p);
- const messages = [];
- const client = { sessionId: id, send: (type, data) => messages.push({ type, data }), messages };
- room.clients.push(client);
- room.priv.set(id, { xp: {}, bank: [], cooldowns: { gather: 0, attack: 0 }, rate: new Map() });
- return { p, client };
-}
-
-function firstTomb(room) {
- for (const [, t] of room.state.tombstones) return t;
- return null;
-}
-function tombItems(t) {
- const out = {};
- for (const s of t.items) if (s.item) out[s.item] = (out[s.item] || 0) + s.qty;
- return out;
-}
-function invCount(p, item) {
- let n = 0;
- for (const s of [...p.inv, ...p.hotbar]) if (s.item === item) n += s.qty;
- return n;
-}
-
-// --------------------------------------------------------------------------
-console.log('Test 1 — danger realm drops a tombstone (tools kept, loot dropped)');
-{
- const room = makeRoom('wilderness');
- const { p, client } = addPlayer(room, 'A', 'Alice', 12, 12);
- p.inv[0].item = 'wood'; p.inv[0].qty = 500;
- p.inv[1].item = 'stone'; p.inv[1].qty = 10;
- p.inv[2].item = 'pickaxe'; p.inv[2].qty = 1; // a TOOL sitting in the backpack
- p.hotbar[0].item = 'axe'; p.hotbar[0].qty = 1;
- p.hotbar[1].item = 'sword'; p.hotbar[1].qty = 1;
- p.hotbar[2].item = 'fish'; p.hotbar[2].qty = 3;
- const goldBefore = p.gold;
-
- room._killPlayer(p, { byName: 'a goblin' });
-
- ok(p.dead === true, 'player is dead');
- ok(p.respawnAt > 0, 'respawnAt scheduled');
- eq(p.gold, goldBefore, 'gold is NOT dropped');
- ok(invCount(p, 'axe') === 1 && invCount(p, 'sword') === 1 && invCount(p, 'pickaxe') === 1, 'all tools kept');
- ok(invCount(p, 'wood') === 0 && invCount(p, 'stone') === 0 && invCount(p, 'fish') === 0, 'non-tool items removed from pack');
- const t = firstTomb(room);
- ok(!!t, 'tombstone created');
- eq(t.owner, 'A', 'tombstone owner');
- eq(t.ownerName, 'Alice', 'tombstone ownerName');
- eq(t.tx, 12, 'tombstone tx = death tile'); eq(t.ty, 12, 'tombstone ty = death tile');
- ok(Math.abs(t.expiresAt - (p.respawnAt - 4000 + TTL)) < 5, 'expiresAt ~ now + TTL');
- const items = tombItems(t);
- ok(items.wood === 500 && items.stone === 10 && items.fish === 3, 'bag holds exactly the dropped loot');
- eq(t.items.length, 3, 'bag has 3 slots');
- const died = client.messages.find((m) => m.type === 'died');
- ok(!!died && died.data.dropped === 3 && died.data.danger === true, "'died' notice carries dropped count + danger");
-}
-
-console.log('Test 2 — safe realm: no tombstone, no items lost');
-{
- const room = makeRoom('mainland');
- const { p, client } = addPlayer(room, 'B', 'Bob', 24, 30);
- p.inv[0].item = 'wood'; p.inv[0].qty = 99;
- room._killPlayer(p);
- ok(p.dead === true, 'player is dead');
- eq(room.state.tombstones.size, 0, 'no tombstone in a safe realm');
- eq(invCount(p, 'wood'), 99, 'items retained in a safe realm');
- const died = client.messages.find((m) => m.type === 'died');
- ok(!!died && died.data.danger === false && died.data.dropped === 0, "'died' notice marks safe realm");
-}
-
-console.log('Test 3 — _damagePlayer funnels into death at 0 HP');
-{
- const room = makeRoom('wilderness');
- const { p } = addPlayer(room, 'C', 'Cara', 5, 5);
- p.hp = 8;
- const fatal1 = room._damagePlayer(p, 3);
- ok(fatal1 === false && p.hp === 5 && !p.dead, 'non-fatal hit reduces HP');
- const fatal2 = room._damagePlayer(p, 999);
- ok(fatal2 === true && p.hp === 0 && p.dead, 'lethal hit kills + clamps HP at 0');
- const again = room._damagePlayer(p, 10);
- ok(again === false, 'damaging an already-dead player is a no-op');
-}
-
-console.log('Test 4 — ownership: only owner loots before grace; adjacency enforced');
-{
- const room = makeRoom('wilderness');
- const { p: owner } = addPlayer(room, 'O', 'Owner', 10, 10);
- owner.inv[0].item = 'wood'; owner.inv[0].qty = 50;
- room._killPlayer(owner);
- const t = firstTomb(room);
-
- // A thief joins, NOT adjacent → denied with an adjacency notice.
- const { p: thief, client: thiefC } = addPlayer(room, 'T', 'Thief', 20, 20);
- room._handleTombLoot(thiefC, { id: t.id });
- ok(thiefC.messages.some((m) => m.data?.text?.includes('Walk up')), 'far player told to walk up');
- eq(tombItems(t).wood, 50, 'bag untouched when not adjacent');
-
- // Thief walks adjacent but it's still the owner-only window → ownership notice.
- thief.tx = 11; thief.ty = 10;
- room._handleTombLoot(thiefC, { id: t.id });
- ok(thiefC.messages.some((m) => m.data?.text?.includes('belongs to Owner')), 'adjacent non-owner blocked pre-grace');
- eq(tombItems(t).wood, 50, 'bag untouched by non-owner pre-grace');
-
- // Owner respawns far away (cannot loot until they walk back).
- owner.dead = false; owner.hp = 100; owner.tx = 20; owner.ty = 36;
- const ownerC = room.clients.find((c) => c.sessionId === 'O');
- room._handleTombLoot(ownerC, { id: t.id });
- ok(ownerC.messages.some((m) => m.data?.text?.includes('Walk up')), 'owner must be adjacent too');
-
- // Owner walks back adjacent → recovers everything, bag removed.
- owner.tx = 10; owner.ty = 11;
- room._handleTombLoot(ownerC, { id: t.id });
- eq(invCount(owner, 'wood'), 50, 'owner recovered all wood');
- eq(room.state.tombstones.size, 0, 'emptied bag removed');
-}
-
-console.log('Test 5 — grace window opens the bag to anyone adjacent');
-{
- const room = makeRoom('wilderness');
- const { p: owner } = addPlayer(room, 'O', 'Owner', 10, 10);
- owner.inv[0].item = 'coal'; owner.inv[0].qty = 20;
- room._killPlayer(owner);
- const t = firstTomb(room);
- // Force the bag into its final grace window.
- t.expiresAt = Date.now() + GRACE - 1000;
- const { p: looter, client: looterC } = addPlayer(room, 'L', 'Looter', 11, 10);
- room._handleTombLoot(looterC, { id: t.id });
- eq(invCount(looter, 'coal'), 20, 'non-owner loots during grace window');
- eq(room.state.tombstones.size, 0, 'emptied bag removed');
-}
-
-console.log('Test 6 — inventory math is exact (full pack + partial fit)');
-{
- const { Tombstone } = await import('../multiplayer/src/schemas/game.js');
- // Full pack: every backpack + hotbar slot maxed with wood. Nothing can fit;
- // the bag must keep everything (no loss) and survive.
- const room = makeRoom('wilderness');
- const { p: owner, client } = addPlayer(room, 'O', 'Owner', 10, 11);
- for (const s of [...owner.inv, ...owner.hotbar]) { s.item = 'wood'; s.qty = 999; }
- const t = new Tombstone();
- t.id = 'tomb_manual'; t.owner = 'O'; t.ownerName = 'Owner'; t.tx = 10; t.ty = 10;
- t.expiresAt = Date.now() + TTL; t.items.push(new Slot('wood', 500));
- room.state.tombstones.set(t.id, t);
-
- const totalBefore = invCount(owner, 'wood') + 500;
- room._handleTombLoot(client, { id: t.id });
- eq(invCount(owner, 'wood') + (tombItems(t).wood || 0), totalBefore, 'no duplication/loss with a full pack');
- eq(tombItems(t).wood, 500, 'full pack leaves all 500 in the bag');
- ok(room.state.tombstones.has(t.id), 'bag remains when nothing could be taken');
- ok(client.messages.some((m) => m.data?.text?.includes('pack is full')), 'full-pack notice shown');
-
- // Partial fit: free exactly 499 of room in one backpack stack.
- owner.inv[0].qty = 500; // room for 499 more in this stack
- const total2 = invCount(owner, 'wood') + (tombItems(t).wood || 0);
- room._handleTombLoot(client, { id: t.id });
- eq(invCount(owner, 'wood') + (tombItems(t).wood || 0), total2, 'conserved across a partial recovery');
- eq(tombItems(t).wood || 0, 1, 'exactly the overflow (1) remains in the bag');
- ok(room.state.tombstones.has(t.id), 'partially-emptied bag remains');
-}
-
-console.log('Test 7 — expiry in _tick + realm-aware respawn');
-{
- const room = makeRoom('wilderness');
- const { p } = addPlayer(room, 'O', 'Owner', 10, 10);
- p.inv[0].item = 'wood'; p.inv[0].qty = 5;
- room._killPlayer(p);
- const t = firstTomb(room);
- t.expiresAt = Date.now() - 1; // already crumbled
- p.respawnAt = Date.now() - 1; // due to respawn
- room._tick();
- eq(room.state.tombstones.size, 0, 'expired bag removed in the sim tick');
- ok(!p.dead && p.hp === p.maxHp, 'player respawned at full HP');
- eq(p.tx, REALMS.wilderness.spawn.tx, 'respawn tx = THIS realm spawn');
- eq(p.ty, REALMS.wilderness.spawn.ty, 'respawn ty = THIS realm spawn');
-}
-
-console.log('Test 8 — a bag with zero droppable loot is never created');
-{
- const room = makeRoom('wilderness');
- const { p } = addPlayer(room, 'O', 'Owner', 10, 10);
- // Only tools on board — nothing to drop.
- p.hotbar[0].item = 'axe'; p.hotbar[0].qty = 1;
- room._killPlayer(p);
- eq(room.state.tombstones.size, 0, 'no empty bag spawned');
-}
-
-console.log(`\n${passed} passed, ${failed} failed`);
-process.exit(failed ? 1 : 0);
diff --git a/scripts/verify-chat-commands.mjs b/scripts/verify-chat-commands.mjs
deleted file mode 100644
index c2f772286..000000000
--- a/scripts/verify-chat-commands.mjs
+++ /dev/null
@@ -1,172 +0,0 @@
-// Browser verification for Task 13 — the client slash-command autocomplete.
-//
-// The server command router (parse/validate/dispatch, /help, /who, rate-limit,
-// unknown-command errors) is covered by a separate logic check; this harness
-// drives the real /game page in a browser to exercise the NEW client UI:
-// the autocomplete dropdown, keyboard navigation, Tab/Enter completion, and
-// mouse selection — against the real DOM, CSS, and event wiring.
-//
-// It reaches the live IsoGame instance (window.__ISO__), puts it in the 'world'
-// phase, and feeds it the command manifest exactly as the server sends it on
-// join (commandManifest()). No multiplayer server required.
-//
-// npm run dev # http://localhost:3000
-// node scripts/verify-chat-commands.mjs
-import { chromium } from 'playwright';
-
-const URL = process.env.GAME_URL || 'http://localhost:3000/game.html';
-// Mirrors multiplayer/src/rooms/commands.js commandManifest() — the shape the
-// server pushes over the 'commands' message on join.
-const MANIFEST = [
- { name: 'help', args: '', aliases: ['commands', 'h', '?'], desc: 'List the commands you can use' },
- { name: 'who', args: '', aliases: ['players', 'online'], desc: 'List the players in your realm' },
- { name: 'pickup', args: '', aliases: ['take'], desc: 'Pick up your firepit or shack you are standing beside' },
- { name: 'lock', args: '', aliases: [], desc: 'Lock the structure beside you against stray clicks' },
- { name: 'unlock', args: '', aliases: [], desc: 'Unlock the structure beside you' },
- { name: 'dismount', args: '', aliases: ['unmount'], desc: 'Climb down from your mount' },
-];
-
-const ok = [];
-const fail = [];
-const check = (cond, msg) => (cond ? ok : fail).push(msg);
-
-const browser = await chromium.launch();
-const page = await browser.newContext({ viewport: { width: 1280, height: 800 } }).then((c) => c.newPage());
-const consoleErrors = [];
-// Filter environmental noise: colyseus/vite-HMR sockets fail without a running
-// server, and auth/API endpoints require credentials not present in this test env.
-const ENV_NOISE = /WebSocket|game-net|ERR_CONNECTION|vite|websocket|401|403|api\//i;
-page.on('console', (m) => { if (m.type() === 'error' && !ENV_NOISE.test(m.text())) consoleErrors.push(m.text()); });
-page.on('pageerror', (e) => { if (!ENV_NOISE.test(e.message)) consoleErrors.push('pageerror: ' + e.message); });
-
-await page.goto(URL, { waitUntil: 'domcontentloaded' });
-await page.waitForFunction(() => window.__ISO__ && typeof window.__ISO__._onCommands === 'function', { timeout: 15000 });
-
-// Put the game in-world and hand it the manifest exactly as the server would.
-await page.evaluate((manifest) => {
- const g = window.__ISO__;
- g.phase = 'world';
- g._setHudPhase('world'); // hides the start overlay, reveals the chat panel
- g._onCommands(manifest);
-}, MANIFEST);
-check(true, 'reached in-world IsoGame and loaded command manifest');
-
-const input = page.locator('#kg-chat-input');
-await input.click();
-
-// '/' → full registry, in registry order.
-await input.type('/');
-await page.waitForSelector('#kg-chat-hint:not([hidden])', { timeout: 3000 });
-const all = await page.$$eval('#kg-chat-hint .kg-chat-hint-cmd', (els) => els.map((e) => e.textContent.trim()));
-check(all.length === 6, `'/' lists all 6 commands (got ${all.length}: ${all.join(', ')})`);
-check(all[0] === '/help' && all.includes('/dismount'), 'list is registry-ordered and complete');
-const descs = await page.$$eval('#kg-chat-hint .kg-chat-hint-desc', (els) => els.map((e) => e.textContent.trim()));
-check(descs.every((d) => d.length > 0), 'every suggestion shows a description');
-
-// Alias match: 'unm' → /dismount (alias 'unmount').
-await input.fill('/unm');
-await page.waitForTimeout(80);
-const alias = await page.$$eval('#kg-chat-hint .kg-chat-hint-cmd', (els) => els.map((e) => e.textContent.trim()));
-check(alias.length === 1 && alias[0] === '/dismount', `alias 'unm' resolves to /dismount (got ${alias.join(', ')})`);
-
-// Prefix narrowing: '/l' → /lock only.
-await input.fill('/l');
-await page.waitForTimeout(80);
-const pre = await page.$$eval('#kg-chat-hint .kg-chat-hint-cmd', (els) => els.map((e) => e.textContent.trim()));
-check(pre.length === 1 && pre[0] === '/lock', `'/l' narrows to /lock (got ${pre.join(', ')})`);
-
-// Keyboard nav: ArrowDown highlights the first row.
-await input.fill('/');
-await page.waitForTimeout(60);
-await input.press('ArrowDown');
-const active1 = await page.$eval('#kg-chat-hint .kg-chat-hint-item--active .kg-chat-hint-cmd', (e) => e.textContent.trim()).catch(() => null);
-check(active1 === '/help', `ArrowDown highlights first command (got ${active1})`);
-await input.press('ArrowUp'); // wrap to last
-const active2 = await page.$eval('#kg-chat-hint .kg-chat-hint-item--active .kg-chat-hint-cmd', (e) => e.textContent.trim()).catch(() => null);
-check(active2 === '/dismount', `ArrowUp from first wraps to last (got ${active2})`);
-const aria = await input.getAttribute('aria-activedescendant');
-check(aria === 'kg-chat-hint-5', `aria-activedescendant tracks selection (got ${aria})`);
-
-// Tab completes the highlighted command into the field and (no args) hides the hint.
-await input.press('Tab');
-check((await input.inputValue()) === '/dismount', `Tab completes highlighted command (got "${await input.inputValue()}")`);
-check(await page.locator('#kg-chat-hint').isHidden(), 'hint hides after completing a no-arg command');
-
-// Typing a space (args) hides the hint; clearing back to a bare name reopens it.
-await input.fill('/who ');
-await page.waitForTimeout(60);
-check(await page.locator('#kg-chat-hint').isHidden(), 'hint hides once a space (args) is typed');
-
-// Escape dismisses an open hint without closing the chat.
-await input.fill('/p');
-await page.waitForTimeout(60);
-check(await page.locator('#kg-chat-hint').isVisible(), "'/p' reopens the hint");
-await input.press('Escape');
-check(await page.locator('#kg-chat-hint').isHidden(), 'Escape dismisses the hint');
-check(await page.locator('#kg-chat-input').isVisible(), 'chat input still present after Escape');
-
-// Mouse pick fills the input (it then sends via the net path).
-await input.fill('/pi');
-await page.waitForTimeout(60);
-await page.locator('#kg-chat-hint .kg-chat-hint-item').first().click();
-await page.waitForTimeout(60);
-// After a pick the field is cleared by _sendChat; assert the hint closed cleanly.
-check(await page.locator('#kg-chat-hint').isHidden(), 'mouse pick completes + closes the hint');
-
-// Chat history: send a message, then use ↑ to recall it.
-// Seed the history directly via the game instance (net is offline so chat() is a no-op).
-await page.evaluate(() => {
- const g = window.__ISO__;
- g._chatHistory = ['hello realm', '/who']; // reset to a known state
- g._chatHistoryCursor = -1;
- g._chatHistoryDraft = '';
-});
-await input.fill('');
-await input.press('ArrowUp'); // → most recent: /who
-await page.waitForTimeout(60);
-check((await input.inputValue()) === '/who', `ArrowUp recalls most recent message (got "${await input.inputValue()}")`);
-await input.press('ArrowUp'); // → older: hello realm
-await page.waitForTimeout(60);
-check((await input.inputValue()) === 'hello realm', `ArrowUp again recalls older message (got "${await input.inputValue()}")`);
-await input.press('ArrowUp'); // at oldest → stays
-await page.waitForTimeout(60);
-check((await input.inputValue()) === 'hello realm', `ArrowUp at oldest clamps (got "${await input.inputValue()}")`);
-await input.press('ArrowDown'); // → /who
-await page.waitForTimeout(60);
-check((await input.inputValue()) === '/who', `ArrowDown moves to newer (got "${await input.inputValue()}")`);
-await input.press('ArrowDown'); // → back to draft (empty)
-await page.waitForTimeout(60);
-check((await input.inputValue()) === '', `ArrowDown to draft restores empty field (got "${await input.inputValue()}")`);
-
-// Editing while in history recall resets cursor so next ↑ starts fresh from most recent.
-await input.press('ArrowUp'); // enter history
-await input.type('x'); // edit → cursor resets
-await page.waitForTimeout(60);
-await input.fill(''); await input.press('ArrowUp'); // fresh recall from most recent
-await page.waitForTimeout(60);
-check((await input.inputValue()) === '/who', `editing breaks recall; fresh ArrowUp starts from most recent (got "${await input.inputValue()}")`);
-
-// /help reply has kg-chat-line--help CSS class applied.
-// /who reply has kg-chat-line--who CSS class applied.
-// Drive a local sysLine to confirm (it goes through _appendChatLine).
-await page.evaluate(() => { window.__ISO__._sysLine('Commands\n /help', 'help'); });
-await page.waitForTimeout(60);
-const hasHelpClass = await page.$eval('.kg-chat-line--help', () => true).catch(() => false);
-check(hasHelpClass, '/help system line gets kg-chat-line--help class');
-await page.evaluate(() => { window.__ISO__._sysLine('1 player in Mainland\n • Verifier (you)', 'who'); });
-await page.waitForTimeout(60);
-const hasWhoClass = await page.$eval('.kg-chat-line--who', () => true).catch(() => false);
-check(hasWhoClass, '/who system line gets kg-chat-line--who class');
-
-check(consoleErrors.length === 0, `no unexpected console errors (${consoleErrors.length}): ${consoleErrors.slice(0, 3).join(' | ')}`);
-
-await browser.close();
-
-console.log('\n=== client autocomplete ===');
-ok.forEach((m) => console.log(' PASS ' + m));
-if (fail.length) {
- console.log('\n=== FAILURES ===');
- fail.forEach((m) => console.log(' FAIL ' + m));
- process.exit(1);
-}
-console.log(`\nAll ${ok.length} checks passed.`);
diff --git a/src/forge.js b/src/forge.js
new file mode 100644
index 000000000..814d7b4b1
--- /dev/null
+++ b/src/forge.js
@@ -0,0 +1,251 @@
+// Forge — text → 3D generator (browser client).
+//
+// Drives /api/forge: POST a prompt to start a job, then poll GET /api/forge?job
+// until it resolves to a GLB. State transitions are driven by real API
+// responses — the reference image appears the moment the text-to-image pass
+// returns, the "mesh" step lights up when the reconstruction job is actually
+// running, and the result panel shows the real downloadable GLB. The only timer
+// is the honest elapsed counter; nothing fakes progress.
+
+const POLL_INTERVAL_MS = 2500;
+const MAX_POLL_MS = 5 * 60 * 1000; // give the reconstruction a generous ceiling
+
+const els = {
+ form: document.getElementById('composer'),
+ prompt: document.getElementById('prompt'),
+ aspect: document.getElementById('aspect'),
+ generate: document.getElementById('generate'),
+ generateLabel: document.getElementById('generate-label'),
+ examples: document.getElementById('examples'),
+ stage: document.getElementById('stage'),
+ states: {
+ empty: document.getElementById('state-empty'),
+ generating: document.getElementById('state-generating'),
+ result: document.getElementById('state-result'),
+ error: document.getElementById('state-error'),
+ unconfigured: document.getElementById('state-unconfigured'),
+ },
+ genPreview: document.getElementById('gen-preview'),
+ genMeta: document.getElementById('gen-meta'),
+ steps: {
+ image: document.getElementById('step-image'),
+ mesh: document.getElementById('step-mesh'),
+ finish: document.getElementById('step-finish'),
+ },
+ cancel: document.getElementById('cancel'),
+ viewer: document.getElementById('viewer'),
+ resultLabel: document.getElementById('result-label'),
+ download: document.getElementById('download'),
+ again: document.getElementById('again'),
+ retry: document.getElementById('retry'),
+ errorMessage: document.getElementById('error-message'),
+};
+
+let aspectRatio = '1:1';
+let elapsedTimer = null;
+let pollAbort = false;
+let lastPrompt = '';
+
+function showState(name) {
+ for (const [key, node] of Object.entries(els.states)) {
+ node.classList.toggle('is-hidden', key !== name);
+ }
+}
+
+function setStep(step, state) {
+ if (els.steps[step]) els.steps[step].dataset.state = state;
+}
+
+function startElapsed() {
+ const started = performance.now();
+ stopElapsed();
+ const tick = () => {
+ const s = Math.floor((performance.now() - started) / 1000);
+ els.genMeta.textContent = `Elapsed ${s}s`;
+ };
+ tick();
+ elapsedTimer = window.setInterval(tick, 1000);
+}
+
+function stopElapsed() {
+ if (elapsedTimer) {
+ window.clearInterval(elapsedTimer);
+ elapsedTimer = null;
+ }
+}
+
+function setBusy(busy) {
+ els.generate.disabled = busy;
+ els.generateLabel.textContent = busy ? 'Forging…' : 'Generate';
+}
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+async function startJob(prompt) {
+ const res = await fetch('/api/forge', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ prompt, aspect_ratio: aspectRatio }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503 || data.error === 'unconfigured') {
+ const e = new Error(data.message || 'unconfigured');
+ e.kind = 'unconfigured';
+ throw e;
+ }
+ if (!res.ok) {
+ throw new Error(data.message || `The generator returned ${res.status}.`);
+ }
+ return data;
+}
+
+async function pollUntilDone(jobId) {
+ const deadline = performance.now() + MAX_POLL_MS;
+ while (!pollAbort && performance.now() < deadline) {
+ await sleep(POLL_INTERVAL_MS);
+ if (pollAbort) return null;
+ const res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`);
+ const data = await res.json().catch(() => ({}));
+ if (data.error === 'unconfigured') {
+ const e = new Error(data.message || 'unconfigured');
+ e.kind = 'unconfigured';
+ throw e;
+ }
+ if (data.status === 'done' && data.glb_url) return data.glb_url;
+ if (data.status === 'failed') throw new Error(data.error || 'Generation failed.');
+ if (data.status === 'running') setStep('mesh', 'active');
+ }
+ if (pollAbort) return null;
+ throw new Error('Generation timed out. The model may be too complex — try a simpler prompt.');
+}
+
+function showResult(glbUrl, prompt) {
+ stopElapsed();
+ els.viewer.setAttribute('src', glbUrl);
+ els.viewer.setAttribute('alt', `3D model: ${prompt}`);
+ els.resultLabel.textContent = prompt;
+ els.download.href = glbUrl;
+ els.download.setAttribute(
+ 'download',
+ `${prompt.replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'forge'}.glb`,
+ );
+ showState('result');
+}
+
+function showError(message) {
+ stopElapsed();
+ els.errorMessage.textContent = message;
+ showState('error');
+}
+
+async function run(prompt) {
+ lastPrompt = prompt;
+ pollAbort = false;
+ setBusy(true);
+
+ // Reset generating UI to its initial real state.
+ els.genPreview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';
+ setStep('image', 'active');
+ setStep('mesh', 'pending');
+ setStep('finish', 'pending');
+ startElapsed();
+ showState('generating');
+
+ try {
+ const job = await startJob(prompt);
+
+ // Text-to-image really resolved before the POST returned: show it.
+ if (job.preview_image_url) {
+ setStep('image', 'done');
+ setStep('mesh', 'active');
+ const img = new Image();
+ img.alt = 'Reference image';
+ img.src = job.preview_image_url;
+ img.onload = () => {
+ els.genPreview.innerHTML = '';
+ els.genPreview.appendChild(img);
+ };
+ }
+
+ const glbUrl = await pollUntilDone(job.job_id);
+ if (pollAbort || !glbUrl) return; // cancelled
+
+ setStep('mesh', 'done');
+ setStep('finish', 'done');
+ showResult(glbUrl, prompt);
+ } catch (err) {
+ if (pollAbort) return;
+ if (err.kind === 'unconfigured') {
+ stopElapsed();
+ showState('unconfigured');
+ return;
+ }
+ showError(err.message || 'Something went wrong. Try a simpler, single-subject prompt.');
+ } finally {
+ setBusy(false);
+ }
+}
+
+function submit() {
+ const prompt = els.prompt.value.trim();
+ if (prompt.length < 3) {
+ els.prompt.focus();
+ return;
+ }
+ run(prompt);
+}
+
+// Wiring ----------------------------------------------------------------------
+
+els.form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ submit();
+});
+
+// Cmd/Ctrl+Enter submits from the textarea.
+els.prompt.addEventListener('keydown', (e) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
+ e.preventDefault();
+ submit();
+ }
+});
+
+els.aspect.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-aspect]');
+ if (!btn) return;
+ aspectRatio = btn.dataset.aspect;
+ for (const b of els.aspect.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(b === btn));
+ }
+});
+
+els.examples.addEventListener('click', (e) => {
+ const chip = e.target.closest('.chip');
+ if (!chip) return;
+ els.prompt.value = chip.textContent.trim();
+ els.prompt.focus();
+ submit();
+});
+
+els.cancel.addEventListener('click', () => {
+ pollAbort = true;
+ stopElapsed();
+ setBusy(false);
+ showState('empty');
+});
+
+els.again.addEventListener('click', () => {
+ els.prompt.focus();
+ els.prompt.select();
+ showState('empty');
+});
+
+els.retry.addEventListener('click', () => {
+ if (lastPrompt) run(lastPrompt);
+ else {
+ showState('empty');
+ els.prompt.focus();
+ }
+});
diff --git a/src/game/game-hud.js b/src/game/game-hud.js
deleted file mode 100644
index 8409cf769..000000000
--- a/src/game/game-hud.js
+++ /dev/null
@@ -1,1415 +0,0 @@
-// GameHud — the DOM HUD layer for the /game isometric client: the hotbar, the
-// quest panel (tutorial + daily quests), Aldric's dialog, and the bank panel.
-//
-// It owns only DOM + presentation. Every player intent flows back out through
-// callbacks passed in `opts` (onEquip, onDeposit, onWithdraw, onTurnIn, …) so
-// the scene controller (iso-game.js) stays the single owner of the network and
-// world state. The HUD is told what to render via setHotbar/setInventory/
-// setBank/setQuests and never reaches into the scene itself.
-//
-// All quest state shown here is the server's authoritative snapshot — progress
-// bars, reward previews, turn-in availability, and the reset countdown are
-// derived from it. The countdown ticks on the real clock and, when it elapses,
-// asks the controller to re-fetch (onReset) so a new day's board appears
-// without a reconnect.
-
-// Item presentation. Icons are emoji so there is no asset pipeline to miss; the
-// server's item registry (the 'items' message) can override labels later, but
-// these cover everything the world produces today.
-const ITEM_META = {
- axe: { icon: '🪓', label: 'Axe' },
- pickaxe: { icon: '⛏️', label: 'Pickaxe' },
- rod: { icon: '🎣', label: 'Fishing Rod' },
- hammer: { icon: '🔨', label: 'Hammer' },
- sword: { icon: '⚔️', label: 'Sword' },
- wood: { icon: '🪵', label: 'Wood' },
- stone: { icon: '🪨', label: 'Stone' },
- coal: { icon: '⚫', label: 'Coal' },
- fish: { icon: '🐟', label: 'Raw Fish' },
- cookedFish: { icon: '🍤', label: 'Cooked Fish' },
- bones: { icon: '🦴', label: 'Bones' },
- hide: { icon: '🟫', label: 'Beast Hide' },
- healthPotion: { icon: '🧪', label: 'Health Potion' },
- dire_wolf: { icon: '🐺', label: 'Dire Wolf' },
- war_boar: { icon: '🐗', label: 'War Boar' },
-};
-export function itemMeta(id) {
- return ITEM_META[id] || { icon: '📦', label: id ? id[0].toUpperCase() + id.slice(1) : '' };
-}
-
-// Emoji shown on a worn-prop cosmetic's shop/wardrobe chip, by cosmetic id. The
-// 3D prop itself is the real cosmetic; this is just the catalogue glyph.
-const PROP_ICON = {
- 'hat-beanie': '🧢',
- 'hat-baseball': '🧢',
- 'hat-cowboy': '🤠',
- 'glasses-round': '👓',
- 'glasses-shades': '🕶️',
-};
-
-// Cosmetics at or above this price ask for a second confirming click before the
-// gold is spent, so a stray tap never burns a big purchase.
-const CONFIRM_PRICE = 400;
-
-const SKILL_LABEL = { combat: 'Combat', woodcutting: 'Woodcutting', mining: 'Mining', fishing: 'Fishing', cooking: 'Cooking' };
-
-function fmtCountdown(ms) {
- if (ms <= 0) return 'now';
- const s = Math.floor(ms / 1000);
- const h = Math.floor(s / 3600);
- const m = Math.floor((s % 3600) / 60);
- const sec = s % 60;
- if (h > 0) return `${h}h ${m}m`;
- if (m > 0) return `${m}m ${sec}s`;
- return `${sec}s`;
-}
-
-function el(tag, cls, html) {
- const e = document.createElement(tag);
- if (cls) e.className = cls;
- if (html != null) e.innerHTML = html;
- return e;
-}
-
-export class GameHud {
- constructor(opts = {}) {
- this.opts = opts;
- this.snapshot = null; // latest quest snapshot
- this.inv = []; // local player's backpack slots
- this.bank = []; // bank contents
- this.hotbarSlots = [];
- this.activeSlot = -1;
- this._tutHintSlot = -1; // hotbar index the active tutorial step is teaching (-1 = none)
- this._questOpen = false;
- this._bankOpen = false;
- this._npcOpen = false;
- this._resetAt = 0;
- // Cosmetics shop (Task 21): the static catalogue (id → entry) + rarity
- // palette, the latest live board (offers/owned/equipped), the current gold,
- // the open flag + active tab, and the rotation deadlines the ticker counts
- // down to (re-fetching the board when one elapses).
- this.cosmetics = new Map();
- this.rarities = {};
- this.shop = null;
- this.gold = 0;
- this._shopOpen = false;
- this._shopTab = 'shop';
- this._dailyResetAt = 0;
- this._weeklyResetAt = 0;
- // Wardrobe try-before-equip: the id currently previewed on the local
- // avatar (null = none). Local-only; cleared when the shop closes.
- this._previewId = null;
- // Two-step buy confirmation for pricier cosmetics: the id awaiting a second
- // click (null = none) and the timer that resets it if the player hesitates.
- this._confirmBuyId = null;
- this._confirmTimer = null;
- // Marketplace (Task 20): the latest board (active listings + your own), the
- // token-payment capability flags, the open flag + active tab, per-listing
- // "busy" labels driven by the controller during an on-chain buy, an error
- // banner, and the Sell-form draft state (mode + selected item + inputs).
- this.market = { listings: [], mine: [], token: { enabled: false, symbol: '$THREE', decimals: 6, treasuryBps: 500 }, canToken: false };
- this._marketOpen = false;
- this._marketTab = 'buy';
- this._marketBusy = new Map(); // listingId -> status label shown on its card
- this._marketError = '';
- this._marketLoading = false;
- this._buyFilter = '';
- this._buySort = 'recent';
- this._sellMode = 'gold'; // 'gold' (item→gold) | 'token' (gold→$THREE)
- this._sellItem = ''; // selected backpack item id for a gold listing
- this._build();
- // One shared 1Hz ticker drives the live reset countdown wherever it shows.
- this._tick = this._tick.bind(this);
- this._timer = setInterval(this._tick, 1000);
- }
-
- // ---------------------------------------------------------------- build
- _build() {
- const root = el('div', 'kq-root');
- root.innerHTML = `
- <div id="kq-toolbar" class="kq-toolbar" hidden>
- <button id="kq-quest-btn" class="kq-tool-btn" type="button" aria-label="Quests (Q)" title="Quests (Q)">
- <span class="kq-tool-ic">📜</span><span class="kq-tool-lbl">Quests</span>
- <span id="kq-quest-dot" class="kq-dot" hidden></span>
- </button>
- <button id="kq-bank-btn" class="kq-tool-btn" type="button" aria-label="Open bank" title="Open bank" hidden>
- <span class="kq-tool-ic">🏦</span><span class="kq-tool-lbl">Bank</span>
- </button>
- <button id="kq-build-btn" class="kq-tool-btn" type="button" aria-label="Build (B)" title="Build (B)" hidden aria-expanded="false">
- <span class="kq-tool-ic">🔨</span><span class="kq-tool-lbl">Build</span>
- </button>
- <button id="kq-shop-btn" class="kq-tool-btn" type="button" aria-label="Cosmetics shop" title="Cosmetics shop" aria-expanded="false">
- <span class="kq-tool-ic">✨</span><span class="kq-tool-lbl">Shop</span>
- </button>
- <button id="kq-market-btn" class="kq-tool-btn" type="button" aria-label="Marketplace (M)" title="Marketplace (M)" aria-expanded="false">
- <span class="kq-tool-ic">🛒</span><span class="kq-tool-lbl">Market</span>
- </button>
- <span id="kq-gold" class="kq-gold" title="Gold"><span class="kq-gold-ic">🪙</span><b id="kq-gold-n">0</b></span>
- </div>
-
- <div id="kq-hotbar" class="kq-hotbar" hidden role="toolbar" aria-label="Hotbar"></div>
-
- <div id="kq-build-menu" class="kq-build-menu" hidden role="dialog" aria-label="Build menu">
- <header class="kq-build-head"><span class="kq-tool-ic">🔨</span><h2>Build</h2><button class="kq-x" id="kq-build-x" type="button" aria-label="Close">✕</button></header>
- <div class="kq-build-list" id="kq-build-list"></div>
- </div>
-
- <div id="kq-build-banner" class="kq-build-banner" hidden role="status">
- <span class="kq-build-banner-ic" id="kq-build-banner-ic">🔥</span>
- <span class="kq-build-banner-txt">Placing <b id="kq-build-banner-name">structure</b> · tap a tile to place</span>
- <button class="kq-btn kq-btn-ghost" id="kq-build-cancel" type="button">Cancel</button>
- </div>
-
- <aside id="kq-quests" class="kq-panel" hidden aria-label="Quests">
- <header class="kq-panel-head">
- <h2>Quests</h2>
- <button class="kq-x" id="kq-quests-x" type="button" aria-label="Close">✕</button>
- </header>
- <div class="kq-panel-body" id="kq-quests-body"></div>
- </aside>
-
- <div id="kq-npc" class="kq-modal" hidden>
- <div class="kq-modal-card kq-npc-card" role="dialog" aria-modal="true" aria-label="Conversation">
- <button class="kq-x" id="kq-npc-x" type="button" aria-label="Close">✕</button>
- <div class="kq-npc-head"><span class="kq-npc-portrait">🧙</span><div><div class="kq-npc-name" id="kq-npc-name">Aldric the Guide</div><div class="kq-npc-role">Mainland Guide</div></div></div>
- <p class="kq-npc-line" id="kq-npc-line"></p>
- <div class="kq-npc-body" id="kq-npc-body"></div>
- <button class="kq-btn kq-btn-ghost" id="kq-npc-quests" type="button">Open quest log</button>
- </div>
- </div>
-
- <div id="kq-bank" class="kq-modal" hidden>
- <div class="kq-modal-card kq-bank-card" role="dialog" aria-modal="true" aria-label="Bank">
- <button class="kq-x" id="kq-bank-x" type="button" aria-label="Close">✕</button>
- <header class="kq-bank-head"><span class="kq-tool-ic">🏦</span><h2>Bank</h2><span class="kq-bank-hint">Click an item to move it</span></header>
- <div class="kq-bank-cols">
- <section class="kq-bank-col"><h3>Backpack</h3><div class="kq-grid" id="kq-bank-inv"></div></section>
- <section class="kq-bank-col"><h3>Stored</h3><div class="kq-grid" id="kq-bank-store"></div></section>
- </div>
- </div>
- </div>
-
- <div id="kq-shop" class="kq-modal" hidden>
- <div class="kq-modal-card kq-shop-card" role="dialog" aria-modal="true" aria-label="Cosmetics shop">
- <button class="kq-x" id="kq-shop-x" type="button" aria-label="Close">✕</button>
- <header class="kq-shop-head">
- <span class="kq-tool-ic">✨</span>
- <h2>Cosmetics</h2>
- <span class="kq-shop-purse" title="Your gold">🪙 <b id="kq-shop-gold">0</b></span>
- </header>
- <div class="kq-shop-tabs" role="tablist">
- <button class="kq-shop-tab kq-shop-tab--on" id="kq-shop-tab-shop" type="button" role="tab" aria-selected="true">Shop</button>
- <button class="kq-shop-tab" id="kq-shop-tab-wardrobe" type="button" role="tab" aria-selected="false">Wardrobe</button>
- <button class="kq-shop-tab" id="kq-shop-tab-collection" type="button" role="tab" aria-selected="false">Collection</button>
- </div>
- <p class="kq-shop-note">Cosmetics are purely cosmetic — they change how you look, never how you play.</p>
- <div class="kq-shop-body" id="kq-shop-body"></div>
- </div>
- </div>
-
- <div id="kq-market" class="kq-modal" hidden>
- <div class="kq-modal-card kq-market-card" role="dialog" aria-modal="true" aria-label="Marketplace">
- <button class="kq-x" id="kq-market-x" type="button" aria-label="Close">✕</button>
- <header class="kq-market-head">
- <span class="kq-tool-ic">🛒</span>
- <h2>Marketplace</h2>
- <span class="kq-shop-purse" title="Your gold">🪙 <b id="kq-market-gold">0</b></span>
- </header>
- <div class="kq-market-tabs" role="tablist">
- <button class="kq-market-tab kq-market-tab--on" id="kq-market-tab-buy" type="button" role="tab" aria-selected="true">Buy</button>
- <button class="kq-market-tab" id="kq-market-tab-sell" type="button" role="tab" aria-selected="false">Sell</button>
- <button class="kq-market-tab" id="kq-market-tab-mine" type="button" role="tab" aria-selected="false">My Listings</button>
- </div>
- <div class="kq-market-body" id="kq-market-body"></div>
- </div>
- </div>
- `;
- document.body.appendChild(root);
- this.root = root;
- this.elToolbar = root.querySelector('#kq-toolbar');
- this.elQuestBtn = root.querySelector('#kq-quest-btn');
- this.elQuestDot = root.querySelector('#kq-quest-dot');
- this.elBankBtn = root.querySelector('#kq-bank-btn');
- this.elHotbar = root.querySelector('#kq-hotbar');
- this.elQuests = root.querySelector('#kq-quests');
- this.elQuestsBody = root.querySelector('#kq-quests-body');
- this.elNpc = root.querySelector('#kq-npc');
- this.elNpcName = root.querySelector('#kq-npc-name');
- this.elNpcLine = root.querySelector('#kq-npc-line');
- this.elNpcBody = root.querySelector('#kq-npc-body');
- this.elBank = root.querySelector('#kq-bank');
- this.elBankInv = root.querySelector('#kq-bank-inv');
- this.elBankStore = root.querySelector('#kq-bank-store');
- this.elBuildBtn = root.querySelector('#kq-build-btn');
- this.elBuildMenu = root.querySelector('#kq-build-menu');
- this.elBuildList = root.querySelector('#kq-build-list');
- this.elBuildBanner = root.querySelector('#kq-build-banner');
- this.elBuildBannerIc = root.querySelector('#kq-build-banner-ic');
- this.elBuildBannerName = root.querySelector('#kq-build-banner-name');
- this.elShopBtn = root.querySelector('#kq-shop-btn');
- this.elGoldN = root.querySelector('#kq-gold-n');
- this.elShop = root.querySelector('#kq-shop');
- this.elShopBody = root.querySelector('#kq-shop-body');
- this.elShopGold = root.querySelector('#kq-shop-gold');
- this.elShopTabShop = root.querySelector('#kq-shop-tab-shop');
- this.elShopTabWardrobe = root.querySelector('#kq-shop-tab-wardrobe');
- this.elShopTabCollection = root.querySelector('#kq-shop-tab-collection');
-
- this.elQuestBtn.addEventListener('click', () => this.toggleQuests());
- root.querySelector('#kq-quests-x').addEventListener('click', () => this.closeQuests());
- this.elBankBtn.addEventListener('click', () => { this.opts.onBankOpen?.(); this.openBank(); });
- root.querySelector('#kq-bank-x').addEventListener('click', () => this.closeBank());
- root.querySelector('#kq-npc-x').addEventListener('click', () => this.closeNpc());
- root.querySelector('#kq-npc-quests').addEventListener('click', () => { this.closeNpc(); this.openQuests(); });
- // Click the backdrop (outside the card) to dismiss modals.
- this.elNpc.addEventListener('click', (e) => { if (e.target === this.elNpc) this.closeNpc(); });
- this.elBank.addEventListener('click', (e) => { if (e.target === this.elBank) this.closeBank(); });
- this.elBuildBtn.addEventListener('click', () => this.toggleBuild());
- root.querySelector('#kq-build-x').addEventListener('click', () => this.closeBuild());
- root.querySelector('#kq-build-cancel').addEventListener('click', () => this.opts.onBuildCancel?.());
- this.elShopBtn.addEventListener('click', () => this.toggleShop());
- root.querySelector('#kq-shop-x').addEventListener('click', () => this.closeShop());
- this.elShop.addEventListener('click', (e) => { if (e.target === this.elShop) this.closeShop(); });
- this.elShopTabShop.addEventListener('click', () => this._setShopTab('shop'));
- this.elShopTabWardrobe.addEventListener('click', () => this._setShopTab('wardrobe'));
- this.elShopTabCollection.addEventListener('click', () => this._setShopTab('collection'));
-
- // Marketplace (Task 20).
- this.elMarketBtn = root.querySelector('#kq-market-btn');
- this.elMarket = root.querySelector('#kq-market');
- this.elMarketBody = root.querySelector('#kq-market-body');
- this.elMarketGold = root.querySelector('#kq-market-gold');
- this.elMarketTabBuy = root.querySelector('#kq-market-tab-buy');
- this.elMarketTabSell = root.querySelector('#kq-market-tab-sell');
- this.elMarketTabMine = root.querySelector('#kq-market-tab-mine');
- this.elMarketBtn.addEventListener('click', () => this.toggleMarket());
- root.querySelector('#kq-market-x').addEventListener('click', () => this.closeMarket());
- this.elMarket.addEventListener('click', (e) => { if (e.target === this.elMarket) this.closeMarket(); });
- this.elMarketTabBuy.addEventListener('click', () => this._setMarketTab('buy'));
- this.elMarketTabSell.addEventListener('click', () => this._setMarketTab('sell'));
- this.elMarketTabMine.addEventListener('click', () => this._setMarketTab('mine'));
- }
-
- // Reveal the toolbar + hotbar once the player is in the world.
- enterWorld() {
- this.elToolbar.hidden = false;
- this.elHotbar.hidden = false;
- }
-
- // ---------------------------------------------------------------- hotbar
- setHotbar(slots, activeSlot) {
- this.hotbarSlots = slots || [];
- this.activeSlot = activeSlot;
- this._renderHotbar();
- }
-
- _renderHotbar() {
- const frag = document.createDocumentFragment();
- for (let i = 0; i < this.hotbarSlots.length; i++) {
- const s = this.hotbarSlots[i] || { item: '', qty: 0 };
- const active = i === this.activeSlot;
- const hint = i === this._tutHintSlot && !active; // pulse only when not already selected
- const slot = el('button', 'kq-slot' + (active ? ' kq-slot--active' : '') + (hint ? ' kq-slot--hint' : '') + (s.item ? '' : ' kq-slot--empty'));
- slot.type = 'button';
- slot.setAttribute('aria-label', s.item ? `${itemMeta(s.item).label} (slot ${i + 1})` : `Empty slot ${i + 1}`);
- slot.setAttribute('aria-pressed', String(active));
- slot.innerHTML =
- `<span class="kq-key">${i + 1}</span>` +
- (s.item ? `<span class="kq-ic">${itemMeta(s.item).icon}</span>` : '') +
- (s.item && s.qty > 1 ? `<span class="kq-qty">${s.qty}</span>` : '');
- slot.addEventListener('click', () => this.opts.onEquip?.(i));
- frag.appendChild(slot);
- }
- this.elHotbar.replaceChildren(frag);
- }
-
- // ---------------------------------------------------------------- quests
- setQuests(snapshot) {
- this.snapshot = snapshot || null;
- this._resetAt = snapshot?.daily?.resetAt || 0;
- // Extract the hotbar slot the current tutorial step is teaching so the
- // hotbar can pulse it as a visual hint. -1 when there is none.
- const newHint = snapshot?.tutorial?.done === false && snapshot.tutorial.step
- ? (snapshot.tutorial.step.slot ?? -1)
- : -1;
- if (newHint !== this._tutHintSlot) {
- this._tutHintSlot = newHint;
- this._renderHotbar(); // re-render so the hint class applies/removes
- }
- this._renderQuestDot();
- if (this._questOpen) this._renderQuests();
- if (this._npcOpen) this._renderNpc();
- }
-
- // A pulsing dot on the Quests button when there's something to do: tutorial in
- // progress, or a daily finished and waiting to be claimed.
- _renderQuestDot() {
- this.elQuestDot.hidden = !this._hasActionableQuest();
- }
-
- _hasActionableQuest() {
- const s = this.snapshot;
- if (!s) return false;
- if (s.tutorial && !s.tutorial.done) return true;
- return (s.daily?.quests || []).some((q) => q.progress >= q.count && !q.claimed);
- }
-
- // True when a daily is finished and unclaimed — drives Aldric's "?" marker.
- hasTurnInReady() {
- return (this.snapshot?.daily?.quests || []).some((q) => q.progress >= q.count && !q.claimed);
- }
-
- tutorialActive() {
- return !!(this.snapshot?.tutorial && !this.snapshot.tutorial.done);
- }
-
- toggleQuests() { this._questOpen ? this.closeQuests() : this.openQuests(); }
- openQuests() { this._questOpen = true; this.elQuests.hidden = false; this.elQuests.classList.add('kq-in'); this._renderQuests(); }
- closeQuests() { this._questOpen = false; this.elQuests.classList.remove('kq-in'); this.elQuests.hidden = true; }
-
- _renderQuests() {
- const s = this.snapshot;
- const body = this.elQuestsBody;
- if (!s) { body.replaceChildren(el('p', 'kq-empty', 'Loading your quests…')); return; }
- const frag = document.createDocumentFragment();
-
- // Tutorial section.
- const tut = s.tutorial || {};
- const tutWrap = el('section', 'kq-section');
- if (tut.done) {
- tutWrap.appendChild(el('h3', 'kq-h3', 'Tutorial'));
- tutWrap.appendChild(el('div', 'kq-tut-done', '🎓 Training complete — you know the ropes.'));
- } else if (tut.step) {
- const stepHead = el('div', 'kq-tut-head');
- stepHead.appendChild(el('h3', 'kq-h3', 'Tutorial'));
- // Overall tutorial progress pill (steps done out of total).
- const overallBar = el('div', 'kq-tut-overall');
- const pctDone = tut.total > 0 ? (tut.stepIndex / tut.total) * 100 : 0;
- overallBar.innerHTML = `<span class="kq-tut-pips">${Array.from({ length: tut.total }, (_, i) => `<span class="kq-tut-pip${i < tut.stepIndex ? ' kq-tut-pip--done' : i === tut.stepIndex ? ' kq-tut-pip--active' : ''}"></span>`).join('')}</span><span class="kq-tut-frac">${tut.stepIndex + 1} / ${tut.total}</span>`;
- stepHead.appendChild(overallBar);
- tutWrap.appendChild(stepHead);
-
- const card = el('div', 'kq-card-q kq-card-tut');
- // Slot hint chip — "Equip slot 3" — when the step targets a hotbar slot.
- if (typeof tut.step.slot === 'number' && tut.step.slot >= 0) {
- const chip = el('div', 'kq-tut-slot-chip', `Equip slot <b>${tut.step.slot + 1}</b>`);
- chip.title = `Press ${tut.step.slot + 1} to equip`;
- card.appendChild(chip);
- }
- card.appendChild(el('div', 'kq-q-title', tut.step.title));
- card.appendChild(el('div', 'kq-q-desc', tut.step.desc));
- // Always show a progress bar — for count=1 it acts as a completion indicator.
- card.appendChild(this._bar(tut.progress, tut.step.count));
- tutWrap.appendChild(card);
- }
- frag.appendChild(tutWrap);
-
- // Daily section.
- const daily = s.daily || { quests: [] };
- const dWrap = el('section', 'kq-section');
- const head = el('div', 'kq-daily-head');
- head.appendChild(el('h3', 'kq-h3', 'Daily quests'));
- const reset = el('span', 'kq-reset');
- reset.id = 'kq-reset-q';
- reset.textContent = this._resetText();
- head.appendChild(reset);
- dWrap.appendChild(head);
-
- const allClaimed = daily.quests.length > 0 && daily.quests.every((q) => q.claimed);
- if (allClaimed) {
- const done = el('div', 'kq-empty kq-empty-good');
- done.innerHTML = `🌟 All dailies complete — back tomorrow.<br><span class="kq-reset-inline">${this._resetText()}</span>`;
- dWrap.appendChild(done);
- }
- for (const q of daily.quests) dWrap.appendChild(this._questCard(q));
- frag.appendChild(dWrap);
-
- // Badges.
- const badges = s.badges || [];
- const bWrap = el('section', 'kq-section');
- bWrap.appendChild(el('h3', 'kq-h3', 'Badges'));
- if (badges.length) {
- const row = el('div', 'kq-badges');
- for (const b of badges) {
- const chip = el('span', 'kq-badge', `<span class="kq-badge-ic">${b.icon}</span>${b.label}`);
- chip.title = b.desc || b.label;
- row.appendChild(chip);
- }
- bWrap.appendChild(row);
- } else {
- bWrap.appendChild(el('p', 'kq-empty', 'No badges yet — clear daily quests to earn them.'));
- }
- frag.appendChild(bWrap);
-
- body.replaceChildren(frag);
- }
-
- _questCard(q) {
- const complete = q.progress >= q.count;
- const card = el('div', 'kq-card-q' + (q.claimed ? ' kq-claimed' : complete ? ' kq-ready' : ''));
- card.appendChild(el('div', 'kq-q-title', q.title));
- card.appendChild(el('div', 'kq-q-desc', q.desc));
- card.appendChild(this._bar(q.progress, q.count));
- const footer = el('div', 'kq-q-foot');
- footer.appendChild(this._rewardChips(q.reward));
- if (q.claimed) {
- footer.appendChild(el('span', 'kq-claimed-tag', '✓ Claimed'));
- } else {
- const btn = el('button', 'kq-btn kq-turnin' + (complete ? '' : ' kq-btn-disabled'), complete ? 'Turn in' : `${q.progress}/${q.count}`);
- btn.type = 'button';
- btn.disabled = !complete;
- btn.addEventListener('click', () => this.opts.onTurnIn?.(q.id));
- footer.appendChild(btn);
- }
- card.appendChild(footer);
- return card;
- }
-
- _bar(progress, count) {
- const pct = count > 0 ? Math.max(0, Math.min(1, progress / count)) : 0;
- const wrap = el('div', 'kq-progress');
- wrap.innerHTML = `<i style="width:${(pct * 100).toFixed(1)}%"></i><span class="kq-progress-txt">${Math.min(progress, count)} / ${count}</span>`;
- return wrap;
- }
-
- _rewardChips(reward) {
- const row = el('div', 'kq-rewards');
- if (!reward) return row;
- if (reward.gold) row.appendChild(el('span', 'kq-rw', `🪙 ${reward.gold}`));
- if (reward.xp) {
- for (const [skill, amt] of Object.entries(reward.xp)) {
- row.appendChild(el('span', 'kq-rw', `✦ ${amt} ${SKILL_LABEL[skill] || skill}`));
- }
- }
- if (reward.item) row.appendChild(el('span', 'kq-rw', `${itemMeta(reward.item.id).icon} ${reward.item.qty}`));
- if (reward.badge) {
- const chip = el('span', 'kq-rw kq-rw-badge', `${reward.badge.icon} ${reward.badge.label}`);
- chip.title = `Badge: ${reward.badge.label}`;
- row.appendChild(chip);
- }
- return row;
- }
-
- _resetText() {
- return this._resetAt ? `Resets in ${fmtCountdown(this._resetAt - Date.now())}` : '';
- }
-
- // ---------------------------------------------------------------- NPC dialog
- openNpc(name) {
- this._npcOpen = true;
- if (name) this.elNpcName.textContent = name;
- this.elNpc.hidden = false;
- this._renderNpc();
- }
- closeNpc() { this._npcOpen = false; this.elNpc.hidden = true; }
-
- _renderNpc() {
- const s = this.snapshot;
- this.elNpcLine.textContent = s?.guide || '…';
- const frag = document.createDocumentFragment();
-
- // Current tutorial objective, phrased as the guide's instruction.
- if (s?.tutorial && !s.tutorial.done && s.tutorial.step) {
- const obj = el('div', 'kq-npc-objective');
- obj.innerHTML = `<span class="kq-npc-obj-label">Your task</span>${s.tutorial.step.title}<span class="kq-npc-obj-desc">${s.tutorial.step.desc}</span>`;
- frag.appendChild(obj);
- }
-
- // Any daily ready to be turned in, with a claim button right here.
- const ready = (s?.daily?.quests || []).filter((q) => q.progress >= q.count && !q.claimed);
- if (ready.length) {
- frag.appendChild(el('div', 'kq-npc-sub', 'Bounties ready to settle'));
- for (const q of ready) {
- const row = el('div', 'kq-npc-turnin');
- row.appendChild(el('span', 'kq-npc-turnin-name', q.title));
- const btn = el('button', 'kq-btn kq-turnin', 'Claim');
- btn.type = 'button';
- btn.addEventListener('click', () => this.opts.onTurnIn?.(q.id));
- row.appendChild(btn);
- frag.appendChild(row);
- }
- }
- this.elNpcBody.replaceChildren(frag);
- }
-
- // ---------------------------------------------------------------- bank
- setBankAvailable(available) {
- this.elBankBtn.hidden = !available;
- if (!available && this._bankOpen) this.closeBank();
- }
- setInventory(inv) {
- this.inv = inv || [];
- if (this._bankOpen) this._renderBank();
- // The Sell tab picks from the backpack, so a pickup/drop while it's open keeps
- // the item picker honest. Drop a stale selection that no longer exists.
- if (this._marketOpen && this._marketTab === 'sell') {
- if (this._sellItem && !this.inv.some((s) => s && s.item === this._sellItem)) this._sellItem = '';
- this._renderMarket();
- }
- }
- setBank(slots) { this.bank = slots || []; if (this._bankOpen) this._renderBank(); }
-
- openBank() { this._bankOpen = true; this.elBank.hidden = false; this._renderBank(); }
- closeBank() { this._bankOpen = false; this.elBank.hidden = true; }
-
- _renderBank() {
- // Backpack (deposit on click).
- const invFrag = document.createDocumentFragment();
- let invItems = 0;
- this.inv.forEach((s, i) => {
- if (!s || !s.item) return;
- invItems++;
- invFrag.appendChild(this._bankCell(s, () => this.opts.onDeposit?.(i)));
- });
- if (!invItems) invFrag.appendChild(el('p', 'kq-empty', 'Your backpack is empty.'));
- this.elBankInv.replaceChildren(invFrag);
-
- // Stored (withdraw on click).
- const stFrag = document.createDocumentFragment();
- let stItems = 0;
- this.bank.forEach((s, i) => {
- if (!s || !s.item) return;
- stItems++;
- stFrag.appendChild(this._bankCell(s, () => this.opts.onWithdraw?.(i)));
- });
- if (!stItems) stFrag.appendChild(el('p', 'kq-empty', 'Nothing stored yet.'));
- this.elBankStore.replaceChildren(stFrag);
- }
-
- _bankCell(slot, onClick) {
- const m = itemMeta(slot.item);
- const cell = el('button', 'kq-cell');
- cell.type = 'button';
- cell.title = m.label;
- cell.setAttribute('aria-label', `${m.label}${slot.qty > 1 ? ' ×' + slot.qty : ''}`);
- cell.innerHTML = `<span class="kq-ic">${m.icon}</span>${slot.qty > 1 ? `<span class="kq-qty">${slot.qty}</span>` : ''}`;
- cell.addEventListener('click', onClick);
- return cell;
- }
-
- // ---------------------------------------------------------------- cosmetics shop
- // The persistent gold readout (toolbar + shop header). Drives buy affordability,
- // so an open shop re-renders when the purse changes.
- setGold(gold) {
- const g = Math.max(0, gold | 0);
- if (g === this.gold) return;
- this.gold = g;
- if (this.elGoldN) this.elGoldN.textContent = g.toLocaleString('en-US');
- if (this.elShopGold) this.elShopGold.textContent = g.toLocaleString('en-US');
- if (this.elMarketGold) this.elMarketGold.textContent = g.toLocaleString('en-US');
- if (this._shopOpen) this._renderShop();
- // The Sell tab's affordability + max-amount caps read off live gold.
- if (this._marketOpen && (this._marketTab === 'sell' || this._marketTab === 'buy')) this._renderMarket();
- }
-
- // The static catalogue (sent once on join): every cosmetic's id, name, rarity,
- // price, rotation, and visual, plus the rarity palette. Everything the shop +
- // wardrobe render from — no prices or rarities are hard-coded in the HUD.
- setCosmeticCatalog(list, rarities) {
- this.cosmetics = new Map((list || []).map((c) => [c.id, c]));
- this.rarities = rarities || {};
- if (this._shopOpen) this._renderShop();
- }
-
- // The live shop board (offers + rotation deadlines + owned ids + equipped + gold).
- setShop(snapshot) {
- this.shop = snapshot || null;
- this._clearConfirm();
- if (snapshot) {
- this._dailyResetAt = snapshot.offers?.dailyResetAt || 0;
- this._weeklyResetAt = snapshot.offers?.weeklyResetAt || 0;
- if (Number.isFinite(snapshot.gold)) this.setGold(snapshot.gold);
- }
- if (this._shopOpen) this._renderShop();
- }
-
- toggleShop() { this._shopOpen ? this.closeShop() : this.openShop(); }
- openShop() {
- this._shopOpen = true;
- this.elShop.hidden = false;
- this.elShopBtn.setAttribute('aria-expanded', 'true');
- // Always pull a fresh board on open so offers + the countdown are current.
- this.opts.onShopOpen?.();
- this._renderShop();
- }
- closeShop() {
- this._shopOpen = false;
- this.elShop.hidden = true;
- this.elShopBtn.setAttribute('aria-expanded', 'false');
- // Drop any uncommitted wardrobe preview — revert the avatar to the
- // server-authoritative equipped look.
- if (this._previewId !== null) { this._previewId = null; this.opts.onStopPreview?.(); }
- this._clearConfirm();
- }
-
- _setShopTab(tab) {
- this._shopTab = ['shop', 'wardrobe', 'collection'].includes(tab) ? tab : 'shop';
- this._clearConfirm();
- const tabs = { shop: this.elShopTabShop, wardrobe: this.elShopTabWardrobe, collection: this.elShopTabCollection };
- for (const [name, btn] of Object.entries(tabs)) {
- const on = name === this._shopTab;
- btn.classList.toggle('kq-shop-tab--on', on);
- btn.setAttribute('aria-selected', String(on));
- }
- this._renderShop();
- }
-
- // Reset any pending two-step buy confirmation (tab switch, close, board refresh).
- _clearConfirm() {
- if (this._confirmTimer) { clearTimeout(this._confirmTimer); this._confirmTimer = null; }
- this._confirmBuyId = null;
- }
-
- _renderShop() {
- if (!this._shopOpen) return;
- const body = this.elShopBody;
- if (!this.cosmetics.size) { body.replaceChildren(el('p', 'kq-empty', 'Loading the shop…')); return; }
- const view = this._shopTab === 'wardrobe' ? this._renderWardrobe()
- : this._shopTab === 'collection' ? this._renderCollection()
- : this._renderShopCatalog();
- body.replaceChildren(view);
- }
-
- // Buy tab: the rotating board grouped by bucket, each rotating group headed by a
- // live countdown to its next rotation. Cosmetics already owned read "Owned";
- // affordable ones get a Buy button; short ones show how much more gold is needed.
- _renderShopCatalog() {
- const frag = document.createDocumentFragment();
- if (!this.shop) { frag.appendChild(el('p', 'kq-empty', 'Loading the shop…')); return frag; }
- const owned = new Set(this.shop.owned || []);
- const offers = this.shop.offers || {};
- const section = (title, ids, resetId, resetAt) => {
- if (!ids || !ids.length) return;
- const sec = el('section', 'kq-shop-section');
- const head = el('div', 'kq-shop-section-head');
- head.appendChild(el('h3', 'kq-h3', title));
- if (resetId) {
- const r = el('span', 'kq-shop-reset', this._rotateText(resetAt));
- r.id = resetId;
- head.appendChild(r);
- }
- sec.appendChild(head);
- const grid = el('div', 'kq-cos-grid');
- for (const id of ids) {
- const c = this.cosmetics.get(id);
- if (c) grid.appendChild(this._shopCard(c, owned.has(id)));
- }
- sec.appendChild(grid);
- frag.appendChild(sec);
- };
- section('Daily rotation', offers.daily, 'kq-shop-daily-reset', this._dailyResetAt);
- section('Weekly rotation', offers.weekly, 'kq-shop-weekly-reset', this._weeklyResetAt);
- section('Always available', offers.always, null, 0);
- return frag;
- }
-
- // Collection tab: the entire catalogue at a glance — owned looks (tappable to
- // preview, even here) and locked ones with their price + how they're obtained.
- // A completion count gives players something to chase.
- _renderCollection() {
- const frag = document.createDocumentFragment();
- const all = [...this.cosmetics.values()];
- if (!all.length) { frag.appendChild(el('p', 'kq-empty', 'Loading…')); return frag; }
- const owned = new Set(this.shop?.owned || []);
- const order = Object.keys(this.rarities);
- const rank = (r) => { const i = order.indexOf(r); return i < 0 ? 99 : i; };
- all.sort((a, b) => rank(a.rarity) - rank(b.rarity) || a.price - b.price);
- const ownedN = all.filter((c) => owned.has(c.id)).length;
- frag.appendChild(el('p', 'kq-shop-sub', `${ownedN} / ${all.length} collected. Tap any look to preview it on your avatar.`));
- const grid = el('div', 'kq-cos-grid');
- const SRC = { always: 'Always in shop', daily: 'Daily rotation', weekly: 'Weekly rotation' };
- for (const c of all) {
- const have = owned.has(c.id);
- const isPreview = this._previewId === c.id;
- const card = el('div', `kq-cos-card kq-cos-card--pick kq-cos--${c.rarity}`
- + (have ? '' : ' kq-cos--locked') + (isPreview ? ' kq-cos--preview' : ''));
- card.style.setProperty('--cos-accent', this._rarityColor(c.rarity));
- card.dataset.cosId = c.id;
- card.setAttribute('role', 'button');
- card.tabIndex = 0;
- card.setAttribute('aria-label', `Preview ${c.name}`);
- card.addEventListener('click', () => this._previewCosmetic(c.id));
- card.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this._previewCosmetic(c.id); } });
- card.appendChild(this._cosSwatch(c));
- const meta = el('div', 'kq-cos-meta');
- meta.appendChild(el('div', 'kq-cos-name', c.name));
- meta.appendChild(el('div', 'kq-cos-rarity', this._rarityLabel(c.rarity)));
- card.appendChild(meta);
- const foot = el('div', 'kq-cos-foot');
- if (have) {
- foot.appendChild(el('span', 'kq-cos-owned', '✓ Owned'));
- } else {
- foot.appendChild(el('span', 'kq-cos-price', `🪙 ${c.price.toLocaleString('en-US')}`));
- foot.appendChild(el('span', 'kq-cos-src', SRC[c.rotation] || ''));
- }
- card.appendChild(foot);
- grid.appendChild(card);
- }
- frag.appendChild(grid);
- return frag;
- }
-
- _shopCard(c, owned) {
- const equipped = this.shop?.equipped || '';
- const affordable = this.gold >= c.price;
- const card = el('div', `kq-cos-card kq-cos--${c.rarity}`
- + (owned ? ' kq-cos--owned' : affordable ? '' : ' kq-cos--short')
- + (equipped === c.id ? ' kq-cos--equipped' : ''));
- card.style.setProperty('--cos-accent', this._rarityColor(c.rarity));
- card.dataset.cosId = c.id;
- card.appendChild(this._cosSwatch(c));
- const meta = el('div', 'kq-cos-meta');
- meta.appendChild(el('div', 'kq-cos-name', c.name));
- meta.appendChild(el('div', 'kq-cos-rarity', this._rarityLabel(c.rarity)));
- card.appendChild(meta);
- const foot = el('div', 'kq-cos-foot');
- if (owned) {
- // Already bought — equip straight from the shop (no trip to the wardrobe).
- if (equipped === c.id) {
- foot.appendChild(el('span', 'kq-cos-equipped', '✓ Equipped'));
- } else {
- const b = el('button', 'kq-btn kq-cos-equip', 'Equip');
- b.type = 'button';
- b.addEventListener('click', () => this._commitCosmetic(c.id));
- foot.appendChild(b);
- }
- } else {
- foot.appendChild(el('span', 'kq-cos-price' + (affordable ? '' : ' kq-cos-price--short'), `🪙 ${c.price.toLocaleString('en-US')}`));
- const confirming = this._confirmBuyId === c.id;
- const label = !affordable ? `Need ${(c.price - this.gold).toLocaleString('en-US')}` : confirming ? 'Confirm?' : 'Buy';
- const btn = el('button', 'kq-btn kq-cos-buy' + (affordable ? '' : ' kq-btn-disabled') + (confirming ? ' kq-cos-buy--confirm' : ''), label);
- btn.type = 'button';
- btn.disabled = !affordable;
- if (affordable) btn.addEventListener('click', () => this._buyClicked(c));
- foot.appendChild(btn);
- }
- card.appendChild(foot);
- return card;
- }
-
- // Buy with a one-tap confirm for pricier cosmetics: cheap looks buy on the first
- // click; anything >= CONFIRM_PRICE arms a "Confirm?" state that the next click
- // (within a few seconds) commits, so a misclick never spends a big sum.
- _buyClicked(c) {
- if (c.price < CONFIRM_PRICE || this._confirmBuyId === c.id) {
- this._clearConfirm();
- this.opts.onBuyCosmetic?.(c.id);
- return;
- }
- this._clearConfirm();
- this._confirmBuyId = c.id;
- this._confirmTimer = setTimeout(() => {
- this._confirmBuyId = null;
- if (this._shopOpen && this._shopTab === 'shop') this._renderShop();
- }, 4000);
- this._renderShop();
- }
-
- // Wardrobe tab: a "Default look" tile (unequip) plus every owned cosmetic, with
- // the equipped one highlighted. Equipping previews live on the avatar in-world.
- _renderWardrobe() {
- const frag = document.createDocumentFragment();
- const ownedIds = (this.shop?.owned || []).filter((id) => this.cosmetics.has(id));
- const equipped = this.shop?.equipped || '';
- frag.appendChild(el('p', 'kq-shop-sub', 'Tap a look to preview it live on your avatar; press Equip to keep it. Everyone around you sees what you equip.'));
- const grid = el('div', 'kq-cos-grid');
-
- // Build one wardrobe tile. `id` is '' for the Default-look tile. A click on the
- // tile body previews the look locally (no server round-trip); Equip commits it.
- const tile = (id) => {
- const c = id ? this.cosmetics.get(id) : null;
- const isEq = id === equipped;
- const isPreview = this._previewId === id && !isEq;
- const rarityCls = c ? ` kq-cos--${c.rarity}` : ' kq-cos--default';
- // A div (not a button) so the real Equip button can nest inside it without
- // invalid button-in-button markup; role+tabindex+keydown keep it keyboard-usable.
- const card = el('div', 'kq-cos-card kq-cos-card--pick' + rarityCls
- + (isEq ? ' kq-cos--equipped' : '') + (isPreview ? ' kq-cos--preview' : ''));
- if (c) card.style.setProperty('--cos-accent', this._rarityColor(c.rarity));
- if (id) card.dataset.cosId = id;
- card.setAttribute('role', 'button');
- card.tabIndex = 0;
- card.setAttribute('aria-pressed', String(isEq));
- card.setAttribute('aria-label', `Preview ${c ? c.name : 'default look'}`);
- card.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this._previewCosmetic(id); } });
- if (c) card.appendChild(this._cosSwatch(c));
- else card.appendChild(el('span', 'kq-cos-swatch kq-cos-swatch--default', '🙂'));
- const meta = el('div', 'kq-cos-meta');
- meta.appendChild(el('div', 'kq-cos-name', c ? c.name : 'Default look'));
- meta.appendChild(el('div', 'kq-cos-rarity', c ? this._rarityLabel(c.rarity) : 'No cosmetic'));
- card.appendChild(meta);
- const foot = el('div', 'kq-cos-foot');
- if (isEq) {
- foot.appendChild(el('span', 'kq-cos-equipped', '✓ Equipped'));
- } else {
- const b = el('button', 'kq-btn kq-cos-equip', isPreview ? 'Equip ✓' : 'Equip');
- b.type = 'button';
- b.addEventListener('click', (e) => { e.stopPropagation(); this._commitCosmetic(id); });
- foot.appendChild(b);
- }
- card.appendChild(foot);
- card.addEventListener('click', () => this._previewCosmetic(id));
- return card;
- };
-
- grid.appendChild(tile(''));
- for (const id of ownedIds) grid.appendChild(tile(id));
- frag.appendChild(grid);
-
- if (!ownedIds.length) {
- const empty = el('div', 'kq-empty kq-shop-empty');
- empty.innerHTML = 'You don\u2019t own any cosmetics yet.';
- const go = el('button', 'kq-btn kq-btn-ghost', 'Browse the shop \u2192');
- go.type = 'button';
- go.addEventListener('click', () => this._setShopTab('shop'));
- empty.appendChild(go);
- frag.appendChild(empty);
- }
- return frag;
- }
-
- // Preview a wardrobe look on the local avatar (no server round-trip). Re-renders
- // so the previewed tile reads as selected.
- _previewCosmetic(id) {
- if (this._previewId === id) return;
- this._previewId = id;
- this.opts.onPreviewCosmetic?.(id);
- if (this._shopOpen && this._shopTab === 'wardrobe') this._renderShop();
- }
-
- // Commit the previewed look to the server (equip an id, or unequip for '').
- _commitCosmetic(id) {
- this._previewId = id;
- this.opts.onPreviewCosmetic?.(id); // keep the avatar showing it through the round-trip
- if (id) this.opts.onEquipCosmetic?.(id);
- else this.opts.onUnequipCosmetic?.();
- }
-
- // A small visual chip for a cosmetic: auras glow, tints fill, props show their
- // emoji over a neutral chip — enough to tell looks apart at a glance.
- _cosSwatch(c) {
- const v = c.visual || {};
- const sw = el('span', 'kq-cos-swatch');
- if (v.aura) {
- sw.style.background = `radial-gradient(circle at 50% 55%, ${v.aura}, rgba(0,0,0,0.25) 72%)`;
- sw.style.boxShadow = `0 0 12px ${v.aura}`;
- } else if (v.tint) {
- sw.style.background = `linear-gradient(150deg, ${v.tint}, rgba(255,255,255,0.18))`;
- }
- if (v.prop) {
- // Real rendered thumbnail of the worn prop, falling back to the emoji glyph
- // if the image is missing so a card never renders blank.
- const base = v.prop.split('/').pop().replace(/\.[^.]+$/, '');
- const img = el('img', 'kq-cos-thumb');
- img.src = `/accessories/thumbs/${base}.png`;
- img.alt = '';
- img.loading = 'lazy';
- img.addEventListener('error', () => { img.remove(); sw.textContent = PROP_ICON[c.id] || '🎩'; });
- sw.appendChild(img);
- }
- return sw;
- }
-
- _rarityColor(rarity) { return this.rarities[rarity]?.color || '#9aa7b4'; }
- _rarityLabel(rarity) { return this.rarities[rarity]?.label || (rarity ? rarity[0].toUpperCase() + rarity.slice(1) : ''); }
- _rotateText(at) { return at ? `resets in ${fmtCountdown(at - Date.now())}` : ''; }
-
- // ---------------------------------------------------------------- build
- // The Build button shows only in realms that permit player building (the scene
- // derives this from the realm's structure list). Hidden elsewhere so a mine or
- // the wilderness town never offers a no-op button.
- setBuildAvailable(available) {
- if (!this.elBuildBtn) return;
- this.elBuildBtn.hidden = !available;
- if (!available) this.closeBuild();
- }
-
- // Render the buildable list. `items` is the scene's affordability-resolved view:
- // [{ kind, icon, label, desc, capNote, affordable, costs:[{item,icon,need,have,ok}] }]
- // Each row shows the live cost (red where short) and a Build button gated on
- // affordability — the authoritative server re-checks everything on placement.
- setBuildables(items) {
- this._buildables = items || [];
- if (this._buildOpen) this._renderBuild();
- }
-
- toggleBuild() { this._buildOpen ? this.closeBuild() : this.openBuild(); }
- openBuild() {
- if (this.elBuildBtn?.hidden) return;
- this._buildOpen = true;
- this.elBuildMenu.hidden = false;
- this.elBuildMenu.classList.add('kq-in');
- this.elBuildBtn?.setAttribute('aria-expanded', 'true');
- this._renderBuild();
- }
- closeBuild() {
- this._buildOpen = false;
- if (this.elBuildMenu) { this.elBuildMenu.classList.remove('kq-in'); this.elBuildMenu.hidden = true; }
- this.elBuildBtn?.setAttribute('aria-expanded', 'false');
- }
-
- _renderBuild() {
- const list = this.elBuildList;
- if (!list) return;
- const items = this._buildables || [];
- if (!items.length) { list.replaceChildren(el('p', 'kq-empty', 'Nothing to build here.')); return; }
- const frag = document.createDocumentFragment();
- for (const b of items) {
- const card = el('div', 'kq-build-card' + (b.affordable ? '' : ' kq-build-card--short'));
- const head = el('div', 'kq-build-card-head');
- head.appendChild(el('span', 'kq-build-ic', b.icon));
- const title = el('div', 'kq-build-titles');
- title.appendChild(el('div', 'kq-build-name', b.label + (b.capNote ? ` <span class="kq-build-cap">${b.capNote}</span>` : '')));
- title.appendChild(el('div', 'kq-build-desc', b.desc || ''));
- head.appendChild(title);
- card.appendChild(head);
-
- const costs = el('div', 'kq-build-costs');
- for (const c of b.costs || []) {
- const chip = el('span', 'kq-build-cost' + (c.ok ? '' : ' kq-build-cost--short'));
- chip.innerHTML = `<span class="kq-build-cost-ic">${c.icon}</span>${c.have}/${c.need}`;
- chip.title = `${c.have} of ${c.need} ${itemMeta(c.item).label}`;
- costs.appendChild(chip);
- }
- card.appendChild(costs);
-
- const btn = el('button', 'kq-btn kq-build-go' + (b.affordable ? '' : ' kq-btn-disabled'), b.affordable ? 'Build' : 'Need more');
- btn.type = 'button';
- btn.disabled = !b.affordable;
- btn.addEventListener('click', () => { this.opts.onBuildSelect?.(b.kind); this.closeBuild(); });
- card.appendChild(btn);
- frag.appendChild(card);
- }
- list.replaceChildren(frag);
- }
-
- // Build-mode banner: shown while a ghost is being placed, with a Cancel control
- // (the only cancel affordance on touch, where there's no right-click).
- showBuildBanner(meta) {
- if (!this.elBuildBanner) return;
- this.elBuildBannerIc.textContent = meta?.icon || '🔨';
- this.elBuildBannerName.textContent = meta?.label || 'structure';
- this.elBuildBanner.hidden = false;
- }
- hideBuildBanner() { if (this.elBuildBanner) this.elBuildBanner.hidden = true; }
-
- // ---------------------------------------------------------------- marketplace (Task 20)
- //
- // A player-to-player market with Buy / Sell / My Listings tabs. The board is the
- // server's authoritative snapshot (setMarket); every action flows back out
- // through opts callbacks so the controller owns the network + the on-chain token
- // flow. Gold buys are one click; token buys go through a controller-driven
- // quote → wallet-sign → settle sequence whose progress shows as a per-listing
- // busy label (setMarketBusy).
-
- toggleMarket() { this._marketOpen ? this.closeMarket() : this.openMarket(); }
-
- openMarket() {
- if (this._marketOpen) return;
- this._marketOpen = true;
- this._marketError = '';
- this._marketLoading = !this.market.listings.length && !this.market.mine.length;
- this.elMarket.hidden = false;
- this.elMarketBtn.setAttribute('aria-expanded', 'true');
- this._renderMarket();
- // Always refetch on open so the board is live, not whatever was last cached.
- this.opts.onMarketOpen?.();
- }
-
- closeMarket() {
- this._marketOpen = false;
- this.elMarket.hidden = true;
- this.elMarketBtn.setAttribute('aria-expanded', 'false');
- }
-
- _setMarketTab(tab) {
- this._marketTab = tab;
- for (const [name, btn] of [['buy', this.elMarketTabBuy], ['sell', this.elMarketTabSell], ['mine', this.elMarketTabMine]]) {
- const on = name === tab;
- btn.classList.toggle('kq-market-tab--on', on);
- btn.setAttribute('aria-selected', String(on));
- }
- // Re-pull a fresh board when switching to a browse tab so it never shows stale
- // listings after time on the Sell form.
- if (tab === 'buy' || tab === 'mine') this.opts.onMarketOpen?.();
- this._renderMarket();
- }
-
- // The server's market board: active listings, the player's own, and the token
- // capability flags. Clears the loading/error state and re-renders if open.
- setMarket(data) {
- if (!data) return;
- this.market = {
- listings: Array.isArray(data.listings) ? data.listings : [],
- mine: Array.isArray(data.mine) ? data.mine : [],
- token: data.token || this.market.token,
- canToken: !!data.canToken,
- };
- this._marketLoading = false;
- this._marketError = '';
- if (this._marketOpen) this._renderMarket();
- }
-
- // A listing changed somewhere — refetch if the market is open on a browse tab.
- marketDirty() {
- if (this._marketOpen && (this._marketTab === 'buy' || this._marketTab === 'mine')) this.opts.onMarketOpen?.();
- }
-
- setMarketError(msg) {
- this._marketError = msg || '';
- this._marketLoading = false;
- if (this._marketOpen) this._renderMarket();
- }
-
- // The controller drives these during an on-chain token buy so the listing's card
- // shows "Preparing…", "Confirm in wallet…", "Settling…", etc.
- setMarketBusy(id, label) {
- if (!id) return;
- this._marketBusy.set(id, label || 'Working…');
- if (this._marketOpen) this._renderMarket();
- }
- clearMarketBusy(id) {
- if (id) this._marketBusy.delete(id); else this._marketBusy.clear();
- if (this._marketOpen) this._renderMarket();
- }
-
- _fmtGold(n) { return Math.max(0, n | 0).toLocaleString('en-US'); }
- _fmtUsd(n) { return '$' + (Math.round(Number(n) * 100) / 100).toFixed(2); }
-
- _renderMarket() {
- if (!this.elMarketBody) return;
- let node;
- if (this._marketTab === 'sell') node = this._renderSell();
- else if (this._marketTab === 'mine') node = this._renderMine();
- else node = this._renderBuy();
- this.elMarketBody.replaceChildren(node);
- }
-
- // ---- Buy tab ----------------------------------------------------------
- _renderBuy() {
- const wrap = el('div', 'kq-market-pane');
- if (this._marketError) { wrap.appendChild(this._marketErrorEl()); return wrap; }
- if (this._marketLoading) { wrap.appendChild(this._marketSkeleton()); return wrap; }
-
- // Filter + sort controls.
- const controls = el('div', 'kq-market-controls');
- const search = el('input', 'kq-market-search');
- search.type = 'search';
- search.placeholder = 'Filter by item or seller…';
- search.value = this._buyFilter;
- search.setAttribute('aria-label', 'Filter listings');
- search.addEventListener('input', () => { this._buyFilter = search.value.toLowerCase(); this._renderBuyList(list); });
- const sort = el('select', 'kq-market-sort');
- sort.setAttribute('aria-label', 'Sort listings');
- for (const [val, label] of [['recent', 'Newest'], ['priceAsc', 'Price ↑'], ['priceDesc', 'Price ↓']]) {
- const o = el('option'); o.value = val; o.textContent = label; if (val === this._buySort) o.selected = true; sort.appendChild(o);
- }
- sort.addEventListener('change', () => { this._buySort = sort.value; this._renderBuyList(list); });
- controls.append(search, sort);
- wrap.appendChild(controls);
-
- const list = el('div', 'kq-market-list');
- this._renderBuyList(list);
- wrap.appendChild(list);
- return wrap;
- }
-
- _renderBuyList(list) {
- const q = this._buyFilter;
- let items = this.market.listings.slice();
- if (q) {
- items = items.filter((l) => {
- const label = l.type === 'gold' ? itemMeta(l.item).label : 'gold';
- return label.toLowerCase().includes(q) || (l.seller || '').toLowerCase().includes(q);
- });
- }
- const priceOf = (l) => (l.type === 'gold' ? l.priceGold : l.priceUsd * 1e9); // token prices sort above gold consistently
- if (this._buySort === 'priceAsc') items.sort((a, b) => priceOf(a) - priceOf(b));
- else if (this._buySort === 'priceDesc') items.sort((a, b) => priceOf(b) - priceOf(a));
- else items.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
-
- if (!items.length) {
- const empty = el('div', 'kq-market-empty');
- empty.innerHTML = this._buyFilter
- ? '<div class="kq-market-empty-ic">🔍</div><p>No listings match that filter.</p>'
- : '<div class="kq-market-empty-ic">🛒</div><p><b>No listings yet — be the first to sell.</b></p><span>Open the Sell tab to list items for gold, or gold for $THREE.</span>';
- list.replaceChildren(empty);
- return;
- }
- const frag = document.createDocumentFragment();
- for (const l of items) frag.appendChild(this._buyCard(l));
- list.replaceChildren(frag);
- }
-
- _buyCard(l) {
- const card = el('div', 'kq-market-card-row' + (l.mine ? ' kq-market-mine' : ''));
- const icon = el('span', 'kq-market-ic', l.type === 'gold' ? itemMeta(l.item).icon : '🪙');
- const info = el('div', 'kq-market-info');
- const title = el('div', 'kq-market-title');
- if (l.type === 'gold') title.textContent = `${l.qty}× ${itemMeta(l.item).label}`;
- else title.textContent = `${this._fmtGold(l.goldAmount)} gold`;
- const sub = el('div', 'kq-market-sub');
- const seller = el('span', 'kq-market-seller'); seller.textContent = `by ${l.seller || 'Trader'}`;
- sub.appendChild(seller);
- info.append(title, sub);
-
- const right = el('div', 'kq-market-right');
- const price = el('div', 'kq-market-price');
- if (l.type === 'gold') price.innerHTML = `<span class="kq-market-coin">🪙</span>${this._fmtGold(l.priceGold)}`;
- else price.innerHTML = `<span class="kq-market-usd">${this._fmtUsd(l.priceUsd)}</span><span class="kq-market-token">in ${this.market.token.symbol}</span>`;
- right.appendChild(price);
-
- const busy = this._marketBusy.get(l.id);
- if (l.mine) {
- right.appendChild(el('span', 'kq-market-badge', 'Your listing'));
- } else if (busy) {
- const b = el('span', 'kq-market-busy'); b.innerHTML = `<span class="kq-spin"></span>${busy}`;
- right.appendChild(b);
- } else if (l.type === 'gold') {
- const afford = this.gold >= l.priceGold;
- const buy = el('button', 'kq-btn kq-market-buy' + (afford ? '' : ' kq-btn-disabled'), 'Buy');
- buy.type = 'button';
- buy.disabled = !afford;
- if (!afford) buy.title = `Need ${this._fmtGold(l.priceGold - this.gold)} more gold`;
- buy.addEventListener('click', () => this.opts.onMarketBuyGold?.(l.id));
- right.appendChild(buy);
- } else {
- // Token listing.
- if (!this.market.canToken) {
- right.appendChild(el('span', 'kq-market-note', 'Connect a wallet to buy'));
- } else {
- const buy = el('button', 'kq-btn kq-market-buy', `Buy with ${this.market.token.symbol}`);
- buy.type = 'button';
- buy.addEventListener('click', () => this.opts.onMarketBuyToken?.(l.id));
- right.appendChild(buy);
- }
- }
- card.append(icon, info, right);
- return card;
- }
-
- // ---- Sell tab ---------------------------------------------------------
- _renderSell() {
- const wrap = el('div', 'kq-market-pane kq-market-sell');
- // Mode toggle: items-for-gold vs gold-for-token.
- const modes = el('div', 'kq-market-modes');
- for (const [val, label] of [['gold', 'Item → Gold'], ['token', `Gold → ${this.market.token.symbol}`]]) {
- const b = el('button', 'kq-market-mode' + (this._sellMode === val ? ' kq-market-mode--on' : ''), label);
- b.type = 'button';
- b.addEventListener('click', () => { this._sellMode = val; this._renderMarket(); });
- modes.appendChild(b);
- }
- wrap.appendChild(modes);
- wrap.appendChild(this._sellMode === 'token' ? this._renderSellToken() : this._renderSellGold());
- return wrap;
- }
-
- _renderSellGold() {
- const pane = el('div', 'kq-market-sellform');
- // Aggregate backpack stacks by item so the picker shows one tile per item.
- const totals = new Map();
- for (const s of this.inv) if (s && s.item && s.qty > 0) totals.set(s.item, (totals.get(s.item) || 0) + s.qty);
- if (!totals.size) {
- pane.appendChild(el('p', 'kq-market-hint', 'Your backpack is empty — gather or loot something to sell.'));
- return pane;
- }
- pane.appendChild(el('label', 'kq-market-label', 'Choose an item to sell'));
- const grid = el('div', 'kq-market-pick');
- for (const [item, qty] of totals) {
- const m = itemMeta(item);
- const cell = el('button', 'kq-cell kq-market-pickcell' + (this._sellItem === item ? ' kq-cell--on' : ''));
- cell.type = 'button';
- cell.title = `${m.label} ×${qty}`;
- cell.setAttribute('aria-label', `${m.label} ×${qty}`);
- cell.setAttribute('aria-pressed', String(this._sellItem === item));
- cell.innerHTML = `<span class="kq-ic">${m.icon}</span><span class="kq-qty">${qty}</span>`;
- cell.addEventListener('click', () => { this._sellItem = item; this._renderMarket(); });
- grid.appendChild(cell);
- }
- pane.appendChild(grid);
-
- if (!this._sellItem) {
- pane.appendChild(el('p', 'kq-market-hint', 'Pick an item above to set the amount and price.'));
- return pane;
- }
- const held = totals.get(this._sellItem) || 0;
- const m = itemMeta(this._sellItem);
-
- const row = el('div', 'kq-market-fields');
- const qtyWrap = el('label', 'kq-market-field');
- qtyWrap.appendChild(el('span', 'kq-market-field-lbl', `Quantity (max ${held})`));
- const qtyInput = el('input', 'kq-market-input');
- qtyInput.type = 'number'; qtyInput.min = '1'; qtyInput.max = String(held); qtyInput.value = String(held); qtyInput.step = '1';
- qtyWrap.appendChild(qtyInput);
-
- const priceWrap = el('label', 'kq-market-field');
- priceWrap.appendChild(el('span', 'kq-market-field-lbl', 'Price (gold)'));
- const priceInput = el('input', 'kq-market-input');
- priceInput.type = 'number'; priceInput.min = '1'; priceInput.step = '1'; priceInput.placeholder = 'e.g. 100';
- priceWrap.appendChild(priceInput);
- row.append(qtyWrap, priceWrap);
- pane.appendChild(row);
-
- const btn = el('button', 'kq-btn kq-market-listbtn', `List ${m.label} for gold`);
- btn.type = 'button';
- btn.addEventListener('click', () => {
- const qty = Math.max(1, Math.min(held, qtyInput.value | 0));
- const price = priceInput.value | 0;
- if (!(price >= 1)) { priceInput.focus(); priceInput.classList.add('kq-input-bad'); return; }
- if (!(qty >= 1)) { qtyInput.focus(); qtyInput.classList.add('kq-input-bad'); return; }
- this.opts.onMarketListGold?.(this._sellItem, qty, price);
- this._sellItem = '';
- // Switch to My Listings so they see the new listing immediately.
- this._setMarketTab('mine');
- });
- pane.appendChild(btn);
- pane.appendChild(el('p', 'kq-market-fineprint', 'Gold sales have no fee — you receive the full price.'));
- return pane;
- }
-
- _renderSellToken() {
- const pane = el('div', 'kq-market-sellform');
- if (!this.market.token.enabled) {
- pane.appendChild(el('p', 'kq-market-hint', `${this.market.token.symbol} sales are unavailable right now.`));
- return pane;
- }
- if (!this.market.canToken) {
- pane.appendChild(el('p', 'kq-market-hint', 'Connect a Solana wallet to sell gold for tokens — your proceeds are paid on-chain to your wallet.'));
- return pane;
- }
- if (this.gold <= 0) {
- pane.appendChild(el('p', 'kq-market-hint', 'You have no gold to sell yet.'));
- return pane;
- }
- const feePct = (this.market.token.treasuryBps / 100).toFixed(0);
- const row = el('div', 'kq-market-fields');
- const goldWrap = el('label', 'kq-market-field');
- goldWrap.appendChild(el('span', 'kq-market-field-lbl', `Gold to sell (max ${this._fmtGold(this.gold)})`));
- const goldInput = el('input', 'kq-market-input');
- goldInput.type = 'number'; goldInput.min = '1'; goldInput.max = String(this.gold); goldInput.step = '1'; goldInput.placeholder = 'e.g. 1000';
- goldWrap.appendChild(goldInput);
-
- const usdWrap = el('label', 'kq-market-field');
- usdWrap.appendChild(el('span', 'kq-market-field-lbl', 'Price (USD)'));
- const usdInput = el('input', 'kq-market-input');
- usdInput.type = 'number'; usdInput.min = '0.01'; usdInput.step = '0.01'; usdInput.placeholder = 'e.g. 1.50';
- usdWrap.appendChild(usdInput);
- row.append(goldWrap, usdWrap);
- pane.appendChild(row);
-
- const btn = el('button', 'kq-btn kq-market-listbtn', `List gold for ${this.market.token.symbol}`);
- btn.type = 'button';
- btn.addEventListener('click', () => {
- const goldAmount = Math.max(1, Math.min(this.gold, goldInput.value | 0));
- const usd = Math.round(Number(usdInput.value) * 100) / 100;
- if (!(goldAmount >= 1)) { goldInput.focus(); goldInput.classList.add('kq-input-bad'); return; }
- if (!(usd >= 0.01)) { usdInput.focus(); usdInput.classList.add('kq-input-bad'); return; }
- this.opts.onMarketListToken?.(goldAmount, usd);
- // Switch to My Listings so they see the new listing immediately.
- this._setMarketTab('mine');
- });
- pane.appendChild(btn);
- pane.appendChild(el('p', 'kq-market-fineprint', `Buyers pay in ${this.market.token.symbol}. You receive ${100 - Number(feePct)}% to your wallet; ${feePct}% goes to the treasury.`));
- return pane;
- }
-
- // ---- My Listings tab --------------------------------------------------
- _renderMine() {
- const wrap = el('div', 'kq-market-pane');
- if (this._marketError) { wrap.appendChild(this._marketErrorEl()); return wrap; }
- const mine = (this.market.mine || []).slice().sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
- if (!mine.length) {
- const empty = el('div', 'kq-market-empty');
- empty.innerHTML = '<div class="kq-market-empty-ic">📦</div><p><b>You have no listings.</b></p><span>List items for gold or gold for $THREE from the Sell tab.</span>';
- wrap.appendChild(empty);
- return wrap;
- }
- const list = el('div', 'kq-market-list');
- for (const l of mine) list.appendChild(this._mineCard(l));
- wrap.appendChild(list);
- return wrap;
- }
-
- _mineCard(l) {
- const card = el('div', 'kq-market-card-row kq-market-status-' + l.status);
- const icon = el('span', 'kq-market-ic', l.type === 'gold' ? itemMeta(l.item).icon : '🪙');
- const info = el('div', 'kq-market-info');
- const title = el('div', 'kq-market-title');
- title.textContent = l.type === 'gold' ? `${l.qty}× ${itemMeta(l.item).label}` : `${this._fmtGold(l.goldAmount)} gold`;
- const sub = el('div', 'kq-market-sub');
- const price = l.type === 'gold' ? `🪙 ${this._fmtGold(l.priceGold)}` : `${this._fmtUsd(l.priceUsd)} in ${this.market.token.symbol}`;
- sub.textContent = price;
- info.append(title, sub);
-
- const right = el('div', 'kq-market-right');
- if (l.status === 'active') {
- right.appendChild(el('span', 'kq-market-statlbl kq-market-statlbl--active', 'Active'));
- const cancel = el('button', 'kq-btn kq-btn-ghost kq-market-cancel', 'Cancel');
- cancel.type = 'button';
- cancel.addEventListener('click', () => this.opts.onMarketCancel?.(l.id));
- right.appendChild(cancel);
- } else if (l.status === 'sold') {
- right.appendChild(el('span', 'kq-market-statlbl kq-market-statlbl--sold', l.buyer ? `Sold to ${l.buyer}` : 'Sold'));
- } else if (l.status === 'settling') {
- right.appendChild(el('span', 'kq-market-statlbl', 'Payment pending…'));
- } else {
- right.appendChild(el('span', 'kq-market-statlbl kq-market-statlbl--cancelled', 'Cancelled'));
- }
- card.append(icon, info, right);
- return card;
- }
-
- _marketErrorEl() {
- const e = el('div', 'kq-market-empty kq-market-err');
- e.innerHTML = `<div class="kq-market-empty-ic">⚠️</div><p>${this._marketError}</p>`;
- const retry = el('button', 'kq-btn kq-btn-ghost', 'Retry');
- retry.type = 'button';
- retry.addEventListener('click', () => { this._marketError = ''; this._marketLoading = true; this._renderMarket(); this.opts.onMarketOpen?.(); });
- e.appendChild(retry);
- return e;
- }
-
- _marketSkeleton() {
- const sk = el('div', 'kq-market-list');
- for (let i = 0; i < 4; i++) sk.appendChild(el('div', 'kq-market-card-row kq-market-skel'));
- return sk;
- }
-
- // ---------------------------------------------------------------- ticker
- _tick() {
- // Daily-quest reset countdown + auto re-fetch when the day turns over.
- if (this._resetAt) {
- if (this._resetAt - Date.now() <= 0) { this.opts.onReset?.(); }
- else if (this._questOpen) {
- const q = this.elQuestsBody.querySelector('#kq-reset-q');
- if (q) q.textContent = this._resetText();
- const inline = this.elQuestsBody.querySelector('.kq-reset-inline');
- if (inline) inline.textContent = this._resetText();
- }
- }
- // Cosmetics shop rotation countdowns. When a rotation elapses, re-fetch the
- // board so the new offers + a fresh countdown appear without a reconnect.
- if (this._shopOpen && this._shopTab === 'shop') {
- const now = Date.now();
- let rotated = false;
- if (this._dailyResetAt && now >= this._dailyResetAt) { this._dailyResetAt = 0; rotated = true; }
- if (this._weeklyResetAt && now >= this._weeklyResetAt) { this._weeklyResetAt = 0; rotated = true; }
- if (rotated) { this.opts.onShopOpen?.(); return; }
- const d = this.elShopBody.querySelector('#kq-shop-daily-reset');
- if (d) d.textContent = this._rotateText(this._dailyResetAt);
- const w = this.elShopBody.querySelector('#kq-shop-weekly-reset');
- if (w) w.textContent = this._rotateText(this._weeklyResetAt);
- }
- // Keep an open Buy/My-Listings board live as others list and sell — a light
- // refetch every few seconds (the Sell form is left alone so typing isn't lost).
- if (this._marketOpen && (this._marketTab === 'buy' || this._marketTab === 'mine')) {
- this._marketPoll = (this._marketPoll || 0) + 1;
- if (this._marketPoll >= 5) { this._marketPoll = 0; this.opts.onMarketOpen?.(); }
- }
- }
-
- destroy() {
- clearInterval(this._timer);
- this.root?.remove();
- }
-}
diff --git a/src/game/game-net.js b/src/game/game-net.js
deleted file mode 100644
index 614fbedfe..000000000
--- a/src/game/game-net.js
+++ /dev/null
@@ -1,406 +0,0 @@
-// Multiplayer client for /play (Coin Communities) — wraps colyseus.js with a small
-// event API the game scene subscribes to without knowing anything about
-// Colyseus. Mirrors the design of walk-net.js: graceful offline fallback,
-// bounded reconnect, and a flat event surface.
-//
-// Unlike walk (free 3D position at 15Hz), the game is tile-stepped: the client
-// sends one 'step' per tile as the avatar paths, plus discrete intents
-// (gather, attack, inventory ops, banking). The server is authoritative for
-// all of it.
-
-import { Client, getStateCallbacks } from 'colyseus.js';
-import { GameState } from '../../multiplayer/src/schemas/game.js';
-
-const REALMS = ['mainland', 'wilderness', 'whisperwood', 'pond', 'mine', 'wilderness_north', 'wilderness_cave', 'wilderness_east', 'arena'];
-const DEFAULT_REALM = 'mainland';
-const RECONNECT_BASE_MS = 3000;
-const RECONNECT_MAX_MS = 60_000;
-const MAX_RECONNECT_ATTEMPTS = 6;
-
-function defaultServerUrl() {
- // Resolution priority mirrors community-net / walk-net:
- // 1. window.GAME_SERVER_URL (test override)
- // 2. local dev → ws://<host>:2567, ignoring the production <meta> baked
- // into the static page (so `npm run dev:walk-all` works out of the box)
- // 3. <meta name="game-server"> then <meta name="walk-server"> (prod host)
- // 4. Same host on :2567
- if (typeof window !== 'undefined' && window.GAME_SERVER_URL) return window.GAME_SERVER_URL;
- const host = typeof location !== 'undefined' ? location.hostname : '';
- if (host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0') {
- return `ws://${host}:2567`;
- }
- if (typeof document !== 'undefined') {
- for (const sel of ['meta[name="game-server"]', 'meta[name="walk-server"]']) {
- const v = document.querySelector(sel)?.getAttribute('content')?.trim();
- if (v) return v;
- }
- }
- if (typeof location !== 'undefined') {
- const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
- return `${proto}//${location.hostname}:2567`;
- }
- return 'ws://localhost:2567';
-}
-
-// Derive the HTTP(S) origin of the multiplayer host from its ws(s):// URL, so the
-// login picker can hit the server's plain-HTTP discovery endpoint (/servers) on
-// the same host without a second config value.
-export function gameHttpBase(url) {
- const u = (url || defaultServerUrl()).replace(/^ws(s?):\/\//i, 'http$1://');
- return u.replace(/\/+$/, '');
-}
-
-// Fetch the live world-instance roster + real population counts (Task 23) for the
-// login picker. Returns the array of { id, name, blurb, players, recommended }.
-// Throws on a network/HTTP error so the caller can fall back to a no-counts list
-// rather than render stale or faked numbers.
-export async function fetchServers(url) {
- const res = await fetch(`${gameHttpBase(url)}/servers`, {
- headers: { accept: 'application/json' },
- cache: 'no-store',
- });
- if (!res.ok) throw new Error(`/servers ${res.status}`);
- const data = await res.json();
- return Array.isArray(data?.servers) ? data.servers : [];
-}
-
-export class GameNet {
- constructor(opts = {}) {
- this.name = opts.name || 'guest';
- this.avatar = opts.avatar || ''; // loadable GLB/VRM URL or path; '' = default
- this.pid = opts.pid || ''; // stable account id (wallet / persistent guest) — keys persistence
- // One Colyseus room definition per realm (game_mainland, game_wilderness,
- // …). Each realm is its own instance, so players in different realms never
- // see or affect one another. Defaults to Mainland.
- this.realm = REALMS.includes(opts.realm) ? opts.realm : DEFAULT_REALM;
- this.roomName = `game_${this.realm}`;
- // Chosen world instance (Task 23). filterBy(['server']) on the server pins
- // every realm room of this session to the same instance, so the player only
- // ever matches others who picked the same server. '' lets the server resolve
- // its default; the server validates it regardless.
- this.server = typeof opts.server === 'string' ? opts.server : '';
- // Set true when the server disconnects us because the same account signed in
- // elsewhere — suppresses the auto-reconnect that would otherwise fight the
- // new session for the single allowed seat.
- this._takenOver = false;
- this.url = opts.url || defaultServerUrl();
- this.client = null;
- this.room = null;
- this.status = 'idle'; // 'idle'|'connecting'|'online'|'offline'|'failed'
- this.error = null;
- this.sessionId = null;
- this._handlers = {
- status: new Set(),
- realm: new Set(), // (layout)
- items: new Set(), // (registry) — server item catalogue: icons, labels, mount tuning
- commands: new Set(), // ([{name, args, aliases, desc}]) — slash-command manifest for chat autocomplete
- notice: new Set(), // ({kind, text})
- chat: new Set(), // ({id, name, text, ts}) player msg | ({system, kind, text, ts}) system/command reply
- bank: new Set(), // ({slots})
- skills: new Set(), // ({cap, skills, total, average}) — requester's own XP detail
- xpgain: new Set(), // ({skill, amount, xp, level, levelXp, nextXp}) — every XP earn, earner only
- levelup: new Set(), // ({skill, level}) — a skill the local player just raised
- died: new Set(), // ({realm, danger, respawnAt, dropped, byName}) — local death
- cooked: new Set(), // ({cooked, burned, level}) — result of a cook action at the Roast Pit
- playerAdd: new Set(), // (player, id)
- playerChange: new Set(), // (player, id)
- playerRemove: new Set(), // (id)
- nodeAdd: new Set(),
- nodeChange: new Set(),
- nodeRemove: new Set(),
- mobAdd: new Set(),
- mobChange: new Set(),
- mobRemove: new Set(),
- tombAdd: new Set(), // (tombstone, id)
- tombChange: new Set(), // (tombstone, id)
- tombRemove: new Set(), // (id)
- structAdd: new Set(), // (structure, id) — player-built firepit/shack (Task 07)
- structChange: new Set(), // (structure, id)
- structRemove: new Set(), // (id)
- quests: new Set(), // ({tutorial, daily, badges, guide, npc}) — requester's own quest snapshot
- takeover: new Set(), // ({reason}) — this account signed in elsewhere; this session is being closed
- cosmetics: new Set(), // ({rarities, cosmetics}) — static cosmetics catalogue (Task 21)
- shop: new Set(), // ({offers, owned, equipped, gold}) — live cosmetics shop board
- market: new Set(), // ({listings, mine, token, canToken}) — marketplace board (Task 20)
- marketDirty: new Set(), // () — a listing changed; open panels should refetch
- marketQuote: new Set(), // ({id, tx, quote, ...}) — unsigned split tx + signed quote for a token buy
- marketSettled: new Set(), // ({id, goldAmount, txSig}) — token purchase verified + gold delivered
- marketBuyFail: new Set(), // ({id}) — a token quote/settle was rejected; release the spinner
- marketPayout: new Set(), // ({gold, items}) — proceeds delivered for a sale completed while away
- // Wheel of Fortune (Task 19): board/eligibility, a paid-spin tx + quote to
- // sign, the server-rolled outcome to animate toward, and refusals with the
- // fields each designed state needs (level gate, free-spin countdown).
- spinInfo: new Set(), // ({segments, avgLevel, minLevel, eligible, atWheel, nextFreeSpinAt, now, costUsd, symbol, paidAvailable})
- spinPrep: new Set(), // ({tx, quote, tokenAmount, burnAmount, treasuryAmount, priceUsd, ttlMs, ...})
- spinResult: new Set(), // ({mode, index, kind, item, qty, gold, label, awardedGold, awardedQty, overflow, nextFreeSpinAt, txSig?})
- spinDenied: new Set(), // ({mode, reason, avgLevel, minLevel, nextFreeSpinAt, now})
- handoff: new Set(), // ({realm, sessionId}) — switched rooms via a portal; scene resets dynamic views
- social: new Set(), // ({type, ...}) — friends events: live DM, friend request/accept (Task 15)
- };
- // Optional async supplier of a presence ticket (Task 15). When provided,
- // its resolved token is sent on join so the realm room can publish this
- // account's presence to friends. Resolved fresh on every (re)connect so an
- // expired ticket self-heals.
- this.getPresence = typeof opts.getPresence === 'function' ? opts.getPresence : null;
- this._reconnectTimer = null;
- this._reconnectAttempts = 0;
- this._destroyed = false;
- this._transferring = false; // a portal room-handoff is in flight
- }
-
- on(event, fn) {
- const bucket = this._handlers[event];
- if (!bucket) throw new Error(`GameNet: unknown event "${event}"`);
- bucket.add(fn);
- return () => bucket.delete(fn);
- }
-
- _emit(event, ...args) {
- for (const fn of this._handlers[event]) {
- try { fn(...args); } catch (e) { console.error(`[game-net] ${event} handler threw:`, e); }
- }
- }
-
- _setStatus(status, error = null) {
- this.status = status;
- this.error = error;
- this._emit('status', { status, error });
- }
-
- // (Re)assert this account's presence ticket to the live room. Sent after every
- // bind so a portal handoff — whose seat reservation carries no join options —
- // still publishes presence + keeps live DM delivery flowing in the new realm.
- async _announcePresence() {
- if (!this.getPresence || !this.room) return;
- try {
- const token = await this.getPresence();
- if (token && this.room) this.room.send('presence', token);
- } catch {
- /* presence is best-effort; the friends list falls back to polling */
- }
- }
-
- async connect() {
- if (this._destroyed) return;
- this._setStatus('connecting');
- try {
- this.client = new Client(this.url);
- const presence = this.getPresence ? await this.getPresence().catch(() => null) : null;
- this.room = await this.client.joinOrCreate(this.roomName, { name: this.name, avatar: this.avatar, pid: this.pid, server: this.server, ...(presence ? { presence } : {}) }, GameState);
- this.sessionId = this.room.sessionId;
- this._bindRoom();
- this._announcePresence();
- this._reconnectAttempts = 0;
- this._setStatus('online');
- } catch (err) {
- console.warn('[game-net] connect failed:', err?.message ?? err);
- this._setStatus('failed', err?.message ?? String(err));
- this._scheduleReconnect();
- }
- }
-
- // Attach every message + state-sync handler to the current room. Used by the
- // initial connect AND by a portal handoff, which swaps in a brand-new room
- // object. onLeave is keyed to the specific room instance it was bound to, so a
- // superseded room (the one we just portalled out of) can't flip us offline or
- // trigger a phantom reconnect.
- _bindRoom() {
- const room = this.room;
- room.onMessage('realm', (layout) => this._emit('realm', layout));
- room.onMessage('items', (r) => this._emit('items', r));
- room.onMessage('commands', (c) => this._emit('commands', c));
- room.onMessage('notice', (n) => this._emit('notice', n));
- room.onMessage('chat', (m) => this._emit('chat', m));
- room.onMessage('bank', (b) => this._emit('bank', b));
- room.onMessage('skills', (s) => this._emit('skills', s));
- room.onMessage('xpgain', (g) => this._emit('xpgain', g));
- room.onMessage('levelup', (l) => this._emit('levelup', l));
- room.onMessage('died', (d) => this._emit('died', d));
- room.onMessage('hit', (h) => this._emit('hit', h));
- room.onMessage('cooked', (c) => this._emit('cooked', c));
- room.onMessage('quests', (q) => this._emit('quests', q));
- room.onMessage('cosmetics', (c) => this._emit('cosmetics', c));
- room.onMessage('shop', (s) => this._emit('shop', s));
- room.onMessage('market', (m) => this._emit('market', m));
- room.onMessage('marketDirty', () => this._emit('marketDirty'));
- room.onMessage('marketQuote', (q) => this._emit('marketQuote', q));
- room.onMessage('marketSettled', (s) => this._emit('marketSettled', s));
- room.onMessage('marketBuyFail', (f) => this._emit('marketBuyFail', f));
- room.onMessage('marketPayout', (p) => this._emit('marketPayout', p));
- room.onMessage('spinInfo', (m) => this._emit('spinInfo', m));
- room.onMessage('spinPrep', (m) => this._emit('spinPrep', m));
- room.onMessage('spinResult', (m) => this._emit('spinResult', m));
- room.onMessage('spinDenied', (m) => this._emit('spinDenied', m));
- // Friends (Task 15): live DM + friend request/accept events pushed by the
- // server's social hub to whichever realm room this account is connected to.
- room.onMessage('social', (m) => this._emit('social', m));
- // Portal traversal: the server reserved us a seat in the destination realm.
- room.onMessage('portal', ({ to, reservation }) => this._handlePortal(to, reservation));
- // Single-active-session (Task 23): the same account just signed in on another
- // tab/server, so the server is closing this seat. Mark it so the imminent
- // onLeave doesn't auto-reconnect into a tug-of-war, and surface it to the UI.
- room.onMessage('takeover', (m) => {
- if (room !== this.room) return;
- this._takenOver = true;
- this._emit('takeover', m || {});
- });
-
- const $ = getStateCallbacks(room);
- const wire = (mapName, addEv, changeEv, removeEv) => {
- $(room.state)[mapName].onAdd((item, id) => {
- this._emit(addEv, item, id);
- $(item).onChange(() => this._emit(changeEv, item, id));
- });
- $(room.state)[mapName].onRemove((_item, id) => this._emit(removeEv, id));
- };
- wire('players', 'playerAdd', 'playerChange', 'playerRemove');
- wire('nodes', 'nodeAdd', 'nodeChange', 'nodeRemove');
- wire('mobs', 'mobAdd', 'mobChange', 'mobRemove');
- wire('tombstones', 'tombAdd', 'tombChange', 'tombRemove');
- wire('structures', 'structAdd', 'structChange', 'structRemove');
-
- room.onLeave((code) => {
- if (room !== this.room) return; // superseded by a portal handoff — ignore
- // Taken over by another login (server close code 4001, or the takeover
- // message already flagged it): stay offline with a clear reason and do NOT
- // reconnect — the account's one allowed seat now belongs to the new session.
- if (this._takenOver || code === 4001) {
- this._setStatus('offline', 'Your account signed in on another server or tab.');
- return;
- }
- this._setStatus('offline');
- if (!this._destroyed && code !== 1000) this._scheduleReconnect();
- });
- room.onError((code, message) => console.warn('[game-net] room.onError', code, message));
- }
-
- // Consume the destination-realm seat reservation the server handed us, swap it
- // in as the live room, then leave the old one. Joining the new room before
- // leaving the old means the old room's onLeave sees `room !== this.room` and
- // stays quiet, so the UI never flickers offline mid-portal. On failure we keep
- // the old room rather than stranding the player.
- //
- // onBeforeHandoff / onAfterHandoff are optional callbacks the scene injects for
- // the portal fade overlay — they are awaited so the blackout is solid before
- // the geometry swap and the fade-in starts only after the scene is rebuilt.
- async _handlePortal(to, reservation) {
- if (this._destroyed || this._transferring || !this.client) return;
- this._transferring = true;
- const old = this.room;
- try {
- // Fade out first, then do the room swap — so the player never sees a
- // half-rebuilt world flash.
- if (this.onBeforeHandoff) await this.onBeforeHandoff();
- const next = await this.client.consumeSeatReservation(reservation, GameState);
- this.room = next;
- this.sessionId = next.sessionId;
- this.realm = REALMS.includes(to) ? to : this.realm;
- this.roomName = `game_${this.realm}`;
- try { old?.leave(true); } catch {}
- // Reset dynamic views + adopt the new session id BEFORE binding state
- // callbacks, which immediately replay the destination realm's entities.
- this._emit('handoff', { realm: this.realm, sessionId: this.sessionId });
- this._bindRoom();
- this._announcePresence();
- this._reconnectAttempts = 0;
- this._setStatus('online');
- } catch (err) {
- console.warn('[game-net] portal handoff failed:', err?.message ?? err);
- this.room = old; // never left it — stay put
- if (this.onAfterHandoff) this.onAfterHandoff(); // always lift the fade
- } finally {
- this._transferring = false;
- }
- }
-
- // Exponential backoff with a hard ceiling. When the server is unreachable
- // (e.g. not deployed), each attempt costs a connection timeout — retrying
- // forever at a fixed interval floods the console. After MAX_RECONNECT_ATTEMPTS
- // we stop and stay 'offline'; the UI offers a manual reconnect via retry().
- _scheduleReconnect() {
- if (this._reconnectTimer || this._destroyed) return;
- if (this._reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
- this._setStatus('offline', 'game server unreachable');
- return;
- }
- const attempt = this._reconnectAttempts++;
- const backoff = Math.min(RECONNECT_BASE_MS * 2 ** attempt, RECONNECT_MAX_MS);
- const delay = backoff + Math.random() * 1000;
- this._reconnectTimer = setTimeout(() => {
- this._reconnectTimer = null;
- if (!this._destroyed) this.connect();
- }, delay);
- }
-
- // ----- intents ---------------------------------------------------------
-
- step(tx, ty, yaw) { this.room?.send('step', { tx, ty, yaw }); }
- setAvatar(url) { this.avatar = url; this.room?.send('setAvatar', { avatar: url }); }
- chat(text) { this.room?.send('chat', { text }); }
- gather(id) { this.room?.send('gather', { id }); }
- attack(id) { this.room?.send('attack', { id }); }
- fish() { this.room?.send('fish'); }
- tombLoot(id) { this.room?.send('tombLoot', { id }); }
- cook(qty = 1) { this.room?.send('cook', { qty }); }
- consume(ref) { this.room?.send('consume', { slot: ref }); }
- invMove(from, to) { this.room?.send('invMove', { from, to }); }
- equip(slot) { this.room?.send('equip', { slot }); }
- bankOpen() { this.room?.send('bankOpen'); }
- skills() { this.room?.send('skills'); }
- bankDeposit(i, qty) { this.room?.send('bankDeposit', { i, qty }); }
- bankWithdraw(i, qty) { this.room?.send('bankWithdraw', { i, qty }); }
- // Quests: request a fresh snapshot, talk to an NPC, claim a finished daily.
- questOpen() { this.room?.send('questOpen'); }
- npcTalk(id) { this.room?.send('npcTalk', { id }); }
- questTurnIn(id) { this.room?.send('questTurnIn', { id }); }
- // Cosmetics shop (Task 21): fetch the live board, buy a rotating cosmetic,
- // equip an owned one, or revert to the default look.
- shopOpen() { this.room?.send('shopOpen'); }
- buyCosmetic(id) { this.room?.send('buyCosmetic', { id }); }
- equipCosmetic(id) { this.room?.send('equipCosmetic', { id }); }
- unequipCosmetic() { this.room?.send('unequipCosmetic'); }
- // Marketplace (Task 20): fetch the board, list/cancel your own goods, buy a gold
- // listing, and the two-step on-chain flow for token listings (quote → settle).
- marketOpen() { this.room?.send('mktOpen'); }
- marketListGold(item, qty, priceGold) { this.room?.send('mktList', { type: 'gold', item, qty, priceGold }); }
- marketListToken(goldAmount, priceUsd) { this.room?.send('mktList', { type: 'goldForToken', goldAmount, priceUsd }); }
- marketCancel(id) { this.room?.send('mktCancel', { id }); }
- marketBuyGold(id) { this.room?.send('mktBuyGold', { id }); }
- marketTokenQuote(id) { this.room?.send('mktTokenQuote', { id }); }
- marketTokenSettle(quote, txSig) { this.room?.send('mktTokenSettle', { quote, txSig }); }
- // Wheel of Fortune (Task 19): fetch the board/eligibility, take the free spin,
- // and the two-step paid spin (prep builds the tx + quote; settle hands back the
- // broadcast signature for on-chain verification before the prize is rolled).
- spinInfo() { this.room?.send('spinInfo'); }
- spinFree() { this.room?.send('spinFree'); }
- spinPaidPrep() { this.room?.send('spinPaidPrep'); }
- spinPaidSettle(quote, txSig) { this.room?.send('spinPaidSettle', { quote, txSig }); }
- // Mounts (Task 09): ride the active hotbar item if it's a mount, leave the
- // saddle, and a generic slash-command channel (Task 13 chat forwards here).
- use(slot) { this.room?.send('use', slot == null ? {} : { slot }); }
- dismount() { this.room?.send('dismount'); }
- command(text) { this.room?.send('command', { text }); }
- // Building (Task 07): place a structure on an adjacent tile. Pickup/lock/unlock
- // go through the command channel above (/pickup, /lock, /unlock).
- build(kind, tx, ty) { this.room?.send('build', { kind, tx, ty }); }
-
- get state() { return this.room?.state ?? null; }
-
- retry() {
- if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }
- this._reconnectAttempts = 0;
- // A manual reconnect after a takeover is the player reclaiming the seat on
- // purpose — clear the flag so the connect path runs normally (and itself
- // evicts whatever session currently holds the account).
- this._takenOver = false;
- this.connect();
- }
-
- destroy() {
- this._destroyed = true;
- if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }
- try { this.room?.leave(); } catch {}
- this.room = null;
- this.client = null;
- }
-}
diff --git a/src/game/iso-controls.js b/src/game/iso-controls.js
deleted file mode 100644
index cec6b5f15..000000000
--- a/src/game/iso-controls.js
+++ /dev/null
@@ -1,834 +0,0 @@
-// Controls layer for the isometric MMO (/game) — hotbar selection, the panel
-// toggles (inventory · map · build · friends), and the rebindable Controls
-// settings UI.
-//
-// This module is the single home for discrete keyboard input. It owns one
-// capture-phase keydown listener that routes every game action through the
-// central keybinding map (keybindings.js) instead of scattered key literals, so
-// any action can be rebound and the binding persists per account. Movement
-// (WASD / arrows) stays a held-key set inside iso-game.js; this layer never
-// touches it — when a pressed key isn't a bound action it lets the event flow
-// through to the renderer untouched.
-//
-// The visual hotbar lives in game-hud.js (#kq-hotbar), fed by the renderer's
-// authoritative player sync (it already reflects the active slot). This layer
-// drives that hotbar by keyboard — selection routes through game._equipOrRide so
-// 1–6 ride a mount slot just like a click does, and 0 sends equip(-1) to clear.
-//
-// It attaches to the live IsoGame instance (window.__ISO__) and subscribes to the
-// network bus directly (game.net.on('playerChange', …)) for the local player's
-// inventory / active slot, which back the Inventory panel. That keeps the
-// renderer (which is large and evolving) free of UI-coupling: this file is
-// self-contained and self-mounting.
-
-import { Keybindings, ACTIONS, normalizeKey, keyLabel } from './keybindings.js';
-import { itemDisplay } from './items.js';
-import { FriendsPanel } from './friends-panel.js';
-import { friendsClient } from '../friends.js';
-
-const HOTBAR = 6;
-const INV = 24;
-
-// Designed placeholders for panels whose owning task hasn't landed yet. The key
-// is never dead: it opens this surface, and the owning task fills the body.
-const PLACEHOLDERS = {};
-
-// Tiny DOM helper (mirrors the el() convention used elsewhere in src/game).
-function el(tag, attrs = {}, kids = []) {
- const n = document.createElement(tag);
- for (const [k, v] of Object.entries(attrs)) {
- if (v == null || v === false) continue;
- if (k === 'class') n.className = v;
- else if (k === 'text') n.textContent = v;
- else if (k === 'html') n.innerHTML = v;
- else if (k === 'dataset') Object.assign(n.dataset, v);
- else if (k.startsWith('on') && typeof v === 'function')
- n.addEventListener(k.slice(2).toLowerCase(), v);
- else if (v === true) n.setAttribute(k, '');
- else n.setAttribute(k, v);
- }
- for (const c of [].concat(kids)) {
- if (c == null || c === false) continue;
- n.append(c.nodeType ? c : document.createTextNode(String(c)));
- }
- return n;
-}
-
-export class IsoControls {
- constructor(game) {
- this.game = game;
- this.kb = new Keybindings(localStorage.getItem('cc-name') || '');
-
- // Local-player mirror, fed by the network bus — backs the Inventory panel.
- this._inv = Array.from({ length: INV }, () => ({ item: '', qty: 0 }));
- this._gold = 0;
- this._me = null;
-
- this._open = []; // stack of open surface keys (top = last)
- this._surfaces = {}; // key -> { overlay, card, body }
- this._capture = null; // { id, chip } while rebinding
- this._lastFocus = null; // restore target when a surface closes
- this._mapTimer = null;
- this._netBound = false;
-
- // Friends (Task 15): the shared social-graph client + the panel view bound
- // to the friends surface. The panel mounts lazily on first open; the client
- // lives for the session so the HUD unread badge stays live in the background.
- this._friends = friendsClient();
- this._friendsPanel = null;
- this._friendsBtn = null;
- this._friendsUnsub = null;
-
- this._onKeyDown = this._onKeyDown.bind(this);
- this._sync = this._sync.bind(this);
- }
-
- // -------------------------------------------------------------- mount
- mount() {
- if (this._mounted) return;
- this._mounted = true;
-
- this._buildGear();
- this._buildFriendsButton();
-
- window.addEventListener('keydown', this._onKeyDown, true);
- this._unsub = this.kb.subscribe(() => this._onBindingsChanged());
-
- // Keep the HUD unread badge live whether or not the panel is open. A single
- // background load seeds existing unread; live DM events keep it current.
- this._friendsUnsub = this._friends.subscribe(() => this._updateFriendsBadge());
- this._friends.refresh();
-
- // Poll for the network connection + phase changes. Cheap (5Hz) and only
- // needs to wire the net bus once; visibility follows game.phase.
- this._syncTimer = setInterval(this._sync, 200);
- this._sync();
- }
-
- _sync() {
- const game = this.game;
- if (game.net && !this._netBound) {
- this._netBound = true;
- this.kb.setAccount(localStorage.getItem('cc-name') || '');
- game.net.on('playerAdd', (p, id) => this._onPlayer(p, id));
- game.net.on('playerChange', (p, id) => this._onPlayer(p, id));
- // Friends realtime (Task 15): live DMs + request/accept events arrive on
- // whatever realm room this account is connected to; hand them to the
- // shared friends client so the panel + unread badge update instantly.
- game.net.on('social', (m) => this._friends.handleSocial(m));
- }
- // A reconnect builds a fresh GameNet; rebind against the new bus.
- if (game.net && this._boundNet && this._boundNet !== game.net) {
- this._netBound = false;
- }
- this._boundNet = game.net || this._boundNet;
- this._applyPhase(game.phase);
- }
-
- _applyPhase(phase) {
- const world = phase === 'world';
- if (this._gearEl) this._gearEl.hidden = !world;
- if (this._friendsBtn) this._friendsBtn.hidden = !world;
- if (world && !this._hintDone) {
- this._updateHint();
- this._hintDone = true;
- }
- if (!world && this._open.length) this._closeAll();
- }
-
- // -------------------------------------------------------------- network
- _onPlayer(p, id) {
- const myId = this.game.myId || this.game.net?.sessionId;
- if (!myId || id !== myId) return;
- const read = (arr, n) =>
- Array.from({ length: n }, (_, i) => ({
- item: arr?.[i]?.item || '',
- qty: arr?.[i]?.qty | 0,
- }));
- this._inv = read(p.inv, INV);
- this._gold = p.gold | 0;
- this._me = { tx: p.tx | 0, ty: p.ty | 0 };
- if (this._isOpen('inv')) this._renderInv();
- }
-
- // -------------------------------------------------------------- hotbar
- // Select hotbar slot `i` (0-5); pass -1 to clear. Selecting is idempotent so
- // 1–6 always *set* the active slot per the world-guide spec; 0 clears.
- //
- // Selection routes through the renderer's _equipOrRide so a number key behaves
- // exactly like clicking the slot in the game-hud hotbar — equip, and ride the
- // steed if the slot holds a mount. The visual (active-slot highlight) is owned
- // by that hotbar, fed by the server's authoritative activeSlot patch. Clearing
- // has no slot to ride, so it sends equip(-1) straight to the net; the server
- // accepts -1 and patches activeSlot back, dropping the highlight.
- _select(i) {
- const net = this.game.net;
- if (!net) return;
- if (i >= 0 && typeof this.game._equipOrRide === 'function') this.game._equipOrRide(i);
- else net.equip(i);
- }
-
- // -------------------------------------------------------------- gear button
- _buildGear() {
- this._gearEl = el(
- 'button',
- {
- id: 'kg-controls-btn',
- class: 'kg-iconbtn',
- type: 'button',
- hidden: true,
- 'aria-haspopup': 'dialog',
- 'aria-controls': 'kg-ov-settings',
- 'aria-label': 'Controls and settings',
- title: 'Controls',
- onclick: () => this._toggle('settings'),
- },
- '⚙',
- );
- const bar = document.getElementById('kg-topbar');
- const status = document.getElementById('kg-status');
- if (bar && status) bar.insertBefore(this._gearEl, status);
- else if (bar) bar.appendChild(this._gearEl);
- else document.body.appendChild(this._gearEl);
- }
-
- // -------------------------------------------------------------- friends button
- // A topbar entry point for the friends panel (Task 15), alongside the F hotkey.
- // Carries a live unread badge so a new DM is noticeable without opening it.
- _buildFriendsButton() {
- this._friendsBadge = el('span', { class: 'kg-fr-hudbadge', hidden: true, 'aria-hidden': 'true' });
- this._friendsBtn = el(
- 'button',
- {
- id: 'kg-friends-btn',
- class: 'kg-iconbtn',
- type: 'button',
- hidden: true,
- 'aria-haspopup': 'dialog',
- 'aria-controls': 'kg-ov-friends',
- 'aria-label': 'Friends',
- title: 'Friends (F)',
- onclick: () => this._toggle('friends'),
- },
- ['👥', this._friendsBadge],
- );
- const bar = document.getElementById('kg-topbar');
- if (this._gearEl && this._gearEl.parentNode) this._gearEl.parentNode.insertBefore(this._friendsBtn, this._gearEl);
- else if (bar) bar.appendChild(this._friendsBtn);
- else document.body.appendChild(this._friendsBtn);
- }
-
- _updateFriendsBadge() {
- if (!this._friendsBadge) return;
- const n = this._friends.totalUnread;
- this._friendsBadge.textContent = n > 9 ? '9+' : String(n);
- this._friendsBadge.hidden = n <= 0;
- this._friendsBtn?.classList.toggle('kg-iconbtn--alert', n > 0);
- }
-
- // -------------------------------------------------------------- keyboard
- _onKeyDown(e) {
- if (this._capture) {
- e.preventDefault();
- e.stopImmediatePropagation();
- this._applyCapture(e);
- return;
- }
-
- const key = normalizeKey(e.key);
- const a = document.activeElement;
- const onButton = a && a.tagName === 'BUTTON' && a.closest && a.closest('.kg-ov');
-
- // While a controls surface is open, the modal owns the keyboard: Esc closes,
- // Enter confirms (unless a control is focused, then it activates it), Tab
- // navigates, and every other key is swallowed so the avatar can't walk or
- // switch slots beneath the dialog.
- if (this._open.length) {
- if (key === this.kb.get('closeModal')) {
- e.preventDefault();
- e.stopImmediatePropagation();
- this._closeTop();
- return;
- }
- if (key === this.kb.get('confirm')) {
- if (onButton) {
- e.stopImmediatePropagation();
- return;
- }
- e.preventDefault();
- e.stopImmediatePropagation();
- this._confirmTop();
- return;
- }
- if (key === 'tab') {
- e.stopImmediatePropagation();
- return;
- }
- if (onButton && key === 'space') {
- e.stopImmediatePropagation();
- return;
- }
- e.preventDefault();
- e.stopImmediatePropagation();
- return;
- }
-
- if (this._isTyping()) return; // chat / name inputs own their keys
- if (this.game.phase !== 'world') return;
-
- const action = this.kb.actionFor(key);
- if (!action || action === 'closeModal' || action === 'confirm') return;
-
- e.preventDefault();
- e.stopImmediatePropagation();
- this._dispatch(action);
- }
-
- _dispatch(action) {
- if (action.startsWith('hotbar') && action !== 'hotbarClear') {
- this._select(Number(action.slice(6)) - 1);
- return;
- }
- switch (action) {
- case 'hotbarClear':
- this._select(-1);
- break;
- case 'inventory':
- this._toggle('inv');
- break;
- case 'quests':
- this.game.q?.toggleQuests();
- break;
- case 'map':
- this._toggle('map');
- break;
- case 'build':
- // Delegate to the renderer's build-menu toggle (Task 07) so B opens the
- // real game-hud build panel, not a placeholder surface here.
- this.game._toggleBuildMenu?.();
- break;
- case 'friends':
- this._toggle('friends');
- break;
- case 'chat':
- this.game._openChat?.();
- break;
- case 'skills':
- this.game._toggleSkills?.();
- break;
- case 'rotateCam':
- this._rotateCamera();
- break;
- default:
- break;
- }
- }
-
- // Snap the follow camera 45° (matches the fixed three-quarter read). camYaw is
- // the renderer's public orbit angle, consumed every frame by _placeCamera.
- _rotateCamera() {
- this.game.camYaw = (this.game.camYaw || 0) - Math.PI / 4;
- }
-
- _isTyping() {
- const a = document.activeElement;
- return !!(a && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA' || a.isContentEditable));
- }
-
- // -------------------------------------------------------------- surfaces
- _isOpen(key) {
- return this._open.includes(key);
- }
-
- _toggle(key) {
- this._isOpen(key) ? this._close(key) : this._openSurface(key);
- }
-
- _openSurface(key) {
- // Single-panel policy: opening one closes the others (and the skills drawer)
- // so the screen never stacks competing dialogs.
- for (const k of [...this._open]) if (k !== key) this._close(k);
- this.game._toggleSkills?.(false);
-
- const surf = this._ensureSurface(key);
- if (!surf) return;
- this._lastFocus = document.activeElement;
- surf.overlay.hidden = false;
- // reflow so the fade/scale transition runs
- void surf.overlay.offsetWidth;
- surf.overlay.classList.add('kg-ov--in');
- this._open.push(key);
- this._renderSurface(key);
- if (key === 'map') this._mapTimer = setInterval(() => this._renderMap(), 700);
- (surf.card.querySelector('button, [tabindex]') || surf.card).focus();
- }
-
- _close(key) {
- const surf = this._surfaces[key];
- if (!surf) return;
- surf.overlay.classList.remove('kg-ov--in');
- surf.overlay.hidden = true;
- this._open = this._open.filter((k) => k !== key);
- if (key === 'map' && this._mapTimer) {
- clearInterval(this._mapTimer);
- this._mapTimer = null;
- }
- if (key === 'friends' && this._friendsPanel) {
- this._friendsPanel.unmount();
- this._friendsPanel = null;
- }
- if (this._capture && key === 'settings') this._capture = null;
- const back = this._lastFocus;
- if (back && document.contains(back)) back.focus();
- else this._gearEl?.focus();
- }
-
- _closeTop() {
- if (this._open.length) this._close(this._open[this._open.length - 1]);
- }
- _closeAll() {
- for (const k of [...this._open]) this._close(k);
- }
-
- _confirmTop() {
- const key = this._open[this._open.length - 1];
- const surf = this._surfaces[key];
- surf?.card.querySelector('.kg-ov-primary')?.click();
- }
-
- _ensureSurface(key) {
- if (this._surfaces[key]) return this._surfaces[key];
- const titles = { inv: 'Inventory', map: 'Map', settings: 'Controls', friends: 'Friends' };
- const title = titles[key] || PLACEHOLDERS[key]?.title || key;
- const closeBtn = el(
- 'button',
- {
- class: 'kg-ov-x',
- type: 'button',
- 'aria-label': 'Close',
- onclick: () => this._close(key),
- },
- '✕',
- );
- const head = el('div', { class: 'kg-ov-head' }, [
- el('h2', { class: 'kg-ov-title', id: `kg-ov-title-${key}` }, title),
- closeBtn,
- ]);
- const body = el('div', { class: 'kg-ov-body' });
- const card = el(
- 'div',
- {
- class: 'kg-ov-card',
- role: 'dialog',
- 'aria-modal': 'true',
- 'aria-labelledby': `kg-ov-title-${key}`,
- tabindex: '-1',
- },
- [head, body],
- );
- const overlay = el(
- 'div',
- {
- id: `kg-ov-${key}`,
- class: 'kg-ov',
- hidden: true,
- onclick: (e) => {
- if (e.target === overlay) this._close(key);
- },
- },
- [card],
- );
- document.body.appendChild(overlay);
- this._surfaces[key] = { overlay, card, body };
- return this._surfaces[key];
- }
-
- _renderSurface(key) {
- if (key === 'inv') this._renderInv();
- else if (key === 'map') this._renderMap();
- else if (key === 'settings') this._renderControls();
- else if (key === 'friends') this._mountFriends();
- else this._renderPlaceholder(key);
- }
-
- // -------------------------------------------------------------- inventory
- _renderInv() {
- const body = this._surfaces.inv?.body;
- if (!body) return;
- body.innerHTML = '';
- body.append(
- el('div', { class: 'kg-inv-meta' }, [
- el('span', {}, [el('b', {}, String(this._gold)), ' gold']),
- el('span', { class: 'kg-inv-hint' }, 'Slots 1–6 are your hotbar.'),
- ]),
- );
- const grid = el('div', { class: 'kg-inv-grid' });
- const filled = this._inv.some((s) => s.item);
- for (let i = 0; i < INV; i++) {
- const cell = this._inv[i] || { item: '', qty: 0 };
- const disp = itemDisplay(cell.item);
- const node = el(
- 'div',
- {
- class:
- 'kg-inv-cell' +
- (i < HOTBAR ? ' kg-inv-cell--hb' : '') +
- (cell.item ? '' : ' kg-inv-cell--empty'),
- title: disp ? disp.name : '',
- 'aria-label': disp
- ? `${disp.name}${cell.qty > 1 ? ` ×${cell.qty}` : ''}`
- : 'Empty slot',
- },
- [
- el(
- 'span',
- { class: 'kg-inv-glyph', 'aria-hidden': 'true' },
- disp ? disp.glyph : '',
- ),
- cell.qty > 1 ? el('span', { class: 'kg-inv-qty' }, String(cell.qty)) : null,
- ],
- );
- grid.append(node);
- }
- body.append(grid);
- if (!filled) {
- body.append(
- el(
- 'p',
- { class: 'kg-ov-empty' },
- 'Your backpack is empty. Gather wood and stone, or defeat mobs to fill it.',
- ),
- );
- }
- }
-
- // -------------------------------------------------------------- map
- _renderMap() {
- let surf = this._surfaces.map;
- if (!surf) return;
- if (!surf._canvas) {
- const cv = el('canvas', {
- class: 'kg-map-canvas',
- width: '260',
- height: '260',
- role: 'img',
- 'aria-label': 'Realm map',
- });
- const legend = el('div', { class: 'kg-map-legend' }, [
- el('span', {}, [el('i', { class: 'kg-map-dot kg-map-dot--me' }), 'You']),
- el('span', {}, [el('i', { class: 'kg-map-dot kg-map-dot--peer' }), 'Players']),
- el('span', {}, [el('i', { class: 'kg-map-sw kg-map-sw--bank' }), 'Bank']),
- el('span', {}, [el('i', { class: 'kg-map-sw kg-map-sw--block' }), 'Blocked']),
- ]);
- surf.body.append(cv, legend);
- surf._canvas = cv;
- }
- const cv = surf._canvas;
- const realm = this.game.realm;
- const ctx = cv.getContext('2d');
- const SZ = cv.width;
- ctx.clearRect(0, 0, SZ, SZ);
- if (!realm) {
- ctx.fillStyle = '#95a1b6';
- ctx.font = '13px system-ui';
- ctx.textAlign = 'center';
- ctx.fillText('Map loads when you enter the world.', SZ / 2, SZ / 2);
- return;
- }
- const grid = realm.grid || 48;
- const s = SZ / grid;
- ctx.fillStyle = '#33492b';
- ctx.fillRect(0, 0, SZ, SZ);
- ctx.fillStyle = 'rgba(8,11,16,0.55)';
- for (const b of realm.blocked || [])
- ctx.fillRect(b.x0 * s, b.y0 * s, (b.x1 - b.x0 + 1) * s, (b.y1 - b.y0 + 1) * s);
- ctx.fillStyle = 'rgba(255,206,92,0.6)';
- for (const t of realm.bankZone || []) ctx.fillRect(t.tx * s, t.ty * s, s, s);
- if (realm.fountain) {
- ctx.fillStyle = '#3aa0d0';
- ctx.beginPath();
- ctx.arc(
- (realm.fountain.tx + 0.5) * s,
- (realm.fountain.ty + 0.5) * s,
- Math.max(2.5, s * 0.7),
- 0,
- Math.PI * 2,
- );
- ctx.fill();
- }
- for (const [, pv] of this.game.players || []) {
- if (pv.dead) continue;
- const me = pv.isLocal;
- ctx.fillStyle = me ? '#ffffff' : '#8fd3ff';
- const r = Math.max(me ? 2.6 : 1.9, s * (me ? 0.75 : 0.55));
- ctx.beginPath();
- ctx.arc((pv.tx + 0.5) * s, (pv.ty + 0.5) * s, r, 0, Math.PI * 2);
- ctx.fill();
- if (me) {
- ctx.strokeStyle = '#0d1420';
- ctx.lineWidth = 1.5;
- ctx.stroke();
- }
- }
- }
-
- // -------------------------------------------------------------- friends
- // Lazily mount the friends panel into its surface body on first open; reuse it
- // thereafter. The panel owns its own polling/realtime lifecycle via mount()/
- // unmount() (the latter fires from _close).
- _mountFriends() {
- const body = this._surfaces.friends?.body;
- if (!body) return;
- if (!this._friendsPanel) {
- body.innerHTML = '';
- this._friendsPanel = new FriendsPanel(body);
- }
- this._friendsPanel.mount();
- }
-
- // -------------------------------------------------------------- placeholder
- _renderPlaceholder(key) {
- const meta = PLACEHOLDERS[key];
- const body = this._surfaces[key]?.body;
- if (!meta || !body) return;
- body.innerHTML = '';
- body.append(
- el('div', { class: 'kg-ph' }, [
- el('div', { class: 'kg-ph-glyph', 'aria-hidden': 'true' }, meta.glyph),
- el('p', { class: 'kg-ph-blurb' }, meta.blurb),
- el('p', { class: 'kg-ph-note' }, meta.note),
- ]),
- );
- body.append(
- el('div', { class: 'kg-ov-foot' }, [
- el(
- 'button',
- {
- class: 'kg-ov-btn kg-ov-primary',
- type: 'button',
- onclick: () => this._close(key),
- },
- 'Got it',
- ),
- ]),
- );
- }
-
- // -------------------------------------------------------------- controls UI
- _renderControls() {
- const body = this._surfaces.settings?.body;
- if (!body) return;
- body.innerHTML = '';
- body.append(
- el(
- 'p',
- { class: 'kg-ov-sub' },
- 'Click a key to rebind it, then press the new key. Esc cancels. Esc and Enter are reserved.',
- ),
- );
-
- const conflicts = new Map();
- for (const { key, ids } of this.kb.allConflicts()) conflicts.set(key, ids);
-
- const groups = [];
- for (const a of ACTIONS) {
- let g = groups.find((x) => x.name === a.group);
- if (!g) {
- g = { name: a.group, items: [] };
- groups.push(g);
- }
- g.items.push(a);
- }
-
- for (const g of groups) {
- const rows = [];
- for (const action of g.items) {
- const cur = this.kb.get(action.id);
- const sharedIds = (conflicts.get(cur) || []).filter((id) => id !== action.id);
- const chip = action.fixed
- ? el(
- 'span',
- {
- class: 'kg-bind-chip kg-bind-chip--fixed',
- title: 'System key (cannot be rebound)',
- },
- keyLabel(cur),
- )
- : el(
- 'button',
- {
- class: 'kg-bind-chip',
- type: 'button',
- dataset: { action: action.id },
- 'aria-label': `Rebind ${action.label}, currently ${keyLabel(cur)}`,
- onclick: (e) => this._beginCapture(action.id, e.currentTarget),
- },
- keyLabel(cur),
- );
- const row = el(
- 'div',
- { class: 'kg-bind-row' + (sharedIds.length ? ' kg-bind-row--conflict' : '') },
- [el('span', { class: 'kg-bind-label' }, action.label), chip],
- );
- if (sharedIds.length) {
- const names = sharedIds
- .map((id) => ACTIONS.find((x) => x.id === id)?.label || id)
- .join(', ');
- row.append(
- el(
- 'span',
- { class: 'kg-bind-warn', role: 'note' },
- `⚠ shared with ${names}`,
- ),
- );
- }
- rows.push(row);
- }
- body.append(
- el('section', { class: 'kg-bind-group' }, [
- el('h3', { class: 'kg-bind-h' }, g.name),
- ...rows,
- ]),
- );
- }
-
- this._msgEl = el(
- 'p',
- { class: 'kg-bind-msg', role: 'status', 'aria-live': 'polite' },
- this._pendingMsg || '',
- );
- this._pendingMsg = '';
- body.append(this._msgEl);
- body.append(
- el('div', { class: 'kg-ov-foot' }, [
- el(
- 'button',
- {
- class: 'kg-ov-btn kg-ov-ghost',
- type: 'button',
- onclick: () => this._resetBindings(),
- },
- 'Reset to defaults',
- ),
- el(
- 'button',
- {
- class: 'kg-ov-btn kg-ov-primary',
- type: 'button',
- onclick: () => this._close('settings'),
- },
- 'Done',
- ),
- ]),
- );
- }
-
- _beginCapture(id, chip) {
- this._capture = { id, chip };
- chip.classList.add('kg-bind-chip--capturing');
- chip.textContent = 'Press a key…';
- this._setMsg(`Press a key for “${ACTIONS.find((a) => a.id === id)?.label}”. Esc cancels.`);
- }
-
- _applyCapture(e) {
- const { id } = this._capture;
- const key = normalizeKey(e.key);
- this._capture = null;
- if (key === 'escape' || key === 'tab') {
- this._setMsg('Rebind cancelled.');
- this._renderControls();
- this._focusChip(id);
- return;
- }
- const res = this.kb.set(id, key);
- if (!res.ok) {
- const reasons = {
- fixed: 'That action can’t be rebound.',
- reserved: 'Esc and Enter are reserved.',
- empty: 'Unrecognized key.',
- unknown: 'Unknown action.',
- };
- this._setMsg(reasons[res.reason] || 'Could not bind that key.');
- } else if (res.conflicts.length) {
- const names = res.conflicts
- .map((c) => ACTIONS.find((a) => a.id === c)?.label || c)
- .join(', ');
- this._setMsg(`Bound to ${keyLabel(key)} — also used by ${names}.`);
- } else {
- this._setMsg(`Bound to ${keyLabel(key)}.`);
- }
- this._renderControls();
- this._focusChip(id);
- }
-
- _focusChip(id) {
- this._surfaces.settings?.body.querySelector(`.kg-bind-chip[data-action="${id}"]`)?.focus();
- }
-
- _setMsg(text) {
- this._pendingMsg = text;
- if (this._msgEl) this._msgEl.textContent = text;
- }
-
- _resetBindings() {
- this.kb.reset();
- this._setMsg('Restored default controls.');
- this._renderControls();
- }
-
- _onBindingsChanged() {
- this._updateHint();
- if (this._isOpen('settings')) {
- const msg = this._pendingMsg;
- this._renderControls();
- if (msg) this._setMsg(msg);
- }
- }
-
- _updateHint() {
- const hint = document.getElementById('kg-hint');
- if (!hint) return;
- const kl = (id) => keyLabel(this.kb.get(id));
- hint.innerHTML =
- `<kbd>WASD</kbd> move · <kbd>${kl('hotbar1')}</kbd>–<kbd>${kl('hotbar6')}</kbd> hotbar · ` +
- `<kbd>${kl('inventory')}</kbd> bag · <kbd>${kl('quests')}</kbd> quests · ` +
- `<kbd>${kl('map')}</kbd> map · <kbd>${kl('build')}</kbd> build · ` +
- `<kbd>${kl('skills')}</kbd> skills · <kbd>${kl('chat')}</kbd> chat · <kbd>⚙</kbd> controls`;
- }
-
- // -------------------------------------------------------------- teardown
- destroy() {
- window.removeEventListener('keydown', this._onKeyDown, true);
- clearInterval(this._syncTimer);
- if (this._mapTimer) clearInterval(this._mapTimer);
- this._unsub?.();
- this._friendsUnsub?.();
- this._friendsPanel?.unmount();
- this._friendsPanel = null;
- this._gearEl?.remove();
- this._friendsBtn?.remove();
- for (const k of Object.keys(this._surfaces)) this._surfaces[k].overlay.remove();
- this._surfaces = {};
- this._mounted = false;
- }
-}
-
-// Self-mount onto the live game instance. iso-game.js creates window.__ISO__ at
-// module load; we poll briefly to cover either load order, then attach once.
-function boot() {
- const attach = () => {
- const game = window.__ISO__;
- if (!game) return false;
- if (game.__controls) return true;
- game.__controls = new IsoControls(game);
- game.__controls.mount();
- return true;
- };
- if (attach()) return;
- const t = setInterval(() => {
- if (attach()) clearInterval(t);
- }, 120);
- setTimeout(() => clearInterval(t), 30000);
-}
-
-if (typeof window !== 'undefined') boot();
diff --git a/src/game/iso-game.css b/src/game/iso-game.css
deleted file mode 100644
index 57d8ebe4f..000000000
--- a/src/game/iso-game.css
+++ /dev/null
@@ -1,3441 +0,0 @@
-/* Isometric RPG (/game) — HUD, overlays, nameplates, toasts.
- Dark, sleek, monochrome-leaning to match the /play client; avatars and world
- provide the colour. */
-
-:root {
- --kg-bg: #0d1420;
- --kg-panel: rgba(16, 22, 34, 0.92);
- --kg-line: rgba(255, 255, 255, 0.12);
- --kg-text: #e8edf6;
- --kg-dim: #95a1b6;
- --kg-accent: #cdd6e6;
-}
-
-* {
- box-sizing: border-box;
-}
-html,
-body {
- margin: 0;
- height: 100%;
- overflow: hidden;
- background: var(--kg-bg);
- color: var(--kg-text);
- font-family:
- system-ui,
- -apple-system,
- 'Segoe UI',
- sans-serif;
- -webkit-font-smoothing: antialiased;
- overscroll-behavior: none;
-}
-#kg-canvas {
- position: fixed;
- inset: 0;
- width: 100%;
- height: 100%;
- display: block;
- touch-action: none;
-}
-body.kg-loading-cursor {
- cursor: progress;
-}
-
-/* Portal fade-to-black overlay — covers the full viewport during realm handoffs
- so the geometry swap is invisible and the transition reads as intentional travel.
- Fades in on portal trigger (opacity 0→1), stays opaque while the new room loads,
- then fades out once _onHandoff fires (opacity 1→0). pointer-events auto blocks
- accidental clicks during the swap. */
-#kg-portal-fade {
- position: fixed;
- inset: 0;
- z-index: 50;
- background: #000;
- opacity: 0;
- pointer-events: none;
- transition: opacity 0.35s ease;
-}
-#kg-portal-fade.kg-fading-out {
- opacity: 1;
- pointer-events: auto;
-}
-
-/* DOM layer for projected nameplates (pointer-transparent). */
-#kg-labels {
- position: fixed;
- inset: 0;
- pointer-events: none;
- overflow: hidden;
- z-index: 5;
-}
-
-.kg-label {
- position: absolute;
- top: 0;
- left: 0;
- will-change: transform;
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 3px;
- font-size: 12px;
- font-weight: 600;
- letter-spacing: 0.01em;
- text-shadow: 0 1px 3px rgba(0, 0, 0, 0.8);
-}
-.kg-label-name {
- padding: 1px 7px;
- border-radius: 6px;
- background: rgba(13, 20, 32, 0.66);
- border: 1px solid var(--kg-line);
- white-space: nowrap;
- max-width: 160px;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-.kg-label--me .kg-label-name {
- background: rgba(40, 52, 74, 0.82);
- border-color: rgba(255, 255, 255, 0.28);
-}
-.kg-hp {
- width: 46px;
- height: 4px;
- border-radius: 3px;
- overflow: hidden;
- background: rgba(0, 0, 0, 0.55);
- border: 1px solid rgba(0, 0, 0, 0.4);
- opacity: 0;
- transition: opacity 0.2s;
-}
-.kg-label.kg-hurt .kg-hp {
- opacity: 1;
-}
-.kg-hp i {
- display: block;
- height: 100%;
- width: 100%;
- background: linear-gradient(90deg, #6ee787, #d7ff7a);
- transition: width 0.2s ease;
-}
-
-/* Speech bubble — floats above the nameplate when a player chats. Positioned
- each frame by the label projection loop; hidden between messages.
- The transform set by JS already includes translate(-50%, -100%) centering;
- we only need padding/background/shape here. */
-.kg-chat-bubble {
- position: absolute;
- top: 0;
- left: 0;
- will-change: transform;
- max-width: 200px;
- padding: 5px 10px;
- background: rgba(13, 20, 32, 0.88);
- border: 1px solid rgba(255, 255, 255, 0.18);
- border-radius: 10px;
- font-size: 12px;
- color: var(--kg-text);
- text-shadow: 0 1px 3px rgba(0, 0, 0, 0.8);
- white-space: pre-wrap;
- overflow-wrap: anywhere;
- pointer-events: none;
- line-height: 1.4;
- transition: opacity 0.4s ease;
-}
-.kg-chat-bubble[hidden] { display: none; }
-.kg-chat-bubble--fade { opacity: 0; }
-
-/* Top bar: realm + online + connection status. */
-#kg-topbar {
- position: fixed;
- top: 0;
- left: 0;
- right: 0;
- z-index: 8;
- display: flex;
- align-items: center;
- gap: 14px;
- padding: 10px 16px;
- pointer-events: none;
- background: linear-gradient(180deg, rgba(8, 12, 20, 0.7), transparent);
-}
-#kg-realm {
- font-weight: 700;
- font-size: 15px;
- letter-spacing: 0.02em;
-}
-.kg-stat {
- font-size: 12px;
- color: var(--kg-dim);
- display: inline-flex;
- align-items: center;
- gap: 5px;
-}
-.kg-stat b {
- color: var(--kg-text);
- font-weight: 700;
-}
-#kg-status {
- margin-left: auto;
- pointer-events: auto;
- font-size: 11px;
- text-transform: uppercase;
- letter-spacing: 0.08em;
- padding: 4px 10px;
- border-radius: 999px;
- background: rgba(255, 255, 255, 0.06);
- border: 1px solid var(--kg-line);
- color: var(--kg-dim);
-}
-#kg-status[data-status='online'] {
- color: #6ee787;
- border-color: rgba(110, 231, 135, 0.4);
-}
-#kg-status[data-status='connecting'] {
- color: #ffce5c;
- border-color: rgba(255, 206, 92, 0.4);
-}
-#kg-status[data-status='offline'],
-#kg-status[data-status='failed'] {
- color: #ff8a8a;
- border-color: rgba(255, 138, 138, 0.4);
-}
-
-/* Controls hint (bottom). */
-#kg-hint {
- position: fixed;
- bottom: 14px;
- left: 50%;
- transform: translateX(-50%);
- z-index: 7;
- font-size: 12px;
- color: var(--kg-dim);
- pointer-events: none;
- text-align: center;
- background: rgba(13, 20, 32, 0.5);
- padding: 6px 12px;
- border-radius: 8px;
- border: 1px solid var(--kg-line);
-}
-#kg-hint kbd {
- font: inherit;
- font-weight: 700;
- color: var(--kg-text);
- background: rgba(255, 255, 255, 0.08);
- border: 1px solid var(--kg-line);
- border-radius: 4px;
- padding: 0 5px;
-}
-
-/* Toasts (server notices: gathered, killed, inventory full, …). */
-#kg-toasts {
- position: fixed;
- top: 56px;
- left: 50%;
- transform: translateX(-50%);
- z-index: 9;
- display: flex;
- flex-direction: column;
- gap: 8px;
- align-items: center;
- pointer-events: none;
-}
-.kg-toast {
- padding: 8px 16px;
- border-radius: 10px;
- font-size: 13px;
- font-weight: 600;
- background: var(--kg-panel);
- border: 1px solid var(--kg-line);
- color: var(--kg-text);
- opacity: 0;
- transform: translateY(-8px);
- transition:
- opacity 0.3s,
- transform 0.3s;
- box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45);
-}
-.kg-toast--in {
- opacity: 1;
- transform: translateY(0);
-}
-.kg-toast--kill {
- border-color: rgba(110, 231, 135, 0.45);
-}
-.kg-toast--full,
-.kg-toast--tool,
-.kg-toast--bank {
- border-color: rgba(255, 206, 92, 0.45);
-}
-.kg-toast--cook,
-.kg-toast--eat {
- border-color: rgba(110, 231, 135, 0.45);
-}
-.kg-toast--burn {
- border-color: rgba(255, 122, 58, 0.5);
-}
-.kg-toast--fish {
- border-color: rgba(92, 182, 230, 0.5);
-}
-.kg-toast--market {
- border-color: rgba(110, 231, 176, 0.5);
-}
-.kg-toast-link {
- color: var(--kg-text);
- pointer-events: auto;
- text-decoration: underline;
- text-underline-offset: 2px;
- text-decoration-color: rgba(110, 231, 176, 0.6);
- white-space: nowrap;
- transition: text-decoration-color 0.15s;
-}
-.kg-toast-link:hover,
-.kg-toast-link:focus-visible {
- text-decoration-color: var(--kg-text);
- outline: none;
-}
-
-/* Contextual action bar (cook at a Roast Pit, eat to heal). Buttons reveal only
- when the action is actually possible; see _updateActions in iso-game.js. */
-#kg-actions {
- position: fixed;
- left: 50%;
- bottom: 96px;
- transform: translateX(-50%);
- z-index: 8;
- display: flex;
- gap: 10px;
- align-items: center;
-}
-#kg-actions[hidden] {
- display: none;
-}
-.kg-action {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- cursor: pointer;
- padding: 10px 16px;
- font-size: 14px;
- font-weight: 700;
- color: var(--kg-text);
- background: var(--kg-panel);
- border: 1px solid var(--kg-line);
- border-radius: 12px;
- box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45);
- backdrop-filter: blur(4px);
- transition:
- transform 0.08s ease,
- border-color 0.15s,
- opacity 0.15s;
-}
-.kg-action[hidden] {
- display: none;
-}
-.kg-action:hover {
- border-color: var(--kg-accent);
- transform: translateY(-1px);
-}
-.kg-action:active {
- transform: translateY(1px);
-}
-.kg-action:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-.kg-action-dot {
- width: 9px;
- height: 9px;
- border-radius: 50%;
- background: var(--kg-dim);
- box-shadow: 0 0 8px currentColor;
-}
-#kg-cook .kg-action-dot {
- background: #ff7a3a;
- color: #ff7a3a;
-}
-#kg-eat .kg-action-dot {
- background: #6ee787;
- color: #6ee787;
-}
-#kg-cast .kg-action-dot {
- background: #5cb6e6;
- color: #5cb6e6;
-}
-#kg-pickup .kg-action-dot {
- background: #c9a26b;
- color: #c9a26b;
-}
-/* Cast is shown beside water even without a rod, so the player learns where to
- fish — muted + a help cursor signal it's gated until they hold a rod. */
-.kg-action--muted {
- opacity: 0.6;
-}
-.kg-action--muted .kg-action-dot {
- background: var(--kg-dim);
- color: var(--kg-dim);
- box-shadow: none;
-}
-.kg-action--muted:hover {
- border-color: var(--kg-line);
- transform: none;
-}
-.kg-action--pulse {
- animation: kg-cook-pulse 0.7s ease;
-}
-@keyframes kg-cook-pulse {
- 0% {
- box-shadow:
- 0 10px 30px rgba(0, 0, 0, 0.45),
- 0 0 0 0 rgba(255, 122, 58, 0.55);
- }
- 60% {
- box-shadow:
- 0 10px 30px rgba(0, 0, 0, 0.45),
- 0 0 0 14px rgba(255, 122, 58, 0);
- }
- 100% {
- box-shadow:
- 0 10px 30px rgba(0, 0, 0, 0.45),
- 0 0 0 0 rgba(255, 122, 58, 0);
- }
-}
-/* Green heal flash on the local nameplate when eating. */
-.kg-label.kg-heal {
- animation: kg-heal-flash 0.7s ease;
-}
-@keyframes kg-heal-flash {
- 0% {
- box-shadow: 0 0 0 0 rgba(110, 231, 135, 0);
- }
- 30% {
- box-shadow: 0 0 14px 4px rgba(110, 231, 135, 0.6);
- }
- 100% {
- box-shadow: 0 0 0 0 rgba(110, 231, 135, 0);
- }
-}
-@media (max-width: 480px) {
- #kg-actions {
- bottom: 128px;
- }
-}
-
-/* Joystick zone (touch only). */
-#kg-joystick {
- position: fixed;
- left: 0;
- bottom: 0;
- width: 180px;
- height: 200px;
- z-index: 6;
-}
-
-/* Start + offline overlays. */
-.kg-overlay {
- position: fixed;
- inset: 0;
- z-index: 20;
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 24px;
- background: radial-gradient(120% 120% at 50% 30%, rgba(20, 28, 44, 0.55), rgba(8, 12, 20, 0.9));
- backdrop-filter: blur(2px);
-}
-.kg-overlay[hidden] {
- display: none;
-}
-.kg-card {
- width: 100%;
- max-width: 380px;
- text-align: center;
- background: var(--kg-panel);
- border: 1px solid var(--kg-line);
- border-radius: 18px;
- padding: 30px 26px;
- box-shadow: 0 24px 70px rgba(0, 0, 0, 0.55);
-}
-.kg-eyebrow {
- font-size: 11px;
- letter-spacing: 0.22em;
- text-transform: uppercase;
- color: var(--kg-dim);
-}
-.kg-title {
- font-size: 26px;
- font-weight: 800;
- margin: 8px 0 4px;
- letter-spacing: -0.01em;
-}
-.kg-sub {
- font-size: 14px;
- color: var(--kg-dim);
- line-height: 1.5;
- margin: 0 0 22px;
-}
-.kg-field {
- display: block;
- width: 100%;
- margin-bottom: 14px;
-}
-.kg-field input {
- width: 100%;
- padding: 12px 14px;
- font-size: 15px;
- background: rgba(0, 0, 0, 0.3);
- color: var(--kg-text);
- border: 1px solid var(--kg-line);
- border-radius: 10px;
- outline: none;
- transition: border-color 0.15s;
-}
-.kg-field input:focus {
- border-color: var(--kg-accent);
-}
-.kg-btn {
- width: 100%;
- padding: 13px 18px;
- font-size: 15px;
- font-weight: 700;
- cursor: pointer;
- background: var(--kg-text);
- color: #0d1420;
- border: 0;
- border-radius: 10px;
- transition:
- transform 0.08s ease,
- opacity 0.15s;
-}
-.kg-btn:hover {
- opacity: 0.92;
-}
-.kg-btn:active {
- transform: translateY(1px);
-}
-.kg-btn:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-.kg-feats {
- display: flex;
- gap: 8px;
- justify-content: center;
- margin-top: 18px;
- flex-wrap: wrap;
-}
-.kg-feat {
- font-size: 11px;
- color: var(--kg-dim);
- border: 1px solid var(--kg-line);
- border-radius: 999px;
- padding: 4px 10px;
-}
-
-/* ---------------------------------------------------------------- server picker
- Login-time world-instance chooser (Task 23). Radio cards with real live
- population; the recommended (least-full) server is badged. */
-.kg-servers {
- border: 0;
- margin: 0 0 14px;
- padding: 0;
- text-align: left;
-}
-.kg-servers-legend {
- font-size: 11px;
- letter-spacing: 0.16em;
- text-transform: uppercase;
- color: var(--kg-dim);
- padding: 0;
- margin-bottom: 8px;
-}
-.kg-servers-list {
- display: flex;
- flex-direction: column;
- gap: 8px;
-}
-.kg-servers-loading {
- font-size: 13px;
- color: var(--kg-dim);
- padding: 10px 2px;
-}
-.kg-server-opt {
- position: relative;
- display: flex;
- align-items: center;
- gap: 12px;
- padding: 11px 13px;
- border: 1px solid var(--kg-line);
- border-radius: 12px;
- background: rgba(0, 0, 0, 0.22);
- cursor: pointer;
- transition:
- border-color 0.15s,
- background 0.15s,
- transform 0.08s ease;
-}
-.kg-server-opt:hover {
- border-color: rgba(255, 255, 255, 0.28);
- background: rgba(255, 255, 255, 0.04);
-}
-.kg-server-opt:active {
- transform: translateY(1px);
-}
-.kg-server-opt input {
- position: absolute;
- opacity: 0;
- pointer-events: none;
-}
-.kg-server-opt[data-selected='true'] {
- border-color: var(--kg-accent);
- background: color-mix(in srgb, var(--kg-accent) 14%, transparent);
-}
-.kg-server-opt:focus-within {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-.kg-server-dot {
- flex: 0 0 auto;
- width: 9px;
- height: 9px;
- border-radius: 50%;
- background: #3ad07a;
- box-shadow: 0 0 0 3px color-mix(in srgb, #3ad07a 22%, transparent);
-}
-.kg-server-opt[data-empty='true'] .kg-server-dot {
- background: var(--kg-dim);
- box-shadow: none;
-}
-.kg-server-main {
- flex: 1 1 auto;
- min-width: 0;
-}
-.kg-server-name {
- display: flex;
- align-items: center;
- gap: 8px;
- font-size: 14px;
- font-weight: 700;
- color: var(--kg-text);
-}
-.kg-server-blurb {
- font-size: 12px;
- color: var(--kg-dim);
- margin-top: 2px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.kg-server-pop {
- flex: 0 0 auto;
- font-size: 12px;
- color: var(--kg-dim);
- text-align: right;
- line-height: 1.25;
-}
-.kg-server-pop b {
- display: block;
- font-size: 15px;
- color: var(--kg-text);
-}
-.kg-server-rec {
- font-size: 9.5px;
- font-weight: 700;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: #0d1420;
- background: var(--kg-accent);
- border-radius: 999px;
- padding: 2px 7px;
-}
-.kg-servers-note {
- font-size: 11.5px;
- color: var(--kg-dim);
- line-height: 1.45;
- margin: 10px 2px 0;
-}
-
-/* Topbar chip naming the world instance you're on. */
-.kg-server-chip {
- font-size: 11px;
- font-weight: 600;
- color: var(--kg-dim);
- border: 1px solid var(--kg-line);
- border-radius: 999px;
- padding: 2px 9px;
-}
-.kg-server-chip[hidden] {
- display: none;
-}
-
-.kg-spinner {
- width: 34px;
- height: 34px;
- margin: 4px auto 18px;
- border-radius: 50%;
- border: 3px solid rgba(255, 255, 255, 0.15);
- border-top-color: var(--kg-text);
- animation: kg-spin 0.8s linear infinite;
-}
-@keyframes kg-spin {
- to {
- transform: rotate(360deg);
- }
-}
-
-@media (max-width: 480px) {
- .kg-card {
- padding: 24px 20px;
- }
- .kg-title {
- font-size: 22px;
- }
-}
-
-/* ---------------------------------------------------------------- world chat
- Bottom-left panel. Collapsed by default (click-through, masked scrollback);
- focusing the input or pressing C/Enter opens it (full scrollback, mute UI). */
-#kg-chat {
- position: fixed;
- left: 14px;
- bottom: 14px;
- z-index: 7;
- width: min(340px, calc(100vw - 28px));
- display: flex;
- flex-direction: column;
- gap: 6px;
- pointer-events: none; /* world stays clickable through the gaps; children opt back in */
- font-size: 13px;
-}
-#kg-chat[hidden] {
- display: none;
-}
-
-.kg-chat-head {
- display: none;
- align-items: center;
- justify-content: space-between;
- padding: 0 2px;
-}
-.kg-chat--open .kg-chat-head {
- display: flex;
-}
-.kg-chat-title {
- font-size: 11px;
- text-transform: uppercase;
- letter-spacing: 0.12em;
- color: var(--kg-dim);
- font-weight: 700;
-}
-.kg-chat-muted-btn {
- pointer-events: auto;
- cursor: pointer;
- font: inherit;
- font-size: 11px;
- color: var(--kg-dim);
- background: rgba(255, 255, 255, 0.05);
- border: 1px solid var(--kg-line);
- border-radius: 999px;
- padding: 2px 9px;
- transition:
- color 0.15s,
- border-color 0.15s;
-}
-.kg-chat-muted-btn:hover {
- color: var(--kg-text);
- border-color: var(--kg-accent);
-}
-.kg-chat-muted-btn b {
- color: var(--kg-text);
-}
-.kg-chat-muted-btn:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-
-.kg-chat-log {
- display: flex;
- flex-direction: column;
- gap: 3px;
- max-height: 132px;
- overflow-y: auto;
- overflow-x: hidden;
- padding: 2px 4px;
- pointer-events: none; /* collapsed: clicks fall through to the world */
- -webkit-mask-image: linear-gradient(180deg, transparent 0, #000 20px);
- mask-image: linear-gradient(180deg, transparent 0, #000 20px);
- scrollbar-width: thin;
- scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
- transition: max-height 0.18s ease;
-}
-.kg-chat--open .kg-chat-log {
- max-height: 230px;
- pointer-events: auto;
- -webkit-mask-image: none;
- mask-image: none;
-}
-.kg-chat-log::-webkit-scrollbar {
- width: 7px;
-}
-.kg-chat-log::-webkit-scrollbar-thumb {
- background: rgba(255, 255, 255, 0.18);
- border-radius: 4px;
-}
-
-.kg-chat-line {
- line-height: 1.4;
- overflow-wrap: anywhere;
- text-shadow: 0 1px 3px rgba(0, 0, 0, 0.85);
- background: rgba(13, 20, 32, 0.42);
- border-radius: 7px;
- padding: 2px 8px;
- animation: kg-chat-in 0.18s ease;
-}
-.kg-chat--open .kg-chat-line {
- background: rgba(13, 20, 32, 0.66);
-}
-.kg-chat-line--muted {
- display: none;
-}
-@keyframes kg-chat-in {
- from {
- opacity: 0;
- transform: translateY(4px);
- }
-}
-
-.kg-chat-name {
- pointer-events: auto;
- cursor: pointer;
- font: inherit;
- font-weight: 700;
- color: var(--kg-accent);
- background: none;
- border: 0;
- padding: 0;
- margin-right: 5px;
- border-radius: 4px;
-}
-.kg-chat-name:hover {
- text-decoration: underline;
-}
-.kg-chat-name:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 1px;
-}
-.kg-chat-name--me {
- color: #d7ff7a;
- cursor: default;
-}
-.kg-chat-name--me:hover {
- text-decoration: none;
-}
-.kg-chat-text {
- color: var(--kg-text);
-}
-
-.kg-chat-line--system {
- background: rgba(40, 52, 74, 0.5);
-}
-.kg-chat-line--system .kg-chat-text {
- color: var(--kg-dim);
- white-space: pre-wrap;
- font-style: italic;
-}
-.kg-chat-line--error {
- background: rgba(120, 40, 40, 0.42);
-}
-.kg-chat-line--error .kg-chat-text {
- color: #ff9c9c;
- font-style: normal;
-}
-.kg-chat-line--help {
- background: rgba(20, 28, 44, 0.7);
- border-left: 2px solid var(--kg-accent);
- padding-left: 10px;
-}
-.kg-chat-line--help .kg-chat-text {
- font-family: monospace;
- font-size: 12px;
- font-style: normal;
- color: var(--kg-text);
- opacity: 0.9;
-}
-.kg-chat-line--who {
- border-left: 2px solid #5dd9c1;
-}
-.kg-chat-line--who .kg-chat-text {
- color: #a8eee4;
- font-style: normal;
-}
-
-.kg-chat-form {
- display: flex;
- position: relative; /* anchors the slash-command autocomplete above the input */
-}
-
-/* Character counter — appears once the message exceeds 160 chars, right-aligned
- inside the form so it overlays the trailing edge of the input without taking up
- layout space. */
-.kg-chat-counter {
- position: absolute;
- right: 10px;
- top: 50%;
- transform: translateY(-50%);
- font-size: 11px;
- font-variant-numeric: tabular-nums;
- color: var(--kg-dim);
- pointer-events: none;
- transition: color 0.15s;
-}
-.kg-chat-counter[data-state="warn"] { color: #f0a830; }
-.kg-chat-counter[data-state="danger"] { color: #ff5a5a; font-weight: 700; }
-
-/* Slash-command autocomplete — floats just above the chat input. */
-.kg-chat-hint {
- position: absolute;
- left: 0;
- right: 0;
- bottom: calc(100% + 6px);
- z-index: 10;
- margin: 0;
- padding: 4px;
- list-style: none;
- max-height: 216px;
- overflow-y: auto;
- pointer-events: auto;
- background: var(--kg-panel);
- border: 1px solid var(--kg-line);
- border-radius: 10px;
- box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45);
-}
-.kg-chat-hint[hidden] {
- display: none;
-}
-.kg-chat-hint-item {
- display: flex;
- align-items: baseline;
- gap: 8px;
- padding: 6px 9px;
- border-radius: 7px;
- cursor: pointer;
- transition: background 0.12s;
-}
-.kg-chat-hint-item:hover,
-.kg-chat-hint-item--active {
- background: rgba(120, 170, 255, 0.16);
-}
-.kg-chat-hint-cmd {
- flex: none;
- font-weight: 700;
- color: var(--kg-accent);
- font-variant-numeric: tabular-nums;
-}
-.kg-chat-hint-desc {
- flex: 1;
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- font-size: 12px;
- color: var(--kg-dim);
-}
-.kg-chat-input {
- pointer-events: auto;
- width: 100%;
- padding: 8px 12px;
- font: inherit;
- font-size: 13px;
- color: var(--kg-text);
- background: rgba(13, 20, 32, 0.5);
- border: 1px solid var(--kg-line);
- border-radius: 9px;
- outline: none;
- opacity: 0.55;
- transition:
- opacity 0.15s,
- border-color 0.15s,
- background 0.15s;
-}
-.kg-chat-input::placeholder {
- color: var(--kg-dim);
-}
-.kg-chat--open .kg-chat-input,
-.kg-chat-input:focus {
- opacity: 1;
- background: rgba(0, 0, 0, 0.45);
- border-color: var(--kg-accent);
-}
-
-/* Mute menu popover (click a sender's name). */
-.kg-chat-menu {
- position: absolute;
- z-index: 9;
- pointer-events: auto;
- min-width: 140px;
- background: var(--kg-panel);
- border: 1px solid var(--kg-line);
- border-radius: 9px;
- padding: 4px;
- box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
- animation: kg-chat-in 0.12s ease;
-}
-.kg-chat-menu-btn {
- display: block;
- width: 100%;
- text-align: left;
- cursor: pointer;
- font: inherit;
- font-size: 12px;
- color: var(--kg-text);
- background: none;
- border: 0;
- border-radius: 6px;
- padding: 7px 9px;
-}
-.kg-chat-menu-btn:hover {
- background: rgba(255, 255, 255, 0.08);
-}
-.kg-chat-menu-btn:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: -2px;
-}
-
-/* Muted-players list (floats above the panel). */
-.kg-chat-muted {
- position: absolute;
- left: 0;
- right: 0;
- bottom: calc(100% + 6px);
- z-index: 9;
- pointer-events: auto;
- background: var(--kg-panel);
- border: 1px solid var(--kg-line);
- border-radius: 10px;
- padding: 8px;
- box-shadow: 0 12px 34px rgba(0, 0, 0, 0.5);
- max-height: 220px;
- overflow-y: auto;
- animation: kg-chat-in 0.14s ease;
-}
-.kg-chat-muted[hidden] {
- display: none;
-}
-.kg-chat-muted-row {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 10px;
- padding: 5px 4px;
-}
-.kg-chat-muted-name {
- color: var(--kg-text);
- font-weight: 600;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.kg-chat-unmute {
- cursor: pointer;
- font: inherit;
- font-size: 11px;
- font-weight: 700;
- color: #0d1420;
- background: var(--kg-text);
- border: 0;
- border-radius: 6px;
- padding: 4px 10px;
- transition: opacity 0.15s;
-}
-.kg-chat-unmute:hover {
- opacity: 0.88;
-}
-.kg-chat-unmute:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-.kg-chat-muted-empty {
- color: var(--kg-dim);
- font-size: 12px;
- text-align: center;
- padding: 10px 4px;
-}
-
-/* On touch the joystick owns the bottom-left corner — float chat above it. */
-@media (pointer: coarse) {
- #kg-chat {
- bottom: 216px;
- width: min(300px, calc(100vw - 28px));
- }
- .kg-chat-log {
- max-height: 110px;
- }
-}
-
-/* ===========================================================================
- Skills — topbar toggle, slide-in panel, per-skill progress, level-up toast.
- =========================================================================== */
-
-/* Topbar "Skills" toggle. Sits to the right; the status pill follows it. */
-.kg-hud-btn {
- margin-left: auto;
- pointer-events: auto;
- cursor: pointer;
- display: inline-flex;
- align-items: center;
- gap: 6px;
- font-size: 12px;
- font-weight: 700;
- letter-spacing: 0.02em;
- padding: 5px 11px;
- border-radius: 999px;
- background: rgba(255, 255, 255, 0.06);
- border: 1px solid var(--kg-line);
- color: var(--kg-text);
- transition:
- background 0.15s,
- border-color 0.15s,
- transform 0.08s;
-}
-.kg-hud-btn:hover {
- background: rgba(255, 255, 255, 0.12);
- border-color: rgba(255, 255, 255, 0.28);
-}
-.kg-hud-btn:active {
- transform: translateY(1px);
-}
-.kg-hud-btn:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-.kg-hud-btn[aria-expanded='true'] {
- background: rgba(120, 150, 220, 0.22);
- border-color: rgba(150, 180, 255, 0.45);
-}
-.kg-hud-ico {
- width: 15px;
- height: 15px;
- fill: none;
- stroke: currentColor;
- stroke-width: 2;
- stroke-linecap: round;
- stroke-linejoin: round;
-}
-/* Keep the status pill grouped with the toggle (override its margin-left:auto). */
-#kg-status {
- margin-left: 12px;
-}
-
-/* Slide-in panel, right edge. */
-.kg-skills {
- position: fixed;
- top: 0;
- right: 0;
- bottom: 0;
- z-index: 12;
- width: min(340px, 88vw);
- display: flex;
- flex-direction: column;
- background: var(--kg-panel);
- border-left: 1px solid var(--kg-line);
- box-shadow: -18px 0 50px rgba(0, 0, 0, 0.5);
- backdrop-filter: blur(6px);
- transform: translateX(100%);
- transition: transform 0.22s cubic-bezier(0.22, 1, 0.36, 1);
- will-change: transform;
-}
-.kg-skills.kg-skills--open {
- transform: translateX(0);
-}
-.kg-skills[hidden] {
- display: none;
-}
-
-.kg-skills-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 16px 18px 12px;
- border-bottom: 1px solid var(--kg-line);
-}
-.kg-skills-title {
- margin: 0;
- font-size: 16px;
- font-weight: 800;
- letter-spacing: 0.01em;
-}
-.kg-skills-close {
- display: inline-flex;
- padding: 6px;
- border-radius: 8px;
- cursor: pointer;
- background: transparent;
- border: 1px solid transparent;
- color: var(--kg-dim);
- transition:
- color 0.15s,
- background 0.15s,
- border-color 0.15s;
-}
-.kg-skills-close svg {
- width: 18px;
- height: 18px;
- fill: none;
- stroke: currentColor;
- stroke-width: 2;
- stroke-linecap: round;
-}
-.kg-skills-close:hover {
- color: var(--kg-text);
- background: rgba(255, 255, 255, 0.07);
- border-color: var(--kg-line);
-}
-.kg-skills-close:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-
-.kg-skills-summary {
- display: flex;
- gap: 10px;
- padding: 14px 18px 4px;
-}
-.kg-skills-sum {
- flex: 1;
- display: flex;
- flex-direction: column;
- gap: 2px;
- align-items: center;
- padding: 10px 8px;
- border-radius: 12px;
- background: rgba(255, 255, 255, 0.04);
- border: 1px solid var(--kg-line);
-}
-.kg-skills-sum-val {
- font-size: 22px;
- font-weight: 800;
- line-height: 1;
- font-variant-numeric: tabular-nums;
-}
-.kg-skills-sum-lbl {
- font-size: 10px;
- text-transform: uppercase;
- letter-spacing: 0.1em;
- color: var(--kg-dim);
-}
-
-.kg-skills-list {
- list-style: none;
- margin: 0;
- padding: 12px 14px;
- display: flex;
- flex-direction: column;
- gap: 8px;
- overflow-y: auto;
- flex: 1;
- scrollbar-width: thin;
- scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
-}
-.kg-skills-loading {
- color: var(--kg-dim);
- font-size: 13px;
- text-align: center;
- padding: 28px 12px;
-}
-
-.kg-skill {
- display: flex;
- align-items: center;
- gap: 12px;
- padding: 11px 12px;
- border-radius: 12px;
- background: rgba(255, 255, 255, 0.03);
- border: 1px solid var(--kg-line);
- transition:
- border-color 0.15s,
- background 0.15s;
- animation: kg-skill-in 0.28s ease both;
-}
-.kg-skill:hover {
- background: rgba(255, 255, 255, 0.06);
- border-color: rgba(255, 255, 255, 0.2);
-}
-@keyframes kg-skill-in {
- from {
- opacity: 0;
- transform: translateY(6px);
- }
- to {
- opacity: 1;
- transform: none;
- }
-}
-
-.kg-skill-ico {
- flex: 0 0 36px;
- width: 36px;
- height: 36px;
- display: grid;
- place-items: center;
- border-radius: 10px;
- background: color-mix(in srgb, var(--kg-hue) 16%, transparent);
- border: 1px solid color-mix(in srgb, var(--kg-hue) 38%, transparent);
-}
-.kg-skill-ico svg {
- width: 20px;
- height: 20px;
- fill: none;
- stroke: var(--kg-hue);
- stroke-width: 1.9;
- stroke-linecap: round;
- stroke-linejoin: round;
-}
-
-.kg-skill-main {
- flex: 1;
- min-width: 0;
- display: flex;
- flex-direction: column;
- gap: 5px;
-}
-.kg-skill-top {
- display: flex;
- align-items: baseline;
- justify-content: space-between;
- gap: 8px;
-}
-.kg-skill-name {
- font-size: 13px;
- font-weight: 700;
- letter-spacing: 0.01em;
-}
-.kg-skill-lvl {
- font-size: 12px;
- color: var(--kg-dim);
- font-variant-numeric: tabular-nums;
- white-space: nowrap;
-}
-.kg-skill-lvl b {
- color: var(--kg-text);
- font-size: 15px;
- font-weight: 800;
-}
-.kg-skill-lvl i {
- font-style: normal;
- opacity: 0.6;
-}
-.kg-skill-lvl em {
- font-style: normal;
- font-size: 9px;
- font-weight: 800;
- letter-spacing: 0.08em;
- color: #0d1420;
- background: var(--kg-hue);
- border-radius: 4px;
- padding: 1px 4px;
- margin-right: 6px;
- vertical-align: 1px;
-}
-
-.kg-skill-bar {
- height: 7px;
- border-radius: 5px;
- overflow: hidden;
- background: rgba(0, 0, 0, 0.4);
- border: 1px solid rgba(0, 0, 0, 0.3);
-}
-.kg-skill-bar i {
- display: block;
- height: 100%;
- min-width: 0;
- border-radius: 5px;
- background: linear-gradient(90deg, color-mix(in srgb, var(--kg-hue) 65%, #fff), var(--kg-hue));
- box-shadow: 0 0 8px color-mix(in srgb, var(--kg-hue) 60%, transparent);
- transition: width 0.45s cubic-bezier(0.22, 1, 0.36, 1);
-}
-.kg-skill-xp {
- font-size: 11px;
- color: var(--kg-dim);
- font-variant-numeric: tabular-nums;
-}
-
-/* Maxed skill: hue-tinted rim + a steady full bar. */
-.kg-skill--max {
- border-color: color-mix(in srgb, var(--kg-hue) 45%, transparent);
- background: color-mix(in srgb, var(--kg-hue) 8%, transparent);
-}
-.kg-skill--max .kg-skill-xp {
- color: var(--kg-hue);
- font-weight: 700;
-}
-/* Fresh skill (level 1, no XP yet): the empty bar reads as a starting line. */
-.kg-skill--fresh .kg-skill-xp {
- opacity: 0.8;
-}
-
-.kg-skills-foot {
- margin: 0;
- padding: 12px 18px 16px;
- font-size: 11px;
- color: var(--kg-dim);
- border-top: 1px solid var(--kg-line);
- text-align: center;
-}
-.kg-skills-foot b {
- color: var(--kg-text);
- font-weight: 700;
-}
-
-/* Level-up celebration toasts — driven by real server 'levelup' events. */
-#kg-levelups {
- position: fixed;
- top: 22%;
- left: 50%;
- transform: translateX(-50%);
- z-index: 11;
- display: flex;
- flex-direction: column;
- gap: 10px;
- align-items: center;
- pointer-events: none;
-}
-.kg-levelup {
- display: flex;
- align-items: center;
- gap: 12px;
- padding: 12px 20px 12px 14px;
- border-radius: 14px;
- background: var(--kg-panel);
- border: 1px solid color-mix(in srgb, var(--kg-hue) 55%, var(--kg-line));
- box-shadow:
- 0 12px 40px rgba(0, 0, 0, 0.5),
- 0 0 26px color-mix(in srgb, var(--kg-hue) 35%, transparent);
- opacity: 0;
- transform: translateY(-10px) scale(0.92);
- transition:
- opacity 0.3s ease,
- transform 0.35s cubic-bezier(0.18, 1.4, 0.4, 1);
-}
-.kg-levelup--in {
- opacity: 1;
- transform: translateY(0) scale(1);
-}
-.kg-levelup-ico {
- flex: 0 0 40px;
- width: 40px;
- height: 40px;
- display: grid;
- place-items: center;
- border-radius: 11px;
- background: color-mix(in srgb, var(--kg-hue) 18%, transparent);
- border: 1px solid color-mix(in srgb, var(--kg-hue) 42%, transparent);
- animation: kg-levelup-pop 0.5s ease both;
-}
-.kg-levelup-ico svg {
- width: 22px;
- height: 22px;
- fill: none;
- stroke: var(--kg-hue);
- stroke-width: 1.9;
- stroke-linecap: round;
- stroke-linejoin: round;
-}
-@keyframes kg-levelup-pop {
- 0% {
- transform: scale(0.5) rotate(-12deg);
- }
- 60% {
- transform: scale(1.15) rotate(4deg);
- }
- 100% {
- transform: scale(1);
- }
-}
-.kg-levelup-txt {
- display: flex;
- flex-direction: column;
- gap: 1px;
-}
-.kg-levelup-kicker {
- font-size: 10px;
- font-weight: 800;
- letter-spacing: 0.14em;
- text-transform: uppercase;
- color: var(--kg-hue);
-}
-.kg-levelup-main {
- font-size: 15px;
- font-weight: 700;
-}
-.kg-levelup-main b {
- font-size: 18px;
- font-weight: 800;
-}
-
-/* XP drop chips — "+N XP" floaters that rise and fade on each XP earn.
- Anchored just below the topbar so they don't obscure the level-up cards. */
-#kg-xpdrops {
- position: fixed;
- top: 54px;
- right: 20px;
- display: flex;
- flex-direction: column;
- align-items: flex-end;
- gap: 4px;
- pointer-events: none;
- z-index: 320;
-}
-
-.kg-xpdrop {
- padding: 3px 9px;
- border-radius: 20px;
- background: color-mix(in srgb, var(--kg-hue, #cdd6e6) 18%, rgba(13, 20, 32, 0.88));
- border: 1px solid color-mix(in srgb, var(--kg-hue, #cdd6e6) 35%, transparent);
- color: var(--kg-hue, #cdd6e6);
- font-size: 11px;
- font-weight: 700;
- letter-spacing: 0.02em;
- white-space: nowrap;
- opacity: 0;
- transform: translateY(6px);
- transition: opacity 0.18s ease, transform 0.18s ease;
-}
-
-.kg-xpdrop--in {
- opacity: 1;
- transform: translateY(0);
- animation: kg-xpdrop-rise 1.2s ease forwards;
-}
-
-@keyframes kg-xpdrop-rise {
- 0% { opacity: 1; transform: translateY(0); }
- 70% { opacity: 1; transform: translateY(-14px); }
- 100% { opacity: 0; transform: translateY(-20px); }
-}
-
-@media (prefers-reduced-motion: reduce) {
- .kg-skills,
- .kg-skill,
- .kg-skill-bar i,
- .kg-levelup,
- .kg-levelup-ico,
- .kg-xpdrop {
- transition: none;
- animation: none;
- }
-}
-
-@media (max-width: 480px) {
- .kg-hud-btn span:not(.kg-hud-ico) {
- display: none;
- } /* icon-only on small screens */
- .kg-skills {
- width: min(360px, 94vw);
- }
- #kg-levelups {
- top: auto;
- bottom: 96px;
- }
-}
-
-/* --------------------------------------------------------------------------
- Death-bags (tombstones), the recovery panel, and the respawn overlay.
- Violet keys the "lootable death-bag" colour used by the tombstone mesh.
- -------------------------------------------------------------------------- */
-:root {
- --kg-tomb: #ae7bff;
-}
-
-/* Floating tombstone label (owner + expiry countdown), projected each frame. */
-.kg-tomblabel {
- position: absolute;
- top: 0;
- left: 0;
- will-change: transform;
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 2px;
- font-size: 11px;
- font-weight: 700;
- letter-spacing: 0.01em;
- text-shadow: 0 1px 3px rgba(0, 0, 0, 0.85);
- pointer-events: none;
-}
-.kg-tomb-name {
- padding: 1px 7px;
- border-radius: 6px;
- white-space: nowrap;
- background: rgba(26, 18, 40, 0.74);
- border: 1px solid rgba(174, 123, 255, 0.5);
- color: #e7ddff;
-}
-.kg-tomb-ttl {
- font-size: 10px;
- font-weight: 600;
- color: var(--kg-dim);
- background: rgba(13, 20, 32, 0.6);
- border-radius: 5px;
- padding: 0 5px;
-}
-.kg-tomblabel.kg-tomb-soon .kg-tomb-ttl {
- color: #ffce5c;
-} /* grace window is open */
-
-/* Recovery panel — bottom-centre, above the hint line. */
-.kg-tomb-panel {
- position: fixed;
- left: 50%;
- bottom: 64px;
- transform: translateX(-50%) translateY(8px);
- z-index: 12;
- width: min(320px, 92vw);
- background: var(--kg-panel);
- border: 1px solid rgba(174, 123, 255, 0.35);
- border-radius: 14px;
- box-shadow: 0 18px 50px rgba(0, 0, 0, 0.55);
- padding: 12px 14px 14px;
- opacity: 0;
- transition:
- opacity 0.2s ease,
- transform 0.2s ease;
-}
-.kg-tomb-panel[hidden] {
- display: none;
-}
-.kg-tomb-panel--in {
- opacity: 1;
- transform: translateX(-50%) translateY(0);
-}
-.kg-tomb-head {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-bottom: 10px;
-}
-.kg-tomb-owner {
- font-weight: 700;
- font-size: 14px;
- color: #e7ddff;
- flex: 1;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.kg-tomb-head .kg-tomb-ttl {
- background: none;
- padding: 0;
- font-size: 11px;
-}
-.kg-tomb-close {
- display: grid;
- place-items: center;
- width: 26px;
- height: 26px;
- flex: none;
- background: rgba(255, 255, 255, 0.06);
- border: 1px solid var(--kg-line);
- border-radius: 7px;
- color: var(--kg-dim);
- cursor: pointer;
- transition:
- color 0.15s,
- border-color 0.15s;
-}
-.kg-tomb-close:hover {
- color: var(--kg-text);
- border-color: var(--kg-accent);
-}
-.kg-tomb-close svg {
- width: 14px;
- height: 14px;
- fill: none;
- stroke: currentColor;
- stroke-width: 2;
- stroke-linecap: round;
-}
-.kg-tomb-close:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-
-.kg-tomb-items {
- display: flex;
- flex-direction: column;
- gap: 6px;
- max-height: 220px;
- overflow-y: auto;
- margin-bottom: 12px;
-}
-.kg-tomb-item {
- display: flex;
- align-items: center;
- gap: 9px;
- font-size: 13px;
- padding: 4px 2px;
-}
-.kg-tomb-chip {
- width: 14px;
- height: 14px;
- border-radius: 4px;
- background: var(--chip);
- border: 1px solid rgba(0, 0, 0, 0.35);
- flex: none;
-}
-.kg-tomb-iname {
- flex: 1;
- color: var(--kg-text);
-}
-.kg-tomb-iqty {
- color: var(--kg-dim);
- font-variant-numeric: tabular-nums;
- font-weight: 600;
-}
-.kg-tomb-empty {
- font-size: 13px;
- color: var(--kg-dim);
- text-align: center;
- padding: 14px 0;
-}
-
-.kg-tomb-take {
- width: 100%;
- padding: 10px 14px;
- font-size: 14px;
- font-weight: 700;
- cursor: pointer;
- background: var(--kg-tomb);
- color: #160c2a;
- border: 0;
- border-radius: 9px;
- transition:
- transform 0.08s ease,
- opacity 0.15s;
-}
-.kg-tomb-take:hover {
- opacity: 0.92;
-}
-.kg-tomb-take:active {
- transform: translateY(1px);
-}
-.kg-tomb-take:disabled {
- opacity: 0.4;
- cursor: not-allowed;
-}
-.kg-tomb-take:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-
-/* Respawn overlay — pointer-transparent vignette + centred status. */
-.kg-death {
- position: fixed;
- inset: 0;
- z-index: 18;
- pointer-events: none;
- display: flex;
- align-items: center;
- justify-content: center;
- background: radial-gradient(120% 120% at 50% 45%, rgba(60, 8, 8, 0.32), rgba(8, 6, 10, 0.74));
- animation: kg-death-in 0.35s ease both;
-}
-.kg-death[hidden] {
- display: none;
-}
-@keyframes kg-death-in {
- from {
- opacity: 0;
- }
- to {
- opacity: 1;
- }
-}
-.kg-death-card {
- text-align: center;
- max-width: 360px;
- padding: 0 24px;
-}
-.kg-death-eyebrow {
- font-size: 12px;
- letter-spacing: 0.28em;
- text-transform: uppercase;
- color: #ff8a8a;
- font-weight: 700;
-}
-.kg-death-msg {
- font-size: 16px;
- color: var(--kg-text);
- line-height: 1.5;
- margin: 10px 0 16px;
- text-shadow: 0 2px 8px rgba(0, 0, 0, 0.7);
-}
-.kg-death-count {
- display: inline-block;
- font-size: 13px;
- font-weight: 700;
- letter-spacing: 0.04em;
- color: var(--kg-text);
- background: rgba(13, 20, 32, 0.7);
- border: 1px solid var(--kg-line);
- border-radius: 999px;
- padding: 7px 16px;
- font-variant-numeric: tabular-nums;
-}
-
-.kg-toast--tomb {
- border-color: rgba(174, 123, 255, 0.5);
-}
-
-@media (prefers-reduced-motion: reduce) {
- .kg-tomb-panel,
- .kg-tomb-take {
- transition: none;
- }
- .kg-death {
- animation: none;
- }
-}
-
-/* ===========================================================================
- Task 12 — Controls: topbar buttons, hotbar, panels (inventory / map /
- placeholders) and the rebindable Controls settings dialog. Uses the same
- token set as the rest of this file (--kg-panel / --kg-line / --kg-text / …).
- =========================================================================== */
-
-/* Topbar icon buttons (skills, controls/gear). */
-.kg-iconbtn {
- pointer-events: auto;
- cursor: pointer;
- font: inherit;
- font-size: 12px;
- font-weight: 700;
- line-height: 1;
- color: var(--kg-text);
- background: rgba(255, 255, 255, 0.06);
- border: 1px solid var(--kg-line);
- border-radius: 8px;
- padding: 6px 10px;
- transition:
- background 0.15s,
- border-color 0.15s,
- transform 0.08s;
-}
-.kg-iconbtn:hover {
- background: rgba(255, 255, 255, 0.12);
- border-color: var(--kg-accent);
-}
-.kg-iconbtn:active {
- transform: translateY(1px);
-}
-.kg-iconbtn:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-#kg-controls-btn {
- font-size: 15px;
- padding: 5px 9px;
-}
-
-/* Keep the bottom hint clear of the hotbar. */
-#kg-hint {
- bottom: 96px;
-}
-
-/* --------------------------------------------------------------- hotbar --- */
-.kg-hotbar {
- position: fixed;
- left: 50%;
- bottom: 16px;
- transform: translateX(-50%);
- z-index: 7;
- display: flex;
- gap: 8px;
- padding: 8px;
- background: rgba(13, 20, 32, 0.55);
- border: 1px solid var(--kg-line);
- border-radius: 14px;
- backdrop-filter: blur(6px);
- box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
-}
-.kg-hotbar[hidden] {
- display: none;
-}
-.kg-hb-slot {
- position: relative;
- width: 56px;
- height: 56px;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- background: rgba(255, 255, 255, 0.05);
- border: 1px solid var(--kg-line);
- border-radius: 10px;
- color: var(--kg-text);
- transition:
- border-color 0.15s,
- background 0.15s,
- transform 0.08s;
-}
-.kg-hb-slot:hover {
- background: rgba(255, 255, 255, 0.1);
- border-color: var(--kg-accent);
-}
-.kg-hb-slot:active {
- transform: translateY(1px);
-}
-.kg-hb-slot:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-.kg-hb--active {
- border-color: #ffce5c;
- background: rgba(255, 206, 92, 0.16);
- box-shadow:
- 0 0 0 1px #ffce5c,
- 0 4px 16px rgba(255, 206, 92, 0.25);
-}
-.kg-hb--empty {
- color: var(--kg-dim);
- opacity: 0.8;
-}
-.kg-hb-key {
- position: absolute;
- top: 3px;
- left: 5px;
- font-size: 10px;
- font-weight: 700;
- color: var(--kg-dim);
- letter-spacing: 0.02em;
-}
-.kg-hb--active .kg-hb-key {
- color: #ffce5c;
-}
-.kg-hb-glyph {
- font-size: 26px;
- line-height: 1;
-}
-.kg-hb-qty {
- position: absolute;
- right: 4px;
- bottom: 3px;
- font-size: 11px;
- font-weight: 800;
- color: var(--kg-text);
- text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
-}
-
-/* --------------------------------------------------------- modal overlays - */
-.kg-ov {
- position: fixed;
- inset: 0;
- z-index: 24;
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 24px;
- background: rgba(6, 10, 18, 0.62);
- backdrop-filter: blur(3px);
- opacity: 0;
- transition: opacity 0.18s;
-}
-.kg-ov[hidden] {
- display: none;
-}
-.kg-ov--in {
- opacity: 1;
-}
-.kg-ov-card {
- width: 100%;
- max-width: 460px;
- max-height: min(80vh, 640px);
- overflow: auto;
- background: var(--kg-panel);
- border: 1px solid var(--kg-line);
- border-radius: 16px;
- box-shadow: 0 24px 70px rgba(0, 0, 0, 0.6);
- transform: translateY(8px) scale(0.98);
- transition: transform 0.18s;
-}
-.kg-ov--in .kg-ov-card {
- transform: translateY(0) scale(1);
-}
-.kg-ov-card:focus {
- outline: none;
-}
-.kg-ov-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 12px;
- padding: 16px 18px 12px;
- border-bottom: 1px solid var(--kg-line);
- position: sticky;
- top: 0;
- background: var(--kg-panel);
- z-index: 1;
-}
-.kg-ov-title {
- margin: 0;
- font-size: 17px;
- font-weight: 800;
- letter-spacing: -0.01em;
-}
-.kg-ov-x {
- cursor: pointer;
- font-size: 14px;
- line-height: 1;
- color: var(--kg-dim);
- background: transparent;
- border: 1px solid var(--kg-line);
- border-radius: 8px;
- padding: 6px 9px;
- transition:
- color 0.15s,
- border-color 0.15s;
-}
-.kg-ov-x:hover {
- color: var(--kg-text);
- border-color: var(--kg-accent);
-}
-.kg-ov-x:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-.kg-ov-body {
- padding: 16px 18px 18px;
-}
-.kg-ov-sub {
- margin: 0 0 14px;
- font-size: 12.5px;
- color: var(--kg-dim);
- line-height: 1.5;
-}
-.kg-ov-empty {
- margin: 14px 0 0;
- font-size: 13px;
- color: var(--kg-dim);
- line-height: 1.5;
- text-align: center;
-}
-.kg-ov-foot {
- display: flex;
- justify-content: flex-end;
- gap: 10px;
- margin-top: 18px;
-}
-.kg-ov-btn {
- cursor: pointer;
- font: inherit;
- font-size: 13px;
- font-weight: 700;
- padding: 9px 16px;
- border-radius: 9px;
- border: 1px solid var(--kg-line);
- background: rgba(255, 255, 255, 0.06);
- color: var(--kg-text);
- transition:
- background 0.15s,
- border-color 0.15s,
- transform 0.08s;
-}
-.kg-ov-btn:hover {
- background: rgba(255, 255, 255, 0.12);
- border-color: var(--kg-accent);
-}
-.kg-ov-btn:active {
- transform: translateY(1px);
-}
-.kg-ov-btn:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-.kg-ov-primary {
- background: var(--kg-text);
- color: #0d1420;
- border-color: var(--kg-text);
-}
-.kg-ov-primary:hover {
- opacity: 0.92;
- background: var(--kg-text);
-}
-.kg-ov-ghost {
- color: var(--kg-dim);
-}
-
-/* ----------------------------------------------------------- inventory --- */
-.kg-inv-meta {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 10px;
- margin-bottom: 12px;
- font-size: 13px;
- color: var(--kg-dim);
-}
-.kg-inv-meta b {
- color: var(--kg-text);
-}
-.kg-inv-hint {
- font-size: 11px;
-}
-.kg-inv-grid {
- display: grid;
- grid-template-columns: repeat(6, 1fr);
- gap: 6px;
-}
-.kg-inv-cell {
- position: relative;
- aspect-ratio: 1;
- display: flex;
- align-items: center;
- justify-content: center;
- background: rgba(255, 255, 255, 0.05);
- border: 1px solid var(--kg-line);
- border-radius: 9px;
-}
-.kg-inv-cell--hb {
- border-color: rgba(255, 206, 92, 0.4);
-}
-.kg-inv-cell--empty {
- background: rgba(255, 255, 255, 0.02);
-}
-.kg-inv-glyph {
- font-size: 22px;
- line-height: 1;
-}
-.kg-inv-qty {
- position: absolute;
- right: 3px;
- bottom: 2px;
- font-size: 11px;
- font-weight: 800;
- text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
-}
-
-/* ----------------------------------------------------------------- map --- */
-.kg-map-canvas {
- display: block;
- width: 100%;
- max-width: 320px;
- height: auto;
- margin: 0 auto;
- border: 1px solid var(--kg-line);
- border-radius: 10px;
- image-rendering: pixelated;
- background: #1a2417;
-}
-.kg-map-legend {
- display: flex;
- flex-wrap: wrap;
- gap: 12px;
- justify-content: center;
- margin-top: 12px;
- font-size: 11px;
- color: var(--kg-dim);
-}
-.kg-map-legend span {
- display: inline-flex;
- align-items: center;
- gap: 5px;
-}
-.kg-map-dot {
- width: 9px;
- height: 9px;
- border-radius: 50%;
-}
-.kg-map-dot--me {
- background: #fff;
- border: 1.5px solid #0d1420;
-}
-.kg-map-dot--peer {
- background: #8fd3ff;
-}
-.kg-map-sw {
- width: 10px;
- height: 10px;
- border-radius: 2px;
-}
-.kg-map-sw--bank {
- background: rgba(255, 206, 92, 0.8);
-}
-.kg-map-sw--block {
- background: rgba(8, 11, 16, 0.7);
- border: 1px solid var(--kg-line);
-}
-
-/* --------------------------------------------------------- placeholders --- */
-.kg-ph {
- text-align: center;
- padding: 14px 6px 6px;
-}
-.kg-ph-glyph {
- font-size: 44px;
- line-height: 1;
- margin-bottom: 12px;
-}
-.kg-ph-blurb {
- margin: 0 0 8px;
- font-size: 14px;
- color: var(--kg-text);
- line-height: 1.5;
-}
-.kg-ph-note {
- margin: 0;
- font-size: 12px;
- color: var(--kg-dim);
-}
-
-/* ----------------------------------------------------- controls (rebind) - */
-.kg-bind-group {
- margin-bottom: 18px;
-}
-.kg-bind-h {
- margin: 0 0 8px;
- font-size: 11px;
- text-transform: uppercase;
- letter-spacing: 0.12em;
- color: var(--kg-dim);
-}
-.kg-bind-row {
- display: grid;
- grid-template-columns: 1fr auto;
- align-items: center;
- gap: 8px 12px;
- padding: 7px 0;
- border-bottom: 1px solid rgba(255, 255, 255, 0.05);
-}
-.kg-bind-row--conflict {
- /* warning lives on its own row span below */
-}
-.kg-bind-label {
- font-size: 13.5px;
- color: var(--kg-text);
-}
-.kg-bind-chip {
- min-width: 58px;
- cursor: pointer;
- font: inherit;
- font-size: 12px;
- font-weight: 700;
- padding: 6px 12px;
- border-radius: 7px;
- text-align: center;
- background: rgba(255, 255, 255, 0.06);
- border: 1px solid var(--kg-line);
- color: var(--kg-text);
- transition:
- background 0.15s,
- border-color 0.15s;
-}
-.kg-bind-chip:hover {
- background: rgba(255, 255, 255, 0.12);
- border-color: var(--kg-accent);
-}
-.kg-bind-chip:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-.kg-bind-chip--fixed {
- cursor: default;
- color: var(--kg-dim);
- opacity: 0.8;
-}
-.kg-bind-chip--fixed:hover {
- background: rgba(255, 255, 255, 0.06);
- border-color: var(--kg-line);
-}
-.kg-bind-chip--capturing {
- background: rgba(255, 206, 92, 0.18);
- border-color: #ffce5c;
- color: #ffce5c;
-}
-.kg-bind-warn {
- grid-column: 1 / -1;
- font-size: 11px;
- color: #ffce5c;
- margin-top: -2px;
-}
-.kg-bind-msg {
- min-height: 1.2em;
- margin: 6px 0 0;
- font-size: 12px;
- color: var(--kg-dim);
-}
-
-@media (max-width: 480px) {
- .kg-hb-slot {
- width: 46px;
- height: 46px;
- }
- .kg-hb-glyph {
- font-size: 22px;
- }
- .kg-ov-card {
- max-width: 100%;
- }
- .kg-inv-grid {
- gap: 5px;
- }
-}
-
-/* ============================================================================
- Quests, hotbar, NPC dialog & bank (Task 10). Self-contained `kq-*` namespace
- layered over the base `kg-*` HUD; matches the dark, monochrome-leaning palette
- so quest reward colour and avatars carry the eye.
- ========================================================================== */
-
-/* ----- nameplate badges + NPC plates -------------------------------------- */
-.kg-label-row { display: inline-flex; align-items: center; gap: 4px; }
-.kg-badges { display: inline-flex; gap: 2px; }
-.kg-badge-glyph { font-size: 11px; line-height: 1; filter: drop-shadow(0 1px 2px rgba(0,0,0,0.7)); }
-
-.kg-npc-label {
- position: absolute; top: 0; left: 0; will-change: transform; pointer-events: none;
- display: flex; flex-direction: column; align-items: center; gap: 2px;
- font-size: 12px; font-weight: 700; text-shadow: 0 1px 3px rgba(0,0,0,0.85);
-}
-.kg-npc-tag {
- padding: 1px 8px; border-radius: 6px; white-space: nowrap;
- background: rgba(59, 91, 140, 0.55); border: 1px solid rgba(170, 190, 230, 0.4); color: #eaf1ff;
-}
-.kg-npc-marker {
- font-size: 18px; font-weight: 900; line-height: 1;
- animation: kq-bob 1.4s ease-in-out infinite;
-}
-.kq-marker-new { color: #ffce5c; text-shadow: 0 0 8px rgba(255, 206, 92, 0.7); }
-.kq-marker-turnin { color: #6ee787; text-shadow: 0 0 8px rgba(110, 231, 135, 0.7); }
-@keyframes kq-bob { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-4px); } }
-
-/* ----- toolbar (Quests / Bank buttons) ------------------------------------ */
-.kq-toolbar { position: fixed; top: 52px; right: 12px; z-index: 11; display: flex; gap: 8px; }
-.kq-toolbar[hidden] { display: none; }
-.kq-tool-btn {
- position: relative; display: inline-flex; align-items: center; gap: 7px; cursor: pointer;
- padding: 8px 13px; border-radius: 10px; font: inherit; font-size: 13px; font-weight: 700;
- color: var(--kg-text); background: var(--kg-panel); border: 1px solid var(--kg-line);
- box-shadow: 0 6px 20px rgba(0,0,0,0.35); transition: transform .08s, border-color .15s, background .15s;
-}
-.kq-tool-btn:hover { border-color: var(--kg-accent); background: rgba(40, 52, 74, 0.92); }
-.kq-tool-btn:active { transform: translateY(1px); }
-.kq-tool-btn:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
-.kq-tool-ic { font-size: 15px; }
-.kq-dot {
- position: absolute; top: -4px; right: -4px; width: 11px; height: 11px; border-radius: 50%;
- background: #6ee787; border: 2px solid var(--kg-bg); box-shadow: 0 0 8px rgba(110,231,135,0.8);
- animation: kq-pulse 1.6s ease-in-out infinite;
-}
-.kq-dot[hidden] { display: none; }
-@keyframes kq-pulse { 0%,100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.25); opacity: 0.7; } }
-
-/* ----- hotbar ------------------------------------------------------------- */
-.kq-hotbar {
- position: fixed; left: 50%; bottom: 44px; transform: translateX(-50%); z-index: 9;
- display: flex; gap: 8px; padding: 8px; border-radius: 14px;
- background: rgba(13, 20, 32, 0.6); border: 1px solid var(--kg-line); backdrop-filter: blur(4px);
-}
-.kq-hotbar[hidden] { display: none; }
-.kq-slot {
- position: relative; width: 52px; height: 52px; cursor: pointer; padding: 0;
- display: flex; align-items: center; justify-content: center; font: inherit;
- background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 10px;
- transition: transform .08s, border-color .15s, background .15s;
-}
-.kq-slot:hover { border-color: var(--kg-accent); }
-.kq-slot:active { transform: translateY(1px); }
-.kq-slot:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
-.kq-slot--active { border-color: #ffce5c; background: rgba(255, 206, 92, 0.14); box-shadow: 0 0 0 1px rgba(255,206,92,0.5) inset; }
-.kq-slot--empty { opacity: 0.55; }
-/* Tutorial step hint: pulse-glow the relevant hotbar slot */
-.kq-slot--hint { border-color: #6ee787; background: rgba(110,231,135,0.12); animation: kq-slot-hint 1.4s ease-in-out infinite; }
-@keyframes kq-slot-hint {
- 0%,100% { box-shadow: 0 0 0 0 rgba(110,231,135,0); }
- 50% { box-shadow: 0 0 0 4px rgba(110,231,135,0.5), 0 0 14px rgba(110,231,135,0.35); }
-}
-.kq-slot .kq-key { position: absolute; top: 3px; left: 5px; font-size: 9px; font-weight: 700; color: var(--kg-dim); }
-.kq-slot .kq-ic { font-size: 24px; line-height: 1; }
-.kq-slot .kq-qty { position: absolute; bottom: 3px; right: 5px; font-size: 10px; font-weight: 700; color: var(--kg-text); text-shadow: 0 1px 2px #000; }
-@media (max-width: 560px) {
- .kq-hotbar { bottom: 12px; gap: 6px; padding: 6px; }
- .kq-slot { width: 44px; height: 44px; }
- .kq-slot .kq-ic { font-size: 20px; }
-}
-
-/* ----- quest panel (left drawer) ------------------------------------------ */
-.kq-panel {
- position: fixed; top: 0; left: 0; bottom: 0; z-index: 13; width: min(360px, 92vw);
- display: flex; flex-direction: column;
- background: var(--kg-panel); border-right: 1px solid var(--kg-line);
- box-shadow: 14px 0 50px rgba(0,0,0,0.5); backdrop-filter: blur(8px);
- transform: translateX(-105%); transition: transform .24s cubic-bezier(.2,.7,.2,1);
-}
-.kq-panel.kq-in { transform: translateX(0); }
-.kq-panel[hidden] { display: none; }
-.kq-panel-head { display: flex; align-items: center; justify-content: space-between; padding: 16px 18px 12px; border-bottom: 1px solid var(--kg-line); }
-.kq-panel-head h2 { margin: 0; font-size: 17px; font-weight: 800; letter-spacing: .01em; }
-.kq-x { width: 30px; height: 30px; cursor: pointer; border-radius: 8px; font-size: 14px; color: var(--kg-dim); background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); transition: color .15s, border-color .15s; }
-.kq-x:hover { color: var(--kg-text); border-color: var(--kg-accent); }
-.kq-panel-body { padding: 14px 16px 24px; overflow-y: auto; }
-.kq-section { margin-bottom: 22px; }
-.kq-h3 { margin: 0 0 10px; font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: .12em; color: var(--kg-dim); }
-.kq-daily-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
-.kq-reset, .kq-reset-inline { font-size: 11px; font-weight: 700; color: #ffce5c; font-variant-numeric: tabular-nums; }
-
-.kq-card-q { padding: 12px 14px; margin-bottom: 10px; border-radius: 12px; background: rgba(255,255,255,0.035); border: 1px solid var(--kg-line); transition: border-color .2s, opacity .2s; }
-.kq-card-tut { border-color: rgba(255, 206, 92, 0.4); background: rgba(255, 206, 92, 0.07); }
-.kq-card-tut .kq-progress i { background: linear-gradient(90deg, #ffce5c, #ffe999); }
-/* Tutorial pip progress + slot chip */
-.kq-tut-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 8px; }
-.kq-tut-head .kq-h3 { margin: 0; }
-.kq-tut-overall { display: flex; align-items: center; gap: 6px; }
-.kq-tut-pips { display: flex; gap: 4px; align-items: center; }
-.kq-tut-pip { width: 8px; height: 8px; border-radius: 50%; background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.18); transition: background .2s; flex-shrink: 0; }
-.kq-tut-pip--done { background: #6ee787; border-color: #6ee787; }
-.kq-tut-pip--active { background: #ffce5c; border-color: #ffce5c; box-shadow: 0 0 6px rgba(255,206,92,0.7); animation: kq-pip-pulse 1.2s ease-in-out infinite; }
-@keyframes kq-pip-pulse { 0%,100% { transform: scale(1); } 50% { transform: scale(1.3); } }
-.kq-tut-frac { font-size: 10px; font-weight: 700; color: var(--kg-dim); font-variant-numeric: tabular-nums; }
-.kq-tut-slot-chip { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; font-weight: 700; color: #6ee787; background: rgba(110,231,135,0.12); border: 1px solid rgba(110,231,135,0.35); border-radius: 999px; padding: 3px 10px; margin-bottom: 8px; }
-.kq-card-q.kq-ready { border-color: rgba(110, 231, 135, 0.5); background: rgba(110, 231, 135, 0.07); }
-.kq-card-q.kq-claimed { opacity: 0.55; }
-.kq-q-title { font-size: 14px; font-weight: 700; color: var(--kg-text); }
-.kq-q-desc { font-size: 12px; color: var(--kg-dim); margin: 3px 0 9px; line-height: 1.4; }
-.kq-progress { position: relative; height: 16px; border-radius: 8px; overflow: hidden; background: rgba(0,0,0,0.4); border: 1px solid rgba(0,0,0,0.3); }
-.kq-progress i { display: block; height: 100%; background: linear-gradient(90deg, #6ee787, #d7ff7a); transition: width .35s ease; }
-.kq-progress-txt { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: 700; color: var(--kg-text); text-shadow: 0 1px 2px rgba(0,0,0,0.8); font-variant-numeric: tabular-nums; }
-.kq-q-foot { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-top: 10px; }
-.kq-rewards { display: flex; flex-wrap: wrap; gap: 5px; }
-.kq-rw { font-size: 11px; font-weight: 700; color: var(--kg-text); background: rgba(255,255,255,0.06); border: 1px solid var(--kg-line); border-radius: 6px; padding: 2px 7px; white-space: nowrap; }
-.kq-rw-badge { color: #ffce5c; border-color: rgba(255,206,92,0.4); }
-.kq-claimed-tag { font-size: 12px; font-weight: 700; color: #6ee787; white-space: nowrap; }
-
-.kq-btn {
- cursor: pointer; font: inherit; font-size: 12px; font-weight: 800; padding: 7px 14px;
- border: 0; border-radius: 8px; background: var(--kg-text); color: #0d1420;
- transition: transform .08s, opacity .15s;
-}
-.kq-btn:hover { opacity: 0.9; }
-.kq-btn:active { transform: translateY(1px); }
-.kq-btn:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
-.kq-turnin { background: #6ee787; }
-.kq-btn-disabled, .kq-btn:disabled { background: rgba(255,255,255,0.08); color: var(--kg-dim); cursor: not-allowed; }
-.kq-btn-ghost { background: transparent; color: var(--kg-text); border: 1px solid var(--kg-line); margin-top: 12px; width: 100%; padding: 9px; }
-.kq-btn-ghost:hover { border-color: var(--kg-accent); opacity: 1; }
-.kq-btn-primary { /* alias — .kq-btn already uses the primary fill */ }
-
-.kq-empty { font-size: 12px; color: var(--kg-dim); line-height: 1.5; padding: 8px 2px; }
-.kq-empty-good { color: var(--kg-text); background: rgba(110, 231, 135, 0.08); border: 1px solid rgba(110,231,135,0.3); border-radius: 10px; padding: 12px 14px; text-align: center; }
-.kq-tut-done { font-size: 13px; color: var(--kg-text); background: rgba(255,206,92,0.08); border: 1px solid rgba(255,206,92,0.3); border-radius: 10px; padding: 11px 14px; }
-.kq-badges { display: flex; flex-wrap: wrap; gap: 7px; }
-.kq-badge { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 700; color: var(--kg-text); background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 999px; padding: 4px 11px; }
-.kq-badge-ic { font-size: 14px; }
-
-/* ----- modals (NPC dialog + bank) ----------------------------------------- */
-.kq-modal {
- position: fixed; inset: 0; z-index: 16; display: flex; align-items: center; justify-content: center; padding: 24px;
- background: radial-gradient(120% 120% at 50% 35%, rgba(20,28,44,0.45), rgba(8,12,20,0.82)); backdrop-filter: blur(2px);
-}
-.kq-modal[hidden] { display: none; }
-.kq-modal-card {
- position: relative; width: 100%; max-width: 440px; max-height: 86vh; overflow-y: auto;
- background: var(--kg-panel); border: 1px solid var(--kg-line); border-radius: 18px;
- padding: 22px 22px 20px; box-shadow: 0 24px 70px rgba(0,0,0,0.6);
- animation: kq-rise .22s cubic-bezier(.2,.7,.2,1);
-}
-@keyframes kq-rise { from { opacity: 0; transform: translateY(10px) scale(.98); } to { opacity: 1; transform: none; } }
-.kq-modal-card .kq-x { position: absolute; top: 12px; right: 12px; }
-
-/* NPC dialog */
-.kq-npc-head { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
-.kq-npc-portrait { font-size: 34px; width: 54px; height: 54px; display: grid; place-items: center; border-radius: 12px; background: rgba(59,91,140,0.25); border: 1px solid rgba(170,190,230,0.35); }
-.kq-npc-name { font-size: 17px; font-weight: 800; }
-.kq-npc-role { font-size: 11px; text-transform: uppercase; letter-spacing: .1em; color: var(--kg-dim); }
-.kq-npc-line { font-size: 14px; line-height: 1.55; color: var(--kg-text); margin: 0 0 14px; }
-.kq-npc-objective { background: rgba(255,206,92,0.08); border: 1px solid rgba(255,206,92,0.3); border-radius: 12px; padding: 12px 14px; font-size: 14px; font-weight: 700; color: var(--kg-text); display: flex; flex-direction: column; gap: 4px; }
-.kq-npc-obj-label { font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .12em; color: #ffce5c; }
-.kq-npc-obj-desc { font-size: 12px; font-weight: 500; color: var(--kg-dim); line-height: 1.4; }
-.kq-npc-sub { font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .12em; color: var(--kg-dim); margin: 16px 0 8px; }
-.kq-npc-turnin { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 9px 12px; border-radius: 10px; background: rgba(110,231,135,0.08); border: 1px solid rgba(110,231,135,0.3); margin-bottom: 7px; }
-.kq-npc-turnin-name { font-size: 13px; font-weight: 700; }
-
-/* Bank */
-.kq-bank-head { display: flex; align-items: center; gap: 10px; margin-bottom: 16px; }
-.kq-bank-head h2 { margin: 0; font-size: 17px; font-weight: 800; }
-.kq-bank-hint { margin-left: auto; font-size: 11px; color: var(--kg-dim); }
-.kq-bank-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
-.kq-bank-col h3 { margin: 0 0 8px; font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: .12em; color: var(--kg-dim); }
-.kq-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; min-height: 56px; align-content: start; }
-.kq-cell {
- position: relative; aspect-ratio: 1; cursor: pointer; padding: 0;
- display: flex; align-items: center; justify-content: center;
- background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 9px;
- transition: transform .08s, border-color .15s, background .15s;
-}
-.kq-cell:hover { border-color: var(--kg-accent); background: rgba(40,52,74,0.9); }
-.kq-cell:active { transform: translateY(1px); }
-.kq-cell:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
-.kq-cell .kq-ic { font-size: 22px; }
-.kq-cell .kq-qty { position: absolute; bottom: 2px; right: 4px; font-size: 10px; font-weight: 700; text-shadow: 0 1px 2px #000; }
-.kq-bank-col .kq-empty { grid-column: 1 / -1; }
-@media (max-width: 480px) {
- .kq-bank-cols { grid-template-columns: 1fr; gap: 12px; }
- .kq-grid { grid-template-columns: repeat(6, 1fr); }
-}
-
-/* ----- build menu + banner (Task 07) -------------------------------------- */
-.kq-build-menu {
- position: fixed; top: 96px; right: 12px; z-index: 14; width: min(320px, 92vw);
- background: var(--kg-panel); border: 1px solid var(--kg-line); border-radius: 16px;
- box-shadow: 0 18px 50px rgba(0,0,0,0.55); backdrop-filter: blur(8px);
- padding: 14px; opacity: 0; transform: translateY(-8px) scale(.98);
- transition: opacity .18s, transform .18s cubic-bezier(.2,.7,.2,1);
-}
-.kq-build-menu[hidden] { display: none; }
-.kq-build-menu.kq-in { opacity: 1; transform: none; }
-.kq-build-head { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
-.kq-build-head h2 { margin: 0; font-size: 15px; font-weight: 800; }
-.kq-build-head .kq-x { margin-left: auto; position: static; }
-.kq-build-list { display: flex; flex-direction: column; gap: 10px; }
-.kq-build-card {
- padding: 12px; border-radius: 12px; background: rgba(255,255,255,0.035);
- border: 1px solid var(--kg-line); transition: border-color .15s;
-}
-.kq-build-card--short { opacity: 0.92; }
-.kq-build-card-head { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 9px; }
-.kq-build-ic { font-size: 26px; line-height: 1; }
-.kq-build-titles { min-width: 0; }
-.kq-build-name { font-size: 14px; font-weight: 800; display: flex; align-items: center; gap: 7px; }
-.kq-build-cap { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--kg-dim); background: rgba(255,255,255,0.06); border-radius: 999px; padding: 2px 7px; }
-.kq-build-desc { font-size: 12px; color: var(--kg-dim); line-height: 1.45; margin-top: 2px; }
-.kq-build-costs { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 11px; }
-.kq-build-cost {
- display: inline-flex; align-items: center; gap: 4px; font-size: 12px; font-weight: 700;
- color: var(--kg-text); background: rgba(110,231,135,0.1); border: 1px solid rgba(110,231,135,0.3);
- border-radius: 999px; padding: 3px 9px;
-}
-.kq-build-cost-ic { font-size: 13px; }
-.kq-build-cost--short { color: #ff9a9a; background: rgba(255,90,90,0.1); border-color: rgba(255,90,90,0.35); }
-.kq-build-go { width: 100%; padding: 9px; background: #ffce5c; color: #2a1c00; }
-
-.kq-build-banner {
- position: fixed; left: 50%; bottom: 116px; transform: translateX(-50%); z-index: 12;
- display: inline-flex; align-items: center; gap: 12px; padding: 9px 9px 9px 15px;
- border-radius: 999px; font-size: 13px; font-weight: 700; color: var(--kg-text);
- background: rgba(13, 20, 32, 0.92); border: 1px solid var(--kg-accent);
- box-shadow: 0 10px 30px rgba(0,0,0,0.5); animation: kq-rise .2s cubic-bezier(.2,.7,.2,1);
-}
-.kq-build-banner[hidden] { display: none; }
-.kq-build-banner-ic { font-size: 18px; }
-.kq-build-banner .kq-btn-ghost { margin-top: 0; width: auto; padding: 6px 14px; }
-@media (max-width: 560px) {
- .kq-build-menu { top: auto; bottom: 150px; right: 8px; left: 8px; width: auto; }
- .kq-build-banner { bottom: 84px; }
-}
-
-/* ----- gold readout (toolbar) --------------------------------------------- */
-.kq-gold {
- display: inline-flex; align-items: center; gap: 5px; padding: 8px 13px; border-radius: 10px;
- font-size: 13px; font-weight: 800; color: #ffce5c; font-variant-numeric: tabular-nums;
- background: var(--kg-panel); border: 1px solid var(--kg-line); box-shadow: 0 6px 20px rgba(0,0,0,0.35);
-}
-.kq-gold-ic { font-size: 14px; }
-
-/* ----- cosmetics shop (Task 21) ------------------------------------------- */
-.kq-shop-card { max-width: 620px; }
-.kq-shop-head { display: flex; align-items: center; gap: 10px; margin-bottom: 14px; padding-right: 34px; }
-.kq-shop-head h2 { margin: 0; font-size: 17px; font-weight: 800; }
-.kq-shop-purse {
- margin-left: auto; display: inline-flex; align-items: center; gap: 5px; font-size: 13px; font-weight: 800;
- color: #ffce5c; font-variant-numeric: tabular-nums; background: rgba(255,206,92,0.1);
- border: 1px solid rgba(255,206,92,0.32); border-radius: 999px; padding: 4px 12px;
-}
-.kq-shop-tabs { display: flex; gap: 6px; margin-bottom: 10px; }
-.kq-shop-tab {
- flex: 1; cursor: pointer; font: inherit; font-size: 13px; font-weight: 700; padding: 8px 10px;
- color: var(--kg-dim); background: rgba(255,255,255,0.04); border: 1px solid var(--kg-line);
- border-radius: 10px; transition: color .15s, border-color .15s, background .15s;
-}
-.kq-shop-tab:hover { color: var(--kg-text); border-color: var(--kg-accent); }
-.kq-shop-tab:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
-.kq-shop-tab--on { color: #0d1420; background: var(--kg-text); border-color: var(--kg-text); }
-.kq-shop-note { margin: 0 0 14px; font-size: 11px; color: var(--kg-dim); line-height: 1.45; }
-.kq-shop-sub { margin: 0 0 12px; font-size: 12px; color: var(--kg-dim); line-height: 1.45; }
-.kq-shop-section { margin-bottom: 20px; }
-.kq-shop-section-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
-.kq-shop-reset { font-size: 11px; font-weight: 700; color: #ffce5c; font-variant-numeric: tabular-nums; }
-
-.kq-cos-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; }
-.kq-cos-card {
- --cos-accent: #9aa7b4;
- display: flex; flex-direction: column; align-items: center; text-align: center; gap: 8px;
- padding: 14px 12px 12px; border-radius: 14px; background: rgba(255,255,255,0.035);
- border: 1px solid var(--kg-line); border-top: 3px solid var(--cos-accent);
- transition: border-color .15s, transform .08s, background .15s;
-}
-.kq-cos-card.kq-cos--equipped { background: rgba(110,231,135,0.08); border-color: rgba(110,231,135,0.5); }
-.kq-cos-card--pick { cursor: pointer; font: inherit; color: inherit; text-align: center; -webkit-appearance: none; appearance: none; }
-.kq-cos-card--pick:hover { border-color: var(--cos-accent); transform: translateY(-1px); }
-.kq-cos-card--pick:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
-.kq-cos-card.kq-cos--preview { border-color: var(--cos-accent); box-shadow: 0 0 0 1px var(--cos-accent) inset, 0 0 16px -4px var(--cos-accent); }
-.kq-cos-thumb { width: 100%; height: 100%; object-fit: contain; border-radius: 50%; }
-.kq-cos-card.kq-cos--locked { opacity: 0.62; }
-.kq-cos-card.kq-cos--locked:hover { opacity: 1; }
-.kq-cos-src { font-size: 10px; font-weight: 700; color: var(--kg-dim); }
-.kq-cos-buy--confirm { background: #ffce5c; color: #2a1c00; animation: kq-pulse 1s ease-in-out infinite; }
-.kq-cos-card.kq-cos--short { opacity: 0.78; }
-.kq-cos-swatch {
- width: 58px; height: 58px; border-radius: 50%; display: grid; place-items: center;
- font-size: 30px; line-height: 1; background: rgba(255,255,255,0.06); border: 1px solid var(--kg-line);
-}
-.kq-cos-swatch--default { background: rgba(255,255,255,0.06); }
-.kq-cos-meta { display: flex; flex-direction: column; gap: 2px; }
-.kq-cos-name { font-size: 13px; font-weight: 800; color: var(--kg-text); }
-.kq-cos-rarity { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--cos-accent); }
-.kq-cos-foot { display: flex; align-items: center; justify-content: center; gap: 8px; margin-top: auto; padding-top: 4px; }
-.kq-cos-price { font-size: 12px; font-weight: 800; color: #ffce5c; font-variant-numeric: tabular-nums; }
-.kq-cos-price--short { color: #ff9a9a; }
-.kq-cos-owned { font-size: 12px; font-weight: 800; color: var(--kg-dim); }
-.kq-cos-equipped { font-size: 12px; font-weight: 800; color: #6ee787; }
-.kq-cos-buy { background: #ffce5c; color: #2a1c00; padding: 6px 14px; }
-.kq-cos-equip { background: var(--kg-text); color: #0d1420; padding: 6px 14px; }
-.kq-shop-empty { display: flex; flex-direction: column; align-items: center; gap: 10px; text-align: center; margin-top: 16px; }
-.kq-shop-empty .kq-btn-ghost { margin-top: 0; width: auto; }
-@media (max-width: 480px) {
- .kq-cos-grid { grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); }
- .kq-gold .kq-gold-ic + b { display: inline; }
-}
-
-/* Marketplace (Task 20) — player-to-player trading: Buy / Sell / My Listings. */
-.kq-market-card { max-width: 640px; }
-.kq-market-head { display: flex; align-items: center; gap: 10px; margin-bottom: 14px; padding-right: 34px; }
-.kq-market-head h2 { margin: 0; font-size: 17px; font-weight: 800; }
-.kq-market-tabs { display: flex; gap: 6px; margin-bottom: 14px; }
-.kq-market-tab {
- flex: 1; cursor: pointer; font: inherit; font-size: 13px; font-weight: 700; padding: 8px 10px;
- color: var(--kg-dim); background: rgba(255,255,255,0.04); border: 1px solid var(--kg-line);
- border-radius: 10px; transition: color .15s, border-color .15s, background .15s;
-}
-.kq-market-tab:hover { color: var(--kg-text); border-color: var(--kg-accent); }
-.kq-market-tab:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
-.kq-market-tab--on { color: #0d1420; background: var(--kg-text); border-color: var(--kg-text); }
-.kq-market-body { min-height: 240px; }
-.kq-market-pane { display: flex; flex-direction: column; gap: 12px; }
-
-/* Buy controls */
-.kq-market-controls { display: flex; gap: 8px; }
-.kq-market-search {
- flex: 1; font: inherit; font-size: 13px; padding: 8px 11px; color: var(--kg-text);
- background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 9px;
-}
-.kq-market-search::placeholder { color: var(--kg-dim); }
-.kq-market-search:focus-visible, .kq-market-input:focus-visible, .kq-market-sort:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 1px; }
-.kq-market-sort {
- font: inherit; font-size: 13px; padding: 8px 10px; color: var(--kg-text);
- background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 9px; cursor: pointer;
-}
-
-/* Listing list + rows */
-.kq-market-list { display: flex; flex-direction: column; gap: 8px; }
-.kq-market-card-row {
- display: flex; align-items: center; gap: 12px; padding: 10px 12px;
- background: rgba(255,255,255,0.035); border: 1px solid var(--kg-line); border-radius: 12px;
- transition: border-color .15s, background .15s;
-}
-.kq-market-card-row:hover { border-color: rgba(255,255,255,0.22); }
-.kq-market-mine { opacity: 0.82; }
-.kq-market-ic {
- flex: 0 0 auto; width: 40px; height: 40px; display: grid; place-items: center; font-size: 22px;
- background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 10px;
-}
-.kq-market-info { flex: 1 1 auto; min-width: 0; }
-.kq-market-title { font-size: 14px; font-weight: 800; color: var(--kg-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.kq-market-sub { font-size: 11px; color: var(--kg-dim); margin-top: 2px; }
-.kq-market-seller { font-variant-numeric: tabular-nums; }
-.kq-market-right { flex: 0 0 auto; display: flex; flex-direction: column; align-items: flex-end; gap: 6px; }
-.kq-market-price { font-size: 14px; font-weight: 800; color: #ffce5c; font-variant-numeric: tabular-nums; display: flex; align-items: baseline; gap: 5px; }
-.kq-market-coin { font-size: 12px; }
-.kq-market-usd { color: #6ee7b0; }
-.kq-market-token { font-size: 10px; font-weight: 700; color: var(--kg-dim); text-transform: uppercase; letter-spacing: .05em; }
-.kq-market-buy { background: #6ee7b0; color: #062017; padding: 6px 14px; white-space: nowrap; }
-.kq-market-buy.kq-btn-disabled { background: rgba(255,255,255,0.08); color: var(--kg-dim); }
-.kq-market-badge { font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .08em; color: var(--kg-dim); }
-.kq-market-note { font-size: 11px; color: var(--kg-dim); max-width: 120px; text-align: right; line-height: 1.35; }
-.kq-market-busy { display: inline-flex; align-items: center; gap: 7px; font-size: 12px; font-weight: 700; color: #ffce5c; }
-.kq-spin { width: 12px; height: 12px; border: 2px solid rgba(255,206,92,0.35); border-top-color: #ffce5c; border-radius: 50%; animation: kq-spin 0.7s linear infinite; }
-@keyframes kq-spin { to { transform: rotate(360deg); } }
-
-/* Status labels (My Listings) */
-.kq-market-statlbl { font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: .06em; color: var(--kg-dim); }
-.kq-market-statlbl--active { color: #6ee7b0; }
-.kq-market-statlbl--sold { color: #ffce5c; text-transform: none; letter-spacing: 0; }
-.kq-market-statlbl--cancelled { color: #ff9a9a; }
-.kq-market-cancel { margin-top: 0; width: auto; padding: 5px 12px; }
-.kq-market-status-sold, .kq-market-status-cancelled { opacity: 0.7; }
-
-/* Sell form */
-.kq-market-modes { display: flex; gap: 6px; }
-.kq-market-mode {
- flex: 1; cursor: pointer; font: inherit; font-size: 12px; font-weight: 700; padding: 8px;
- color: var(--kg-dim); background: rgba(255,255,255,0.04); border: 1px solid var(--kg-line); border-radius: 9px;
- transition: color .15s, border-color .15s, background .15s;
-}
-.kq-market-mode:hover { color: var(--kg-text); border-color: var(--kg-accent); }
-.kq-market-mode--on { color: #0d1420; background: var(--kg-text); border-color: var(--kg-text); }
-.kq-market-sellform { display: flex; flex-direction: column; gap: 12px; }
-.kq-market-label { font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: .1em; color: var(--kg-dim); }
-.kq-market-pick { display: grid; grid-template-columns: repeat(6, 1fr); gap: 6px; }
-.kq-market-pickcell.kq-cell--on { border-color: #6ee7b0; background: rgba(110,231,176,0.12); }
-.kq-market-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
-.kq-market-field { display: flex; flex-direction: column; gap: 5px; }
-.kq-market-field-lbl { font-size: 11px; font-weight: 700; color: var(--kg-dim); }
-.kq-market-input {
- font: inherit; font-size: 14px; padding: 9px 11px; color: var(--kg-text);
- background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 9px; width: 100%;
-}
-.kq-market-input.kq-input-bad { border-color: #ff9a9a; }
-.kq-market-listbtn { width: 100%; padding: 11px; font-size: 13px; background: #6ee7b0; color: #062017; }
-.kq-market-hint { font-size: 12px; color: var(--kg-dim); line-height: 1.5; text-align: center; padding: 18px 8px; }
-.kq-market-fineprint { font-size: 11px; color: var(--kg-dim); line-height: 1.45; margin: 0; text-align: center; }
-
-/* Empty / error / skeleton states */
-.kq-market-empty { display: flex; flex-direction: column; align-items: center; gap: 8px; text-align: center; padding: 36px 16px; color: var(--kg-dim); }
-.kq-market-empty p { margin: 0; font-size: 14px; color: var(--kg-text); }
-.kq-market-empty span { font-size: 12px; color: var(--kg-dim); max-width: 320px; line-height: 1.5; }
-.kq-market-empty-ic { font-size: 38px; opacity: 0.85; }
-.kq-market-empty .kq-btn-ghost { margin-top: 4px; width: auto; }
-.kq-market-err p { color: #ffb4b4; }
-.kq-market-skel { height: 60px; background: linear-gradient(90deg, rgba(255,255,255,0.04), rgba(255,255,255,0.08), rgba(255,255,255,0.04)); background-size: 200% 100%; animation: kq-shimmer 1.2s ease-in-out infinite; border-color: transparent; }
-@keyframes kq-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
-
-@media (max-width: 480px) {
- .kq-market-pick { grid-template-columns: repeat(5, 1fr); }
- .kq-market-fields { grid-template-columns: 1fr; }
- .kq-market-card-row { gap: 9px; padding: 9px 10px; }
-}
-
-@media (prefers-reduced-motion: reduce) {
- .kq-panel, .kq-progress i, .kq-tool-btn, .kq-slot, .kq-cell, .kq-build-menu, .kq-shop-tab, .kq-cos-card, .kq-market-tab, .kq-market-mode { transition: none; }
- .kq-modal-card, .kq-build-banner { animation: none; }
- .kq-npc-marker, .kq-dot, .kq-spin, .kq-market-skel { animation: none; }
-}
-
-/* Loot + mount toasts (Task 09). Mount drops get a celebratory violet accent;
- plain loot a warm gold, matching the bag/portal colour language. */
-.kg-toast--loot {
- border-color: rgba(255, 206, 92, 0.45);
-}
-.kg-toast--mount,
-.kg-toast--cmd {
- border-color: rgba(174, 123, 255, 0.6);
- box-shadow: 0 8px 28px rgba(120, 70, 220, 0.3);
-}
-
-/* Mount status chip — visible only while riding. Sits clear of the centred hotbar
- and the mobile joystick, naming the steed with a one-tap Dismount. */
-.kg-mount {
- position: fixed;
- right: 16px;
- bottom: 104px;
- z-index: 9;
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 7px 10px 7px 12px;
- border-radius: 999px;
- background: var(--kg-panel);
- border: 1px solid rgba(174, 123, 255, 0.55);
- color: var(--kg-text);
- font-size: 13px;
- font-weight: 600;
- box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45);
- animation: kg-mount-in 0.25s ease;
-}
-.kg-mount[hidden] {
- display: none;
-}
-@keyframes kg-mount-in {
- from { opacity: 0; transform: translateY(8px); }
- to { opacity: 1; transform: translateY(0); }
-}
-.kg-mount-ico {
- font-size: 16px;
- line-height: 1;
-}
-.kg-mount-txt {
- color: var(--kg-dim);
- white-space: nowrap;
-}
-.kg-mount-txt b {
- color: var(--kg-text);
- font-weight: 700;
- text-transform: capitalize;
-}
-.kg-mount-btn {
- margin-left: 2px;
- padding: 5px 12px;
- border-radius: 999px;
- border: 1px solid var(--kg-line);
- background: rgba(174, 123, 255, 0.18);
- color: var(--kg-text);
- font: inherit;
- font-size: 12px;
- font-weight: 700;
- cursor: pointer;
- transition: border-color 0.15s, background 0.15s, transform 0.1s;
-}
-.kg-mount-btn:hover {
- border-color: rgba(174, 123, 255, 0.8);
- background: rgba(174, 123, 255, 0.3);
-}
-.kg-mount-btn:active {
- transform: scale(0.96);
-}
-.kg-mount-btn:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
-
-/* ----- Wheel of Fortune (Task 19) ----------------------------------------- */
-.kg-wheel-label .kg-npc-tag {
- background: rgba(245, 197, 66, 0.22); border-color: rgba(245, 197, 66, 0.55); color: #ffe6ad;
-}
-.kg-casino-label .kg-npc-tag {
- background: rgba(150, 50, 110, 0.5); border-color: rgba(255, 180, 220, 0.45); color: #ffd9ee;
- letter-spacing: 0.04em; text-transform: uppercase; font-size: 11px;
-}
-
-.kg-spin-overlay {
- position: fixed; inset: 0; z-index: 40; display: flex; align-items: center; justify-content: center;
- background: rgba(6, 9, 16, 0.72); backdrop-filter: blur(4px); padding: 16px;
- animation: kg-spin-fade .18s ease-out;
-}
-@keyframes kg-spin-fade { from { opacity: 0; } to { opacity: 1; } }
-
-.kg-spin-card {
- width: min(440px, 96vw); max-height: 94vh; overflow: auto;
- background: linear-gradient(180deg, rgba(22, 28, 42, 0.98), rgba(13, 18, 30, 0.98));
- border: 1px solid var(--kg-line); border-radius: 18px; color: var(--kg-text);
- box-shadow: 0 24px 70px rgba(0,0,0,0.6), inset 0 1px 0 rgba(255,255,255,0.05);
- padding: 18px 18px 20px; display: flex; flex-direction: column; gap: 14px;
-}
-.kg-spin-card.kg-spin-flash { animation: kg-spin-flash .4s ease-out; }
-@keyframes kg-spin-flash { 0% { box-shadow: 0 0 0 2px var(--kg-accent); } 100% { box-shadow: 0 24px 70px rgba(0,0,0,0.6); } }
-
-.kg-spin-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
-.kg-spin-title { font-size: 18px; font-weight: 800; display: flex; flex-direction: column; gap: 2px; }
-.kg-spin-sub2 { font-size: 11px; font-weight: 600; color: var(--kg-dim); letter-spacing: 0.03em; text-transform: uppercase; }
-.kg-spin-close {
- flex: 0 0 auto; width: 30px; height: 30px; border-radius: 8px; cursor: pointer;
- background: rgba(255,255,255,0.06); border: 1px solid var(--kg-line); color: var(--kg-dim);
- font-size: 15px; line-height: 1; transition: background .15s, color .15s, border-color .15s;
-}
-.kg-spin-close:hover { background: rgba(255,255,255,0.14); color: var(--kg-text); border-color: var(--kg-accent); }
-.kg-spin-close:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
-
-.kg-spin-wheelwrap { position: relative; align-self: center; width: 300px; height: 300px; }
-.kg-spin-canvas { width: 300px; height: 300px; display: block; filter: drop-shadow(0 10px 26px rgba(0,0,0,0.5)); }
-.kg-spin-pointer {
- position: absolute; top: -4px; left: 50%; transform: translateX(-50%);
- width: 0; height: 0; border-left: 13px solid transparent; border-right: 13px solid transparent;
- border-top: 22px solid #ff5a3a; filter: drop-shadow(0 2px 3px rgba(0,0,0,0.6)); z-index: 2;
-}
-.kg-spin-hub {
- position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
- width: 44px; height: 44px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
- background: radial-gradient(circle at 35% 30%, #fff6da, #e0b54a); color: #6b4e00; font-size: 18px;
- border: 3px solid rgba(0,0,0,0.35); box-shadow: 0 2px 8px rgba(0,0,0,0.45); z-index: 1;
-}
-
-.kg-spin-result {
- min-height: 22px; text-align: center; font-size: 16px; font-weight: 800;
- transition: color .2s;
-}
-.kg-spin-result[data-kind="gold"] { color: #f5c542; text-shadow: 0 0 14px rgba(245,197,66,0.5); }
-.kg-spin-result[data-kind="wood"] { color: #d9a36a; }
-.kg-spin-result[data-kind="stone"] { color: #c2cbda; }
-.kg-spin-result[data-kind="coal"] { color: #aeb6c4; }
-
-.kg-spin-gate {
- border: 1px solid rgba(255, 184, 92, 0.4); background: rgba(255, 184, 92, 0.08);
- border-radius: 12px; padding: 10px 12px;
-}
-.kg-spin-gate[hidden] { display: none; }
-.kg-spin-gate-h { font-size: 11px; font-weight: 800; letter-spacing: 0.06em; text-transform: uppercase; color: #ffce5c; margin-bottom: 4px; }
-.kg-spin-gate-b { font-size: 13px; line-height: 1.45; color: var(--kg-text); }
-
-.kg-spin-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
-.kg-spin-action { display: flex; flex-direction: column; gap: 5px; }
-.kg-spin-btn {
- width: 100%; padding: 12px 10px; border-radius: 12px; cursor: pointer; font: inherit;
- font-size: 14px; font-weight: 800; color: var(--kg-text); border: 1px solid var(--kg-line);
- transition: transform .08s, filter .15s, background .15s, border-color .15s; text-align: center;
-}
-.kg-spin-btn:active:not(:disabled) { transform: translateY(1px); }
-.kg-spin-btn:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
-.kg-spin-btn:disabled { opacity: 0.45; cursor: not-allowed; }
-.kg-spin-free {
- background: linear-gradient(180deg, rgba(110, 231, 135, 0.22), rgba(110, 231, 135, 0.1));
- border-color: rgba(110, 231, 135, 0.5);
-}
-.kg-spin-free:hover:not(:disabled) { filter: brightness(1.12); border-color: rgba(110, 231, 135, 0.85); }
-.kg-spin-paid {
- background: linear-gradient(180deg, rgba(245, 197, 66, 0.22), rgba(245, 197, 66, 0.1));
- border-color: rgba(245, 197, 66, 0.5);
-}
-.kg-spin-paid:hover:not(:disabled) { filter: brightness(1.12); border-color: rgba(245, 197, 66, 0.85); }
-.kg-spin-sub { font-size: 11px; line-height: 1.35; color: var(--kg-dim); text-align: center; min-height: 15px; }
-.kg-spin-sub[data-ready="1"] { color: #6ee787; }
-
-.kg-spin-status { min-height: 18px; text-align: center; font-size: 13px; color: var(--kg-dim); }
-.kg-spin-status[data-kind="ok"] { color: #6ee787; }
-.kg-spin-status[data-kind="err"] { color: #ff8d7a; }
-.kg-spin-status a { color: inherit; text-decoration: underline; }
-
-.kg-spin-legend { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; justify-content: center; }
-.kg-spin-legend-h { font-size: 11px; font-weight: 800; letter-spacing: 0.06em; text-transform: uppercase; color: var(--kg-dim); }
-.kg-spin-chip { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 600; color: var(--kg-accent); }
-.kg-spin-dot { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }
-
-@media (max-width: 380px) {
- .kg-spin-wheelwrap, .kg-spin-canvas { width: 260px; height: 260px; }
- .kg-spin-actions { grid-template-columns: 1fr; }
-}
-
-/* ───────────────────────────── Friends panel (Task 15) ─────────────────────
- Rendered into the shared kg-ov surface body. Reuses the realm palette so it
- feels native: same panel/line/text tokens, the green accent for "online" and
- primary actions, amber for pending, red for destructive. */
-.kg-fr {
- display: flex;
- flex-direction: column;
- min-height: 360px;
-}
-.kg-fr-hudbadge {
- position: absolute;
- top: -4px;
- right: -4px;
- min-width: 16px;
- height: 16px;
- padding: 0 4px;
- border-radius: 999px;
- background: #ff7a3a;
- color: #1a0f08;
- font-size: 10px;
- font-weight: 800;
- line-height: 16px;
- text-align: center;
- box-shadow: 0 0 0 2px var(--kg-bg);
-}
-.kg-iconbtn--alert {
- border-color: rgba(255, 122, 58, 0.6);
-}
-
-/* tabs */
-.kg-fr-tabs {
- display: flex;
- gap: 6px;
- margin-bottom: 14px;
-}
-.kg-fr-tab {
- flex: 1;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- gap: 6px;
- padding: 8px 6px;
- font: inherit;
- font-size: 13px;
- font-weight: 700;
- color: var(--kg-dim);
- background: rgba(255, 255, 255, 0.04);
- border: 1px solid var(--kg-line);
- border-radius: 10px;
- cursor: pointer;
- transition: color 0.15s, background 0.15s, border-color 0.15s;
-}
-.kg-fr-tab:hover {
- color: var(--kg-text);
- border-color: rgba(255, 255, 255, 0.22);
-}
-.kg-fr-tab.is-active {
- color: #0d1420;
- background: var(--kg-accent);
- border-color: var(--kg-accent);
-}
-.kg-fr-pill {
- min-width: 16px;
- padding: 0 5px;
- border-radius: 999px;
- background: rgba(255, 122, 58, 0.95);
- color: #1a0f08;
- font-size: 10px;
- font-weight: 800;
- line-height: 16px;
-}
-.kg-fr-tab.is-active .kg-fr-pill {
- background: #1a2030;
- color: var(--kg-accent);
-}
-
-/* lists + rows */
-.kg-fr-list {
- list-style: none;
- margin: 0;
- padding: 0;
- display: flex;
- flex-direction: column;
- gap: 6px;
-}
-.kg-fr-row {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 7px 8px;
- border: 1px solid var(--kg-line);
- border-radius: 12px;
- background: rgba(255, 255, 255, 0.03);
-}
-.kg-fr-rowmain {
- flex: 1;
- min-width: 0;
- display: flex;
- align-items: center;
- gap: 10px;
- padding: 0;
- font: inherit;
- color: inherit;
- text-align: left;
- background: transparent;
- border: 0;
- cursor: pointer;
- border-radius: 8px;
-}
-.kg-fr-rowmain--static {
- cursor: default;
-}
-.kg-fr-rowmain:not(.kg-fr-rowmain--static):hover .kg-fr-name {
- color: #fff;
-}
-.kg-fr-meta {
- display: flex;
- flex-direction: column;
- gap: 1px;
- min-width: 0;
-}
-.kg-fr-name {
- font-size: 13.5px;
- font-weight: 700;
- color: var(--kg-text);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- max-width: 200px;
- transition: color 0.15s;
-}
-.kg-fr-status {
- font-size: 11.5px;
- color: var(--kg-dim);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- max-width: 220px;
-}
-.kg-fr-status--on {
- color: #6ee787;
-}
-.kg-fr-status--off {
- color: var(--kg-dim);
-}
-
-/* avatar + presence dot */
-.kg-fr-av {
- position: relative;
- flex: none;
- width: 34px;
- height: 34px;
- border-radius: 50%;
-}
-.kg-fr-av-img {
- width: 34px;
- height: 34px;
- border-radius: 50%;
- object-fit: cover;
- background: rgba(255, 255, 255, 0.06);
-}
-.kg-fr-av--mono {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- background: linear-gradient(150deg, #2a3550, #1a2233);
- border: 1px solid var(--kg-line);
-}
-.kg-fr-av-ini {
- font-size: 12.5px;
- font-weight: 800;
- color: var(--kg-accent);
-}
-.kg-fr-dot {
- position: absolute;
- bottom: -1px;
- right: -1px;
- width: 11px;
- height: 11px;
- border-radius: 50%;
- box-shadow: 0 0 0 2px var(--kg-panel);
-}
-.kg-fr-dot--on {
- background: #6ee787;
-}
-.kg-fr-dot--off {
- background: #56627a;
-}
-
-/* unread + row actions */
-.kg-fr-unread {
- flex: none;
- min-width: 18px;
- height: 18px;
- padding: 0 5px;
- border-radius: 999px;
- background: #ff7a3a;
- color: #1a0f08;
- font-size: 11px;
- font-weight: 800;
- line-height: 18px;
- text-align: center;
-}
-.kg-fr-rowactions {
- display: flex;
- align-items: center;
- gap: 4px;
- flex: none;
-}
-.kg-fr-icon {
- width: 28px;
- height: 28px;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- font-size: 13px;
- color: var(--kg-dim);
- background: transparent;
- border: 1px solid transparent;
- border-radius: 8px;
- cursor: pointer;
- transition: color 0.15s, background 0.15s, border-color 0.15s;
-}
-.kg-fr-icon:hover {
- color: var(--kg-text);
- background: rgba(255, 255, 255, 0.06);
- border-color: var(--kg-line);
-}
-.kg-fr-icon--danger:hover {
- color: #ff8a8a;
- border-color: rgba(255, 138, 138, 0.4);
-}
-.kg-fr-icon:disabled {
- opacity: 0.4;
- cursor: default;
-}
-
-/* buttons */
-.kg-fr-btn {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- gap: 6px;
- padding: 8px 14px;
- font: inherit;
- font-size: 13px;
- font-weight: 700;
- border-radius: 10px;
- border: 1px solid var(--kg-line);
- background: rgba(255, 255, 255, 0.05);
- color: var(--kg-text);
- cursor: pointer;
- transition: transform 0.12s, background 0.15s, border-color 0.15s, opacity 0.15s;
- text-decoration: none;
-}
-.kg-fr-btn:hover {
- border-color: rgba(255, 255, 255, 0.26);
-}
-.kg-fr-btn:active {
- transform: scale(0.97);
-}
-.kg-fr-btn:disabled {
- opacity: 0.45;
- cursor: default;
-}
-.kg-fr-btn--sm {
- padding: 6px 11px;
- font-size: 12px;
-}
-.kg-fr-btn--primary {
- background: #6ee787;
- border-color: #6ee787;
- color: #0d1420;
-}
-.kg-fr-btn--primary:hover {
- background: #82ed97;
- border-color: #82ed97;
-}
-.kg-fr-btn--ghost {
- background: transparent;
-}
-.kg-fr-tagpending {
- font-size: 12px;
- font-weight: 700;
- color: #ffce5c;
- padding: 5px 8px;
-}
-.kg-fr-tagpending--ok {
- color: #6ee787;
-}
-
-/* requests subheads */
-.kg-fr-subhead {
- margin: 16px 0 8px;
- font-size: 11px;
- font-weight: 800;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--kg-dim);
-}
-.kg-fr-reqs > .kg-fr-subhead:first-child {
- margin-top: 0;
-}
-
-/* search */
-.kg-fr-searchwrap {
- position: relative;
- margin-bottom: 12px;
-}
-.kg-fr-search-ico {
- position: absolute;
- left: 11px;
- top: 50%;
- transform: translateY(-50%);
- font-size: 13px;
- opacity: 0.6;
- pointer-events: none;
-}
-.kg-fr-search {
- width: 100%;
- padding: 10px 12px 10px 32px;
- font: inherit;
- font-size: 13.5px;
- color: var(--kg-text);
- background: rgba(13, 20, 32, 0.6);
- border: 1px solid var(--kg-line);
- border-radius: 10px;
- outline: none;
- transition: border-color 0.15s;
-}
-.kg-fr-search:focus {
- border-color: var(--kg-accent);
-}
-.kg-fr-hint {
- margin: 14px 4px;
- font-size: 12.5px;
- color: var(--kg-dim);
- text-align: center;
- line-height: 1.5;
-}
-
-/* empty + skeleton + banner */
-.kg-fr-empty {
- flex: 1;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- text-align: center;
- gap: 6px;
- padding: 28px 16px;
-}
-.kg-fr-empty-glyph {
- font-size: 34px;
- opacity: 0.9;
- margin-bottom: 4px;
-}
-.kg-fr-empty-title {
- margin: 0;
- font-size: 15px;
- font-weight: 800;
- color: var(--kg-text);
-}
-.kg-fr-empty-sub {
- margin: 0 0 8px;
- font-size: 12.5px;
- color: var(--kg-dim);
- line-height: 1.5;
- max-width: 280px;
-}
-.kg-fr-skel {
- display: flex;
- flex-direction: column;
- gap: 8px;
- padding-top: 4px;
-}
-.kg-fr-skel-row {
- height: 50px;
- border-radius: 12px;
- background: linear-gradient(90deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.09), rgba(255, 255, 255, 0.04));
- background-size: 200% 100%;
- animation: kg-fr-shimmer 1.3s ease-in-out infinite;
-}
-@keyframes kg-fr-shimmer {
- 0% { background-position: 200% 0; }
- 100% { background-position: -200% 0; }
-}
-.kg-fr-banner {
- margin: 0 0 12px;
- padding: 9px 12px;
- font-size: 12.5px;
- color: #ff8a8a;
- background: rgba(255, 122, 58, 0.1);
- border: 1px solid rgba(255, 138, 138, 0.35);
- border-radius: 10px;
-}
-
-/* DM thread */
-.kg-fr-thread {
- display: flex;
- flex-direction: column;
- min-height: 380px;
- height: min(62vh, 480px);
-}
-.kg-fr-thread-head {
- display: flex;
- align-items: center;
- gap: 10px;
- padding-bottom: 10px;
- margin-bottom: 6px;
- border-bottom: 1px solid var(--kg-line);
-}
-.kg-fr-back {
- flex: none;
- width: 30px;
- height: 30px;
- font-size: 20px;
- line-height: 1;
- color: var(--kg-dim);
- background: transparent;
- border: 1px solid var(--kg-line);
- border-radius: 8px;
- cursor: pointer;
- transition: color 0.15s, border-color 0.15s;
-}
-.kg-fr-back:hover {
- color: var(--kg-text);
- border-color: var(--kg-accent);
-}
-.kg-fr-thread-msgs {
- flex: 1;
- overflow-y: auto;
- display: flex;
- flex-direction: column;
- gap: 5px;
- padding: 6px 2px;
-}
-.kg-fr-thread-empty {
- margin: auto;
- text-align: center;
- padding: 24px 12px;
-}
-.kg-fr-daysep {
- align-self: center;
- margin: 8px 0 4px;
- font-size: 10.5px;
- font-weight: 700;
- letter-spacing: 0.06em;
- text-transform: uppercase;
- color: var(--kg-dim);
-}
-.kg-fr-msg {
- max-width: 78%;
- padding: 7px 11px;
- border-radius: 14px;
- font-size: 13.5px;
- line-height: 1.4;
- word-wrap: break-word;
- overflow-wrap: anywhere;
- display: flex;
- align-items: flex-end;
- gap: 8px;
-}
-.kg-fr-msg--theirs {
- align-self: flex-start;
- background: rgba(255, 255, 255, 0.07);
- color: var(--kg-text);
- border-bottom-left-radius: 5px;
-}
-.kg-fr-msg--mine {
- align-self: flex-end;
- background: #2f6b8a;
- color: #f1f7fb;
- border-bottom-right-radius: 5px;
-}
-.kg-fr-msg-body {
- min-width: 0;
-}
-.kg-fr-msg-time {
- flex: none;
- font-size: 9.5px;
- opacity: 0.6;
- margin-bottom: 1px;
-}
-.kg-fr-dm-bar {
- display: flex;
- align-items: center;
- gap: 8px;
- padding-top: 10px;
- margin-top: 6px;
- border-top: 1px solid var(--kg-line);
-}
-.kg-fr-dm-input {
- flex: 1;
- min-width: 0;
- padding: 10px 14px;
- font: inherit;
- font-size: 13.5px;
- color: var(--kg-text);
- background: rgba(13, 20, 32, 0.6);
- border: 1px solid var(--kg-line);
- border-radius: 999px;
- outline: none;
- transition: border-color 0.15s;
-}
-.kg-fr-dm-input:focus {
- border-color: var(--kg-accent);
-}
-.kg-fr-dm-send {
- flex: none;
- width: 38px;
- height: 38px;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- font-size: 15px;
- color: #0d1420;
- background: #6ee787;
- border: 0;
- border-radius: 50%;
- cursor: pointer;
- transition: transform 0.12s, background 0.15s;
-}
-.kg-fr-dm-send:hover {
- background: #82ed97;
-}
-.kg-fr-dm-send:active {
- transform: scale(0.92);
-}
-.kg-fr-btn:focus-visible,
-.kg-fr-tab:focus-visible,
-.kg-fr-icon:focus-visible,
-.kg-fr-rowmain:focus-visible,
-.kg-fr-back:focus-visible,
-.kg-fr-dm-send:focus-visible,
-.kg-fr-search:focus-visible,
-.kg-fr-dm-input:focus-visible {
- outline: 2px solid var(--kg-accent);
- outline-offset: 2px;
-}
diff --git a/src/game/iso-game.js b/src/game/iso-game.js
deleted file mode 100644
index 1b6b69238..000000000
--- a/src/game/iso-game.js
+++ /dev/null
@@ -1,3817 +0,0 @@
-// Isometric RPG client — the /game scene. The front door to the authoritative
-// MMO that already lives on the server (multiplayer/src/rooms/GameRoom.js):
-// gathering, combat, skills, inventory, banking on the Mainland realm. This
-// scene renders GameRoom's synced state through the GameNet bridge and turns
-// player intent into the server's tile-stepped protocol.
-//
-// Design mirrors coincommunities.js (renderer → scene → RAF loop → phases) but
-// the world is tile-based: a grid the server validates against, with a fixed
-// three-quarter "isometric" camera that follows the local player. Avatar/anim
-// loading is shared via avatar-rig.js so the RPG and the social walkaround
-// never drift apart.
-//
-// Extension seams for the rest of Epic A (kept intentionally small so each task
-// is a localized change):
-// • _buildNodeView(node) — T7 replaces the placeholder gather-node meshes.
-// • _buildMobView(mob) — T8 replaces the placeholder combat-mob meshes.
-// • onGatherTarget / onAttackTarget / bank/inventory hooks — T7/T8/T9.
-// The baseline here renders real, navigable placeholders so the world is alive
-// today; those tasks swap geometry without touching the networking or loop.
-
-import {
- Scene, Color, Fog, WebGLRenderer, PerspectiveCamera, Group, Vector3,
- HemisphereLight, DirectionalLight, AmbientLight, PointLight, PCFSoftShadowMap, SRGBColorSpace,
- Mesh, MeshStandardMaterial, MeshBasicMaterial, PlaneGeometry, BoxGeometry,
- CylinderGeometry, ConeGeometry, DodecahedronGeometry, IcosahedronGeometry,
- CircleGeometry, CanvasTexture, RepeatWrapping, DoubleSide,
- Raycaster, Vector2, SphereGeometry, RingGeometry,
- BufferGeometry, Line, LineBasicMaterial, Float32BufferAttribute,
-} from 'three';
-import nipplejs from 'nipplejs';
-
-import { GameNet, fetchServers } from './game-net.js';
-import { getPresenceTicket } from '../friends.js';
-import {
- loadManifest, resolveAvatarUrl, buildAvatar, newAnim, CLIP_IDLE, CLIP_WALK,
-} from './avatar-rig.js';
-import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';
-import { GameHud } from './game-hud.js';
-import { applyCosmetic } from './cosmetics-visual.js';
-
-const TILE = 1.0; // world units per tile
-const STEP_INTERVAL_MS = 165; // walk cadence — one authoritative step per tile
-const INTERACT_ACTION_MS = 380; // cadence for repeated gather/attack while adjacent to a target
-// Quest badge glyphs, mirrored from the server (quests.js BADGES), so a player's
-// earned badges render as small icons on their nameplate (the in-world profile).
-const BADGE_ICONS = { newcomer: '🎓', warrior: '⚔️', forager: '🧺', devoted: '🌟' };
-const MOVE_LERP = 0.22; // position interpolation toward the server tile
-const YAW_LERP = 0.22;
-const AVATAR_DEFAULT = '/avatars/default.glb';
-
-// Skills surface — display order, label, accent hue, and a line-art glyph for
-// each trainable skill. The order mirrors the server's SKILLS array so the panel
-// reads consistently; the server stays the source of truth for levels/XP/cap.
-const SKILL_ORDER = ['combat', 'woodcutting', 'mining', 'fishing', 'cooking'];
-const SKILL_META = {
- combat: { label: 'Combat', hue: '#ff8a8a', icon: 'M5 5l14 14M19 5L5 19' },
- woodcutting: { label: 'Woodcutting', hue: '#6ee787', icon: 'M12 3l5 8H7zM9.5 11h5l2.5 6H7zM12 17v4' },
- mining: { label: 'Mining', hue: '#c8cedb', icon: 'M3 8c5-4 13-4 18 0M12 7v13' },
- fishing: { label: 'Fishing', hue: '#5cb6e6', icon: 'M3 12c4-5 12-5 16 0-4 5-12 5-16 0zM19 12l3-2v4M7 11v.01' },
- cooking: { label: 'Cooking', hue: '#ff9a4d', icon: 'M12 3c2.5 3.5 4 5.5 4 8a4 4 0 0 1-8 0c0-1.6.8-2.7 1.7-3.6.2 1.7 1 2.6 2.3 2.6-1-2.5 0-4.6 0-7z' },
-};
-const fmtXp = (n) => Math.round(n).toLocaleString('en-US');
-
-// Items the player can eat to heal — mirrors the server item registry's `edible`
-// flag (items.js). Kept as a small client-side set, like the walkability mirror,
-// so the action bar can offer "Eat" without round-tripping the full registry.
-const EDIBLE = new Set(['cookedFish', 'healthPotion']);
-const FOOD_LABEL = { cookedFish: 'cooked fish', healthPotion: 'potion' };
-
-// Mirrors items.js#scaledHeal so the Eat button can preview the exact heal value
-// without a round-trip. Must stay in sync with the server formula.
-function clientScaledHeal(item, baseHeal, cookingLevel) {
- if (item === 'cookedFish') return (baseHeal || 0) + Math.floor((Math.max(1, cookingLevel | 0) - 1) * 0.3);
- return baseHeal || 0;
-}
-
-// Player-built structures (Task 07): presentation only — icon, label, and a short
-// pitch for the build menu. The realm's allowed kinds and the authoritative costs
-// arrive from the server (the realm message's `buildCatalog`), so this never
-// hard-codes prices and never drifts from what the server will actually charge.
-const STRUCTURE_META = {
- firepit: { icon: '🔥', label: 'Firepit', desc: 'Heals allies beside it for ~30s, then burns out.' },
- shack: { icon: '🛖', label: 'Shack', desc: 'A permanent landmark. One per builder.' },
-};
-// Material icons for the build-menu cost chips (mirrors items.js labels/icons; the
-// HUD has its own copy for backpack rendering — this keeps the scene self-contained).
-const MATERIAL_ICON = { wood: '🪵', stone: '🪨', coal: '⚫' };
-
-// Lightweight item presentation for the death-bag recovery panel: a readable
-// label + a chip colour per known item. Unknown items fall back to a titlecase
-// of their id and a neutral chip, so a future item never renders blank.
-const ITEM_LABEL = {
- wood: 'Wood', stone: 'Stone', coal: 'Coal', fish: 'Raw fish',
- cookedFish: 'Cooked fish', gold: 'Gold',
- axe: 'Axe', pickaxe: 'Pickaxe', rod: 'Fishing rod', hammer: 'Hammer', sword: 'Sword',
-};
-const ITEM_COLOR = {
- wood: '#a9743f', stone: '#9aa0ac', coal: '#3a3f48', fish: '#5cb6e6',
- cookedFish: '#e6a85c', gold: '#ffce5c',
-};
-const itemLabel = (id) => ITEM_LABEL[id] || (id ? id.replace(/^\w/, (m) => m.toUpperCase()) : 'Item');
-const itemColor = (id) => ITEM_COLOR[id] || '#7d8696';
-
-// ---------------------------------------------------------------------------
-// GamePlayerView — a player's avatar rig in the tile world. The server owns the
-// authoritative tile; this view interpolates toward it so movement reads smooth
-// at the 15Hz patch rate. Used for both the local player and remote peers
-// (T6 polishes remote-specific touches like HP bars on top of this baseline).
-// ---------------------------------------------------------------------------
-class GamePlayerView {
- constructor(scene, tileToWorld, player, isLocal, cosmeticFor) {
- this.scene = scene;
- this.tileToWorld = tileToWorld;
- this.isLocal = isLocal;
- this.id = player.id;
- // Resolver (id → visual spec) from the server cosmetics catalogue. Lets this
- // view layer any peer's equipped cosmetic (tint / prop / aura) over the base
- // avatar. Strictly visual — never consulted for anything gameplay-affecting.
- this._cosmeticFor = cosmeticFor || (() => null);
-
- this.rig = new Group();
- // Tag the rig so a PvP-realm raycast can resolve a click on this body back to its
- // player id (the local player is filtered out at the call site, you can't hit yourself).
- this.rig.userData.playerId = player.id;
- this.anim = newAnim();
- this.height = 1.7;
-
- // Authoritative tile + facing, and the interpolation targets derived from
- // them. tx/ty always reflect the latest server state (used for stepping).
- this.tx = player.tx;
- this.ty = player.ty;
- this.yaw = player.yaw || 0;
- this.curYaw = this.yaw;
- this.motion = player.motion || 'idle';
- this.hp = player.hp; this.maxHp = player.maxHp;
- this.dead = !!player.dead;
-
- const w = tileToWorld(player.tx, player.ty);
- this.rig.position.set(w.x, 0, w.z);
- this.target = new Vector3(w.x, 0, w.z);
- scene.add(this.rig);
-
- // Floating nameplate (DOM, projected each frame). HP bar fills in for the
- // local player and any damaged peer.
- this.label = document.createElement('div');
- this.label.className = 'kg-label' + (isLocal ? ' kg-label--me' : '');
- this.label.innerHTML =
- `<span class="kg-label-row"><span class="kg-badges"></span><span class="kg-label-name"></span></span><span class="kg-hp"><i></i></span>`;
- this.nameEl = this.label.querySelector('.kg-label-name');
- this.hpFill = this.label.querySelector('.kg-hp i');
- this.badgesEl = this.label.querySelector('.kg-badges');
- this.nameEl.textContent = player.name || 'guest';
- this.badges = '';
- this._renderBadges(player.badges || '');
- document.getElementById('kg-labels')?.appendChild(this.label);
- this._renderHp();
-
- // Speech bubble: floats just above the nameplate when this player chats.
- // Positioned each frame alongside the nameplate so it tracks movement.
- this.bubble = document.createElement('div');
- this.bubble.className = 'kg-chat-bubble';
- this.bubble.hidden = true;
- document.getElementById('kg-labels')?.appendChild(this.bubble);
- this._bubbleTimer = null;
-
- // Mount visuals (Task 09): a steed mesh + saddle lift, attached in applyMount.
- this.mounted = false;
- this._steed = null;
- this._saddleY = 0;
- this._rideRate = 1.5;
- this._avatarUrl = null;
- // Equipped cosmetic (Task 21): the id and the live visual handle layered over
- // the avatar. Re-applied after every avatar (re)load, since loading clears the
- // rig. Both local player and peers render their equipped look.
- this._cosmeticId = player.cosmeticId || '';
- this._cosmeticHandle = null;
- // Wardrobe try-before-equip (local player only): the server-authoritative
- // equipped id, plus a non-null pin that overrides it while previewing a look
- // before committing, so movement patches don't snap the preview back.
- this._serverCosmeticId = this._cosmeticId;
- this._cosmeticPin = null;
- this.setAvatar(player.cosmetic || '');
- }
-
- // Preview a look locally with no server round-trip. `id` is a cosmetic id (or ''
- // for the default look); null clears the preview and reverts to the equipped id.
- previewCosmetic(id) {
- this._cosmeticPin = id;
- this.setCosmetic(id == null ? this._serverCosmeticId : id);
- }
-
- setAvatar(url) {
- const next = url || AVATAR_DEFAULT;
- if (next === this._avatarUrl) return;
- this._avatarUrl = next;
- // Loading rebuilds the rig from scratch, so drop the cosmetic layer first
- // (restoring any tinted materials) and re-mount it once the new model lands.
- this._disposeCosmetic();
- this.rig.clear();
- this.anim = newAnim();
- resolveAvatarUrl(next).then((u) => buildAvatar(this.rig, u, this.anim).then(({ height }) => {
- this.height = height;
- this.anim.crossfadeTo(this.motion === 'walk' ? CLIP_WALK : CLIP_IDLE, 0);
- this._mountCosmetic();
- }));
- }
-
- // Equip (or clear) the cosmetic this view renders. No-op if unchanged; mounts
- // the new look immediately when the model is already loaded (re-mounts after a
- // reload via setAvatar's callback otherwise).
- setCosmetic(id) {
- const next = id || '';
- if (next === this._cosmeticId) return;
- this._cosmeticId = next;
- this._mountCosmetic();
- }
-
- _mountCosmetic() {
- this._disposeCosmetic();
- const visual = this._cosmeticId ? this._cosmeticFor(this._cosmeticId) : null;
- if (visual) this._cosmeticHandle = applyCosmetic(this.rig, this.height, visual);
- }
-
- _disposeCosmetic() {
- if (this._cosmeticHandle) { this._cosmeticHandle.dispose(); this._cosmeticHandle = null; }
- }
-
- apply(player) {
- const moved = player.tx !== this.tx || player.ty !== this.ty;
- this.tx = player.tx; this.ty = player.ty;
- this.yaw = player.yaw ?? this.yaw;
- const w = this.tileToWorld(player.tx, player.ty);
- this.target.set(w.x, 0, w.z);
-
- if (player.name && player.name !== this.nameEl.textContent) this.nameEl.textContent = player.name;
- if ((player.badges || '') !== this.badges) this._renderBadges(player.badges || '');
- if (player.hp !== this.hp || player.maxHp !== this.maxHp) {
- this.hp = player.hp; this.maxHp = player.maxHp; this._renderHp();
- }
- // Keep the authoritative respawn deadline so the local death overlay can
- // count down to it from the synced schema (no client-side fake timer).
- this.respawnAt = player.respawnAt || 0;
- if (!!player.dead !== this.dead) {
- this.dead = !!player.dead;
- this.rig.visible = !this.dead;
- this.label.classList.toggle('kg-dead', this.dead);
- }
- if (player.motion !== this.motion) {
- this.motion = player.motion;
- this.anim.crossfadeTo(this.motion === 'walk' ? CLIP_WALK : CLIP_IDLE, 0.16);
- }
- // Peers' avatars are server-authoritative (the local player owns its own
- // look). setAvatar self-guards, so this is a no-op until a peer changes.
- if (!this.isLocal) this.setAvatar(player.cosmetic || '');
- // The equipped cosmetic is server-authoritative for everyone (including us,
- // after an equip round-trips), so peers AND the local player track it here.
- // setCosmetic self-guards, so it's a no-op until the equipped id changes.
- this._serverCosmeticId = player.cosmeticId || '';
- this.setCosmetic(this._cosmeticPin != null ? this._cosmeticPin : this._serverCosmeticId);
- // Mark when the server says we moved so the loop can settle us to idle on
- // arrival without waiting for a separate motion patch.
- if (moved) this._movedAt = performance.now();
- }
-
- // Render the comma-separated badge ids as small glyphs ahead of the name.
- _renderBadges(badges) {
- this.badges = badges;
- const ids = badges ? badges.split(',').filter(Boolean) : [];
- this.badgesEl.innerHTML = ids
- .map((id) => BADGE_ICONS[id] ? `<span class="kg-badge-glyph" title="${id}">${BADGE_ICONS[id]}</span>` : '')
- .join('');
- }
-
- _renderHp() {
- const pct = this.maxHp > 0 ? Math.max(0, Math.min(1, this.hp / this.maxHp)) : 0;
- this.hpFill.style.width = (pct * 100).toFixed(0) + '%';
- // Hide the bar at full health to keep nameplates clean; show when hurt.
- this.label.classList.toggle('kg-hurt', pct < 1);
- }
-
- tick(dt) {
- this.rig.position.x += (this.target.x - this.rig.position.x) * MOVE_LERP;
- this.rig.position.z += (this.target.z - this.rig.position.z) * MOVE_LERP;
- // Saddle lift: a mount raises the rider; on foot the body settles back to ground.
- this.rig.position.y += ((this.mounted ? this._saddleY : 0) - this.rig.position.y) * 0.2;
- let d = this.yaw - this.curYaw;
- while (d > Math.PI) d -= Math.PI * 2;
- while (d < -Math.PI) d += Math.PI * 2;
- this.curYaw += d * YAW_LERP;
- this.rig.rotation.y = this.curYaw;
- if (this._steed) {
- this._steed.position.set(this.rig.position.x, 0, this.rig.position.z);
- this._steed.rotation.y = this.curYaw;
- }
- // A mounted, moving rider reads faster — nudge the walk clip rate while riding.
- this.anim?.update(dt * (this.mounted && this.motion === 'walk' ? this._rideRate : 1));
- // Animate the equipped cosmetic (e.g. a slowly-spinning, pulsing aura).
- this._cosmeticHandle?.tick(dt);
- }
-
- // Mount or dismount the steed under this avatar. `def` is the registry mount
- // tuning ({ color, accent, scale }) or null to dismount. The steed is a scene
- // sibling (not a child of the async avatar rig), so it survives avatar reloads;
- // tick() keeps it glued under the rider.
- applyMount(def) {
- const want = !!def;
- if (want === this.mounted && (!want || this._steed)) return;
- this.mounted = want;
- if (want) {
- if (this._steed) this.scene.remove(this._steed);
- this._steed = this._buildSteed(def);
- this._steed.position.set(this.rig.position.x, 0, this.rig.position.z);
- this._steed.rotation.y = this.curYaw;
- this.scene.add(this._steed);
- this._saddleY = 0.62 * (def.scale || 1);
- } else if (this._steed) {
- this.scene.remove(this._steed);
- this._steed = null;
- this._saddleY = 0;
- }
- }
-
- // A low-poly quadruped steed coloured from the registry: body + neck + head,
- // four legs, and a tail + snout accent so dire wolf and war boar read distinct.
- _buildSteed(def) {
- const g = new Group();
- const s = def.scale || 1;
- const body = new MeshStandardMaterial({ color: def.color ?? 0x6b7280, roughness: 0.85 });
- const accent = new MeshStandardMaterial({ color: def.accent ?? 0xb9c2d0, roughness: 0.8 });
- const torso = new Mesh(new BoxGeometry(0.5 * s, 0.42 * s, 1.0 * s), body);
- torso.position.y = 0.5 * s; torso.castShadow = true;
- const neck = new Mesh(new BoxGeometry(0.28 * s, 0.4 * s, 0.3 * s), body);
- neck.position.set(0, 0.72 * s, 0.5 * s); neck.rotation.x = -0.5; neck.castShadow = true;
- const head = new Mesh(new BoxGeometry(0.26 * s, 0.26 * s, 0.4 * s), body);
- head.position.set(0, 0.92 * s, 0.66 * s); head.castShadow = true;
- const snout = new Mesh(new BoxGeometry(0.18 * s, 0.16 * s, 0.18 * s), accent);
- snout.position.set(0, 0.86 * s, 0.86 * s);
- const legGeo = new BoxGeometry(0.12 * s, 0.5 * s, 0.12 * s);
- for (const [lx, lz] of [[-0.18, 0.38], [0.18, 0.38], [-0.18, -0.38], [0.18, -0.38]]) {
- const leg = new Mesh(legGeo, body);
- leg.position.set(lx * s, 0.25 * s, lz * s); leg.castShadow = true;
- g.add(leg);
- }
- const tail = new Mesh(new BoxGeometry(0.08 * s, 0.08 * s, 0.34 * s), accent);
- tail.position.set(0, 0.6 * s, -0.6 * s); tail.rotation.x = 0.6;
- g.add(torso, neck, head, snout, tail);
- return g;
- }
-
- // Show a speech bubble above this avatar for a few seconds, then fade it out.
- showBubble(text) {
- if (this._bubbleTimer) { clearTimeout(this._bubbleTimer); this._bubbleTimer = null; }
- this.bubble.textContent = text;
- this.bubble.hidden = false;
- this.bubble.classList.remove('kg-chat-bubble--fade');
- this._bubbleTimer = setTimeout(() => {
- this.bubble.classList.add('kg-chat-bubble--fade');
- this._bubbleTimer = setTimeout(() => {
- this.bubble.hidden = true;
- this.bubble.classList.remove('kg-chat-bubble--fade');
- this._bubbleTimer = null;
- }, 400);
- }, 5000);
- }
-
- dispose() {
- this._disposeCosmetic();
- if (this._bubbleTimer) clearTimeout(this._bubbleTimer);
- this.scene.remove(this.rig);
- if (this._steed) this.scene.remove(this._steed);
- this.label.remove();
- this.bubble.remove();
- }
-}
-
-// ---------------------------------------------------------------------------
-// IsoGame — the scene controller.
-// ---------------------------------------------------------------------------
-export class IsoGame {
- constructor(canvas) {
- this.canvas = canvas;
- this.phase = 'start'; // 'start' | 'connecting' | 'world' | 'offline'
- this.players = new Map(); // sessionId -> GamePlayerView
- this.nodeViews = new Map(); // id -> { group, node }
- this.mobViews = new Map(); // id -> { group, mob }
- this.npcViews = new Map(); // id -> { group, npc, label, markerEl }
- this.wheelViews = new Map(); // id -> { group, landmark } — interactable wheels (Task 19)
- this._landmarkGroups = []; // decorative landmark meshes (casino), cleared per realm
- this._casinoLabels = []; // [{ label, x, z, height }] — decorative landmark nameplates
- this.tombViews = new Map(); // id -> { group, tomb, label, nameEl, ttlEl }
- this.structViews = new Map(); // id -> { group, struct, ring, flame } (Task 07)
- this.keys = new Set();
- this.realm = null;
- this.myId = null;
-
- // Build mode (Task 07): when non-null we're placing a structure — a ghost
- // preview snaps to the tile under the cursor and turns green/red for valid/
- // invalid placement; a tap places it, right-click/Esc cancels, and movement
- // clicks are suppressed until we exit. `_buildCatalog` is the server-sent cost
- // table for the current realm; `_hoverPtr` tracks the cursor so the ghost
- // follows it without a drag.
- this._buildMode = null; // { kind, ghost } | null
- this._buildCatalog = {};
- this._hoverPtr = null;
-
- // Click-to-interact: a tap on a node/mob/NPC sets a target the loop walks
- // to and then services (gather/attack/talk); a tap on open ground sets a
- // move-to tile. _interactAccum paces repeated gather/attack while adjacent.
- this._target = null; // { kind:'node'|'mob'|'npc'|'tile', id?, tx?, ty? }
- this._interactAccum = 0;
- this.items = {}; // server item registry (mount tuning, icons) — arrives on join
- // Latest authoritative quest snapshot (drives the NPC markers + quest dot).
- this.quests = null;
-
- // Death & death-bag UI state. _raycaster/_ptr turn a tap into a world pick
- // (used to click an adjacent tombstone). _lootTombId is the bag whose
- // recovery panel is open; _deathInfo carries the last 'died' notice so the
- // respawn overlay can describe what was dropped.
- this._raycaster = new Raycaster();
- this._ptr = new Vector2();
- this._dragMoved = 0;
- this._lootTombId = null;
- this._deathInfo = null;
- this._deathShown = false;
-
- // Active fishing cast — the line/bobber/ripple visual while a cast is in the
- // water. Local-only (peers don't see our bobber); the authoritative catch
- // result rides back as a 'fish' notice that resolves it. null when idle.
- this._cast = null;
-
- // Skills panel state: latest server snapshot, open flag, and the live-refresh
- // timer that polls XP while the panel is open so bars fill as XP is earned.
- this._skills = null;
- this._skillsOpen = false;
- this._skillsTimer = null;
-
- // World chat: open flag (drives the expanded vs. click-through collapsed
- // state) and the per-account mute set. Mutes are keyed by display name and
- // persisted under the player's stable account id (Task 16) — wallet, else a
- // durable guest id — so a block list follows the account across sessions and
- // two accounts on one machine never share one. The closer fn is the document
- // listener that dismisses an open mute popover.
- this._chatOpen = false;
- this.muted = this._loadMuted();
- this._muteMenuCloser = null;
-
- // Camera: a follow rig at a fixed three-quarter angle. Drag rotates yaw,
- // wheel/pinch zooms. Pitch is steep for the isometric read.
- this.camYaw = 0.7; this.camPitch = 0.95; this.camDist = 16;
- this._dragging = false; this._lastPtr = null; this._downAt = 0;
- this._stepAccum = 0;
- this._last = performance.now();
- this._camTarget = new Vector3(0, 0, 0);
-
- this._initRenderer();
- this._initScene();
- this._bindHud();
- this._bindInput();
-
- // Quest/hotbar/bank HUD. Self-contained DOM; intents route back through net.
- this.q = new GameHud({
- onEquip: (i) => this._equipOrRide(i),
- onTurnIn: (id) => this.net?.questTurnIn(id),
- onBankOpen: () => this.net?.bankOpen(),
- onDeposit: (i) => this.net?.bankDeposit(i, 999),
- onWithdraw: (i) => this.net?.bankWithdraw(i, 999),
- onReset: () => this.net?.questOpen(),
- onBuildSelect: (kind) => this._enterBuildMode(kind),
- onBuildCancel: () => this._exitBuildMode(),
- // Cosmetics shop (Task 21): open re-fetches the live board; buy/equip/
- // unequip route to the authoritative server, which echoes a fresh board.
- onShopOpen: () => this.net?.shopOpen(),
- onBuyCosmetic: (id) => this.net?.buyCosmetic(id),
- onEquipCosmetic: (id) => this.net?.equipCosmetic(id),
- onUnequipCosmetic: () => this.net?.unequipCosmetic(),
- // Wardrobe try-before-equip: preview a look on the local avatar with no
- // server round-trip; null reverts to the server-authoritative equipped look.
- onPreviewCosmetic: (id) => this._previewLocalCosmetic(id),
- onStopPreview: () => this._previewLocalCosmetic(null),
- // Marketplace (Task 20): open fetches the live board; list/cancel/buy-gold
- // route straight to the authoritative server. A token buy is a multi-step
- // on-chain flow the controller drives (_buyTokenListing): quote → wallet
- // sign+send → server-verified settle.
- onMarketOpen: () => this.net?.marketOpen(),
- onMarketListGold: (item, qty, price) => this.net?.marketListGold(item, qty, price),
- onMarketListToken: (gold, usd) => this.net?.marketListToken(gold, usd),
- onMarketCancel: (id) => this.net?.marketCancel(id),
- onMarketBuyGold: (id) => this.net?.marketBuyGold(id),
- onMarketBuyToken: (id) => this._buyTokenListing(id),
- });
-
- this._loop = this._loop.bind(this);
- requestAnimationFrame(this._loop);
- }
-
- // ---------------------------------------------------------------- render
- _initRenderer() {
- const r = new WebGLRenderer({ canvas: this.canvas, antialias: true });
- r.setPixelRatio(Math.min(window.devicePixelRatio, 2));
- r.setSize(window.innerWidth, window.innerHeight);
- r.shadowMap.enabled = true; r.shadowMap.type = PCFSoftShadowMap;
- r.outputColorSpace = SRGBColorSpace;
- this.renderer = r;
- window.addEventListener('resize', () => this._onResize());
- }
-
- _initScene() {
- const scene = new Scene();
- scene.background = new Color(0x223a55);
- scene.fog = new Fog(0x223a55, 48, 120);
- this.scene = scene;
-
- this.camera = new PerspectiveCamera(48, window.innerWidth / window.innerHeight, 0.1, 400);
- this.camera.position.set(12, 16, 12);
-
- const hemi = new HemisphereLight(0xdcebff, 0x49603a, 1.0);
- scene.add(hemi);
- this._hemi = hemi;
- const ambient = new AmbientLight(0xffffff, 0.28);
- scene.add(ambient);
- this._ambient = ambient;
- const sun = new DirectionalLight(0xfff0d4, 1.25);
- sun.position.set(24, 40, 18); sun.castShadow = true;
- sun.shadow.mapSize.set(2048, 2048);
- const s = sun.shadow.camera; s.left = -40; s.right = 40; s.top = 40; s.bottom = -40; s.near = 1; s.far = 140;
- sun.shadow.bias = -0.0004;
- scene.add(sun, sun.target);
- this._sun = sun;
- // Cave torches: warm PointLights added/removed alongside the mine geometry.
- // Stored so _buildRealm can repopulate them on every handoff without leaking.
- this._caveLights = [];
-
- // Static realm geometry (ground, buildings, fountain, tile paint) lives in
- // its own group so a realm (re)build is a single clear + rebuild WITHOUT
- // touching dynamic objects — gather nodes and mobs sync via schema patches
- // whose arrival order vs. the 'realm' message isn't guaranteed, so they
- // must survive a realm rebuild.
- this.staticGroup = new Group();
- this.objectGroup = new Group();
- scene.add(this.staticGroup, this.objectGroup);
- }
-
- // ---------------------------------------------------------------- coords
- // Tile (tx,ty) → world (x,z), centred on the realm so the camera orbits the
- // middle of the map and shadows stay inside the shadow-camera frustum.
- _tileToWorld(tx, ty) {
- const c = (this.realm?.grid ?? 48) / 2;
- return { x: (tx - c + 0.5) * TILE, z: (ty - c + 0.5) * TILE };
- }
-
- // ---------------------------------------------------------------- realm
- _buildRealm(layout) {
- this.realm = layout;
- // Clear only the static realm geometry; dynamic nodes/mobs (objectGroup)
- // and players (added straight to the scene) survive a realm rebuild.
- this.staticGroup.clear();
-
- const grid = layout.grid || 48;
- const size = grid * TILE;
-
- // The mine interior reads as an enclosed cave: a dark rocky floor, rock
- // walls, and a tight, dim atmosphere. Surface realms keep the open sky
- // look. Background + fog are reset on every realm build, so walking back
- // up to the Mainland restores daylight cleanly.
- const isCave = !!layout.cave || layout.name === 'mine';
- this.scene.background.set(isCave ? 0x130f0b : 0x223a55);
- this.scene.fog.color.set(isCave ? 0x130f0b : 0x223a55);
- this.scene.fog.near = isCave ? 16 : 48;
- this.scene.fog.far = isCave ? 70 : 120;
-
- // Scene lighting: underground the sun doesn't reach. Dim the directional
- // and hemi lights to near-zero, deepen the ambient, and scatter warm torch
- // PointLights around the cave so dark corners read as firelit rather than
- // just black. Restoring surface values on exit means the Mainland always
- // looks like open daylight again, never the cave's warmth.
- this._sun.intensity = isCave ? 0.0 : 1.25;
- this._hemi.intensity = isCave ? 0.06 : 1.0;
- this._ambient.intensity = isCave ? 0.18 : 0.28;
- this._ambient.color.set(isCave ? 0x4a3020 : 0xffffff);
- // Remove previous cave lights before adding new ones (handles realm→realm hop).
- for (const l of this._caveLights) this.scene.remove(l);
- this._caveLights = [];
- if (isCave) {
- // Torch positions: corners of each chamber + one near the entrance.
- // Colours alternate between deep orange and warm amber for visual variety.
- const torchTiles = [
- [4, 3, 0xff6a1a], [27, 3, 0xffaa30], [4, 9, 0xffaa30], [27, 9, 0xff6a1a],
- [4, 18, 0xff6a1a], [27, 18, 0xffaa30], [5, 27, 0xffaa30], [27, 27, 0xff6a1a],
- [16, 28, 0xffcc55], // entrance torch — brightest, marks the way out
- ];
- for (const [tx, ty, color] of torchTiles) {
- const pt = new PointLight(color, 2.8, 8.0, 1.4);
- const wp = this._tileToWorld(tx, ty);
- pt.position.set(wp.x, 1.6, wp.z);
- this.scene.add(pt);
- this._caveLights.push(pt);
- }
- }
-
- // Ground plane with a subtle tile grid so movement is legible. The cave
- // uses a dark rock floor instead of grass.
- const ground = new Mesh(
- new PlaneGeometry(size, size),
- new MeshStandardMaterial({ map: this._gridTexture(grid, isCave), color: isCave ? 0x2a241d : 0x6b9a52, roughness: 1 }),
- );
- ground.rotation.x = -Math.PI / 2;
- ground.receiveShadow = true;
- this.staticGroup.add(ground);
-
- // Water bodies are a visual subset of the blocked rects (server marks them in
- // `layout.water`). Render those as low, translucent pools and everything else
- // as solid no-go boxes — both match the server's walkability exactly. A set of
- // per-tile water keys also lets a tap on the pond resolve to a cast.
- const rectKey = (r) => `${r.x0},${r.y0},${r.x1},${r.y1}`;
- const waterRects = new Set((layout.water || []).map(rectKey));
- this._waterTiles = new Set();
- for (const r of layout.water || []) {
- for (let tx = r.x0; tx <= r.x1; tx++) for (let ty = r.y0; ty <= r.y1; ty++) this._waterTiles.add(`${tx},${ty}`);
- }
- // Solid blocks (bank building, walls, etc.) — render each blocked rect as a
- // low box so the no-go zones are visually obvious.
- for (const b of layout.blocked || []) {
- const isWater = waterRects.has(rectKey(b));
- const w = (b.x1 - b.x0 + 1) * TILE;
- const d = (b.y1 - b.y0 + 1) * TILE;
- const h = isWater ? 0.25 : 2.4;
- const box = new Mesh(
- new BoxGeometry(w, h, d),
- isWater
- ? new MeshStandardMaterial({
- color: 0x2c5a86, roughness: 0.3, metalness: 0.1,
- transparent: true, opacity: 0.85,
- emissive: 0x0a2030, emissiveIntensity: 0.35,
- })
- : isCave
- ? new MeshStandardMaterial({ map: this._rockTexture(), color: 0x6a5f4f, roughness: 1 })
- : new MeshStandardMaterial({ color: 0x4a4f5e, roughness: 0.85 }),
- );
- const cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2;
- const w0 = this._tileToWorld(cx, cy);
- box.position.set(w0.x, h / 2, w0.z);
- box.castShadow = !isWater; box.receiveShadow = true;
- this.staticGroup.add(box);
- }
-
- // Fountain landmark.
- if (layout.fountain) {
- const f = new Group();
- const base = new Mesh(new CylinderGeometry(1.6, 1.8, 0.5, 24),
- new MeshStandardMaterial({ color: 0x6b7280, roughness: 0.9 }));
- base.position.y = 0.25; base.castShadow = true; base.receiveShadow = true;
- const water = new Mesh(new CylinderGeometry(1.3, 1.3, 0.12, 24),
- new MeshStandardMaterial({ color: 0x3aa0d0, roughness: 0.2, emissive: 0x0a2a3a, emissiveIntensity: 0.4 }));
- water.position.y = 0.5;
- f.add(base, water);
- const w0 = this._tileToWorld(layout.fountain.tx, layout.fountain.ty);
- f.position.set(w0.x, 0, w0.z);
- this.staticGroup.add(f);
- }
-
- // Bank counter tiles — a warm highlight so players know where to bank.
- this._paintTiles(layout.bankZone, 0xffce5c, 0.85);
- // Fishing + cooking spots, if the realm has them.
- this._paintTiles(layout.fishing, 0x3aa0d0, 0.6);
- this._paintTiles(layout.cooking, 0xff7a3a, 0.6);
- // Portals. An open portal glows violet; a combat-gated one is barred with a
- // red archway. The mine entrance on the Mainland gets a cave-mouth arch so
- // it reads as a tunnel opening rather than a plain glowing tile.
- for (const p of layout.portals || []) {
- const tiles = this._rectTiles(p);
- if (p.gate) { this._paintTiles(tiles, 0xd0455a, 0.75); this._buildGateArch(p); }
- else {
- this._paintTiles(tiles, 0xae7bff, 0.7);
- if (p.to === 'mine') this._buildMineEntrance(p);
- }
- }
- // Arena fittings: spectator stands (no-PvP), the practice boxing ring, and the
- // moving floor rollers — drawn with directional chevrons so the flow is legible.
- this._buildSeating(layout.seating);
- this._buildRing(layout.ring);
- this._buildRollers(layout.rollers);
-
- // Fixed NPCs (Aldric the Guide, …) — distinct characters with a nameplate +
- // quest marker. Rebuilt with the realm since they ride in the realm layout.
- this._buildNpcs(layout);
-
- // Fixed landmarks (Task 19): the casino building + its Wheel of Fortune.
- // The wheel is interactable — clicking it walks the player adjacent and opens
- // the spinner; the casino is decorative (its footprint is blocked server-side).
- this._buildLandmarks(layout);
-
- // Frame the camera on the spawn before the local player exists.
- const sp = this._tileToWorld(layout.spawn?.tx ?? grid / 2, layout.spawn?.ty ?? grid / 2);
- this._camTarget.set(sp.x, 0, sp.z);
-
- this.hud.realm.textContent = this._realmLabel(layout.name);
-
- // Topbar world-instance chip (Task 23). Read the server off the synced state
- // (authoritative — confirms which instance we actually landed on) so it can
- // never disagree with what the login picker requested.
- this._updateServerChip();
-
- // Building (Task 07): the realm's authoritative cost table + allowed kinds.
- // Show the Build button only where this realm permits building, and leave any
- // build mode from a previous realm — its ghost no longer matches these rules.
- this._buildCatalog = layout.buildCatalog || {};
- this._exitBuildMode();
- this.q?.setBuildAvailable(Object.keys(this._buildCatalog).length > 0);
- this._refreshBuildMenu();
- }
-
- // ---------------------------------------------------------------- NPCs
- _buildNpcs(layout) {
- this._disposeNpcs();
- for (const npc of layout.npcs || []) {
- const group = this._buildNpcView(npc);
- const w = this._tileToWorld(npc.tx, npc.ty);
- group.position.set(w.x, 0, w.z);
- group.traverse((o) => { o.userData.npcId = npc.id; }); // raycast → talk target
- this.objectGroup.add(group);
-
- const label = document.createElement('div');
- label.className = 'kg-npc-label';
- label.innerHTML = `<span class="kg-npc-marker" hidden></span><span class="kg-npc-tag"></span>`;
- label.querySelector('.kg-npc-tag').textContent = npc.name;
- document.getElementById('kg-labels')?.appendChild(label);
-
- this.npcViews.set(npc.id, { group, npc, label, markerEl: label.querySelector('.kg-npc-marker'), height: 1.9 });
- }
- this._refreshNpcMarkers();
- }
-
- // A distinct robed guide figure (so it never reads as a player capsule): a
- // hooded body, a face disc, and a small staff. Low-poly, no asset load.
- _buildNpcView(npc) {
- const g = new Group();
- const robe = new Mesh(new CylinderGeometry(0.32, 0.5, 1.3, 12),
- new MeshStandardMaterial({ color: 0x3b5b8c, roughness: 0.85 }));
- robe.position.y = 0.65; robe.castShadow = true;
- const hood = new Mesh(new ConeGeometry(0.36, 0.5, 12),
- new MeshStandardMaterial({ color: 0x2c4468, roughness: 0.85 }));
- hood.position.y = 1.45; hood.castShadow = true;
- const face = new Mesh(new SphereGeometry(0.2, 16, 12),
- new MeshStandardMaterial({ color: 0xe8c9a0, roughness: 0.7 }));
- face.position.y = 1.32;
- const staff = new Mesh(new CylinderGeometry(0.04, 0.04, 1.6, 6),
- new MeshStandardMaterial({ color: 0x6b4a2b, roughness: 1 }));
- staff.position.set(0.42, 0.8, 0); staff.castShadow = true;
- const orb = new Mesh(new IcosahedronGeometry(0.12, 0),
- new MeshStandardMaterial({ color: 0xffce5c, emissive: 0x6b5410, emissiveIntensity: 0.8, roughness: 0.4 }));
- orb.position.set(0.42, 1.65, 0);
- g.add(robe, hood, face, staff, orb);
- return g;
- }
-
- // Aldric's floating "!" (tutorial in progress) / "?" (a daily ready to claim)
- // marker, derived from the local quest snapshot. Cleared when there's nothing
- // to do at him.
- _refreshNpcMarkers() {
- const tutorialActive = !!(this.quests?.tutorial && !this.quests.tutorial.done);
- const turnIn = (this.quests?.daily?.quests || []).some((q) => q.progress >= q.count && !q.claimed);
- for (const [, v] of this.npcViews) {
- const mark = turnIn ? '?' : tutorialActive ? '!' : '';
- v.markerEl.textContent = mark;
- v.markerEl.hidden = !mark;
- v.markerEl.className = 'kg-npc-marker' + (turnIn ? ' kq-marker-turnin' : ' kq-marker-new');
- }
- }
-
- _disposeNpcs() {
- for (const [, v] of this.npcViews) { this.objectGroup.remove(v.group); v.label.remove(); }
- this.npcViews.clear();
- }
-
- // ---------------------------------------------------------------- landmarks
- // Fixed world landmarks (Task 19). The casino is a decorative building; the
- // wheel is an interactable object (tagged for raycast → walk-and-spin). Rebuilt
- // with the realm since they ride in the realm layout.
- _buildLandmarks(layout) {
- this._disposeLandmarks();
- for (const lm of layout.landmarks || []) {
- if (lm.kind === 'wheel') {
- const group = this._buildWheelView();
- const w = this._tileToWorld(lm.tx, lm.ty);
- group.position.set(w.x, 0, w.z);
- group.traverse((o) => { o.userData.wheelId = lm.id; }); // raycast → spin target
- this.objectGroup.add(group);
-
- const label = document.createElement('div');
- label.className = 'kg-npc-label kg-wheel-label';
- label.innerHTML = `<span class="kg-npc-tag"></span>`;
- label.querySelector('.kg-npc-tag').textContent = lm.label || 'Wheel of Fortune';
- document.getElementById('kg-labels')?.appendChild(label);
-
- this.wheelViews.set(lm.id, { group, landmark: lm, label, height: 2.2, spin: 0 });
- } else if (lm.kind === 'casino') {
- const group = this._buildCasinoView();
- const w = this._tileToWorld(lm.tx, lm.ty);
- group.position.set(w.x, 0, w.z);
- this.staticGroup.add(group);
- this._landmarkGroups.push(group);
-
- const label = document.createElement('div');
- label.className = 'kg-npc-label kg-casino-label';
- label.innerHTML = `<span class="kg-npc-tag"></span>`;
- label.querySelector('.kg-npc-tag').textContent = lm.label || 'Casino';
- document.getElementById('kg-labels')?.appendChild(label);
- this._casinoLabels.push({ label, x: w.x, z: w.z, height: 3.0 });
- }
- }
- }
-
- // A carnival prize wheel: an upright disc with alternating gold/teal sectors, a
- // hub, and a top pointer. Low-poly, no asset load. Slowly idles via _updateLandmarks.
- _buildWheelView() {
- const g = new Group();
- const post = new Mesh(new CylinderGeometry(0.12, 0.16, 1.5, 10),
- new MeshStandardMaterial({ color: 0x5a4632, roughness: 0.9 }));
- post.position.y = 0.75; post.castShadow = true;
- const disc = new Group();
- disc.position.y = 1.7;
- const n = 12, seg = (Math.PI * 2) / n;
- for (let i = 0; i < n; i++) {
- const wedge = new Mesh(
- new CylinderGeometry(0.78, 0.78, 0.12, 24, 1, false, i * seg, seg),
- new MeshStandardMaterial({
- color: i % 2 ? 0xf5c542 : 0x2b9fa8,
- emissive: i % 2 ? 0x4a3a08 : 0x0a3034, emissiveIntensity: 0.5, roughness: 0.5,
- }),
- );
- wedge.rotation.x = Math.PI / 2;
- disc.add(wedge);
- }
- const hub = new Mesh(new SphereGeometry(0.16, 16, 12),
- new MeshStandardMaterial({ color: 0xfff1c0, emissive: 0x6b5410, emissiveIntensity: 0.9, roughness: 0.3 }));
- hub.position.z = 0.08;
- disc.add(hub);
- disc.rotation.y = 0; // faces +Z; idles around Z in _updateLandmarks
- const pointer = new Mesh(new ConeGeometry(0.12, 0.28, 4),
- new MeshStandardMaterial({ color: 0xff5a3a, roughness: 0.5 }));
- pointer.position.set(0, 2.56, 0.06); pointer.rotation.x = Math.PI;
- g.add(post, disc, pointer);
- g.userData.disc = disc;
- g.castShadow = true;
- return g;
- }
-
- // A small casino pavilion: a warm-lit body with a striped awning and a glowing
- // sign cube, so the wheel reads as part of a venue, not a stray object.
- _buildCasinoView() {
- const g = new Group();
- const body = new Mesh(new BoxGeometry(3.2, 2.0, 2.4),
- new MeshStandardMaterial({ color: 0x6a2b4a, roughness: 0.85 }));
- body.position.y = 1.0; body.castShadow = true; body.receiveShadow = true;
- const roof = new Mesh(new CylinderGeometry(1.9, 1.9, 0.5, 6),
- new MeshStandardMaterial({ color: 0x3a1830, roughness: 0.8 }));
- roof.position.y = 2.25; roof.rotation.y = Math.PI / 6; roof.castShadow = true;
- const sign = new Mesh(new BoxGeometry(1.4, 0.5, 0.18),
- new MeshStandardMaterial({ color: 0xffce5c, emissive: 0xffae3a, emissiveIntensity: 1.1, roughness: 0.4 }));
- sign.position.set(0, 2.0, 1.25);
- const doorway = new Mesh(new BoxGeometry(0.9, 1.3, 0.12),
- new MeshStandardMaterial({ color: 0x140a12, roughness: 1 }));
- doorway.position.set(0, 0.65, 1.21);
- g.add(body, roof, sign, doorway);
- return g;
- }
-
- _disposeLandmarks() {
- for (const [, v] of this.wheelViews) { this.objectGroup.remove(v.group); v.label?.remove(); }
- this.wheelViews.clear();
- for (const group of this._landmarkGroups) this.staticGroup.remove(group);
- this._landmarkGroups = [];
- for (const cl of this._casinoLabels) cl.label?.remove();
- this._casinoLabels = [];
- }
-
- // Open the Wheel of Fortune (Task 19). The heavy Solana signing path lives in a
- // lazy chunk, so it only loads the first time a player reaches the wheel. The UI
- // owns its own server subscriptions; we just hand it the net and clear our handle
- // when it closes.
- async _openSpinWheel() {
- if (this._spinUI) { this._spinUI.focus(); return; }
- if (this._spinUILoading) return;
- this._spinUILoading = true;
- try {
- const { openSpinWheel } = await import('./spin-wheel-ui.js');
- this._spinUI = openSpinWheel({ net: this.net, onClose: () => { this._spinUI = null; } });
- } catch (err) {
- console.warn('[spin] failed to open wheel:', err?.message);
- this._toast({ kind: 'spin', text: 'Could not open the wheel. Try again.' });
- } finally {
- this._spinUILoading = false;
- }
- }
-
- _rectTiles(r) {
- const out = [];
- for (let tx = r.x0; tx <= r.x1; tx++) for (let ty = r.y0; ty <= r.y1; ty++) out.push({ tx, ty });
- return out;
- }
-
- _paintTiles(tiles, color, opacity) {
- if (!tiles?.length) return;
- const mat = new MeshBasicMaterial({ color, transparent: true, opacity, side: DoubleSide });
- const geo = new PlaneGeometry(TILE * 0.92, TILE * 0.92);
- for (const t of tiles) {
- const m = new Mesh(geo, mat);
- m.rotation.x = -Math.PI / 2;
- const w = this._tileToWorld(t.tx, t.ty);
- m.position.set(w.x, 0.04, w.z);
- this.staticGroup.add(m);
- }
- }
-
- // Title-case a realm id for the HUD, turning multi-word ids into readable labels
- // ('wilderness_north' → 'Wilderness North', 'arena' → 'Arena').
- _realmLabel(name) {
- return (name || 'realm').split('_').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
- }
-
- // A red barred archway over a combat-gated portal — the locked-gate state, drawn
- // so a player reads "you can't just walk in here" before stepping onto the tile.
- _buildGateArch(p) {
- const cx = (p.x0 + p.x1) / 2, cy = (p.y0 + p.y1) / 2;
- const c = this._tileToWorld(cx, cy);
- const g = new Group();
- const mat = new MeshStandardMaterial({ color: 0x7a1f2a, roughness: 0.7, emissive: 0x5a0f1a, emissiveIntensity: 0.5 });
- const postGeo = new BoxGeometry(0.3, 2.4, 0.3);
- const left = new Mesh(postGeo, mat); left.position.set(-TILE * 0.5, 1.2, 0);
- const right = new Mesh(postGeo, mat); right.position.set(TILE * 0.5, 1.2, 0);
- const lintel = new Mesh(new BoxGeometry(TILE * 1.2, 0.35, 0.35), mat); lintel.position.set(0, 2.45, 0);
- left.castShadow = right.castShadow = lintel.castShadow = true;
- g.add(left, right, lintel);
- g.position.set(c.x, 0, c.z);
- this.staticGroup.add(g);
- }
-
- // A jagged cave-mouth arch over the Mainland mine entrance so the portal reads
- // as a tunnel opening rather than a plain glowing tile. Rock-textured posts,
- // rough lintel, and a warm torch glow at the apex.
- _buildMineEntrance(p) {
- const cx = (p.x0 + p.x1) / 2, cy = (p.y0 + p.y1) / 2;
- const c = this._tileToWorld(cx, cy);
- const g = new Group();
- const rockMat = new MeshStandardMaterial({ map: this._rockTexture(), color: 0x5a4f40, roughness: 1 });
- const w = (p.x1 - p.x0 + 1) * TILE;
- // Posts — flanking pillars, slightly wider than a gate arch for a tunnel feel.
- const postGeo = new CylinderGeometry(0.22, 0.3, 2.6, 7);
- const left = new Mesh(postGeo, rockMat); left.position.set(-w / 2 - 0.1, 1.3, 0);
- const right = new Mesh(postGeo, rockMat); right.position.set(w / 2 + 0.1, 1.3, 0);
- // Keystone lintel — a chunky rock span across the top.
- const lintel = new Mesh(new BoxGeometry(w + 0.9, 0.55, 0.6), rockMat);
- lintel.position.set(0, 2.7, 0);
- // Rough cap stones on each post.
- const capGeo = new DodecahedronGeometry(0.32, 0);
- const capL = new Mesh(capGeo, rockMat); capL.position.set(-w / 2 - 0.1, 2.7, 0);
- const capR = new Mesh(capGeo, rockMat); capR.position.set(w / 2 + 0.1, 2.7, 0);
- for (const m of [left, right, lintel, capL, capR]) { m.castShadow = true; m.receiveShadow = true; }
- g.add(left, right, lintel, capL, capR);
- g.position.set(c.x, 0, c.z);
- this.staticGroup.add(g);
- // A warm torch-point at the keystone so the entrance glow reads even at
- // a distance — the mine is dark; this is the last light before you go in.
- const torch = new PointLight(0xff8c30, 2.2, 6.5, 1.6);
- torch.position.set(c.x, 3.1, c.z);
- this.scene.add(torch);
- this._caveLights.push(torch); // reuse the cave-lights list so it's cleaned on next _buildRealm
- }
-
- // Spectator stands: a cool slate tint over the walkable seating tiles plus a corner
- // post at each end, so the stands read as off-floor (and the server keeps them PvP-free).
- _buildSeating(rects) {
- if (!rects?.length) return;
- const postMat = new MeshStandardMaterial({ color: 0x44516a, roughness: 0.9 });
- for (const r of rects) {
- this._paintTiles(this._rectTiles(r), 0x5b7fa6, 0.5);
- for (const [px, py] of [[r.x0, r.y0], [r.x1, r.y0], [r.x0, r.y1], [r.x1, r.y1]]) {
- const post = new Mesh(new CylinderGeometry(0.12, 0.12, 1.0, 8), postMat);
- const w = this._tileToWorld(px, py);
- post.position.set(w.x, 0.5, w.z); post.castShadow = true;
- this.staticGroup.add(post);
- }
- }
- }
-
- // The practice boxing ring (Mainland plaza): a canvas mat with four corner posts
- // and two rope heights. Purely cosmetic + walkable — no death risk on the safe hub.
- _buildRing(ring) {
- if (!ring) return;
- const w = (ring.x1 - ring.x0 + 1) * TILE, d = (ring.y1 - ring.y0 + 1) * TILE;
- const cx = (ring.x0 + ring.x1) / 2, cy = (ring.y0 + ring.y1) / 2;
- const c = this._tileToWorld(cx, cy);
- const g = new Group();
- this._paintTiles(this._rectTiles(ring), 0x2f6b8a, 0.45); // the canvas
- const postMat = new MeshStandardMaterial({ color: 0xb23b3b, roughness: 0.6 });
- const ropeMat = new MeshStandardMaterial({ color: 0xe6e6e6, roughness: 0.5 });
- const hx = w / 2 - 0.3, hz = d / 2 - 0.3;
- const corners = [[-hx, -hz], [hx, -hz], [hx, hz], [-hx, hz]];
- for (const [sx, sz] of corners) {
- const post = new Mesh(new CylinderGeometry(0.1, 0.1, 1.3, 8), postMat);
- post.position.set(sx, 0.65, sz); post.castShadow = true; g.add(post);
- }
- for (const h of [0.5, 0.95]) {
- for (let i = 0; i < 4; i++) {
- const a = corners[i], b = corners[(i + 1) % 4];
- const len = Math.hypot(b[0] - a[0], b[1] - a[1]);
- const rope = new Mesh(new BoxGeometry(len, 0.05, 0.05), ropeMat);
- rope.position.set((a[0] + b[0]) / 2, h, (a[1] + b[1]) / 2);
- rope.rotation.y = Math.atan2(b[1] - a[1], b[0] - a[0]);
- g.add(rope);
- }
- }
- g.position.set(c.x, 0, c.z);
- this.staticGroup.add(g);
- }
-
- // Moving-floor rollers (Arena): a hot conveyor tint over each strip with a flat
- // chevron on every tile pointing the way the server pushes — read the flow, ride it.
- _buildRollers(rollers) {
- if (!rollers?.length) return;
- for (const r of rollers) {
- const tiles = this._rectTiles(r);
- this._paintTiles(tiles, 0xff9a3a, 0.85);
- const [dx, dy] = this._rollerDelta(r.dir);
- const yaw = Math.atan2(-dy, dx); // map the push delta to a flat-XZ heading
- for (const t of tiles) {
- const chevron = this._rollerChevron(yaw);
- const w = this._tileToWorld(t.tx, t.ty);
- chevron.position.set(w.x, 0.07, w.z);
- this.staticGroup.add(chevron);
- }
- }
- }
-
- _rollerDelta(dir) {
- return dir === 'n' ? [0, -1] : dir === 's' ? [0, 1] : dir === 'e' ? [1, 0] : dir === 'w' ? [-1, 0] : [0, 0];
- }
-
- // A flat '>' chevron (two angled bars) lying on the ground, apex toward +X, then
- // turned by yaw so it points the roller's way.
- _rollerChevron(yaw) {
- const g = new Group();
- const mat = new MeshBasicMaterial({ color: 0x3a2410 });
- const barGeo = new BoxGeometry(0.34, 0.05, 0.1);
- const a = new Mesh(barGeo, mat); a.position.set(-0.05, 0, -0.1); a.rotation.y = -Math.PI / 4;
- const b = new Mesh(barGeo, mat); b.position.set(-0.05, 0, 0.1); b.rotation.y = Math.PI / 4;
- g.add(a, b);
- g.rotation.y = yaw;
- return g;
- }
-
- // Climb a raycast hit up to the player rig it belongs to, returning that player's
- // id (set on the rig in GamePlayerView) — used to resolve a PvP tap to a target.
- _playerIdOf(obj) {
- let o = obj;
- while (o) { if (o.userData && o.userData.playerId) return o.userData.playerId; o = o.parent; }
- return null;
- }
-
- // A faint tile grid drawn once into a tiling canvas texture. `dark` swaps the
- // grass palette for a dim rock floor used by the cave (mine) interior.
- _gridTexture(grid, dark = false) {
- const px = 64;
- const c = document.createElement('canvas'); c.width = c.height = px;
- const x = c.getContext('2d');
- x.fillStyle = dark ? '#241f19' : '#5c8a44'; x.fillRect(0, 0, px, px);
- x.strokeStyle = dark ? 'rgba(0,0,0,0.45)' : 'rgba(255,255,255,0.10)'; x.lineWidth = 2;
- x.strokeRect(0, 0, px, px);
- const tex = new CanvasTexture(c);
- tex.wrapS = tex.wrapT = RepeatWrapping;
- tex.repeat.set(grid, grid);
- tex.colorSpace = SRGBColorSpace;
- return tex;
- }
-
- // Mottled rock texture for cave walls, drawn once and cached. Speckle + a few
- // dark cracks over a stone base read as rough rock without an image asset.
- _rockTexture() {
- if (this._rockTex) return this._rockTex;
- const px = 128;
- const c = document.createElement('canvas'); c.width = c.height = px;
- const x = c.getContext('2d');
- x.fillStyle = '#4f4538'; x.fillRect(0, 0, px, px);
- for (let i = 0; i < 480; i++) {
- const g = 40 + Math.floor(Math.random() * 55);
- x.fillStyle = `rgba(${g + 18},${g + 8},${g - 6},${0.18 + Math.random() * 0.4})`;
- x.beginPath(); x.arc(Math.random() * px, Math.random() * px, 1 + Math.random() * 3, 0, Math.PI * 2); x.fill();
- }
- x.strokeStyle = 'rgba(12,9,6,0.5)'; x.lineWidth = 1.5;
- for (let i = 0; i < 9; i++) {
- x.beginPath(); x.moveTo(Math.random() * px, Math.random() * px); x.lineTo(Math.random() * px, Math.random() * px); x.stroke();
- }
- const tex = new CanvasTexture(c);
- tex.wrapS = tex.wrapT = RepeatWrapping;
- tex.colorSpace = SRGBColorSpace;
- this._rockTex = tex;
- return tex;
- }
-
- // ---------------------------------------------------------------- connect
- async start(name) {
- if (this.phase === 'world' || this.phase === 'connecting') return;
- this.phase = 'connecting';
- this._setHudPhase('connecting');
- // Reuse the avatar the player picked on /play (persisted in cc-avatar) and
- // network it through GamePlayer.cosmetic so peers render it too — both
- // scenes now share one look. A locally-staged guest avatar resolves to a
- // blob for our own view and uploads in the background; once it has a public
- // URL we broadcast it.
- this.avatarPref = localStorage.getItem('cc-avatar') || '';
- const isGuest = this.avatarPref === GUEST_SENTINEL;
- this.localAvatarUrl = await resolveAvatarUrl(this.avatarPref);
- const netAvatar = isGuest
- ? ''
- : (/^https?:\/\//i.test(this.avatarPref) || this.avatarPref.startsWith('/')
- ? this.avatarPref : this.localAvatarUrl);
- await loadManifest();
-
- // Realm is chosen by ?realm=<name> (each realm is its own room). Until
- // Task 01's portal traversal lands this is how a danger realm like
- // Wilderness is reached directly; the server still validates everything.
- const realm = new URLSearchParams(location.search).get('realm') || 'mainland';
- // World instance (Task 23) chosen at the login picker — pins every realm room
- // of this session to one server. The server validates/defaults it regardless.
- const server = this._resolveServerChoice();
- this.net = new GameNet({ name, avatar: netAvatar, realm, server, pid: this._playerId(), getPresence: getPresenceTicket });
- if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));
-
- // Fade-to-black during portal room swaps so the geometry rebuild is hidden.
- // onBeforeHandoff is awaited by _handlePortal, so the overlay is fully opaque
- // before the old room tears down. onAfterHandoff is called once _onHandoff
- // has cleared the dynamic views and the new realm is on its way in.
- this._portalFadeEl = document.getElementById('kg-portal-fade');
- this.net.onBeforeHandoff = () => new Promise((resolve) => {
- const el = this._portalFadeEl;
- if (!el) { resolve(); return; }
- el.classList.add('kg-fading-out');
- const done = () => { el.removeEventListener('transitionend', done); resolve(); };
- el.addEventListener('transitionend', done, { once: true });
- // Safety: resolve after transition duration + slack even if event misfires.
- setTimeout(resolve, 500);
- });
- this.net.onAfterHandoff = () => {
- // Brief pause so the scene has one frame to finish the geometry rebuild
- // before we reveal it, avoiding a half-populated flash.
- setTimeout(() => {
- const el = this._portalFadeEl;
- if (!el) return;
- el.classList.remove('kg-fading-out');
- }, 80);
- };
-
- this.net.on('status', ({ status, error }) => this._onStatus(status, error));
- this.net.on('realm', (layout) => this._buildRealm(layout));
- this.net.on('items', (r) => this._onItems(r));
- this.net.on('commands', (c) => this._onCommands(c));
- this.net.on('notice', (n) => this._onNotice(n));
- this.net.on('cooked', (c) => this._onCooked(c));
- this.net.on('chat', (m) => this._onChat(m));
- this.net.on('bank', (b) => this._onBank(b));
- this.net.on('skills', (s) => this._onSkills(s));
- this.net.on('xpgain', (g) => this._onXpGain(g));
- this.net.on('levelup', (l) => this._onLevelup(l));
- this.net.on('playerAdd', (p, id) => this._playerAdd(p, id));
- this.net.on('playerChange', (p, id) => this._playerChange(p, id));
- this.net.on('playerRemove', (id) => this._playerRemove(id));
- this.net.on('nodeAdd', (n, id) => this._nodeAdd(n, id));
- this.net.on('nodeChange', (n, id) => this._nodeChange(n, id));
- this.net.on('nodeRemove', (id) => this._nodeRemove(id));
- this.net.on('mobAdd', (m, id) => this._mobAdd(m, id));
- this.net.on('mobChange', (m, id) => this._mobChange(m, id));
- this.net.on('mobRemove', (id) => this._mobRemove(id));
- this.net.on('tombAdd', (t, id) => this._tombAdd(t, id));
- this.net.on('tombChange', (t, id) => this._tombChange(t, id));
- this.net.on('tombRemove', (id) => this._tombRemove(id));
- this.net.on('structAdd', (s, id) => this._structAdd(s, id));
- this.net.on('structChange', (s, id) => this._structChange(s, id));
- this.net.on('structRemove', (id) => this._structRemove(id));
- this.net.on('died', (d) => this._onDied(d));
- this.net.on('hit', (d) => this._onHit(d));
- this.net.on('quests', (q) => this._onQuests(q));
- this.net.on('cosmetics', (c) => this._onCosmetics(c));
- this.net.on('shop', (s) => this._onShop(s));
- this.net.on('market', (m) => this.q?.setMarket(m));
- this.net.on('marketDirty', () => this.q?.marketDirty());
- this.net.on('marketQuote', (qd) => this._onMarketQuote(qd));
- this.net.on('marketSettled', (s) => this._onMarketSettled(s));
- this.net.on('marketBuyFail', (f) => this._onMarketBuyFail(f));
- this.net.on('marketPayout', (p) => this._onMarketPayout(p));
- this.net.on('handoff', (info) => this._onHandoff(info));
- this.net.on('takeover', (m) => this._onTakeover(m));
-
- await this.net.connect();
- this.myId = this.net.sessionId;
- this._initJoystick();
- }
-
- // Stable account id for persistence (tutorial completion, dailies, badges).
- // Prefers a connected wallet address, else a persistent per-browser guest id.
- _playerId() {
- try {
- const wallet = localStorage.getItem('cc-wallet') || '';
- if (wallet) return wallet;
- let id = localStorage.getItem('kg-pid');
- if (!id) { id = 'g_' + Math.random().toString(36).slice(2) + Date.now().toString(36); localStorage.setItem('kg-pid', id); }
- return id;
- } catch { return ''; }
- }
-
- _onStatus(status, error) {
- this.hud.status.textContent = status;
- this.hud.status.dataset.status = status;
- if (status === 'online') {
- this.phase = 'world';
- this._setHudPhase('world');
- this.q?.enterWorld();
- } else if (status === 'offline' || status === 'failed') {
- // Keep the world visible if we were already in it (a transient drop);
- // only fall back to the offline screen if we never connected.
- if (this.phase !== 'world') { this.phase = 'offline'; this._setHudPhase('offline'); }
- this.hud.offlineMsg.textContent = error || 'Disconnected from the game server.';
- }
- this._updateOnline();
- }
-
- // The same account just signed in on another server or tab (Task 23 single
- // active session). game-net already suppressed the auto-reconnect; pull the
- // player out of the world to the offline screen with an honest, actionable
- // reason. The Reconnect button reclaims the seat (game-net clears the flag).
- _onTakeover() {
- this.phase = 'offline';
- this._setHudPhase('offline');
- if (this.hud.offlineMsg) {
- this.hud.offlineMsg.textContent =
- 'Your account signed in on another server or tab. Only one session can be active at a time.';
- }
- if (this.hud.retryBtn) this.hud.retryBtn.textContent = 'Reconnect here';
- }
-
- // ---------------------------------------------------------------- server picker
- // Login-time world-instance chooser (Task 23). Lists the real roster with live
- // population from the multiplayer host's /servers endpoint; the choice is
- // remembered per browser and pins the whole session to one instance.
-
- // The active choice: an explicit picker selection wins, then a ?server= deep
- // link, then the remembered choice, else '' (server resolves its default).
- _resolveServerChoice() {
- if (this._chosenServer) return this._chosenServer;
- const urlS = new URLSearchParams(location.search).get('server');
- if (urlS) return urlS;
- try { return localStorage.getItem('kg-server') || ''; } catch { return ''; }
- }
-
- _initServerPicker() {
- this._serverList = null;
- this._serverPollTimer = null;
- this._chosenServer = this._resolveServerChoice();
- this._refreshServers();
- }
-
- _startServerPolling() {
- if (this._serverPollTimer || !this.hud?.serversList) return;
- // Refresh live counts every 10s while the picker is visible so the numbers
- // the player chooses from stay honest without hammering the endpoint.
- this._serverPollTimer = setInterval(() => this._refreshServers(), 10_000);
- }
-
- _stopServerPolling() {
- if (this._serverPollTimer) { clearInterval(this._serverPollTimer); this._serverPollTimer = null; }
- }
-
- async _refreshServers() {
- if (!this.hud?.serversList) return;
- let list;
- try {
- list = await fetchServers(this.net?.url);
- } catch {
- // Host unreachable: still let the player in via a single default world
- // rather than blocking on a count we can't get. Never fake a number.
- if (!this._serverList) this._renderServerFallback();
- return;
- }
- if (!Array.isArray(list) || !list.length) { this._renderServerFallback(); return; }
- this._serverList = list;
- // Pre-select the remembered/url choice if it's still a real instance, else
- // the recommended (least-full) one, else the first.
- const ids = new Set(list.map((s) => s.id));
- if (!this._chosenServer || !ids.has(this._chosenServer)) {
- this._chosenServer = (list.find((s) => s.recommended) || list[0]).id;
- }
- this._renderServers(list, false);
- }
-
- _renderServerFallback() {
- this._serverList = [{ id: '', name: 'Default world', blurb: '', players: null, recommended: false }];
- this._chosenServer = '';
- this._renderServers(this._serverList, true);
- }
-
- _renderServers(list, isFallback) {
- const host = this.hud.serversList;
- if (!host) return;
- host.setAttribute('aria-busy', 'false');
- host.textContent = '';
- for (const s of list) {
- const known = Number.isFinite(s.players);
- const selected = s.id === this._chosenServer;
-
- const opt = document.createElement('label');
- opt.className = 'kg-server-opt';
- opt.dataset.selected = String(selected);
- opt.dataset.empty = String(known && s.players === 0);
-
- const input = document.createElement('input');
- input.type = 'radio';
- input.name = 'kg-server';
- input.value = s.id;
- input.checked = selected;
- input.addEventListener('change', () => this._selectServer(s.id));
- opt.appendChild(input);
-
- const dot = document.createElement('span');
- dot.className = 'kg-server-dot';
- dot.setAttribute('aria-hidden', 'true');
- opt.appendChild(dot);
-
- const main = document.createElement('span');
- main.className = 'kg-server-main';
- const nameRow = document.createElement('span');
- nameRow.className = 'kg-server-name';
- nameRow.append(document.createTextNode(s.name || s.id || 'World'));
- if (s.recommended && !isFallback) {
- const rec = document.createElement('span');
- rec.className = 'kg-server-rec';
- rec.textContent = 'Recommended';
- nameRow.appendChild(rec);
- }
- main.appendChild(nameRow);
- if (s.blurb) {
- const blurb = document.createElement('div');
- blurb.className = 'kg-server-blurb';
- blurb.textContent = s.blurb;
- main.appendChild(blurb);
- }
- opt.appendChild(main);
-
- if (known) {
- const pop = document.createElement('span');
- pop.className = 'kg-server-pop';
- const b = document.createElement('b');
- b.textContent = String(s.players);
- pop.append(b, document.createTextNode(s.players === 1 ? 'player' : 'players'));
- opt.appendChild(pop);
- }
-
- opt.addEventListener('click', (e) => {
- // The label already toggles the radio; guard against a double-fire.
- if (e.target !== input) this._selectServer(s.id);
- });
- host.appendChild(opt);
- }
- this._updateServerChip();
- }
-
- _selectServer(id) {
- this._chosenServer = id;
- try { localStorage.setItem('kg-server', id); } catch {}
- // Repaint just the selection state so live counts + focus survive.
- this.hud.serversList?.querySelectorAll('.kg-server-opt').forEach((el) => {
- el.dataset.selected = String((el.querySelector('input')?.value ?? '') === id);
- });
- }
-
- // Topbar chip naming the world instance the player is on. Reads the synced,
- // authoritative server id; only shown when there's a real choice of instances.
- _updateServerChip() {
- const chip = this.hud.server;
- if (!chip) return;
- const id = this.net?.state?.server || this._chosenServer || '';
- const name = this._serverList?.find((s) => s.id === id)?.name || id;
- const multi = (this._serverList?.length || 0) > 1;
- if (name && multi) { chip.textContent = name; chip.hidden = false; }
- else { chip.hidden = true; }
- }
-
- // A portal moved us into a different realm room. The new room replays its own
- // players/nodes/mobs/tombs from scratch, so tear down every dynamic view tied
- // to the old realm (otherwise they linger as ghosts) and adopt the new session
- // id before those replays arrive. The fresh 'realm' message rebuilds the static
- // geometry; the loop's pending target is dropped so we don't chase a stale tile.
- _onHandoff({ sessionId } = {}) {
- for (const id of [...this.players.keys()]) this._playerRemove(id);
- for (const id of [...this.nodeViews.keys()]) this._nodeRemove(id);
- for (const id of [...this.mobViews.keys()]) this._mobRemove(id);
- for (const id of [...this.tombViews.keys()]) this._tombRemove(id);
- for (const id of [...this.structViews.keys()]) this._structRemove(id);
- this._exitBuildMode();
- // The wheel lives only on the Mainland — close an open spinner on a realm hop.
- this._spinUI?.close();
- this._target = null;
- this._lootTombId = null;
- this.myId = sessionId || this.net?.sessionId || this.myId;
- this._updateOnline();
- // Lift the blackout overlay once views are cleared — the new realm layout
- // arrives via the 'realm' message moments later and rebuilds the geometry.
- if (this.net?.onAfterHandoff) this.net.onAfterHandoff();
- }
-
- // ---------------------------------------------------------------- players
- _playerAdd(p, id) {
- if (this.players.has(id)) { this.players.get(id).apply(p); return; }
- const isLocal = id === this.myId;
- const view = new GamePlayerView(this.scene, (tx, ty) => this._tileToWorld(tx, ty), p, isLocal, (cid) => this._cosmeticVisual(cid));
- // The local player renders its own resolved avatar immediately (covers a
- // guest blob the server hasn't received the public URL for yet).
- if (isLocal && this.localAvatarUrl) view.setAvatar(this.localAvatarUrl);
- this.players.set(id, view);
- view.applyMount(p.mounted ? this._mountDef(p.mount) : null);
- if (isLocal) this._syncLocalHud(p);
- this._updateOnline();
- }
- _playerChange(p, id) {
- const v = this.players.get(id);
- if (!v) return;
- v.apply(p);
- v.applyMount(p.mounted ? this._mountDef(p.mount) : null);
- if (id === this.myId) this._syncLocalHud(p);
- }
-
- // Push the local player's authoritative inventory/hotbar into the HUD: the
- // hotbar bar, the bank panel's backpack column, and the "Bank" prompt that
- // appears only while standing on a bank-counter tile.
- _syncLocalHud(p) {
- if (!this.q) return;
- this.q.setHotbar(p.hotbar.map((s) => ({ item: s.item, qty: s.qty })), p.activeSlot);
- this.q.setInventory(p.inv.map((s) => ({ item: s.item, qty: s.qty })));
- const onBank = (this.realm?.bankZone || []).some((t) => t.tx === p.tx && t.ty === p.ty);
- this.q.setBankAvailable(onBank);
- this._updateMountChip(p);
- // Keep the persistent gold readout + any open shop's affordability in sync as
- // the purse changes (mob/quest rewards, a purchase).
- this.q.setGold(p.gold);
- // Affordability of buildables shifts as materials are gained/spent — keep the
- // build menu live (no-op in realms that don't permit building).
- this._refreshBuildMenu();
- }
- _playerRemove(id) {
- const v = this.players.get(id);
- if (v) { v.dispose(); this.players.delete(id); this._updateOnline(); }
- }
- _localView() { return this.myId ? this.players.get(this.myId) : null; }
-
- _updateOnline() {
- if (this.hud?.online) this.hud.online.textContent = String(this.players.size || 0);
- }
-
- // ------------------------------------------------------------ items & mounts
- // The server item registry (icons, labels, mount tuning) arrives once on join.
- // Re-apply mounts to every avatar now that their visuals are resolvable.
- _onItems(reg) {
- this.items = reg || {};
- const players = this.net?.state?.players;
- if (players) {
- for (const [id, v] of this.players) {
- const sp = players.get(id);
- if (sp) v.applyMount(sp.mounted ? this._mountDef(sp.mount) : null);
- }
- }
- const me = this.net?.state?.players?.get(this.myId);
- if (me) this._updateMountChip(me);
- }
-
- _mountDef(id) { return this.items?.[id]?.mount || null; }
-
- // ------------------------------------------------------------ cosmetics (Task 21)
- // The cosmetics catalogue (id → name/rarity/price/rotation/visual) arrives once
- // on join. Index it, hand it to the HUD so the shop/wardrobe render real data,
- // and re-apply every avatar's equipped look now that visuals are resolvable.
- _onCosmetics(catalog) {
- const list = catalog?.cosmetics || [];
- this.cosmetics = new Map(list.map((c) => [c.id, c]));
- this.cosmeticRarities = catalog?.rarities || {};
- this.q?.setCosmeticCatalog(list, this.cosmeticRarities);
- const players = this.net?.state?.players;
- for (const [id, v] of this.players) {
- const sp = players?.get(id);
- v.setCosmetic(sp?.cosmeticId || '');
- }
- }
-
- // Resolve a cosmetic id to its visual spec for the avatar renderer. Returns null
- // for the empty/default look or before the catalogue has loaded.
- _cosmeticVisual(id) {
- return id ? (this.cosmetics?.get(id)?.visual || null) : null;
- }
-
- // The live shop board (offers + rotation countdowns + owned + gold) — straight
- // through to the HUD's shop surface.
- _onShop(snapshot) {
- this.q?.setShop(snapshot || null);
- }
-
- // Preview a cosmetic on the local avatar (wardrobe try-before-equip). `id` is
- // a cosmetic id or '' (default look); null clears the preview. Local-only —
- // peers see nothing until the player actually equips (server-authoritative).
- _previewLocalCosmetic(id) {
- this.players.get(this.myId)?.previewCosmetic?.(id);
- }
-
- // ---------------------------------------------------------------- marketplace (Task 20)
-
- // Begin an on-chain token purchase. We allow one in flight at a time so the
- // per-listing busy state and the wallet handshake stay unambiguous. The server
- // replies with a 'marketQuote' (unsigned split tx + signed quote) which
- // _onMarketQuote then drives through the wallet and back as a settle.
- async _buyTokenListing(id) {
- if (this._tokenBuy) { this._toast({ kind: 'market', text: 'Finish your current purchase first.' }); return; }
- let wallet = null;
- try {
- const { detectSolanaWallet } = await import('../erc8004/solana-deploy.js');
- wallet = detectSolanaWallet();
- } catch { wallet = null; }
- if (!wallet || !wallet.publicKey) {
- this._toast({ kind: 'market', text: 'Connect a Solana wallet to buy with tokens.' });
- return;
- }
- this._tokenBuy = { id };
- this.q?.setMarketBusy(id, 'Preparing…');
- this.net?.marketTokenQuote(id);
- }
-
- // The server quoted the token amount and built the split transaction. Sign it in
- // the wallet, broadcast through our same-origin RPC proxy, wait for confirmation,
- // then hand the signature back for server-side verification + gold release.
- async _onMarketQuote(qd) {
- if (!qd || !this._tokenBuy || this._tokenBuy.id !== qd.id) return; // stale/unsolicited
- const id = qd.id;
- try {
- const { detectSolanaWallet, SOLANA_RPC } = await import('../erc8004/solana-deploy.js');
- const { Transaction, Connection } = await import('@solana/web3.js');
- const wallet = detectSolanaWallet();
- if (!wallet || !wallet.publicKey) throw new Error('wallet-missing');
- this.q?.setMarketBusy(id, 'Confirm in wallet…');
- const bytes = Uint8Array.from(atob(qd.tx), (c) => c.charCodeAt(0));
- const tx = Transaction.from(bytes);
- const signed = await wallet.signTransaction(tx);
- this.q?.setMarketBusy(id, 'Confirming…');
- const conn = new Connection(SOLANA_RPC.mainnet, 'confirmed');
- const sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false, maxRetries: 3 });
- const latest = await conn.getLatestBlockhash('confirmed');
- await conn.confirmTransaction({ signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, 'confirmed');
- this.q?.setMarketBusy(id, 'Settling…');
- this._lastMarketSig = sig;
- this.net?.marketTokenSettle(qd.quote, sig);
- } catch (err) {
- const msg = String(err?.message || err);
- const friendly = /reject|denied|cancell?ed|user/i.test(msg) ? 'Cancelled in wallet.' : 'Payment failed — no gold was charged.';
- this._tokenBuy = null;
- this.q?.clearMarketBusy(id);
- this._toast({ kind: 'market', text: friendly });
- }
- }
-
- // Server verified the payment and released the gold (it also sends a notice +
- // fresh board). Clear the in-flight buy + its busy spinner.
- _onMarketSettled(s) {
- const id = s?.id || this._tokenBuy?.id;
- this._tokenBuy = null;
- if (id) this.q?.clearMarketBusy(id);
- const sig = this._lastMarketSig;
- this._lastMarketSig = null;
- if (sig) this._toast({ kind: 'market', text: 'Purchase settled on-chain.', href: `https://solscan.io/tx/${sig}`, hrefText: 'View on Solscan ↗' });
- }
-
- // Server rejected a token quote/settle (price feed down, expired quote, failed
- // verification). The accompanying notice explains why; here we just release the
- // spinner so the card returns to a buyable state.
- _onMarketBuyFail(info) {
- const id = info?.id || this._tokenBuy?.id;
- this._tokenBuy = null;
- if (id) this.q?.clearMarketBusy(id);
- }
-
- // Proceeds from a sale that completed while this account was offline or in
- // another realm, delivered on login / via a live nudge.
- _onMarketPayout(p) {
- if (!p) return;
- const parts = [];
- if (p.gold) parts.push(`${(p.gold | 0).toLocaleString('en-US')} gold`);
- if (Array.isArray(p.items)) for (const it of p.items) parts.push(`${it.qty}× ${itemLabel(it.item)}`);
- if (parts.length) this._toast({ kind: 'market', text: `Sale settled: +${parts.join(', ')}.` });
- }
-
- // Equip a hotbar slot; if it holds a mount, also ride it — the natural "tap your
- // steed to mount" gesture. Both are server-authoritative (equip + use intents).
- _equipOrRide(i) {
- if (this.phase !== 'world') return;
- this.net?.equip(i);
- const ps = this.net?.state?.players?.get(this.myId);
- const item = ps?.hotbar?.[i]?.item;
- if (item && this._mountDef(item) && !(ps.mounted && ps.mount === item)) this.net?.use(i);
- }
-
- // Effective step cadence: a mount lowers it to (its server floor + headroom) so
- // the client never out-paces what the server accepts, yet rides visibly faster.
- _stepInterval() {
- const ps = this.net?.state?.players?.get(this.myId);
- const ms = ps?.mounted ? this._mountDef(ps.mount)?.stepMs : 0;
- return ms ? ms + 22 : STEP_INTERVAL_MS;
- }
-
- // Mount status chip + Dismount button: shown only while riding, naming the steed
- // from the registry. Driven by the authoritative mounted flag (no client guess).
- _updateMountChip(p) {
- const chip = this.hud?.mount;
- if (!chip) return;
- const show = !!p.mounted && this.phase === 'world';
- if (chip.hidden === show) chip.hidden = !show;
- if (show && this.hud.mountName) {
- const name = this.items?.[p.mount]?.label || (p.mount ? p.mount.replace(/_/g, ' ') : 'mount');
- if (this.hud.mountName.textContent !== name) this.hud.mountName.textContent = name;
- }
- }
-
- // ---------------------------------------------------------------- nodes
- // Resource nodes (trees/rocks/coal). T7 swaps _buildNodeView for richer
- // geometry + gather interactions; the add/change/remove plumbing stays.
- _nodeAdd(node, id) {
- if (this.nodeViews.has(id)) { this._nodeChange(node, id); return; }
- const group = this._buildNodeView(node);
- const w = this._tileToWorld(node.tx, node.ty);
- group.position.set(w.x, 0, w.z);
- group.visible = !node.depleted;
- group.traverse((o) => { o.userData.nodeId = id; }); // resolve raycast hits → gather target
- this.objectGroup.add(group);
- this.nodeViews.set(id, { group, node });
- }
- _nodeChange(node, id) {
- const v = this.nodeViews.get(id);
- if (!v) return;
- v.node = node;
- v.group.visible = !node.depleted;
- }
- _nodeRemove(id) {
- const v = this.nodeViews.get(id);
- if (v) { this.objectGroup.remove(v.group); this.nodeViews.delete(id); }
- }
-
- // Override seam for T7. Baseline: a recognizable low-poly prop per kind.
- _buildNodeView(node) {
- const g = new Group();
- if (node.kind === 'tree') {
- const trunk = new Mesh(new CylinderGeometry(0.12, 0.16, 0.9, 8),
- new MeshStandardMaterial({ color: 0x6b4a2b, roughness: 1 }));
- trunk.position.y = 0.45; trunk.castShadow = true;
- const leaves = new Mesh(new ConeGeometry(0.7, 1.4, 8),
- new MeshStandardMaterial({ color: 0x3f7d3a, roughness: 1 }));
- leaves.position.y = 1.5; leaves.castShadow = true;
- g.add(trunk, leaves);
- } else if (node.kind === 'coal') {
- const m = new Mesh(new IcosahedronGeometry(0.55, 0),
- new MeshStandardMaterial({ color: 0x23262e, roughness: 0.6, metalness: 0.2 }));
- m.position.y = 0.45; m.castShadow = true; g.add(m);
- } else { // rock
- const m = new Mesh(new DodecahedronGeometry(0.6, 0),
- new MeshStandardMaterial({ color: 0x8a8f9c, roughness: 0.9 }));
- m.position.y = 0.45; m.castShadow = true; g.add(m);
- }
- return g;
- }
-
- // ---------------------------------------------------------------- mobs
- // T8 swaps _buildMobView for proper enemies + attack interactions.
- _mobAdd(mob, id) {
- if (this.mobViews.has(id)) { this._mobChange(mob, id); return; }
- const group = this._buildMobView(mob);
- const w = this._tileToWorld(mob.tx, mob.ty);
- group.position.set(w.x, 0, w.z);
- group.visible = !mob.dead;
- group.traverse((o) => { o.userData.mobId = id; }); // resolve raycast hits → attack target
- this.objectGroup.add(group);
- // `body` (the material we tint for the aggro glow) is the first mesh in the
- // stand-in group; `target` drives the per-frame position lerp (Task 03 — mobs
- // chase smoothly, no teleporting between tiles).
- const body = group.children.find((o) => o.isMesh && o.material) || null;
- const v = { group, body, mob, target: new Vector3(w.x, 0, w.z), aggro: false };
- this.mobViews.set(id, v);
- this._setMobAggro(v, !!mob.aggroId);
- }
- _mobChange(mob, id) {
- const v = this.mobViews.get(id);
- if (!v) return;
- const wasDead = v.mob.dead;
- v.mob = mob;
- v.group.visible = !mob.dead;
- const w = this._tileToWorld(mob.tx, mob.ty);
- // Snap on (re)spawn so a mob reappearing at its home tile doesn't glide across
- // the map; otherwise tween toward the new tile each frame.
- if (wasDead && !mob.dead) v.group.position.set(w.x, 0, w.z);
- v.target.set(w.x, 0, w.z);
- this._setMobAggro(v, !!mob.aggroId);
- }
- _mobRemove(id) {
- const v = this.mobViews.get(id);
- if (v) { this.objectGroup.remove(v.group); this.mobViews.delete(id); }
- }
-
- // Per-frame mob position smoothing — mirrors the player view's lerp so a
- // server step (every MOB_MOVE_MS) reads as a glide, never a jump.
- _updateMobs() {
- for (const [, v] of this.mobViews) {
- if (!v.group.visible) continue;
- v.group.position.x += (v.target.x - v.group.position.x) * MOVE_LERP;
- v.group.position.z += (v.target.z - v.group.position.z) * MOVE_LERP;
- }
- }
-
- // Hostile-engaged cue: a mob chasing a player glows red (emissive). Cleared the
- // moment it drops aggro, so the threat state is always legible at a glance.
- _setMobAggro(v, on) {
- if (v.aggro === on || !v.body?.material) return;
- v.aggro = on;
- const m = v.body.material;
- m.emissive = new Color(on ? 0xff2a1a : 0x000000);
- m.emissiveIntensity = on ? 0.6 : 0;
- m.needsUpdate = true;
- }
-
- // Override seam for T8. Baseline: a colour-coded stand-in per mob kind.
- _buildMobView(mob) {
- const g = new Group();
- const color = mob.kind === 'troll' ? 0x6f5b8e : mob.kind === 'ogre' ? 0x9c5a3c : mob.kind === 'goblin' ? 0x5a8c3c : 0x9aa0ac;
- const scale = mob.kind === 'troll' ? 1.7 : mob.kind === 'ogre' ? 1.4 : 1;
- const body = new Mesh(new CylinderGeometry(0.3 * scale, 0.35 * scale, 1.1 * scale, 10),
- new MeshStandardMaterial({ color, roughness: 0.9 }));
- body.position.y = 0.55 * scale; body.castShadow = true;
- g.add(body);
- return g;
- }
-
- // ---------------------------------------------------------------- tombstones
- // Death-bags dropped in danger realms. Each gets a distinct gravestone mesh
- // (so it never reads as a rock node) plus a floating DOM label with the owner
- // name and a live "expires in Xs" countdown driven by the synced expiresAt.
- // Clicking an adjacent bag sends 'tombLoot' and opens the recovery panel.
- _tombAdd(tomb, id) {
- if (this.tombViews.has(id)) { this._tombChange(tomb, id); return; }
- const group = this._buildTombView(id);
- const w = this._tileToWorld(tomb.tx, tomb.ty);
- group.position.set(w.x, 0, w.z);
- this.objectGroup.add(group);
-
- const label = document.createElement('div');
- label.className = 'kg-tomblabel';
- label.innerHTML = `<span class="kg-tomb-name"></span><span class="kg-tomb-ttl"></span>`;
- const nameEl = label.querySelector('.kg-tomb-name');
- const ttlEl = label.querySelector('.kg-tomb-ttl');
- nameEl.textContent = `${tomb.ownerName || 'someone'}’s bag`;
- document.getElementById('kg-labels')?.appendChild(label);
-
- this.tombViews.set(id, { group, tomb, label, nameEl, ttlEl });
- }
- _tombChange(tomb, id) {
- const v = this.tombViews.get(id);
- if (!v) return;
- v.tomb = tomb;
- const w = this._tileToWorld(tomb.tx, tomb.ty);
- v.group.position.set(w.x, 0, w.z);
- v.nameEl.textContent = `${tomb.ownerName || 'someone'}’s bag`;
- // Keep an open recovery panel in sync as items flow out of the bag.
- if (this._lootTombId === id) this._renderLootPanel();
- }
- _tombRemove(id) {
- const v = this.tombViews.get(id);
- if (v) { this.objectGroup.remove(v.group); v.label.remove(); this.tombViews.delete(id); }
- // If the open panel's bag just vanished (looted dry or expired), close it.
- if (this._lootTombId === id) this._closeLootPanel();
- }
-
- _buildTombView(id) {
- const g = new Group();
- // A small earth mound + a glowing headstone slab. The cool violet emissive
- // keys it to the "lootable death-bag" colour used on the panel + portals.
- const mound = new Mesh(
- new CylinderGeometry(0.5, 0.6, 0.18, 16),
- new MeshStandardMaterial({ color: 0x3a2f4a, roughness: 1 }),
- );
- mound.position.y = 0.09; mound.receiveShadow = true;
- const slabMat = new MeshStandardMaterial({ color: 0x6b5a8a, roughness: 0.7, emissive: 0x2a1f4a, emissiveIntensity: 0.6 });
- const slab = new Mesh(new BoxGeometry(0.5, 0.7, 0.14), slabMat);
- slab.position.y = 0.52; slab.castShadow = true;
- const cap = new Mesh(new CylinderGeometry(0.25, 0.25, 0.14, 16, 1, false, 0, Math.PI), slabMat);
- cap.rotation.x = Math.PI / 2; cap.position.set(0, 0.87, 0);
- g.add(mound, slab, cap);
- // Tag every mesh so a raycast hit can resolve back to the tombstone id.
- g.traverse((o) => { o.userData.tombId = id; });
- return g;
- }
-
- // ---------------------------------------------------------------- structures
- // Player-built firepits + shacks (Task 07), synced via the structures map. A
- // firepit carries a flat countdown ring that drains with its remaining lifetime
- // (read off the authoritative expiresAt); a shack is a permanent little hut.
- _structAdd(struct, id) {
- if (this.structViews.has(id)) { this._structChange(struct, id); return; }
- const view = this._buildStructView(struct, id);
- const w = this._tileToWorld(struct.tx, struct.ty);
- view.group.position.set(w.x, 0, w.z);
- view.group.traverse((o) => { o.userData.structId = id; });
- this.objectGroup.add(view.group);
- this.structViews.set(id, { ...view, struct });
- // A new structure changes which tiles are buildable + (if mine) pickup state.
- this._refreshBuildMenu();
- }
- _structChange(struct, id) {
- const v = this.structViews.get(id);
- if (!v) return;
- v.struct = struct;
- const w = this._tileToWorld(struct.tx, struct.ty);
- v.group.position.set(w.x, 0, w.z);
- }
- _structRemove(id) {
- const v = this.structViews.get(id);
- if (v) {
- this.objectGroup.remove(v.group);
- // Dispose the per-structure geometry/materials (a firepit rebuilds its
- // countdown ring each frame, so free the live one on teardown).
- v.group.traverse((o) => { o.geometry?.dispose?.(); o.material?.dispose?.(); });
- this.structViews.delete(id);
- }
- this._refreshBuildMenu();
- }
-
- // Build the mesh for a structure. Returns { group, ring?, flame?, lifetime } so
- // the loop can animate a firepit's flame + countdown ring.
- _buildStructView(struct) {
- const g = new Group();
- if (struct.kind === 'firepit') {
- // A ring of stones, a glowing ember bed, and a flickering flame cone.
- const stoneMat = new MeshStandardMaterial({ color: 0x6b6f7a, roughness: 0.95 });
- const ringN = 8;
- for (let i = 0; i < ringN; i++) {
- const a = (i / ringN) * Math.PI * 2;
- const stone = new Mesh(new DodecahedronGeometry(0.16, 0), stoneMat);
- stone.position.set(Math.cos(a) * 0.42, 0.12, Math.sin(a) * 0.42);
- stone.castShadow = true;
- g.add(stone);
- }
- const embers = new Mesh(new CylinderGeometry(0.34, 0.34, 0.06, 12),
- new MeshStandardMaterial({ color: 0x3a1c0c, emissive: 0xff5a1e, emissiveIntensity: 0.9, roughness: 0.6 }));
- embers.position.y = 0.1;
- const flame = new Mesh(new ConeGeometry(0.26, 0.8, 10),
- new MeshStandardMaterial({ color: 0xffae3a, emissive: 0xff7a1e, emissiveIntensity: 1.3, roughness: 0.4, transparent: true, opacity: 0.92 }));
- flame.position.y = 0.62;
- // A flat countdown ring around the pit — drains from full to empty over the
- // firepit's lifetime. Rebuilt each frame via _updateStructures.
- const ring = new Mesh(
- new RingGeometry(0.5, 0.62, 28),
- new MeshBasicMaterial({ color: 0xffce5c, transparent: true, opacity: 0.85, side: DoubleSide }),
- );
- ring.rotation.x = -Math.PI / 2;
- ring.position.y = 0.06;
- g.add(embers, flame, ring);
- const lifetime = this._buildCatalog?.firepit?.lifetimeMs || 30000;
- return { group: g, ring, flame, lifetime };
- }
- // Shack: a timber cabin with a pitched roof and a dark doorway.
- const wall = new Mesh(new BoxGeometry(0.92, 0.8, 0.92),
- new MeshStandardMaterial({ color: 0x8a5a32, roughness: 0.9 }));
- wall.position.y = 0.4; wall.castShadow = true; wall.receiveShadow = true;
- const roof = new Mesh(new ConeGeometry(0.85, 0.6, 4),
- new MeshStandardMaterial({ color: 0x5a3a20, roughness: 0.9 }));
- roof.position.y = 1.1; roof.rotation.y = Math.PI / 4; roof.castShadow = true;
- const door = new Mesh(new BoxGeometry(0.26, 0.46, 0.06),
- new MeshStandardMaterial({ color: 0x2a1a0e, roughness: 1 }));
- door.position.set(0, 0.23, 0.47);
- g.add(wall, roof, door);
- return { group: g, lifetime: 0 };
- }
-
- // Animate firepits: flicker the flame and drain the countdown ring from its
- // remaining lifetime fraction. Shacks are static. Cheap; runs each frame.
- _updateStructures(now) {
- if (!this.structViews.size) return;
- const t = now / 1000;
- for (const [, v] of this.structViews) {
- if (!v.ring) continue;
- const exp = v.struct?.expiresAt || 0;
- const frac = exp ? Math.max(0, Math.min(1, (exp - Date.now()) / (v.lifetime || 30000))) : 1;
- // Redraw the ring as an arc covering the remaining fraction.
- v.ring.geometry.dispose();
- v.ring.geometry = new RingGeometry(0.5, 0.62, 40, 1, -Math.PI / 2, frac * Math.PI * 2);
- // Warm→red as it runs low; flame shrinks + flickers.
- v.ring.material.color.setHex(frac > 0.33 ? 0xffce5c : 0xff5a3a);
- if (v.flame) {
- const flick = 0.85 + Math.sin(t * 12 + v.group.position.x) * 0.12;
- v.flame.scale.set(1, (0.5 + frac * 0.5) * flick, 1);
- v.flame.material.opacity = 0.8 + Math.sin(t * 9) * 0.12;
- }
- }
- }
-
- // ---------------------------------------------------------------- build mode
- // Enter placement for `kind`: spawn a ghost the loop snaps to the hovered tile,
- // tinting green/red for valid/invalid. Tap places; right-click/Esc cancels.
- _enterBuildMode(kind) {
- if (this.phase !== 'world') return;
- if (!this._buildCatalog?.[kind]) return;
- this._exitBuildMode();
- const ghost = this._makeGhost(kind);
- this.objectGroup.add(ghost);
- this._buildMode = { kind, ghost, valid: false, tile: null };
- this.q?.closeBuild();
- this.q?.showBuildBanner(STRUCTURE_META[kind]);
- this._toast({ kind: 'build', text: `Tap a tile beside you to place the ${STRUCTURE_META[kind]?.label || kind}.` });
- }
-
- _exitBuildMode() {
- if (!this._buildMode) { this.q?.hideBuildBanner?.(); return; }
- this.objectGroup.remove(this._buildMode.ghost);
- this._buildMode.ghost.traverse((o) => { o.geometry?.dispose?.(); o.material?.dispose?.(); });
- this._buildMode = null;
- this.q?.hideBuildBanner();
- }
-
- // A translucent footprint + a faint silhouette of the structure, tinted by
- // validity. Kept light — it's built only on enter, recoloured each frame.
- _makeGhost(kind) {
- const g = new Group();
- const pad = new Mesh(new PlaneGeometry(TILE * 0.94, TILE * 0.94),
- new MeshBasicMaterial({ color: 0x55ff99, transparent: true, opacity: 0.4, side: DoubleSide }));
- pad.rotation.x = -Math.PI / 2; pad.position.y = 0.05;
- const silMat = new MeshBasicMaterial({ color: 0x55ff99, transparent: true, opacity: 0.35, depthWrite: false });
- const sil = kind === 'shack'
- ? new Mesh(new BoxGeometry(0.9, 0.8, 0.9), silMat)
- : new Mesh(new ConeGeometry(0.3, 0.7, 10), silMat);
- sil.position.y = kind === 'shack' ? 0.4 : 0.45;
- g.add(pad, sil);
- g._pad = pad; g._sil = sil; g._silMat = silMat;
- return g;
- }
-
- // Each frame in build mode: snap the ghost to the tile under the cursor and
- // recolour by validity. With no cursor yet, park it on the tile in front of us.
- _updateBuildGhost() {
- const bm = this._buildMode;
- if (!bm) return;
- const tile = this._buildHoverTile();
- if (!tile) { bm.ghost.visible = false; return; }
- bm.ghost.visible = true;
- const w = this._tileToWorld(tile.tx, tile.ty);
- bm.ghost.position.set(w.x, 0, w.z);
- const valid = this._buildValid(bm.kind, tile.tx, tile.ty);
- bm.valid = valid; bm.tile = tile;
- const col = valid ? 0x55ff99 : 0xff5a5a;
- bm.ghost._pad.material.color.setHex(col);
- bm.ghost._silMat.color.setHex(col);
- }
-
- // The tile the ghost should occupy: under the cursor if we have one, else the
- // tile directly in front of the player.
- _buildHoverTile() {
- if (this._hoverPtr) {
- this._ptr.x = (this._hoverPtr.x / window.innerWidth) * 2 - 1;
- this._ptr.y = -(this._hoverPtr.y / window.innerHeight) * 2 + 1;
- this._raycaster.setFromCamera(this._ptr, this.camera);
- const t = this._pickGroundTile();
- if (t) return t;
- }
- const me = this._localView();
- if (!me) return null;
- return { tx: me.tx, ty: me.ty - 1 };
- }
-
- // Client mirror of the server's build gates for instant ghost feedback: adjacent
- // (but not under the player), a free/buildable tile, and affordable. The server
- // re-checks all of it authoritatively on the actual 'build'.
- _buildValid(kind, tx, ty) {
- const ps = this.net?.state?.players?.get(this.myId);
- if (!ps) return false;
- const dx = Math.abs(tx - ps.tx), dy = Math.abs(ty - ps.ty);
- if (dx === 0 && dy === 0) return false;
- if (dx > 1 || dy > 1) return false;
- if (!this._isBuildableTile(tx, ty)) return false;
- return this._canAffordBuild(kind);
- }
-
- // A tile clear for building: walkable (bounds + not blocked + no node/mob/
- // structure) and not a portal/bank/fountain/fishing/cooking tile or a standing
- // player — mirrors the server's _isBuildable.
- _isBuildableTile(tx, ty) {
- if (!this._isWalkable(tx, ty)) return false;
- for (const [, v] of this.structViews) if (v.struct.tx === tx && v.struct.ty === ty) return false;
- for (const [, pv] of this.players) if (!pv.dead && pv.tx === tx && pv.ty === ty) return false;
- const r = this.realm || {};
- for (const p of r.portals || []) {
- if (tx >= p.x0 && tx <= p.x1 && ty >= p.y0 && ty <= p.y1) return false;
- }
- if ((r.bankZone || []).some((t) => t.tx === tx && t.ty === ty)) return false;
- if (r.fountain && r.fountain.tx === tx && r.fountain.ty === ty) return false;
- for (const f of r.fishing || []) if (f.tx === tx && f.ty === ty) return false;
- for (const c of r.cooking || []) if (c.tx === tx && c.ty === ty) return false;
- return true;
- }
-
- _canAffordBuild(kind) {
- const ps = this.net?.state?.players?.get(this.myId);
- const cost = this._buildCatalog?.[kind]?.cost;
- if (!ps || !cost) return false;
- for (const [item, qty] of Object.entries(cost)) {
- if (this._countItem(ps, item) < qty) return false;
- }
- return true;
- }
-
- // Place the ghost: validate client-side for instant feedback, then send the
- // authoritative 'build'. Stays honest — a red ghost explains why instead of
- // firing a doomed request. Exits build mode on a successful send.
- _attemptBuild(tile) {
- const bm = this._buildMode;
- if (!bm || !tile) return;
- const ps = this.net?.state?.players?.get(this.myId);
- const dx = Math.abs(tile.tx - (ps?.tx ?? 0)), dy = Math.abs(tile.ty - (ps?.ty ?? 0));
- if (dx === 0 && dy === 0) { this._toast({ kind: 'build', text: 'Step back a tile to place it.' }); return; }
- if (dx > 1 || dy > 1) { this._toast({ kind: 'build', text: 'Build on a tile right beside you.' }); return; }
- if (!this._isBuildableTile(tile.tx, tile.ty)) { this._toast({ kind: 'build', text: 'You can’t build there.' }); return; }
- if (!this._canAffordBuild(bm.kind)) {
- this._toast({ kind: 'build', text: `Not enough materials for a ${STRUCTURE_META[bm.kind]?.label || bm.kind}.` });
- return;
- }
- this.net?.build(bm.kind, tile.tx, tile.ty);
- this._exitBuildMode();
- }
-
- // Toggle the build menu (B key / toolbar). Refreshes affordability first so the
- // menu opens with live costs. In build mode, B cancels placement instead.
- _toggleBuildMenu() {
- if (this.phase !== 'world') return;
- if (this._buildMode) { this._exitBuildMode(); return; }
- this._refreshBuildMenu();
- this.q?.toggleBuild();
- }
-
- // Recompute the buildable list (kinds + live affordability) and hand it to the
- // HUD. Driven by the realm catalogue + the player's current materials.
- _refreshBuildMenu() {
- const kinds = Object.keys(this._buildCatalog || {});
- if (!kinds.length) { this.q?.setBuildables([]); return; }
- const ps = this.net?.state?.players?.get(this.myId);
- const items = kinds.map((kind) => {
- const def = this._buildCatalog[kind] || {};
- const meta = STRUCTURE_META[kind] || { icon: '🔨', label: kind, desc: '' };
- const costs = Object.entries(def.cost || {}).map(([item, need]) => {
- const have = ps ? this._countItem(ps, item) : 0;
- return { item, icon: MATERIAL_ICON[item] || '📦', need, have, ok: have >= need };
- });
- const owned = this._countOwnedStructures(kind);
- const capped = !!def.cap && owned >= def.cap;
- const affordable = costs.every((c) => c.ok) && !capped;
- const capNote = def.cap ? (capped ? 'placed' : `${owned}/${def.cap}`) : '';
- return { kind, icon: meta.icon, label: meta.label, desc: meta.desc, costs, affordable, capNote };
- });
- this.q?.setBuildables(items);
- }
-
- _countOwnedStructures(kind) {
- let n = 0;
- for (const [, v] of this.structViews) if (v.struct.kind === kind && v.struct.owner === this.myId) n++;
- return n;
- }
-
- // A structure of mine I'm standing beside (for the /pickup affordance), nearest
- // first. Null if none in reach.
- _adjacentOwnedStructure() {
- const ps = this.net?.state?.players?.get(this.myId);
- if (!ps) return null;
- let best = null, bd = Infinity;
- for (const [, v] of this.structViews) {
- const s = v.struct;
- if (s.owner !== this.myId) continue;
- if (Math.abs(ps.tx - s.tx) > 1 || Math.abs(ps.ty - s.ty) > 1) continue;
- const d = (ps.tx - s.tx) ** 2 + (ps.ty - s.ty) ** 2;
- if (d < bd) { bd = d; best = s; }
- }
- return best;
- }
-
- // ---------------------------------------------------------------- death & loot
- // The local player died: stash the notice so the respawn overlay can describe
- // the drop, and close any open bag panel (you can't loot while dead).
- _onDied(info) {
- this._deathInfo = info || null;
- this._closeLootPanel();
- // The 'died' notice can land a frame after the dead-flag patch already
- // showed the overlay — refresh the message so the drop detail isn't lost.
- if (this._deathShown && this.hud.deathMsg) this.hud.deathMsg.textContent = this._deathMessage();
- }
-
- _deathMessage() {
- const info = this._deathInfo;
- let msg = 'You died.';
- if (info?.byName) msg = `Slain by ${info.byName}.`;
- if (info?.danger && info?.dropped > 0) {
- msg += ` Your bag (${info.dropped} item${info.dropped === 1 ? '' : 's'}) dropped where you fell — get back to recover it.`;
- } else if (info && !info.danger) {
- msg += ' Your belongings are safe here.';
- }
- return msg;
- }
-
- // A mob landed a contact hit on the local player (Task 03): red screen flash, a
- // HUD toast, and a floating damage number above the avatar. The HP bar already
- // reflects the new value from the synced schema patch.
- _onHit(d) {
- const dmg = Math.max(0, Math.round(Number(d?.dmg) || 0));
- const by = d && d.byKind ? String(d.byKind) : 'an enemy';
- this._toast({ kind: 'combat', text: dmg > 0 ? `-${dmg} HP — ${by}` : `Hit by ${by}` });
- this._hurtFlash();
- if (dmg > 0) this._floatDamage(dmg);
- }
-
- // Brief red vignette over the viewport on taking damage. Self-removing and
- // never blocks input (pointer-events: none).
- _hurtFlash() {
- const el = document.createElement('div');
- el.setAttribute('aria-hidden', 'true');
- el.style.cssText =
- 'position:fixed;inset:0;z-index:60;pointer-events:none;' +
- 'box-shadow:inset 0 0 120px 40px rgba(220,30,20,0.55);opacity:0;';
- (this.root || document.body).appendChild(el);
- const anim = el.animate(
- [{ opacity: 0 }, { opacity: 1, offset: 0.18 }, { opacity: 0 }],
- { duration: 420, easing: 'ease-out' },
- );
- anim.onfinish = () => el.remove();
- anim.oncancel = () => el.remove();
- }
-
- // Floating "-N" damage number that rises from the local avatar's nameplate.
- _floatDamage(dmg) {
- const anchor = this._localView()?.label;
- if (!anchor) return;
- const r = anchor.getBoundingClientRect();
- const el = document.createElement('div');
- el.textContent = `-${dmg}`;
- el.setAttribute('aria-hidden', 'true');
- el.style.cssText =
- 'position:fixed;z-index:61;pointer-events:none;font:700 18px/1 system-ui,sans-serif;' +
- 'color:#ff5141;text-shadow:0 1px 2px rgba(0,0,0,0.7);' +
- `left:${Math.round(r.left + r.width / 2)}px;top:${Math.round(r.top)}px;transform:translate(-50%,0);`;
- document.body.appendChild(el);
- const anim = el.animate(
- [
- { transform: 'translate(-50%, 0)', opacity: 1 },
- { transform: 'translate(-50%, -40px)', opacity: 0 },
- ],
- { duration: 900, easing: 'ease-out' },
- );
- anim.onfinish = () => el.remove();
- anim.oncancel = () => el.remove();
- }
-
- // A tap (not a drag) in the world. Two world interactions resolve from a pick:
- // click an adjacent tombstone to loot it, or click the pond (water / a shore
- // spot) to cast a line. Camera drags are filtered out before we get here.
- _onTap(clientX, clientY) {
- if (this.phase !== 'world') return;
- const me = this._localView();
- if (!me || me.dead) return;
- this._ptr.x = (clientX / window.innerWidth) * 2 - 1;
- this._ptr.y = -(clientY / window.innerHeight) * 2 + 1;
- this._raycaster.setFromCamera(this._ptr, this.camera);
-
- // Build mode (Task 07) owns the tap: a click places the structure on the
- // ghost's tile; movement/gather clicks are suppressed until we exit.
- if (this._buildMode) {
- const tile = this._pickGroundTile() || this._buildMode.tile;
- this._attemptBuild(tile);
- return;
- }
-
- // 1) Tombstone under the cursor (dynamic objects).
- if (this.tombViews.size) {
- const hits = this._raycaster.intersectObject(this.objectGroup, true);
- let id = null;
- for (const h of hits) {
- const t = h.object?.userData?.tombId;
- if (t && this.tombViews.has(t)) { id = t; break; }
- }
- if (id) {
- const v = this.tombViews.get(id);
- if (Math.abs(me.tx - v.tomb.tx) > 1 || Math.abs(me.ty - v.tomb.ty) > 1) {
- this._toast({ kind: 'tomb', text: 'Walk up to the bag to loot it.' });
- this._openLootPanel(id); // still show contents so they know what's inside
- } else {
- this.net?.tombLoot(id);
- this._openLootPanel(id);
- }
- return;
- }
- }
-
- // 2) A resource node, mob, or NPC under the cursor → set it as the target
- // the loop walks to and interacts with (gather / attack / talk).
- const objHits = this._raycaster.intersectObject(this.objectGroup, true);
- for (const hp of objHits) {
- const ud = hp.object?.userData || {};
- if (ud.nodeId && this.nodeViews.has(ud.nodeId)) { this._setTarget('node', ud.nodeId); return; }
- if (ud.mobId && this.mobViews.has(ud.mobId)) { this._setTarget('mob', ud.mobId); return; }
- if (ud.npcId && this.npcViews.has(ud.npcId)) { this._setTarget('npc', ud.npcId); return; }
- if (ud.wheelId && this.wheelViews.has(ud.wheelId)) { this._setTarget('wheel', ud.wheelId); return; }
- }
-
- // 2b) In a PvP realm, a tap on another living player marks them as an attack
- // target the loop closes on and strikes (the server enforces range + safe zones).
- if (this.realm?.pvp) {
- const rigs = [];
- for (const [pid, pv] of this.players) if (pid !== this.myId && !pv.dead) rigs.push(pv.rig);
- if (rigs.length) {
- for (const h of this._raycaster.intersectObjects(rigs, true)) {
- const pid = this._playerIdOf(h.object);
- if (pid && this.players.has(pid)) { this._setTarget('player', pid); return; }
- }
- }
- }
-
- // 3) Ground pick: water / a shore spot is a cast intent; otherwise a walkable
- // tile is a click-to-walk move target.
- const tile = this._pickGroundTile();
- if (tile) {
- const onWater = this._waterTiles?.has(`${tile.tx},${tile.ty}`);
- const onSpot = (this.realm?.fishing || []).some((f) => f.tx === tile.tx && f.ty === tile.ty);
- if (onWater || onSpot) { this._attemptCast(); return; }
- if (this._isWalkable(tile.tx, tile.ty)) { this._target = { kind: 'tile', tx: tile.tx, ty: tile.ty }; this._interactAccum = 0; }
- }
- }
-
- // Set a click-to-interact target (node/mob/npc). Walking + the action itself
- // are serviced by the loop (_stepTowardTarget / _serviceInteraction).
- _setTarget(kind, id) {
- this._target = { kind, id };
- this._interactAccum = INTERACT_ACTION_MS; // act on the first adjacent frame
- }
-
- // Raycast the static realm geometry (ground + water + painted tiles) and turn
- // the first hit point into a tile index. Returns null if the ray missed.
- _pickGroundTile() {
- const hits = this._raycaster.intersectObject(this.staticGroup, true);
- if (!hits.length) return null;
- const p = hits[0].point;
- const c = (this.realm?.grid ?? 48) / 2;
- return { tx: Math.round(p.x / TILE + c - 0.5), ty: Math.round(p.z / TILE + c - 0.5) };
- }
-
- // ---------------------------------------------------------------- fishing
- // Cast a line. Mirrors the server's gates client-side for instant feedback
- // (adjacent to water, holding a rod) before sending the intent; the server
- // stays authoritative for the catch roll. The rod is auto-equipped from the
- // hotbar the same way the Cook/Eat actions resolve their requirements, so a
- // player never has to hunt for a slot to fish.
- _attemptCast() {
- const me = this._localView();
- const ps = this.net?.state?.players?.get(this.myId);
- if (!me || !ps || me.dead) return;
- if (!this._nearFishingSpot(ps.tx, ps.ty)) {
- this._toast({ kind: 'fish', text: 'Move next to the water to cast.' });
- return;
- }
- if (!this._ensureRodEquipped(ps)) {
- this._toast({ kind: 'tool', text: 'You need a fishing rod to cast.' });
- return;
- }
- this.net?.fish();
- this._spawnCast(ps.tx, ps.ty);
- }
-
- _nearFishingSpot(tx, ty) {
- for (const f of this.realm?.fishing || []) {
- if (Math.abs(tx - f.tx) <= 1 && Math.abs(ty - f.ty) <= 1) return true;
- }
- return false;
- }
-
- _hasRod(ps) {
- return ps.hotbar.some((s) => s.item === 'rod') || ps.inv.some((s) => s.item === 'rod');
- }
-
- // Make sure the rod is the active hotbar tool. Returns true if it already is or
- // we just equipped it; false if the player has no rod on the hotbar at all.
- _ensureRodEquipped(ps) {
- if (ps.hotbar[ps.activeSlot]?.item === 'rod') return true;
- for (let i = 0; i < ps.hotbar.length; i++) {
- if (ps.hotbar[i].item === 'rod') { this.net?.equip(i); return true; }
- }
- return false;
- }
-
- // World position of the water tile nearest (tx,ty) — where the bobber lands.
- _nearestWaterWorld(tx, ty) {
- let best = null, bd = Infinity;
- for (const r of this.realm?.water || []) {
- const cx = Math.max(r.x0, Math.min(tx, r.x1));
- const cy = Math.max(r.y0, Math.min(ty, r.y1));
- const dist = (cx - tx) ** 2 + (cy - ty) ** 2;
- if (dist < bd) { bd = dist; best = { tx: cx, ty: cy }; }
- }
- return best ? this._tileToWorld(best.tx, best.ty) : null;
- }
-
- // Spawn the cast visual: a line from the angler to a bobber floating on the
- // water, with an expanding ripple. Local-only and replaced on each new cast.
- _spawnCast(tx, ty) {
- this._clearCast();
- const w = this._nearestWaterWorld(tx, ty) || this._tileToWorld(tx, ty);
- const group = new Group();
-
- const baseY = 0.34;
- const bob = new Mesh(
- new SphereGeometry(0.12, 12, 10),
- new MeshStandardMaterial({ color: 0xff5a4d, emissive: 0x4a1009, emissiveIntensity: 0.5, roughness: 0.5 }),
- );
- bob.position.set(w.x, baseY, w.z);
- group.add(bob);
-
- const ring = new Mesh(
- new RingGeometry(0.16, 0.24, 22),
- new MeshBasicMaterial({ color: 0x9fe4ff, transparent: true, opacity: 0.6, side: DoubleSide }),
- );
- ring.rotation.x = -Math.PI / 2;
- ring.position.set(w.x, 0.27, w.z);
- group.add(ring);
-
- const lineGeo = new BufferGeometry();
- lineGeo.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 0], 3));
- const line = new Line(lineGeo, new LineBasicMaterial({ color: 0xeaf4ff, transparent: true, opacity: 0.7 }));
- group.add(line);
-
- this.objectGroup.add(group);
- this._cast = { group, bob, ring, line, lineGeo, baseY, start: performance.now(), resolved: false, resolvedAt: 0, caught: false };
- }
-
- // Per-frame cast animation: bob the float, loop the ripple, and keep the line
- // anchored to the angler's hands. After the server resolves the cast, play a
- // short bite splash (or quiet sink on a miss) then dispose.
- _tickCast(now) {
- const c = this._cast;
- if (!c) return;
- const t = (now - c.start) / 1000;
- c.bob.position.y = c.baseY + Math.sin(t * 5) * 0.04;
-
- if (c.resolved) {
- const since = now - c.resolvedAt;
- const k = Math.min(1, since / 280);
- c.ring.scale.setScalar(0.8 + k * (c.caught ? 2.8 : 1.4));
- c.ring.material.opacity = Math.max(0, 0.6 * (1 - k));
- if (since > 320) { this._clearCast(); return; }
- } else {
- const rp = (t % 0.9) / 0.9;
- c.ring.scale.setScalar(0.6 + rp * 1.6);
- c.ring.material.opacity = (1 - rp) * 0.55;
- // Safety net: if the result never arrives (e.g. a silently dropped cast),
- // reel the line in after a beat rather than leaving it dangling.
- if (now - c.start > 2400) { this._clearCast(); return; }
- }
-
- const me = this._localView();
- if (me) {
- const pos = c.lineGeo.attributes.position;
- pos.setXYZ(0, me.rig.position.x, (me.height || 1.6) * 0.85, me.rig.position.z);
- pos.setXYZ(1, c.bob.position.x, c.bob.position.y, c.bob.position.z);
- pos.needsUpdate = true;
- }
- }
-
- // Resolve the active cast from the authoritative result (a 'fish'/'full'
- // notice). `caught` greens the bobber and triggers a bigger bite splash.
- _resolveCast(caught) {
- const c = this._cast;
- if (!c || c.resolved) return;
- c.resolved = true;
- c.resolvedAt = performance.now();
- c.caught = !!caught;
- if (caught) c.bob.material.color.set(0x6ee787);
- }
-
- _clearCast() {
- const c = this._cast;
- if (!c) return;
- this.objectGroup.remove(c.group);
- c.group.traverse((o) => { o.geometry?.dispose?.(); o.material?.dispose?.(); });
- this._cast = null;
- }
-
- _openLootPanel(id) {
- this._lootTombId = id;
- const panel = this.hud.tombPanel;
- if (!panel) return;
- panel.hidden = false;
- requestAnimationFrame(() => panel.classList.add('kg-tomb-panel--in'));
- this._renderLootPanel();
- }
-
- _closeLootPanel() {
- this._lootTombId = null;
- const panel = this.hud.tombPanel;
- if (!panel) return;
- panel.classList.remove('kg-tomb-panel--in');
- setTimeout(() => { if (!this._lootTombId) panel.hidden = true; }, 240);
- }
-
- _renderLootPanel() {
- const panel = this.hud.tombPanel;
- const v = this._lootTombId ? this.tombViews.get(this._lootTombId) : null;
- if (!panel || !v) return;
- const tomb = v.tomb;
- this.hud.tombOwner.textContent = `${tomb.ownerName || 'someone'}’s bag`;
- const items = (tomb.items || []).filter((s) => s.item && s.qty > 0);
- const list = this.hud.tombItems;
- list.innerHTML = '';
- if (!items.length) {
- const empty = document.createElement('div');
- empty.className = 'kg-tomb-empty';
- empty.textContent = 'This bag is empty.';
- list.appendChild(empty);
- this.hud.tombTake.disabled = true;
- } else {
- for (const s of items) {
- const row = document.createElement('div');
- row.className = 'kg-tomb-item';
- row.innerHTML =
- `<span class="kg-tomb-chip" style="--chip:${itemColor(s.item)}"></span>` +
- `<span class="kg-tomb-iname">${itemLabel(s.item)}</span>` +
- `<span class="kg-tomb-iqty">×${s.qty}</span>`;
- list.appendChild(row);
- }
- this.hud.tombTake.disabled = false;
- }
- this._updateTombPanelTtl();
- }
-
- _updateTombPanelTtl() {
- const v = this._lootTombId ? this.tombViews.get(this._lootTombId) : null;
- if (!v || !this.hud.tombTtl) return;
- const ms = Math.max(0, v.tomb.expiresAt - Date.now());
- this.hud.tombTtl.textContent = `expires in ${Math.ceil(ms / 1000)}s`;
- }
-
- // ---------------------------------------------------------------- banking / notices
- // Bank contents arrive here and feed the HUD's bank panel (the "Stored" column).
- _onBank(payload) {
- this._bank = payload?.slots || [];
- this.q?.setBank(this._bank.map((s) => ({ item: s.item, qty: s.qty })));
- }
-
- // Authoritative quest snapshot: drive the panel, refresh Aldric's "!"/"?"
- // markers, and open the NPC dialog when the snapshot answers a talk.
- _onQuests(snapshot) {
- this.quests = snapshot || null;
- this.q?.setQuests(this.quests);
- this._refreshNpcMarkers();
- if (snapshot?.npc && this.npcViews.has(snapshot.npc)) {
- this.q?.openNpc(this.npcViews.get(snapshot.npc).npc.name);
- }
- }
-
- // Server notices route here so a few carry an extra flourish beyond the
- // toast: a successful bite reports "+N HP", which we echo as a green flash
- // on the local nameplate so the heal reads on the avatar too.
- _onNotice(n) {
- this._toast(n);
- if (n?.kind === 'eat' && /^\+\d/.test(n.text || '')) this._healFlash();
- // Resolve the in-water cast from the authoritative result: a 'fish' notice is
- // the catch/miss verdict; 'full' (or a tool gate) ends a cast that can't land.
- if (n?.kind === 'fish') this._resolveCast(/caught/i.test(n.text || ''));
- else if ((n?.kind === 'full' || n?.kind === 'tool') && this._cast) this._resolveCast(false);
- }
-
- _toast({ kind, text, href, hrefText }) {
- if (!text) return;
- const el = document.createElement('div');
- el.className = 'kg-toast kg-toast--' + (kind || 'info');
- el.textContent = text;
- if (href) {
- el.appendChild(document.createTextNode(' '));
- const a = document.createElement('a');
- a.className = 'kg-toast-link';
- a.href = href;
- a.target = '_blank';
- a.rel = 'noopener';
- a.textContent = hrefText || 'view ↗';
- el.appendChild(a);
- }
- this.hud.toasts.appendChild(el);
- requestAnimationFrame(() => el.classList.add('kg-toast--in'));
- // A toast carrying a link lingers longer so it can actually be clicked.
- const ttl = href ? 7000 : 2600;
- setTimeout(() => { el.classList.remove('kg-toast--in'); setTimeout(() => el.remove(), 300); }, ttl);
- }
-
- // ---------------------------------------------------------------- cooking & food
- // Contextual action bar. The client surfaces the two world actions it supports
- // today — Cook (at a Roast Pit, with raw fish) and Eat (when hurt and carrying
- // food) — only when they're actually possible, reading the local player's live
- // server state each frame. Both drive the server's cook/consume intents, so a
- // future full inventory UI can reuse the exact same path.
- _updateActions() {
- const bar = this.hud.actions;
- if (!bar) return;
- const me = this._localView();
- const ps = this.net?.state?.players?.get(this.myId);
- if (!me || !ps || me.dead) { if (!bar.hidden) bar.hidden = true; return; }
-
- // Cook: on/next to a Roast Pit AND carrying raw fish.
- const fishN = this._countItem(ps, 'fish');
- const showCook = fishN > 0 && this._nearCookingTile(ps.tx, ps.ty);
- this._toggleAction(this.hud.cookBtn, showCook, `Cook fish (${fishN})`);
-
- // Eat: below max HP AND carrying something edible.
- const edible = this._findEdibleSlot(ps);
- const showEat = ps.hp < ps.maxHp && !!edible;
- this._eatRef = showEat ? edible.ref : null;
- const eatLabel = showEat
- ? `Eat ${edible.label} (+${edible.healEst} HP, ${edible.count} left)`
- : 'Eat';
- this._toggleAction(this.hud.eatBtn, showEat, eatLabel);
-
- // Cast: standing beside fishable water. The rod auto-equips on cast, so the
- // button just reflects whether the player owns one — when they don't, it
- // reads "Need a rod" and explains on click (casting is gated, not silent).
- const showCast = this._nearFishingSpot(ps.tx, ps.ty);
- const hasRod = this._hasRod(ps);
- this._toggleAction(this.hud.castBtn, showCast, hasRod ? 'Cast line 🎣' : 'Need a rod 🎣');
- if (this.hud.castBtn) this.hud.castBtn.classList.toggle('kg-action--muted', showCast && !hasRod);
-
- // Pick up: standing beside a structure I placed (Task 07). Routes to /pickup;
- // a locked structure tells the player to /unlock first (server enforces it).
- const mine = this._adjacentOwnedStructure();
- const showPickup = !!mine;
- this._toggleAction(this.hud.pickupBtn, showPickup, mine ? `Pick up ${STRUCTURE_META[mine.kind]?.label || mine.kind}${mine.locked ? ' 🔒' : ''}` : 'Pick up');
-
- bar.hidden = !(showCook || showEat || showCast || showPickup);
- }
-
- _toggleAction(btn, show, label) {
- if (!btn) return;
- if (btn.hidden === show) btn.hidden = !show;
- if (show) {
- const lbl = btn.querySelector('.kg-action-lbl');
- if (lbl && lbl.textContent !== label) lbl.textContent = label;
- }
- }
-
- _nearCookingTile(tx, ty) {
- for (const t of this.realm?.cooking || []) {
- if (Math.abs(tx - t.tx) <= 1 && Math.abs(ty - t.ty) <= 1) return true;
- }
- return false;
- }
-
- _countItem(ps, item) {
- let n = 0;
- for (const s of ps.inv) if (s.item === item) n += s.qty;
- for (const s of ps.hotbar) if (s.item === item) n += s.qty;
- return n;
- }
-
- // The first edible slot — hotbar before backpack — with the server-resolvable
- // {zone,i} ref, a friendly label, how many of that food the player holds, and
- // an estimated heal value so the Eat button can show "+N HP" without a server
- // round-trip (mirrors the scaledHeal formula in items.js).
- _findEdibleSlot(ps) {
- const reg = this.items || {};
- const cookLvl = ps.cooking || 1;
- const scan = (arr, zone) => {
- for (let i = 0; i < arr.length; i++) {
- const it = arr[i].item;
- if (!it || !EDIBLE.has(it)) continue;
- const baseHeal = reg[it]?.heal || 0;
- const healEst = clientScaledHeal(it, baseHeal, cookLvl);
- return { ref: { zone, i }, item: it, label: FOOD_LABEL[it] || 'food', count: this._countItem(ps, it), healEst };
- }
- return null;
- };
- return scan(ps.hotbar, 'hotbar') || scan(ps.inv, 'inv');
- }
-
- // A successful cook ('cooked' event) — pulse the Cook button so the action
- // reads as landed; the honest result (cooked/burned counts) arrives as a toast.
- _onCooked() {
- const btn = this.hud.cookBtn;
- if (!btn || btn.hidden) return;
- btn.classList.remove('kg-action--pulse');
- void btn.offsetWidth; // restart the animation
- btn.classList.add('kg-action--pulse');
- }
-
- // Flash the local nameplate green when the player eats, so the heal reads on
- // the avatar, not just in a toast.
- _healFlash() {
- const me = this._localView();
- if (!me?.label) return;
- me.label.classList.remove('kg-heal');
- void me.label.offsetWidth;
- me.label.classList.add('kg-heal');
- setTimeout(() => me.label?.classList.remove('kg-heal'), 700);
- }
-
- // ---------------------------------------------------------------- skills
- // The server replies to a 'skills' request with the local player's own XP
- // detail (raw XP is never broadcast to peers). Cache the snapshot and, when
- // the panel is open, re-render its bars.
- _onSkills(payload) {
- this._skills = payload && payload.skills ? payload : null;
- if (this._skillsOpen) this._renderSkills();
- }
-
- // Server pushes xpgain after every XP grant. Delta-patch the cached snapshot so
- // the panel stays live without a round-trip, then show a "+N XP" float chip.
- _onXpGain({ skill, amount, xp, level, levelXp, nextXp } = {}) {
- const meta = SKILL_META[skill];
- if (!meta || !Number.isFinite(amount)) return;
- if (this._skills?.skills?.[skill]) {
- const s = this._skills.skills[skill];
- s.xp = xp; s.level = level; s.levelXp = levelXp; s.nextXp = nextXp ?? null;
- } else if (!this._skills) {
- // Seed a minimal snapshot so the panel paints immediately on first open.
- this._skills = {
- cap: 99, total: null, average: null,
- skills: Object.fromEntries(SKILL_ORDER.map((sk) => [
- sk, { level: 1, xp: 0, levelXp: 0, nextXp: null },
- ])),
- };
- this._skills.skills[skill] = { xp, level, levelXp, nextXp: nextXp ?? null };
- }
- if (this._skillsOpen) this._renderSkills();
- this._showXpDrop(meta, amount);
- }
-
- // Float a "+N XP" chip near the Skills button. Rapid same-skill hits within 400ms
- // merge into the live chip instead of spawning a new one.
- _showXpDrop(meta, amount) {
- if (!this.hud.xpdrops) return;
- if (!this._xpDropQueue) this._xpDropQueue = new Map();
- const key = meta.label;
- const now = Date.now();
- const pending = this._xpDropQueue.get(key);
- if (pending && now - pending.ts < 400) {
- pending.amount += amount;
- pending.ts = now;
- if (pending.el) pending.el.textContent = `+${fmtXp(pending.amount)} XP`;
- return;
- }
- const el = document.createElement('div');
- el.className = 'kg-xpdrop';
- el.style.setProperty('--kg-hue', meta.hue);
- el.textContent = `+${fmtXp(amount)} XP`;
- this.hud.xpdrops.appendChild(el);
- const entry = { amount, ts: now, el };
- this._xpDropQueue.set(key, entry);
- requestAnimationFrame(() => el.classList.add('kg-xpdrop--in'));
- setTimeout(() => {
- this._xpDropQueue?.delete(key);
- entry.el = null;
- el.classList.remove('kg-xpdrop--in');
- setTimeout(() => el.remove(), 350);
- }, 1200);
- }
-
- // A real server 'levelup' event: patch the cached snapshot level and celebrate.
- // No longer needs a round-trip skills() request — xpgain keeps bars current.
- _onLevelup({ skill, level } = {}) {
- const meta = SKILL_META[skill];
- if (!meta || !Number.isFinite(level)) return;
- if (this._skills?.skills?.[skill]) this._skills.skills[skill].level = level;
- if (this._skillsOpen) this._renderSkills();
-
- const cap = this._skills?.cap || 99;
- const maxed = level >= cap;
- const el = document.createElement('div');
- el.className = 'kg-levelup';
- el.style.setProperty('--kg-hue', meta.hue);
- el.innerHTML =
- `<span class="kg-levelup-ico"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="${meta.icon}"/></svg></span>` +
- `<span class="kg-levelup-txt">` +
- `<span class="kg-levelup-kicker">${maxed ? 'Skill mastered' : 'Level up'}</span>` +
- `<span class="kg-levelup-main">${meta.label} <b>${level}</b></span>` +
- `</span>`;
- this.hud.levelups?.appendChild(el);
- requestAnimationFrame(() => el.classList.add('kg-levelup--in'));
- setTimeout(() => { el.classList.remove('kg-levelup--in'); setTimeout(() => el.remove(), 420); }, 3400);
- }
-
- // Open/close the skills drawer. Panel is event-driven via xpgain — one snapshot
- // request on open seeds it; no poll needed.
- _toggleSkills(force) {
- const next = force === undefined ? !this._skillsOpen : !!force;
- if (next === this._skillsOpen) return;
- if (next && this.phase !== 'world') return;
- this._skillsOpen = next;
-
- const panel = this.hud.skillsPanel;
- this.hud.skillsBtn?.setAttribute('aria-expanded', String(next));
- if (!panel) return;
-
- if (next) {
- panel.hidden = false;
- void panel.offsetWidth;
- panel.classList.add('kg-skills--open');
- this._renderSkills();
- this.net?.skills();
- this.hud.skillsClose?.focus();
- } else {
- panel.classList.remove('kg-skills--open');
- if (document.activeElement && panel.contains(document.activeElement)) this.hud.skillsBtn?.focus();
- setTimeout(() => { if (!this._skillsOpen) panel.hidden = true; }, 220);
- }
- }
-
- _renderSkills() {
- const list = this.hud.skillsList;
- if (!list) return;
- const data = this._skills;
- if (!data) {
- list.setAttribute('aria-busy', 'true');
- list.innerHTML = '<li class="kg-skills-loading">Loading your progress…</li>';
- return;
- }
- list.setAttribute('aria-busy', 'false');
- const cap = data.cap || 99;
- if (this.hud.skillsCap) this.hud.skillsCap.textContent = String(cap);
- if (this.hud.skillsTotal) this.hud.skillsTotal.textContent = data.total != null ? String(data.total) : '—';
- if (this.hud.skillsAvg) this.hud.skillsAvg.textContent = data.average != null ? data.average.toFixed(1) : '—';
-
- const rows = [];
- for (const skill of SKILL_ORDER) {
- const s = data.skills[skill];
- const meta = SKILL_META[skill];
- if (!s || !meta) continue;
- const maxed = s.level >= cap;
- const fresh = s.level <= 1 && (s.xp | 0) === 0;
- let pct, xpLabel, aria;
- if (maxed) {
- pct = 1;
- xpLabel = 'Mastered';
- aria = `${meta.label} mastered, level ${cap}`;
- } else {
- const span = Math.max(1, s.nextXp - s.levelXp);
- const into = Math.max(0, Math.min(span, s.xp - s.levelXp));
- pct = into / span;
- xpLabel = `${fmtXp(into)} / ${fmtXp(span)} XP`;
- aria = `${meta.label} level ${s.level}, ${Math.round(pct * 100)}% to level ${s.level + 1}`;
- }
- const cls = 'kg-skill' + (maxed ? ' kg-skill--max' : '') + (fresh ? ' kg-skill--fresh' : '');
- rows.push(
- `<li class="${cls}" data-skill="${skill}" style="--kg-hue:${meta.hue}" aria-label="${aria}">` +
- `<span class="kg-skill-ico"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="${meta.icon}"/></svg></span>` +
- `<span class="kg-skill-main">` +
- `<span class="kg-skill-top">` +
- `<span class="kg-skill-name">${meta.label}</span>` +
- `<span class="kg-skill-lvl">${maxed ? '<em>MAX</em>' : ''}<b>${s.level}</b><i>/${cap}</i></span>` +
- `</span>` +
- `<span class="kg-skill-bar"><i style="width:${(pct * 100).toFixed(1)}%"></i></span>` +
- `<span class="kg-skill-xp">${xpLabel}</span>` +
- `</span>` +
- `</li>`,
- );
- }
- list.innerHTML = rows.join('');
- }
-
- // ---------------------------------------------------------------- input
- _bindInput() {
- window.addEventListener('keydown', (e) => {
- if (this._typing()) return;
- const k = e.key.toLowerCase();
- // iso-controls (capture-phase) owns all discrete actions: hotbar 1-6/0,
- // I, Q, M, B, C, F, K, R. This listener only handles keys it passes through.
- //
- // Skills drawer: Escape closes it. iso-controls intercepts Escape only for
- // its own surfaces; the skills drawer lives here in iso-game.
- if (k === 'escape' && this._skillsOpen) { e.preventDefault(); this._toggleSkills(false); return; }
- // Escape cancels an in-progress build placement before closing panels.
- if (k === 'escape' && this._buildMode) { e.preventDefault(); this._exitBuildMode(); return; }
- // Escape closes game-hud panels (quests/bank/NPC/build/shop/market).
- if (k === 'escape') { this.q?.closeQuests(); this.q?.closeBank(); this.q?.closeNpc(); this.q?.closeBuild?.(); this.q?.closeShop?.(); this.q?.closeMarket?.(); }
- // Enter opens chat. iso-controls passes Enter through when no surface is open.
- if (this.phase === 'world' && k === 'enter') { e.preventDefault(); this._openChat(); return; }
- this.keys.add(k);
- });
- window.addEventListener('keyup', (e) => this.keys.delete(e.key.toLowerCase()));
- window.addEventListener('blur', () => this.keys.clear());
-
- this.canvas.addEventListener('pointerdown', (e) => {
- this._dragging = true; this._lastPtr = { x: e.clientX, y: e.clientY };
- this._hoverPtr = { x: e.clientX, y: e.clientY }; // build ghost follows the press point
- this._downAt = performance.now(); this._dragMoved = 0;
- });
- // Right-click cancels build placement (the desktop counterpart to the banner's
- // Cancel button on touch). Only swallow the context menu while building.
- this.canvas.addEventListener('contextmenu', (e) => {
- if (this._buildMode) { e.preventDefault(); this._exitBuildMode(); }
- });
- window.addEventListener('pointerup', (e) => {
- const wasDragging = this._dragging;
- this._dragging = false;
- // A short, near-stationary press over the canvas is a tap → world pick
- // (click an adjacent tombstone to loot it). A drag rotated the camera.
- if (!wasDragging || e.target !== this.canvas) return;
- if (performance.now() - this._downAt < 300 && this._dragMoved < 7) {
- this._onTap(e.clientX, e.clientY);
- }
- });
- window.addEventListener('pointermove', (e) => {
- // Track the cursor always (even without a drag) so the build ghost can
- // follow it on desktop hover.
- this._hoverPtr = { x: e.clientX, y: e.clientY };
- if (!this._dragging) return;
- const dx = e.clientX - this._lastPtr.x, dy = e.clientY - this._lastPtr.y;
- this._lastPtr = { x: e.clientX, y: e.clientY };
- this._dragMoved += Math.abs(dx) + Math.abs(dy);
- this.camYaw -= dx * 0.005;
- this.camPitch = Math.max(0.45, Math.min(1.25, this.camPitch + dy * 0.004));
- });
- this.canvas.addEventListener('wheel', (e) => {
- e.preventDefault();
- this.camDist = Math.max(7, Math.min(30, this.camDist * (e.deltaY > 0 ? 1.1 : 0.9)));
- }, { passive: false });
- }
-
- _typing() {
- const a = document.activeElement;
- return a && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA');
- }
-
- _initJoystick() {
- const zone = document.getElementById('kg-joystick');
- if (!zone || this._nipple) return;
- if (!matchMedia('(pointer: coarse)').matches) { zone.style.display = 'none'; return; }
- this._nipple = nipplejs.create({ zone, mode: 'static', position: { left: '64px', bottom: '76px' }, color: '#9aa0ac', size: 110 });
- this._nipple.on('move', (_e, d) => {
- const f = Math.min(1, d.force);
- this._joy = { x: Math.cos(d.angle.radian) * f, z: -Math.sin(d.angle.radian) * f };
- });
- this._nipple.on('end', () => { this._joy = null; });
- }
-
- // Movement intent (keys + joystick) → a camera-relative world direction →
- // the nearest 8-way tile delta, sent as one authoritative step per cadence.
- _attemptStep() {
- const me = this._localView();
- if (!me || me.dead || !this.realm) return;
-
- let f = 0, r = 0;
- if (this.keys.has('w') || this.keys.has('arrowup')) f += 1;
- if (this.keys.has('s') || this.keys.has('arrowdown')) f -= 1;
- if (this.keys.has('d') || this.keys.has('arrowright')) r += 1;
- if (this.keys.has('a') || this.keys.has('arrowleft')) r -= 1;
- if (this._joy) { f += -this._joy.z; r += this._joy.x; }
- // No manual input: walk toward a click-to-interact / move target instead.
- if (!f && !r) { if (this._target) this._stepTowardTarget(me); return; }
- this._target = null; // manual movement overrides any click target
-
- // Camera basis on the ground plane. forward = camera→target.
- const fwd = { x: -Math.sin(this.camYaw), z: -Math.cos(this.camYaw) };
- const right = { x: Math.cos(this.camYaw), z: -Math.sin(this.camYaw) };
- const wx = right.x * r + fwd.x * f;
- const wz = right.z * r + fwd.z * f;
- if (Math.abs(wx) < 1e-3 && Math.abs(wz) < 1e-3) return;
-
- const dtx = wx > 0.4 ? 1 : wx < -0.4 ? -1 : 0;
- const dty = wz > 0.4 ? 1 : wz < -0.4 ? -1 : 0;
- if (!dtx && !dty) return;
-
- const tx = me.tx + dtx, ty = me.ty + dty;
- const yaw = Math.atan2(wx, wz);
- if (!this._isWalkable(tx, ty)) {
- // Try sliding along whichever axis is clear so we hug walls instead of
- // sticking — server still validates the final step.
- if (dtx && this._isWalkable(me.tx + dtx, me.ty)) return this._sendStep(me.tx + dtx, me.ty, yaw);
- if (dty && this._isWalkable(me.tx, me.ty + dty)) return this._sendStep(me.tx, me.ty + dty, yaw);
- me.yaw = yaw; // still face the way we're pushing
- return;
- }
- this._sendStep(tx, ty, yaw);
- }
-
- _sendStep(tx, ty, yaw) {
- this.net?.step(tx, ty, yaw);
- }
-
- // The tile of the current target (a node/mob/npc view, or a plain move tile).
- // Returns null — and clears the target — once the target is gone (node
- // depleted, mob dead, view removed), so the loop never chases a ghost.
- _targetTile() {
- const t = this._target;
- if (!t) return null;
- if (t.kind === 'tile') return { tx: t.tx, ty: t.ty };
- if (t.kind === 'node') { const v = this.nodeViews.get(t.id); if (!v || v.node.depleted) return null; return { tx: v.node.tx, ty: v.node.ty }; }
- if (t.kind === 'mob') { const v = this.mobViews.get(t.id); if (!v || v.mob.dead) return null; return { tx: v.mob.tx, ty: v.mob.ty }; }
- if (t.kind === 'player') { const v = this.players.get(t.id); if (!v || v.dead) return null; return { tx: v.tx, ty: v.ty }; }
- if (t.kind === 'npc') { const v = this.npcViews.get(t.id); if (!v) return null; return { tx: v.npc.tx, ty: v.npc.ty }; }
- if (t.kind === 'wheel') { const v = this.wheelViews.get(t.id); if (!v) return null; return { tx: v.landmark.tx, ty: v.landmark.ty }; }
- return null;
- }
-
- // One greedy 8-way step toward the current target. For interact targets we
- // stop once adjacent (the action fires from _serviceInteraction); for a plain
- // move tile we stop on arrival.
- _stepTowardTarget(me) {
- const t = this._targetTile();
- if (!t) { this._target = null; return; }
- const interact = this._target.kind !== 'tile';
- const adx = Math.abs(me.tx - t.tx), ady = Math.abs(me.ty - t.ty);
- if (interact ? (adx <= 1 && ady <= 1) : (me.tx === t.tx && me.ty === t.ty)) {
- if (!interact) this._target = null; // arrived at a move tile
- return;
- }
- const dtx = Math.sign(t.tx - me.tx);
- const dty = Math.sign(t.ty - me.ty);
- const yaw = Math.atan2(dtx, dty);
- // Prefer the diagonal, then slide along whichever axis is clear; if fully
- // boxed in, give up on the target rather than jitter in place.
- if (dtx && dty && this._isWalkable(me.tx + dtx, me.ty + dty) &&
- (this._isWalkable(me.tx + dtx, me.ty) || this._isWalkable(me.tx, me.ty + dty))) {
- this._sendStep(me.tx + dtx, me.ty + dty, yaw);
- } else if (dtx && this._isWalkable(me.tx + dtx, me.ty)) {
- this._sendStep(me.tx + dtx, me.ty, yaw);
- } else if (dty && this._isWalkable(me.tx, me.ty + dty)) {
- this._sendStep(me.tx, me.ty + dty, yaw);
- } else if (dtx && dty && this._isWalkable(me.tx + dtx, me.ty + dty)) {
- this._sendStep(me.tx + dtx, me.ty + dty, yaw);
- } else {
- this._target = null; // boxed in — drop the target so we don't spin
- }
- }
-
- // When adjacent to an interact target, perform the action on the right cadence:
- // talk once (NPC), or repeatedly gather/attack (auto-equipping the matching
- // tool) until the node depletes / mob dies. Driven each frame from the loop.
- _serviceInteraction(dt) {
- const t = this._target;
- if (!t || t.kind === 'tile') return;
- const me = this._localView();
- const ps = this.net?.state?.players?.get(this.myId);
- if (!me || !ps || me.dead) return;
- const tile = this._targetTile();
- if (!tile) { this._target = null; return; }
- if (Math.abs(me.tx - tile.tx) > 1 || Math.abs(me.ty - tile.ty) > 1) return; // not there yet
-
- if (t.kind === 'npc') { this.net?.npcTalk(t.id); this._target = null; return; }
- if (t.kind === 'wheel') { this._openSpinWheel(); this._target = null; return; }
-
- this._interactAccum += dt * 1000;
- if (this._interactAccum < INTERACT_ACTION_MS) return;
- this._interactAccum = 0;
- if (t.kind === 'node') {
- const v = this.nodeViews.get(t.id);
- if (!v || v.node.depleted) { this._target = null; return; }
- this._equipForGather(ps, v.node.kind);
- this.net?.gather(t.id);
- } else if (t.kind === 'mob') {
- const v = this.mobViews.get(t.id);
- if (!v || v.mob.dead) { this._target = null; return; }
- this._equipTool(ps, 'sword');
- this.net?.attack(t.id);
- } else if (t.kind === 'player') {
- const v = this.players.get(t.id);
- if (!v || v.dead) { this._target = null; return; }
- this._equipTool(ps, 'sword');
- this.net?.attack(t.id); // PvP — server validates realm/range/safe-zone
- }
- }
-
- // Auto-equip the tool a node kind needs (axe for trees, pickaxe for rock/coal),
- // mirroring the rod auto-equip the fishing flow uses, so a click just works.
- _equipForGather(ps, kind) {
- this._equipTool(ps, kind === 'tree' ? 'axe' : 'pickaxe');
- }
- _equipTool(ps, tool) {
- if (ps.hotbar[ps.activeSlot]?.item === tool) return;
- for (let i = 0; i < ps.hotbar.length; i++) {
- if (ps.hotbar[i].item === tool) { this.net?.equip(i); return; }
- }
- }
-
- // Client-side walkability mirror of the server (bounds + blocked + live node/
- // mob occupancy) so we don't spam steps the server will reject.
- _isWalkable(tx, ty) {
- const grid = this.realm?.grid ?? 48;
- if (tx < 0 || ty < 0 || tx >= grid || ty >= grid) return false;
- for (const b of this.realm.blocked || []) {
- if (tx >= b.x0 && tx <= b.x1 && ty >= b.y0 && ty <= b.y1) return false;
- }
- for (const [, v] of this.nodeViews) {
- if (!v.node.depleted && v.node.tx === tx && v.node.ty === ty) return false;
- }
- for (const [, v] of this.mobViews) {
- if (!v.mob.dead && v.mob.tx === tx && v.mob.ty === ty) return false;
- }
- for (const [, v] of this.npcViews) {
- if (v.npc.tx === tx && v.npc.ty === ty) return false;
- }
- return true;
- }
-
- // ---------------------------------------------------------------- HUD
- _bindHud() {
- this.hud = {
- start: document.getElementById('kg-start'),
- startBtn: document.getElementById('kg-start-btn'),
- nameInput: document.getElementById('kg-name'),
- offline: document.getElementById('kg-offline'),
- offlineMsg: document.getElementById('kg-offline-msg'),
- retryBtn: document.getElementById('kg-retry'),
- serversList: document.getElementById('kg-servers-list'),
- topbar: document.getElementById('kg-topbar'),
- realm: document.getElementById('kg-realm'),
- server: document.getElementById('kg-server'),
- online: document.getElementById('kg-online'),
- status: document.getElementById('kg-status'),
- toasts: document.getElementById('kg-toasts'),
- hint: document.getElementById('kg-hint'),
- skillsBtn: document.getElementById('kg-skills-btn'),
- skillsPanel: document.getElementById('kg-skills'),
- skillsClose: document.getElementById('kg-skills-close'),
- skillsList: document.getElementById('kg-skills-list'),
- skillsTotal: document.getElementById('kg-skills-total'),
- skillsAvg: document.getElementById('kg-skills-avg'),
- skillsCap: document.getElementById('kg-skills-cap'),
- levelups: document.getElementById('kg-levelups'),
- xpdrops: document.getElementById('kg-xpdrops'),
- actions: document.getElementById('kg-actions'),
- cookBtn: document.getElementById('kg-cook'),
- eatBtn: document.getElementById('kg-eat'),
- castBtn: document.getElementById('kg-cast'),
- pickupBtn: document.getElementById('kg-pickup'),
- chat: document.getElementById('kg-chat'),
- chatLog: document.getElementById('kg-chat-log'),
- chatForm: document.getElementById('kg-chat-form'),
- chatInput: document.getElementById('kg-chat-input'),
- chatHint: document.getElementById('kg-chat-hint'),
- chatCounter: document.getElementById('kg-chat-counter'),
- chatMutedBtn: document.getElementById('kg-chat-muted-btn'),
- chatMutedN: document.getElementById('kg-chat-muted-n'),
- chatMutedList: document.getElementById('kg-chat-muted'),
- death: document.getElementById('kg-death'),
- deathMsg: document.getElementById('kg-death-msg'),
- deathCount: document.getElementById('kg-death-count'),
- tombPanel: document.getElementById('kg-tomb-panel'),
- tombOwner: document.getElementById('kg-tomb-owner'),
- tombItems: document.getElementById('kg-tomb-items'),
- tombTtl: document.getElementById('kg-tomb-ttl'),
- tombTake: document.getElementById('kg-tomb-take'),
- tombClose: document.getElementById('kg-tomb-close'),
- mount: document.getElementById('kg-mount'),
- mountName: document.getElementById('kg-mount-name'),
- dismountBtn: document.getElementById('kg-dismount'),
- };
- const savedName = localStorage.getItem('cc-name') || '';
- if (savedName) this.hud.nameInput.value = savedName;
- this.hud.nameInput.placeholder = 'guest-' + Math.random().toString(36).slice(2, 6);
-
- // World-instance picker (Task 23): render the live roster + populations and
- // remember the player's choice. Polling starts/stops with the start screen.
- this._initServerPicker();
-
- const begin = () => {
- const name = (this.hud.nameInput.value || this.hud.nameInput.placeholder).trim().slice(0, 24);
- localStorage.setItem('cc-name', name);
- this.start(name);
- };
- this.hud.startBtn.addEventListener('click', begin);
- this.hud.nameInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') begin(); });
- this.hud.retryBtn.addEventListener('click', () => {
- this._setHudPhase('connecting');
- this.phase = 'connecting';
- this.net ? this.net.retry() : this.start(this.hud.nameInput.value || this.hud.nameInput.placeholder);
- });
-
- this.hud.skillsBtn?.addEventListener('click', () => this._toggleSkills());
- this.hud.skillsClose?.addEventListener('click', () => this._toggleSkills(false));
-
- // Death-bag recovery panel: "Take all" re-sends tombLoot (useful once the
- // pack has space again); the X just dismisses the panel (the bag stays).
- this.hud.tombTake?.addEventListener('click', () => { if (this._lootTombId) this.net?.tombLoot(this._lootTombId); });
- this.hud.tombClose?.addEventListener('click', () => this._closeLootPanel());
-
- // Contextual action bar: cook a batch of fish, or eat the first food slot.
- this.hud.cookBtn?.addEventListener('click', () => this.net?.cook(5));
- this.hud.eatBtn?.addEventListener('click', () => { if (this._eatRef) this.net?.consume(this._eatRef); });
- this.hud.dismountBtn?.addEventListener('click', () => this.net?.dismount());
- this.hud.castBtn?.addEventListener('click', () => this._attemptCast());
- // Pick up a structure I'm standing beside — the server action is /pickup.
- this.hud.pickupBtn?.addEventListener('click', () => this.net?.command('/pickup'));
-
- this._bindChat();
- this._setHudPhase('start');
- }
-
- _setHudPhase(phase) {
- this.hud.start.hidden = phase !== 'start';
- this.hud.offline.hidden = phase !== 'offline';
- // Poll live server populations only while the picker is on screen.
- if (phase === 'start') this._startServerPolling();
- else this._stopServerPolling();
- this.hud.topbar.hidden = !(phase === 'world' || phase === 'connecting');
- this.hud.hint.hidden = phase !== 'world';
- // The contextual action bar only makes sense in-world; hide it elsewhere so
- // a reconnect/offline screen never shows stale Cook/Eat buttons.
- if (this.hud.actions && phase !== 'world') this.hud.actions.hidden = true;
- if (this.hud.mount && phase !== 'world') this.hud.mount.hidden = true;
- // The skills toggle is only meaningful once in the world; leaving it closes
- // the panel so a reconnect/offline screen never shows a stale drawer.
- if (phase !== 'world') this._toggleSkills(false);
- // World chat shows only in-world. Reveal the panel on entry; on exit close
- // and hide it so the start/offline screens stay clean.
- if (this.hud.chat) {
- this.hud.chat.hidden = phase !== 'world';
- if (phase !== 'world') this._closeChat(true);
- }
- // Death overlay + bag panel are world-only; clear them on any exit so a
- // reconnect never strands a respawn countdown or an orphaned bag panel.
- if (phase !== 'world') {
- this._deathInfo = null; this._deathShown = false;
- if (this.hud.death) this.hud.death.hidden = true;
- this._closeLootPanel();
- }
- document.body.classList.toggle('kg-loading-cursor', phase === 'connecting');
- }
-
- // ---------------------------------------------------------------- chat
- // World chat: send/receive realm-wide messages, route `/commands` through the
- // server command system, and mute players client-side. The panel is collapsed
- // (click-through) until focused so it never blocks the world.
-
- // Storage key for the mute list — scoped to the stable account id (Task 16) so
- // each account keeps its own block list, matching how keybindings persist.
- _mutedKey() {
- return 'kg-muted:' + (this._playerId() || '_');
- }
-
- _loadMuted() {
- try {
- const key = this._mutedKey();
- let raw = localStorage.getItem(key);
- // Migrate the pre-account global list (kg-muted) into this account once.
- if (raw == null) {
- const legacy = localStorage.getItem('kg-muted');
- if (legacy != null) { raw = legacy; localStorage.setItem(key, legacy); localStorage.removeItem('kg-muted'); }
- }
- const parsed = JSON.parse(raw || '[]');
- return new Set(Array.isArray(parsed) ? parsed.filter((n) => typeof n === 'string') : []);
- } catch { return new Set(); }
- }
-
- _saveMuted() {
- try { localStorage.setItem(this._mutedKey(), JSON.stringify([...this.muted])); } catch { /* storage may be unavailable */ }
- }
-
- _bindChat() {
- if (!this.hud.chat) return;
- this.hud.chatForm?.addEventListener('submit', (e) => { e.preventDefault(); this._sendChat(); });
- // Focusing the input expands the panel; blurring with nothing typed collapses it.
- this.hud.chatInput?.addEventListener('focus', () => this._openChat());
- this.hud.chatInput?.addEventListener('blur', (e) => {
- // Stay open if focus moved to another chat control (a sender name, the
- // Muted button, the mute menu) — only collapse when focus truly leaves.
- if (this.hud.chat?.contains(e.relatedTarget)) return;
- if (!this.hud.chatInput.value.trim()) this._closeChat();
- });
- // Slash-command autocomplete + character counter: refresh on every edit.
- // Also reset the history cursor so a manual edit breaks out of recall mode.
- this.hud.chatInput?.addEventListener('input', () => {
- this._chatHistoryCursor = -1;
- this._refreshCmdHint();
- this._updateChatCounter();
- });
- this.hud.chatInput?.addEventListener('keydown', (e) => {
- // Esc: first dismiss an open command hint, otherwise clear + close chat.
- if (e.key === 'Escape') {
- e.preventDefault();
- if (this._cmdHint) this._hideCmdHint();
- else { this.hud.chatInput.value = ''; this._closeChat(); }
- e.stopPropagation();
- return;
- }
- // When the hint is open, the arrow/Tab keys drive it instead of the field.
- if (this._cmdHint) {
- if (e.key === 'ArrowDown') { e.preventDefault(); this._moveCmdHint(1); e.stopPropagation(); return; }
- if (e.key === 'ArrowUp') { e.preventDefault(); this._moveCmdHint(-1); e.stopPropagation(); return; }
- if (e.key === 'Tab') { e.preventDefault(); this._completeCmdHint(); e.stopPropagation(); return; }
- // Enter on a highlighted suggestion completes it, then falls through to
- // the form submit so the command sends in a single keystroke.
- if (e.key === 'Enter' && this._cmdHint.active >= 0) {
- const c = this._cmdHint.items[this._cmdHint.active];
- if (c) this.hud.chatInput.value = '/' + c.name;
- this._hideCmdHint();
- this._updateChatCounter();
- }
- } else {
- // History navigation: ↑/↓ when the hint is closed steps through the
- // last 50 sent messages. ↑ at the top of history is a no-op; ↓ at the
- // bottom restores the in-progress draft.
- if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
- const hist = this._chatHistory;
- if (hist?.length) {
- e.preventDefault();
- e.stopPropagation();
- const input = this.hud.chatInput;
- if (this._chatHistoryCursor === -1) this._chatHistoryDraft = input.value;
- // cursor=0 → most recent (hist[hist.length-1]); cursor=max → oldest.
- // ArrowUp moves toward older (increases cursor); ArrowDown toward newer.
- const max = hist.length - 1;
- let next;
- if (e.key === 'ArrowUp') {
- next = this._chatHistoryCursor === -1 ? 0 : Math.min(max, this._chatHistoryCursor + 1);
- } else {
- next = this._chatHistoryCursor <= 0 ? -1 : this._chatHistoryCursor - 1;
- }
- this._chatHistoryCursor = next;
- input.value = next === -1 ? (this._chatHistoryDraft || '') : hist[hist.length - 1 - next];
- this._updateChatCounter();
- // Hide the hint while scrolling history — it would open for any '/…'
- // entry and steal subsequent ArrowUp/Down from the history path.
- // When the user stops navigating and edits manually the hint reopens.
- this._hideCmdHint();
- return;
- }
- }
- }
- // Everything else stays in the field (the global keydown bails on
- // _typing(), so movement keys never fire while chatting).
- e.stopPropagation();
- });
- this.hud.chatMutedBtn?.addEventListener('click', () => this._toggleMutedList());
- this._updateMutedCount();
- }
-
- // Slash-command manifest (Task 13) — the same registry that powers /help and the
- // server router, so the autocomplete can never list a command that doesn't exist.
- _onCommands(manifest) {
- this._cmds = Array.isArray(manifest)
- ? manifest
- .map((c) => ({
- name: String(c?.name || ''),
- args: String(c?.args || ''),
- desc: String(c?.desc || ''),
- aliases: Array.isArray(c?.aliases) ? c.aliases.map(String) : [],
- }))
- .filter((c) => c.name)
- : [];
- }
-
- // Recompute the hint list from the current input. Suggestions show only while
- // typing a command NAME — a leading '/' with no space yet. Once a space (args)
- // or a non-command line is typed, the hint hides.
- _refreshCmdHint() {
- const input = this.hud.chatInput;
- if (!input) return;
- const m = /^\/(\S*)$/.exec(input.value);
- if (!m || !this._cmds?.length) { this._hideCmdHint(); return; }
- const frag = m[1].toLowerCase();
- const matches = this._cmds
- .filter((c) => c.name.startsWith(frag) || c.aliases.some((a) => a.startsWith(frag)))
- .slice(0, 8);
- if (!matches.length) { this._hideCmdHint(); return; }
- // Keep the highlighted command across keystrokes when it's still a match, so
- // narrowing the list doesn't reset the user's selection out from under them.
- const prev = this._cmdHint?.active >= 0 ? this._cmdHint.items[this._cmdHint.active]?.name : null;
- const active = prev ? matches.findIndex((c) => c.name === prev) : -1;
- this._cmdHint = { items: matches, active };
- this._renderCmdHint();
- }
-
- _renderCmdHint() {
- const hint = this.hud.chatHint;
- const input = this.hud.chatInput;
- if (!hint || !this._cmdHint) return;
- hint.replaceChildren();
- this._cmdHint.items.forEach((c, i) => {
- const li = document.createElement('li');
- const on = i === this._cmdHint.active;
- li.className = 'kg-chat-hint-item' + (on ? ' kg-chat-hint-item--active' : '');
- li.id = 'kg-chat-hint-' + i;
- li.setAttribute('role', 'option');
- li.setAttribute('aria-selected', on ? 'true' : 'false');
- const sig = document.createElement('span');
- sig.className = 'kg-chat-hint-cmd';
- sig.textContent = '/' + c.name + (c.args ? ' ' + c.args : '');
- const desc = document.createElement('span');
- desc.className = 'kg-chat-hint-desc';
- desc.textContent = c.desc;
- li.append(sig, desc);
- // mousedown (before the input's blur) so a click completes + sends without
- // the panel collapsing first.
- li.addEventListener('mousedown', (e) => { e.preventDefault(); this._chooseCmdHint(i); });
- hint.appendChild(li);
- });
- hint.hidden = false;
- input?.setAttribute('aria-expanded', 'true');
- if (this._cmdHint.active >= 0) {
- input?.setAttribute('aria-activedescendant', 'kg-chat-hint-' + this._cmdHint.active);
- hint.children[this._cmdHint.active]?.scrollIntoView({ block: 'nearest' });
- } else {
- input?.removeAttribute('aria-activedescendant');
- }
- }
-
- _moveCmdHint(dir) {
- if (!this._cmdHint) return;
- const n = this._cmdHint.items.length;
- const cur = this._cmdHint.active;
- this._cmdHint.active = cur < 0 ? (dir > 0 ? 0 : n - 1) : (cur + dir + n) % n;
- this._renderCmdHint();
- }
-
- // Tab: fill the field with the (highlighted, else first) command. Append a space
- // when it takes args so the player keeps typing; refresh then hides or re-narrows.
- _completeCmdHint() {
- if (!this._cmdHint || !this.hud.chatInput) return;
- const idx = this._cmdHint.active >= 0 ? this._cmdHint.active : 0;
- const c = this._cmdHint.items[idx];
- if (!c) return;
- // Tab fills the chosen command in full. For an arg-taking command, append a
- // space and re-narrow so the player keeps typing; for a complete no-arg
- // command there's nothing left to suggest, so dismiss the hint.
- this.hud.chatInput.value = '/' + c.name + (c.args ? ' ' : '');
- if (c.args) this._refreshCmdHint();
- else this._hideCmdHint();
- }
-
- // Mouse pick: complete + send in one action.
- _chooseCmdHint(i) {
- const c = this._cmdHint?.items[i];
- if (!c || !this.hud.chatInput) return;
- this.hud.chatInput.value = '/' + c.name;
- this._hideCmdHint();
- this._sendChat();
- }
-
- _hideCmdHint() {
- this._cmdHint = null;
- if (this.hud.chatHint) { this.hud.chatHint.hidden = true; this.hud.chatHint.replaceChildren(); }
- if (this.hud.chatInput) {
- this.hud.chatInput.setAttribute('aria-expanded', 'false');
- this.hud.chatInput.removeAttribute('aria-activedescendant');
- }
- }
-
- _openChat() {
- if (!this.hud.chat || this.phase !== 'world') return;
- this.keys.clear(); // drop held movement keys so the avatar doesn't walk while typing
- if (!this._chatOpen) {
- this._chatOpen = true;
- this.hud.chat.classList.add('kg-chat--open');
- this._scrollChat();
- }
- if (document.activeElement !== this.hud.chatInput) this.hud.chatInput?.focus();
- }
-
- _closeChat(force) {
- this._closeMuteMenu();
- this._toggleMutedList(false);
- this._hideCmdHint();
- if (!this._chatOpen && !force) return;
- this._chatOpen = false;
- this.hud.chat?.classList.remove('kg-chat--open');
- if (document.activeElement === this.hud.chatInput) this.hud.chatInput.blur();
- }
-
- _sendChat() {
- const input = this.hud.chatInput;
- if (!input) return;
- const text = input.value.trim();
- input.value = '';
- this._hideCmdHint();
- this._updateChatCounter();
- if (!text) { this._closeChat(); return; }
- // Push into history (max 50), deduplicate adjacent identical entries.
- if (!this._chatHistory) this._chatHistory = [];
- if (this._chatHistory[this._chatHistory.length - 1] !== text) {
- this._chatHistory.push(text);
- if (this._chatHistory.length > 50) this._chatHistory.shift();
- }
- this._chatHistoryCursor = -1; // reset to "live" position after send
- this._chatHistoryDraft = '';
- // Server is authoritative: it sanitizes, rate-limits, routes `/commands`, and
- // echoes accepted messages back to everyone (us included) as 'chat' events.
- this.net?.chat(text);
- input.focus(); // keep the field hot for a flowing conversation
- }
-
- // Show remaining-character count once the player has used ≥ 160 chars (the
- // last 40 chars matter). Turns amber at 180, red at 195. Hidden when empty or
- // well under the limit so it never clutters a short message.
- _updateChatCounter() {
- const el = this.hud.chatCounter;
- const input = this.hud.chatInput;
- if (!el || !input) return;
- const len = input.value.length;
- const max = input.maxLength || 200;
- const rem = max - len;
- if (len < 160) {
- el.textContent = '';
- el.dataset.state = '';
- return;
- }
- el.textContent = String(rem);
- el.dataset.state = rem <= 5 ? 'danger' : rem <= 20 ? 'warn' : 'ok';
- }
-
- _onChat(msg) {
- if (!msg || typeof msg.text !== 'string') return;
- const line = this._appendChatLine(msg);
- if (!line) return;
- // Hide muted senders (but never our own messages, even to a namesake).
- if (!msg.system && msg.id !== this.myId && this.muted.has(msg.name)) {
- line.classList.add('kg-chat-line--muted');
- return;
- }
- this._scrollChat();
- // Show a speech bubble above the sender's avatar in the 3D world (non-system
- // messages only; commands/errors stay in the panel). Local player included so
- // they see their own message confirmed above their head immediately.
- if (!msg.system && msg.id) {
- const pv = this.players.get(msg.id);
- pv?.showBubble(msg.text);
- }
- }
-
- _appendChatLine(msg) {
- const log = this.hud.chatLog;
- if (!log) return null;
- const line = document.createElement('div');
- line.className = 'kg-chat-line';
- if (msg.system) {
- line.classList.add('kg-chat-line--system');
- if (msg.kind === 'error') line.classList.add('kg-chat-line--error');
- if (msg.kind === 'help') line.classList.add('kg-chat-line--help');
- if (msg.kind === 'who') line.classList.add('kg-chat-line--who');
- const t = document.createElement('span');
- t.className = 'kg-chat-text';
- t.textContent = msg.text;
- line.appendChild(t);
- } else {
- const name = msg.name || 'player';
- line.dataset.name = name;
- const isMe = msg.id && msg.id === this.myId;
- const nameEl = document.createElement('button');
- nameEl.type = 'button';
- nameEl.className = 'kg-chat-name' + (isMe ? ' kg-chat-name--me' : '');
- nameEl.textContent = name;
- // Apply the sender's world-assigned color so the name in chat matches the
- // floating nameplate above their avatar. Falls back to the CSS accent color
- // when the player isn't in the current state (e.g., they left mid-session).
- if (!isMe && msg.id) {
- const col = this.net?.state?.players?.get(msg.id)?.color;
- if (col) nameEl.style.color = '#' + col.toString(16).padStart(6, '0');
- }
- if (isMe) {
- nameEl.disabled = true;
- } else {
- nameEl.title = `Mute ${name}`;
- nameEl.setAttribute('aria-label', `Mute ${name}`);
- nameEl.addEventListener('click', (e) => this._openMuteMenu(e, name));
- }
- const t = document.createElement('span');
- t.className = 'kg-chat-text';
- t.textContent = msg.text;
- line.append(nameEl, t);
- }
- log.appendChild(line);
- // Bound the scrollback so a long session can't grow the DOM without limit.
- while (log.children.length > 120) log.removeChild(log.firstChild);
- return line;
- }
-
- // Local-only system line (mute confirmations) — same look as server replies.
- _sysLine(text, kind) {
- this._onChat({ system: true, kind: kind || 'system', text, ts: Date.now() });
- }
-
- _scrollChat() {
- const log = this.hud.chatLog;
- if (!log) return;
- // Auto-scroll only when already near the bottom (or collapsed, which always
- // pins to the latest) so reading scrollback isn't yanked away.
- const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 60;
- if (nearBottom || !this._chatOpen) log.scrollTop = log.scrollHeight;
- }
-
- // ----- mute ------------------------------------------------------------
-
- _openMuteMenu(e, name) {
- if (!name || !this.hud.chat) return;
- this._closeMuteMenu();
- const muted = this.muted.has(name);
- const menu = document.createElement('div');
- menu.className = 'kg-chat-menu';
- menu.setAttribute('role', 'menu');
- const btn = document.createElement('button');
- btn.type = 'button';
- btn.className = 'kg-chat-menu-btn';
- btn.setAttribute('role', 'menuitem');
- btn.textContent = (muted ? 'Unmute ' : 'Mute ') + name;
- btn.addEventListener('click', () => {
- if (muted) this._unmute(name); else this._mute(name);
- this._closeMuteMenu();
- });
- menu.appendChild(btn);
- this.hud.chat.appendChild(menu);
- // Float the popover just above the clicked name, clamped inside the panel.
- const target = e.currentTarget.getBoundingClientRect();
- const host = this.hud.chat.getBoundingClientRect();
- const left = Math.max(0, Math.min(target.left - host.left, host.width - menu.offsetWidth));
- menu.style.left = `${left}px`;
- menu.style.bottom = `${host.bottom - target.top + 4}px`;
- this._muteMenu = menu;
- btn.focus();
- // Dismiss on outside click or Escape.
- this._muteMenuCloser = (ev) => {
- if (ev.type === 'keydown' && ev.key !== 'Escape') return;
- if (ev.type === 'pointerdown' && menu.contains(ev.target)) return;
- this._closeMuteMenu();
- };
- setTimeout(() => {
- document.addEventListener('pointerdown', this._muteMenuCloser, true);
- document.addEventListener('keydown', this._muteMenuCloser, true);
- }, 0);
- }
-
- _closeMuteMenu() {
- if (this._muteMenuCloser) {
- document.removeEventListener('pointerdown', this._muteMenuCloser, true);
- document.removeEventListener('keydown', this._muteMenuCloser, true);
- this._muteMenuCloser = null;
- }
- if (this._muteMenu) { this._muteMenu.remove(); this._muteMenu = null; }
- }
-
- _mute(name) {
- if (!name) return;
- this.muted.add(name);
- this._saveMuted();
- this._applyMuteState(name);
- this._updateMutedCount();
- if (this._mutedListOpen) this._renderMutedList();
- this._sysLine(`Muted ${name}. Their messages are hidden.`);
- }
-
- _unmute(name) {
- if (!this.muted.delete(name)) return;
- this._saveMuted();
- this._applyMuteState(name);
- this._updateMutedCount();
- if (this._mutedListOpen) this._renderMutedList();
- this._sysLine(`Unmuted ${name}.`);
- }
-
- // Reveal or hide every existing line from a sender as their mute state flips —
- // so unmuting restores the scrollback, not just future messages.
- _applyMuteState(name) {
- const muted = this.muted.has(name);
- for (const line of this.hud.chatLog?.children || []) {
- if (line.dataset && line.dataset.name === name) {
- line.classList.toggle('kg-chat-line--muted', muted);
- }
- }
- if (!muted) this._scrollChat();
- }
-
- _updateMutedCount() {
- if (this.hud.chatMutedN) this.hud.chatMutedN.textContent = String(this.muted.size);
- }
-
- _toggleMutedList(force) {
- const list = this.hud.chatMutedList;
- if (!list) return;
- const open = force === undefined ? list.hidden : !!force;
- this._mutedListOpen = open;
- this.hud.chatMutedBtn?.setAttribute('aria-expanded', String(open));
- if (open) { this._renderMutedList(); list.hidden = false; }
- else list.hidden = true;
- }
-
- _renderMutedList() {
- const list = this.hud.chatMutedList;
- if (!list) return;
- list.replaceChildren();
- if (!this.muted.size) {
- const empty = document.createElement('div');
- empty.className = 'kg-chat-muted-empty';
- empty.textContent = 'No muted players.';
- list.appendChild(empty);
- return;
- }
- for (const name of [...this.muted].sort((a, b) => a.localeCompare(b))) {
- const row = document.createElement('div');
- row.className = 'kg-chat-muted-row';
- const nm = document.createElement('span');
- nm.className = 'kg-chat-muted-name';
- nm.textContent = name;
- const btn = document.createElement('button');
- btn.type = 'button';
- btn.className = 'kg-chat-unmute';
- btn.textContent = 'Unmute';
- btn.setAttribute('aria-label', `Unmute ${name}`);
- btn.addEventListener('click', () => this._unmute(name));
- row.append(nm, btn);
- list.appendChild(row);
- }
- }
-
- // ---------------------------------------------------------------- loop
- _loop() {
- requestAnimationFrame(this._loop);
- const now = performance.now();
- const dt = Math.min(0.05, (now - this._last) / 1000);
- this._last = now;
-
- if (this.phase === 'world') {
- this._stepAccum += now - (this._stepLast || now);
- this._stepLast = now;
- if (this._stepAccum >= this._stepInterval()) { this._stepAccum = 0; this._attemptStep(); }
- this._serviceInteraction(dt);
- for (const [, v] of this.players) v.tick(dt);
- this._updateMobs();
- this._updateCamera();
- this._updateLabels();
- this._updateNpcLabels();
- this._updateLandmarks(dt);
- this._updateTombLabels();
- this._updateStructures(now);
- this._updateBuildGhost();
- this._updateDeathOverlay();
- this._updateActions();
- this._tickCast(now);
- } else {
- this._stepLast = now;
- this._idleCamera(dt);
- }
- this.renderer.render(this.scene, this.camera);
- }
-
- _updateCamera() {
- const me = this._localView();
- if (me) this._camTarget.lerp(new Vector3(me.rig.position.x, 0.8, me.rig.position.z), 0.12);
- this._placeCamera();
- }
-
- // Slow orbit of the spawn while on the start/offline screens for a touch of life.
- _idleCamera(dt) {
- this.camYaw += dt * 0.05;
- this._placeCamera();
- }
-
- _placeCamera() {
- const t = this._camTarget;
- const x = t.x + this.camDist * Math.cos(this.camPitch) * Math.sin(this.camYaw);
- const z = t.z + this.camDist * Math.cos(this.camPitch) * Math.cos(this.camYaw);
- const y = t.y + this.camDist * Math.sin(this.camPitch);
- this.camera.position.set(x, y, z);
- this.camera.lookAt(t);
- // Keep the sun roughly following the action so shadows stay framed.
- if (this._sun) {
- this._sun.position.set(t.x + 24, 40, t.z + 18);
- this._sun.target.position.set(t.x, 0, t.z);
- this._sun.target.updateMatrixWorld();
- }
- }
-
- // Project each player's head to screen space and place its DOM nameplate.
- _updateLabels() {
- const w = window.innerWidth, h = window.innerHeight;
- const v = new Vector3();
- for (const [, pv] of this.players) {
- if (pv.dead) {
- pv.label.style.display = 'none';
- pv.bubble.style.display = 'none';
- continue;
- }
- v.set(pv.rig.position.x, pv.height + 0.35, pv.rig.position.z).project(this.camera);
- const behind = v.z > 1;
- if (behind) {
- pv.label.style.display = 'none';
- pv.bubble.style.display = 'none';
- continue;
- }
- const sx = (v.x * 0.5 + 0.5) * w;
- const sy = (-v.y * 0.5 + 0.5) * h;
- const t = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${sy.toFixed(1)}px)`;
- pv.label.style.display = '';
- pv.label.style.transform = t;
- // Speech bubble sits above the nameplate — offset up by an extra ~30px so
- // it clears the name row and reads distinctly.
- if (!pv.bubble.hidden) {
- pv.bubble.style.display = '';
- pv.bubble.style.transform = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${(sy - 32).toFixed(1)}px)`;
- } else {
- pv.bubble.style.display = 'none';
- }
- }
- }
-
- // Project each NPC's nameplate + quest marker to screen space.
- _updateNpcLabels() {
- if (!this.npcViews.size) return;
- const w = window.innerWidth, h = window.innerHeight;
- const v = new Vector3();
- for (const [, nv] of this.npcViews) {
- v.set(nv.group.position.x, nv.height + 0.5, nv.group.position.z).project(this.camera);
- if (v.z > 1) { nv.label.style.display = 'none'; continue; }
- nv.label.style.display = '';
- const sx = (v.x * 0.5 + 0.5) * w;
- const sy = (-v.y * 0.5 + 0.5) * h;
- nv.label.style.transform = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${sy.toFixed(1)}px)`;
- }
- }
-
- // Idle-spin each wheel disc for a touch of life, and project the wheel + casino
- // nameplates to screen space (Task 19).
- _updateLandmarks(dt) {
- const w = window.innerWidth, h = window.innerHeight;
- const v = new Vector3();
- for (const [, wv] of this.wheelViews) {
- const disc = wv.group.userData.disc;
- if (disc) disc.rotation.z += dt * 0.6;
- v.set(wv.group.position.x, wv.height + 0.6, wv.group.position.z).project(this.camera);
- if (v.z > 1) { wv.label.style.display = 'none'; continue; }
- wv.label.style.display = '';
- const sx = (v.x * 0.5 + 0.5) * w, sy = (-v.y * 0.5 + 0.5) * h;
- wv.label.style.transform = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${sy.toFixed(1)}px)`;
- }
- for (const cl of this._casinoLabels) {
- v.set(cl.x, cl.height, cl.z).project(this.camera);
- if (v.z > 1) { cl.label.style.display = 'none'; continue; }
- cl.label.style.display = '';
- const sx = (v.x * 0.5 + 0.5) * w, sy = (-v.y * 0.5 + 0.5) * h;
- cl.label.style.transform = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${sy.toFixed(1)}px)`;
- }
- }
-
- // Project each tombstone's headstone to screen space, place its DOM label, and
- // tick the live "expires in Xs" countdown straight off the synced expiresAt.
- _updateTombLabels() {
- if (!this.tombViews.size) return;
- const w = window.innerWidth, h = window.innerHeight;
- const now = Date.now();
- const v = new Vector3();
- for (const [, tv] of this.tombViews) {
- v.set(tv.group.position.x, 1.2, tv.group.position.z).project(this.camera);
- if (v.z > 1) { tv.label.style.display = 'none'; continue; }
- tv.label.style.display = '';
- const sx = (v.x * 0.5 + 0.5) * w;
- const sy = (-v.y * 0.5 + 0.5) * h;
- tv.label.style.transform = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${sy.toFixed(1)}px)`;
- const secs = Math.max(0, Math.ceil((tv.tomb.expiresAt - now) / 1000));
- tv.ttlEl.textContent = `${secs}s`;
- tv.label.classList.toggle('kg-tomb-soon', secs <= 45);
- }
- if (this._lootTombId) this._updateTombPanelTtl();
- }
-
- // Show/hide the respawn overlay from the local player's authoritative state.
- // The countdown reads the synced respawnAt; the overlay clears the instant the
- // server marks us alive again (the schema flip), never a client-side guess.
- _updateDeathOverlay() {
- const me = this._localView();
- const death = this.hud.death;
- if (!death) return;
- if (me?.dead) {
- if (!this._deathShown) {
- this._deathShown = true;
- death.hidden = false;
- this.hud.deathMsg.textContent = this._deathMessage();
- }
- const ms = Math.max(0, (me.respawnAt || 0) - Date.now());
- this.hud.deathCount.textContent = me.respawnAt ? `Respawning in ${Math.ceil(ms / 1000)}s` : 'Respawning…';
- } else if (this._deathShown) {
- this._deathShown = false;
- this._deathInfo = null;
- death.hidden = true;
- }
- }
-
- _onResize() {
- this.camera.aspect = window.innerWidth / window.innerHeight;
- this.camera.updateProjectionMatrix();
- this.renderer.setSize(window.innerWidth, window.innerHeight);
- }
-
- destroy() {
- clearInterval(this._skillsTimer);
- this._skillsTimer = null;
- this._closeMuteMenu();
- this.net?.destroy();
- for (const [, v] of this.players) v.dispose();
- this.players.clear();
- for (const [, tv] of this.tombViews) { this.objectGroup.remove(tv.group); tv.label.remove(); }
- this.tombViews.clear();
- for (const [, sv] of this.structViews) this.objectGroup.remove(sv.group);
- this.structViews.clear();
- this._exitBuildMode();
- this._disposeNpcs();
- this._disposeLandmarks();
- this._spinUI?.close();
- this.q?.destroy();
- this._clearCast();
- this._nipple?.destroy();
- }
-}
-
-const canvas = document.getElementById('kg-canvas');
-if (canvas) {
- const game = new IsoGame(canvas);
- if (typeof window !== 'undefined') window.__ISO__ = game;
-}
diff --git a/src/game/keybindings.js b/src/game/keybindings.js
deleted file mode 100644
index a0585f8a4..000000000
--- a/src/game/keybindings.js
+++ /dev/null
@@ -1,192 +0,0 @@
-// Central keybinding registry for the isometric MMO client (/play).
-//
-// Single source of truth for action -> key. Both the renderer (iso-game.js) and
-// the controls UI (iso-controls.js) route through this instead of hard-coding
-// key literals, so a player can rebind anything and it persists. Movement
-// (WASD / arrows) stays a held-key set in the renderer; this map owns the
-// discrete actions the world guide specifies (hotbar, panels, camera, system).
-//
-// Persistence is per account. Until Task 16 (account-keyed persistence) lands we
-// key on the chosen display name — the only stable account proxy the client has
-// — through localStorage. `_load`/`_save` are the single seam Task 16 swaps for a
-// server-backed store without touching any caller.
-
-// Canonical action list, in display order, grouped for the settings UI. `def` is
-// the default key (already normalized: lowercase, single tokens like 'escape').
-// `fixed: true` marks system keys that must not be rebound (rebinding the key
-// that closes dialogs would let a player lock themselves out of the UI).
-export const ACTIONS = [
- { id: 'hotbar1', label: 'Hotbar slot 1', group: 'Hotbar', def: '1' },
- { id: 'hotbar2', label: 'Hotbar slot 2', group: 'Hotbar', def: '2' },
- { id: 'hotbar3', label: 'Hotbar slot 3', group: 'Hotbar', def: '3' },
- { id: 'hotbar4', label: 'Hotbar slot 4', group: 'Hotbar', def: '4' },
- { id: 'hotbar5', label: 'Hotbar slot 5', group: 'Hotbar', def: '5' },
- { id: 'hotbar6', label: 'Hotbar slot 6', group: 'Hotbar', def: '6' },
- { id: 'hotbarClear', label: 'Clear hotbar selection', group: 'Hotbar', def: '0' },
- { id: 'inventory', label: 'Inventory', group: 'Panels', def: 'i' },
- { id: 'quests', label: 'Quests', group: 'Panels', def: 'q' },
- { id: 'map', label: 'Map', group: 'Panels', def: 'm' },
- { id: 'build', label: 'Build', group: 'Panels', def: 'b' },
- { id: 'chat', label: 'Chat', group: 'Panels', def: 'c' },
- { id: 'friends', label: 'Friends', group: 'Panels', def: 'f' },
- { id: 'skills', label: 'Skills', group: 'Panels', def: 'k' },
- { id: 'rotateCam', label: 'Rotate camera', group: 'Camera', def: 'r' },
- { id: 'closeModal', label: 'Close / cancel', group: 'System', def: 'escape', fixed: true },
- { id: 'confirm', label: 'Confirm', group: 'System', def: 'enter', fixed: true },
-];
-
-const ACTION_BY_ID = new Map(ACTIONS.map((a) => [a.id, a]));
-const STORE_PREFIX = 'kg-keybinds:';
-
-// Normalize a KeyboardEvent.key into a stable token used everywhere (map keys,
-// storage, lookups). Letters/digits lowercase; space and named keys spelled out.
-export function normalizeKey(key) {
- if (!key) return '';
- if (key === ' ' || key === 'Spacebar') return 'space';
- return String(key).toLowerCase();
-}
-
-// Human label for a key token, for the settings UI and hints.
-export function keyLabel(token) {
- if (!token) return '—';
- const named = {
- escape: 'Esc',
- enter: 'Enter',
- space: 'Space',
- tab: 'Tab',
- arrowup: '↑',
- arrowdown: '↓',
- arrowleft: '←',
- arrowright: '→',
- backspace: '⌫',
- delete: 'Del',
- ' ': 'Space',
- };
- if (named[token]) return named[token];
- return token.length === 1 ? token.toUpperCase() : token.replace(/^\w/, (m) => m.toUpperCase());
-}
-
-export function defaultBindings() {
- const m = {};
- for (const a of ACTIONS) m[a.id] = a.def;
- return m;
-}
-
-export class Keybindings {
- constructor(accountKey = '') {
- this.accountKey = accountKey || '_';
- this.map = { ...defaultBindings(), ...this._load() };
- // Repair any unknown/missing ids (e.g. after an action list change) so the
- // stored map can never drift out of sync with the canonical actions.
- for (const a of ACTIONS) if (!this.map[a.id]) this.map[a.id] = a.def;
- this._listeners = new Set();
- }
-
- // Swap the persistence scope at runtime (called once the player picks a name).
- // Re-reads that account's saved map, falling back to defaults.
- setAccount(accountKey) {
- const next = accountKey || '_';
- if (next === this.accountKey) return;
- this.accountKey = next;
- this.map = { ...defaultBindings(), ...this._load() };
- for (const a of ACTIONS) if (!this.map[a.id]) this.map[a.id] = a.def;
- this._emit();
- }
-
- get(id) {
- return this.map[id];
- }
-
- // Which action a key currently triggers, or null. Fixed system keys win so
- // 'escape'/'enter' always resolve to their system action.
- actionFor(token) {
- const key = normalizeKey(token);
- for (const a of ACTIONS) if (a.fixed && this.map[a.id] === key) return a.id;
- for (const a of ACTIONS) if (!a.fixed && this.map[a.id] === key) return a.id;
- return null;
- }
-
- // Assign `token` to `id`. Returns { ok, reason?, conflicts } where conflicts is
- // the list of OTHER action ids that share this key (the caller decides whether
- // to warn or auto-clear; we keep both bound and surface the clash, matching how
- // most game settings present it). Rebinding a fixed action is refused.
- set(id, token) {
- const action = ACTION_BY_ID.get(id);
- if (!action) return { ok: false, reason: 'unknown', conflicts: [] };
- if (action.fixed) return { ok: false, reason: 'fixed', conflicts: [] };
- const key = normalizeKey(token);
- if (!key) return { ok: false, reason: 'empty', conflicts: [] };
- // Reserve the system keys — assigning Esc/Enter to a normal action would
- // shadow closing/confirming dialogs.
- if (key === this.map.closeModal || key === this.map.confirm) {
- return { ok: false, reason: 'reserved', conflicts: [] };
- }
- this.map[id] = key;
- this._save();
- this._emit();
- return { ok: true, conflicts: this.conflictsFor(id) };
- }
-
- conflictsFor(id) {
- const key = this.map[id];
- const out = [];
- for (const a of ACTIONS) if (a.id !== id && this.map[a.id] === key) out.push(a.id);
- return out;
- }
-
- // All keys bound to more than one action -> [{ key, ids }]. Drives the live
- // conflict warnings in the settings panel.
- allConflicts() {
- const byKey = new Map();
- for (const a of ACTIONS) {
- const k = this.map[a.id];
- if (!byKey.has(k)) byKey.set(k, []);
- byKey.get(k).push(a.id);
- }
- const out = [];
- for (const [key, ids] of byKey) if (ids.length > 1) out.push({ key, ids });
- return out;
- }
-
- reset() {
- this.map = defaultBindings();
- this._save();
- this._emit();
- }
-
- subscribe(fn) {
- this._listeners.add(fn);
- return () => this._listeners.delete(fn);
- }
- _emit() {
- for (const fn of this._listeners) {
- try {
- fn(this.map);
- } catch (e) {
- console.error('[keybindings] listener threw:', e);
- }
- }
- }
-
- // ----- persistence seam (Task 16 replaces these two) -------------------
- _storeKey() {
- return STORE_PREFIX + this.accountKey;
- }
- _load() {
- try {
- const raw = localStorage.getItem(this._storeKey());
- if (!raw) return {};
- const parsed = JSON.parse(raw);
- return parsed && typeof parsed === 'object' ? parsed : {};
- } catch {
- return {};
- }
- }
- _save() {
- try {
- localStorage.setItem(this._storeKey(), JSON.stringify(this.map));
- } catch {
- /* storage disabled — bindings stay session-only */
- }
- }
-}
diff --git a/src/game/terrain.js b/src/game/terrain.js
new file mode 100644
index 000000000..d1b8188bc
--- /dev/null
+++ b/src/game/terrain.js
@@ -0,0 +1,225 @@
+// terrain.js — procedural heightfield terrain for the social walkaround.
+//
+// Single source of truth for ground shape: one height grid drives both the
+// rendered Three.js mesh AND the Rapier heightfield collider, so the visible
+// surface and the physics surface can never drift apart.
+//
+// The grid is a square of `size` world-units centred on the origin, sampled at
+// (segments + 1) points per side. Heights are stored COLUMN-MAJOR in a single
+// Float32Array — exactly the layout Rapier's `ColliderDesc.heightfield`
+// expects — so physics-world.js can hand the array straight to Rapier with no
+// copy or transpose. See heightIndex() for the row/col → world mapping.
+
+import {
+ BufferGeometry,
+ BufferAttribute,
+ Mesh,
+ MeshStandardMaterial,
+ Float32BufferAttribute,
+} from 'three';
+
+// Deterministic PRNG (LCG) so a given seed always yields the same terrain —
+// important for multiplayer: every client must generate an identical surface.
+function makePRNG(seed) {
+ let s = (seed >>> 0) || 1;
+ return () => {
+ s = (s * 1664525 + 1013904223) >>> 0;
+ return s / 4294967296;
+ };
+}
+
+// Smooth value-noise on a 256×256 lattice. fBm sums several octaves for
+// natural rolling hills without external noise dependencies.
+function makeValueNoise(seed) {
+ const rand = makePRNG(seed);
+ const G = 256;
+ const lattice = new Float32Array(G * G);
+ for (let i = 0; i < lattice.length; i++) lattice[i] = rand();
+ const at = (xi, yi) => lattice[(xi & 255) + (yi & 255) * G];
+ return (x, y) => {
+ const x0 = Math.floor(x);
+ const y0 = Math.floor(y);
+ const fx = x - x0;
+ const fy = y - y0;
+ // Smoothstep weights kill the lattice-aligned creasing of linear interp.
+ const sx = fx * fx * (3 - 2 * fx);
+ const sy = fy * fy * (3 - 2 * fy);
+ const v00 = at(x0, y0);
+ const v10 = at(x0 + 1, y0);
+ const v01 = at(x0, y0 + 1);
+ const v11 = at(x0 + 1, y0 + 1);
+ const a = v00 + (v10 - v00) * sx;
+ const b = v01 + (v11 - v01) * sx;
+ return a + (b - a) * sy; // 0..1
+ };
+}
+
+const DEFAULTS = {
+ size: 56, // world-units per side (square, centred on origin)
+ segments: 120, // cells per side → (segments+1)² height samples
+ seed: 1337,
+ amplitude: 1.8, // peak height of the hills, metres
+ frequency: 0.045, // noise frequency — lower = broader features
+ octaves: 4,
+ flatRadius: 4.0, // fully flat disc around spawn (metres)
+ flatFalloff: 9.0, // distance over which terrain ramps to full amplitude
+ color: 0x202833,
+};
+
+export function createTerrain(opts = {}) {
+ const cfg = { ...DEFAULTS, ...opts };
+ const { size, segments, amplitude, frequency, octaves, flatRadius, flatFalloff } = cfg;
+ const points = segments + 1; // samples per side
+ const cellSize = size / segments;
+ const half = size / 2;
+ const noise = makeValueNoise(cfg.seed);
+
+ // fBm height at a world (x, z). Returns metres above y=0.
+ function rawHeight(x, z) {
+ let h = 0;
+ let freq = frequency;
+ let amp = 1;
+ let norm = 0;
+ for (let o = 0; o < octaves; o++) {
+ // Offset each octave so they don't share lattice alignment.
+ h += amp * (noise(x * freq + o * 37.1, z * freq - o * 19.7) - 0.5) * 2;
+ norm += amp;
+ freq *= 2;
+ amp *= 0.5;
+ }
+ h = (h / norm) * amplitude;
+ // Flatten a disc around spawn so the avatar and central props start on
+ // even ground; ramp smoothly to full relief beyond flatRadius.
+ const r = Math.hypot(x, z);
+ const t = Math.min(1, Math.max(0, (r - flatRadius) / flatFalloff));
+ const ease = t * t * (3 - 2 * t);
+ return h * ease;
+ }
+
+ // COLUMN-MAJOR height buffer for Rapier: index = row + col * points.
+ // Rapier maps heightfield point (row, col) to local
+ // x = (col/(points-1) - 0.5) * scale.x
+ // z = (row/(points-1) - 0.5) * scale.z
+ // We fill with the SAME world→height function so collider == visual.
+ const heights = new Float32Array(points * points);
+ for (let col = 0; col < points; col++) {
+ const x = (col / segments - 0.5) * size;
+ for (let row = 0; row < points; row++) {
+ const z = (row / segments - 0.5) * size;
+ heights[row + col * points] = rawHeight(x, z);
+ }
+ }
+
+ // Bilinear sample of the baked grid — matches the heightfield's piecewise
+ // surface that physics and props stand on (analytic rawHeight would drift
+ // from the discretised collider on steep cells).
+ function heightAt(x, z) {
+ const fx = ((x + half) / size) * segments;
+ const fz = ((z + half) / size) * segments;
+ const cx = Math.min(segments - 1, Math.max(0, Math.floor(fx)));
+ const cz = Math.min(segments - 1, Math.max(0, Math.floor(fz)));
+ const tx = Math.min(1, Math.max(0, fx - cx));
+ const tz = Math.min(1, Math.max(0, fz - cz));
+ const h00 = heights[cz + cx * points];
+ const h10 = heights[cz + (cx + 1) * points];
+ const h01 = heights[cz + 1 + cx * points];
+ const h11 = heights[cz + 1 + (cx + 1) * points];
+ const a = h00 + (h10 - h00) * tx;
+ const b = h01 + (h11 - h01) * tx;
+ return a + (b - a) * tz;
+ }
+
+ // Surface normal via central differences — for slope-aware prop placement.
+ const _e = cellSize;
+ function normalAt(x, z, out) {
+ const hL = heightAt(x - _e, z);
+ const hR = heightAt(x + _e, z);
+ const hD = heightAt(x, z - _e);
+ const hU = heightAt(x, z + _e);
+ const nx = hL - hR;
+ const nz = hD - hU;
+ const ny = 2 * _e;
+ const len = Math.hypot(nx, ny, nz) || 1;
+ if (out) return out.set(nx / len, ny / len, nz / len);
+ return { x: nx / len, y: ny / len, z: nz / len };
+ }
+
+ // Build the render mesh from the same grid. Custom BufferGeometry (rather
+ // than PlaneGeometry) so vertex order is unambiguously aligned with the
+ // height buffer and we control normals/UVs.
+ const vertCount = points * points;
+ const positions = new Float32Array(vertCount * 3);
+ const uvs = new Float32Array(vertCount * 2);
+ for (let col = 0; col < points; col++) {
+ const x = (col / segments - 0.5) * size;
+ for (let row = 0; row < points; row++) {
+ const z = (row / segments - 0.5) * size;
+ const vi = row + col * points;
+ positions[vi * 3] = x;
+ positions[vi * 3 + 1] = heights[vi];
+ positions[vi * 3 + 2] = z;
+ uvs[vi * 2] = col / segments;
+ uvs[vi * 2 + 1] = row / segments;
+ }
+ }
+ // Two triangles per cell. Winding chosen so normals face +Y (up).
+ const indices = new Uint32Array(segments * segments * 6);
+ let ii = 0;
+ for (let col = 0; col < segments; col++) {
+ for (let row = 0; row < segments; row++) {
+ const a = row + col * points;
+ const b = row + (col + 1) * points;
+ const c = row + 1 + col * points;
+ const d = row + 1 + (col + 1) * points;
+ indices[ii++] = a;
+ indices[ii++] = c;
+ indices[ii++] = b;
+ indices[ii++] = b;
+ indices[ii++] = c;
+ indices[ii++] = d;
+ }
+ }
+
+ const geometry = new BufferGeometry();
+ geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
+ geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
+ geometry.setIndex(new BufferAttribute(indices, 1));
+ geometry.computeVertexNormals();
+ geometry.computeBoundingSphere();
+
+ const material = new MeshStandardMaterial({
+ color: cfg.color,
+ roughness: 0.95,
+ metalness: 0.0,
+ });
+
+ const mesh = new Mesh(geometry, material);
+ mesh.receiveShadow = true;
+ mesh.name = 'terrain';
+
+ // Snap an Object3D onto the surface at (x, z), keeping its base at ground.
+ function placeOnGround(obj, x, z, baseOffset = 0) {
+ obj.position.set(x, heightAt(x, z) + baseOffset, z);
+ }
+
+ return {
+ mesh,
+ material,
+ heights, // Float32Array, column-major — feed directly to Rapier
+ size,
+ segments,
+ points,
+ cellSize,
+ amplitude,
+ heightAt,
+ normalAt,
+ placeOnGround,
+ setColor(hex) {
+ material.color.setHex(hex);
+ },
+ dispose() {
+ geometry.dispose();
+ material.dispose();
+ },
+ };
+}
diff --git a/src/physics/physics-world.js b/src/physics/physics-world.js
new file mode 100644
index 000000000..a7785ddfc
--- /dev/null
+++ b/src/physics/physics-world.js
@@ -0,0 +1,286 @@
+// PhysicsWorld — a thin, reusable wrapper over Rapier (3D, WASM-compat build).
+//
+// Why this exists: the 3D scenes historically faked collision with disc-radius
+// clamps and AABB push-out. That stops you at a wall but can't roll a ball,
+// push a crate, climb a step, or resolve a slide. This module gives every
+// scene one real solver:
+//
+// • a kinematic capsule character controller (slides along walls, steps up
+// small ledges, snaps to ground, and shoves dynamic bodies it walks into),
+// • static colliders for world geometry (ground, buildings, trees),
+// • dynamic rigid bodies for props (balls, crates) that fall, roll, and
+// get kicked, with their Three.js meshes synced from the simulation.
+//
+// Rapier ships its WASM inline in the `-compat` build, so there is no decoder
+// file to host — we just await init() once and memoize it. The character
+// body's translation is its FEET (the collider is offset upward by its own
+// half-height), so callers can copy it straight onto an avatar rig whose
+// origin sits on the floor.
+
+import RAPIER from '@dimforge/rapier3d-compat';
+
+let _rapierReady = null;
+
+/** Initialize the Rapier WASM runtime once and reuse it across worlds. */
+export function initRapier() {
+ if (!_rapierReady) _rapierReady = RAPIER.init().then(() => RAPIER);
+ return _rapierReady;
+}
+
+const _v = { x: 0, y: 0, z: 0 };
+
+export class PhysicsWorld {
+ /**
+ * @param {typeof RAPIER} rapier initialized Rapier module
+ * @param {{ gravity?: {x:number,y:number,z:number} }} [opts]
+ */
+ constructor(rapier, { gravity = { x: 0, y: -14, z: 0 } } = {}) {
+ this.RAPIER = rapier;
+ this.world = new rapier.World(gravity);
+ // Substep budget keeps the dynamic solver stable when a frame runs long
+ // (tab refocus, GC pause) without letting bodies tunnel through walls.
+ this._fixedDt = 1 / 60;
+ this._accumulator = 0;
+ this._ground = null; // { body } — persists across environment swaps
+ this._obstacles = []; // [{ body }] — cleared/rebuilt per environment
+ this._dynamics = []; // [{ body, mesh, spawn }] — props synced to meshes
+ this._character = null;
+ }
+
+ /** Create a world with the WASM runtime guaranteed ready. */
+ static async create(opts) {
+ const rapier = await initRapier();
+ return new PhysicsWorld(rapier, opts);
+ }
+
+ // ── Static world geometry ────────────────────────────────────────────────
+
+ /**
+ * An effectively-infinite floor whose top face sits at `y`. Modeled as a
+ * thick cuboid (not a plane) so the character can never tunnel beneath it.
+ */
+ addGround(y = 0, halfSize = 200) {
+ const R = this.RAPIER;
+ const thickness = 5;
+ const body = this.world.createRigidBody(
+ R.RigidBodyDesc.fixed().setTranslation(0, y - thickness, 0),
+ );
+ this.world.createCollider(
+ R.ColliderDesc.cuboid(halfSize, thickness, halfSize).setFriction(1),
+ body,
+ );
+ this._ground = { body };
+ return body;
+ }
+
+ /**
+ * Static heightfield ground from a terrain.js instance. The terrain's height
+ * buffer is column-major — exactly Rapier's layout — so it maps on with no
+ * copy. The collider spans `terrain.size` square, centred on the origin,
+ * with its base at `y`. Replaces (and supersedes) any flat addGround floor so
+ * the character walks the real rolling surface instead of a flat plane.
+ */
+ addHeightfield(terrain, { y = 0, friction = 1 } = {}) {
+ const R = this.RAPIER;
+ if (this._ground) {
+ this.world.removeRigidBody(this._ground.body);
+ this._ground = null;
+ }
+ const n = terrain.points; // samples per side; heights.length === n*n
+ const scale = { x: terrain.size, y: 1, z: terrain.size };
+ const body = this.world.createRigidBody(
+ R.RigidBodyDesc.fixed().setTranslation(0, y, 0),
+ );
+ this.world.createCollider(
+ R.ColliderDesc.heightfield(n, n, terrain.heights, scale).setFriction(friction),
+ body,
+ );
+ this._ground = { body };
+ return body;
+ }
+
+ /** Axis-aligned-ish box obstacle (optionally yaw-rotated). Center-anchored. */
+ addStaticBox({ position, halfExtents, rotationY = 0 }) {
+ const R = this.RAPIER;
+ const desc = R.RigidBodyDesc.fixed().setTranslation(position.x, position.y, position.z);
+ if (rotationY) {
+ const h = rotationY / 2;
+ desc.setRotation({ x: 0, y: Math.sin(h), z: 0, w: Math.cos(h) });
+ }
+ const body = this.world.createRigidBody(desc);
+ this.world.createCollider(
+ R.ColliderDesc.cuboid(halfExtents.x, halfExtents.y, halfExtents.z),
+ body,
+ );
+ this._obstacles.push({ body });
+ return body;
+ }
+
+ /** Upright cylinder obstacle — trees, posts, palm trunks. Center-anchored. */
+ addStaticCylinder({ position, radius, halfHeight }) {
+ const R = this.RAPIER;
+ const body = this.world.createRigidBody(
+ R.RigidBodyDesc.fixed().setTranslation(position.x, position.y, position.z),
+ );
+ this.world.createCollider(R.ColliderDesc.cylinder(halfHeight, radius), body);
+ this._obstacles.push({ body });
+ return body;
+ }
+
+ /** Remove every per-environment obstacle (ground is preserved). */
+ clearObstacles() {
+ for (const o of this._obstacles) this.world.removeRigidBody(o.body);
+ this._obstacles.length = 0;
+ }
+
+ // ── Dynamic props ────────────────────────────────────────────────────────
+
+ /**
+ * A dynamic rigid body bound to a Three.js mesh. The mesh is driven by the
+ * simulation every frame in sync(); `spawn` is retained so a prop that
+ * tumbles off the world can be respawned.
+ */
+ addDynamicBall({ mesh, radius, restitution = 0.6, density = 0.4, linearDamping = 0.4 }) {
+ const R = this.RAPIER;
+ const p = mesh.position;
+ const body = this.world.createRigidBody(
+ R.RigidBodyDesc.dynamic()
+ .setTranslation(p.x, p.y, p.z)
+ .setLinearDamping(linearDamping)
+ .setAngularDamping(0.5),
+ );
+ this.world.createCollider(
+ R.ColliderDesc.ball(radius).setRestitution(restitution).setDensity(density).setFriction(0.6),
+ body,
+ );
+ const entry = { body, mesh, spawn: { x: p.x, y: p.y, z: p.z } };
+ this._dynamics.push(entry);
+ return entry;
+ }
+
+ addDynamicBox({ mesh, halfExtents, restitution = 0.1, density = 0.6, linearDamping = 0.3 }) {
+ const R = this.RAPIER;
+ const p = mesh.position;
+ const body = this.world.createRigidBody(
+ R.RigidBodyDesc.dynamic()
+ .setTranslation(p.x, p.y, p.z)
+ .setLinearDamping(linearDamping)
+ .setAngularDamping(0.6),
+ );
+ this.world.createCollider(
+ R.ColliderDesc.cuboid(halfExtents.x, halfExtents.y, halfExtents.z)
+ .setRestitution(restitution)
+ .setDensity(density)
+ .setFriction(0.8),
+ body,
+ );
+ const entry = { body, mesh, spawn: { x: p.x, y: p.y, z: p.z } };
+ this._dynamics.push(entry);
+ return entry;
+ }
+
+ /** Remove every dynamic prop body (their meshes are owned by the caller). */
+ clearDynamics() {
+ for (const d of this._dynamics) this.world.removeRigidBody(d.body);
+ this._dynamics.length = 0;
+ }
+
+ // ── Character controller ─────────────────────────────────────────────────
+
+ /**
+ * A kinematic capsule whose body translation tracks the FEET position.
+ * Returns a controller façade with move()/setPosition().
+ */
+ createCharacter({ position = { x: 0, y: 0, z: 0 }, radius = 0.3, halfHeight = 0.55, offset = 0.04 } = {}) {
+ const R = this.RAPIER;
+ const body = this.world.createRigidBody(
+ R.RigidBodyDesc.kinematicPositionBased().setTranslation(position.x, position.y, position.z),
+ );
+ // Lift the capsule so the body origin is the feet, not the capsule center.
+ const collider = this.world.createCollider(
+ R.ColliderDesc.capsule(halfHeight, radius).setTranslation(0, radius + halfHeight, 0),
+ body,
+ );
+
+ const controller = this.world.createCharacterController(offset);
+ controller.enableAutostep(0.4, 0.2, true); // step up curbs / ledges
+ controller.enableSnapToGround(0.3); // hug terrain on the way down
+ controller.setApplyImpulsesToDynamicBodies(true); // kick balls & crates
+ controller.setSlideEnabled(true); // slide along walls instead of stopping dead
+ controller.setMaxSlopeClimbAngle((50 * Math.PI) / 180);
+ controller.setMinSlopeSlideAngle((35 * Math.PI) / 180);
+
+ this._character = {
+ body,
+ collider,
+ controller,
+ /**
+ * Resolve one frame of desired motion against the world.
+ * @param {{x:number,y:number,z:number}} desired world-space displacement this frame
+ * @returns {{ position:{x:number,y:number,z:number}, grounded:boolean }}
+ */
+ move: (desired) => {
+ controller.computeColliderMovement(collider, desired);
+ const m = controller.computedMovement();
+ const t = body.translation();
+ _v.x = t.x + m.x;
+ _v.y = t.y + m.y;
+ _v.z = t.z + m.z;
+ body.setNextKinematicTranslation(_v);
+ return { position: { x: _v.x, y: _v.y, z: _v.z }, grounded: controller.computedGrounded() };
+ },
+ /** Hard-teleport (respawn, boundary snap) — bypasses collision. */
+ setPosition: (p) => {
+ body.setTranslation({ x: p.x, y: p.y, z: p.z }, true);
+ body.setNextKinematicTranslation({ x: p.x, y: p.y, z: p.z });
+ },
+ };
+ return this._character;
+ }
+
+ get character() {
+ return this._character;
+ }
+
+ // ── Per-frame integration ────────────────────────────────────────────────
+
+ /**
+ * Advance the simulation. The character's setNextKinematicTranslation (from
+ * move()) is consumed here, so call move() BEFORE step(). Uses a fixed
+ * timestep accumulator so dynamic bodies stay stable across variable frames.
+ */
+ step(dt) {
+ this._accumulator += Math.min(dt, 0.1);
+ let steps = 0;
+ this.world.timestep = this._fixedDt;
+ while (this._accumulator >= this._fixedDt && steps < 5) {
+ this.world.step();
+ this._accumulator -= this._fixedDt;
+ steps++;
+ }
+ this._syncDynamics();
+ }
+
+ _syncDynamics() {
+ for (const d of this._dynamics) {
+ const t = d.body.translation();
+ const r = d.body.rotation();
+ d.mesh.position.set(t.x, t.y, t.z);
+ d.mesh.quaternion.set(r.x, r.y, r.z, r.w);
+ // A prop that tumbles into the void gets relaunched from its spawn.
+ if (t.y < -8) {
+ d.body.setTranslation({ ...d.spawn }, true);
+ d.body.setLinvel({ x: 0, y: 0, z: 0 }, true);
+ d.body.setAngvel({ x: 0, y: 0, z: 0 }, true);
+ }
+ }
+ }
+
+ dispose() {
+ this.world.free();
+ this._ground = null;
+ this._obstacles.length = 0;
+ this._dynamics.length = 0;
+ this._character = null;
+ }
+}
diff --git a/src/walk-companion.js b/src/walk-companion.js
index 18f0a1490..4c9e755cd 100644
--- a/src/walk-companion.js
+++ b/src/walk-companion.js
@@ -62,7 +62,6 @@ const EXCLUDED_PREFIXES = [
'/walk',
'/walk-embed',
'/embed',
- '/game',
'/play',
'/club',
'/city',
diff --git a/src/walk.js b/src/walk.js
index 631c04517..613ba0d27 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -49,6 +49,7 @@ import { AnimationManager } from './animation-manager.js';
import { WalkNet } from './walk-net.js';
import { getPresenceTicket, friendsClient } from './friends.js';
import { FriendsPanel } from './game/friends-panel.js';
+import { PhysicsWorld } from './physics/physics-world.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
@@ -715,7 +716,27 @@ const JUMP_FORCE = 5.8;
const GRAVITY = -14;
const GROUND_Y = 0;
+// ── Physics ────────────────────────────────────────────────────────────────
+// A real Rapier solver drives roaming when available (non-AR). Until the WASM
+// runtime finishes loading — and in AR, where the avatar floats in the room —
+// movement falls back to the legacy direct-mutation path below.
+let physics = null;
+let physicsReady = false;
+let character = null;
+let verticalVel = 0; // m/s — integrated vertical velocity for the physics path
+let characterGrounded = true;
+let physicsActivePrev = false; // rising-edge guard to resync after AR/legacy
+
function triggerJump() {
+ // Physics path: only launch when actually standing on something.
+ if (physicsReady && character && !arActive) {
+ if (characterGrounded) {
+ verticalVel = JUMP_FORCE;
+ haptics.buzz(10);
+ }
+ return;
+ }
+ // Legacy parabola (AR / pre-physics).
if (jumpActive) return;
jumpActive = true;
jumpVelocity = JUMP_FORCE;
@@ -1554,8 +1575,14 @@ function tick() {
cameraPitch = Math.max(PITCH_MIN, Math.min(PITCH_MAX, cameraPitch + input.look.y * LOOK_PITCH_SPEED * dt));
}
- // Jump physics — simple parabola in Y, lands back at GROUND_Y.
- if (jumpActive && avatar) {
+ // When the Rapier solver is up (and we're not in AR), the kinematic
+ // character controller owns position, collision, and gravity. Otherwise the
+ // legacy direct-mutation path keeps the scene fully playable.
+ const usePhysics = physicsReady && !!character && !arActive;
+
+ // Legacy jump — simple parabola in Y, lands back at GROUND_Y. The physics
+ // path integrates verticalVel against real ground contact instead.
+ if (!usePhysics && jumpActive && avatar) {
jumpVelocity += GRAVITY * dt;
avatarRig.position.y += jumpVelocity * dt;
if (avatarRig.position.y <= GROUND_Y) {
@@ -1586,17 +1613,21 @@ function tick() {
.normalize()
.multiplyScalar(speed * dt);
- avatarRig.position.add(moveWorld);
-
- // Clamp roaming radius so the avatar can't walk off the ground disc
- // in non-AR mode. In AR there's no ground, so let it roam freely.
- if (!arActive) {
- const r = Math.hypot(avatarRig.position.x, avatarRig.position.z);
- const max = GROUND_RADIUS - 0.5;
- if (r > max) {
- const k = max / r;
- avatarRig.position.x *= k;
- avatarRig.position.z *= k;
+ // Legacy path applies horizontal motion directly; the physics path feeds
+ // moveWorld to the character controller after this block.
+ if (!usePhysics) {
+ avatarRig.position.add(moveWorld);
+
+ // Clamp roaming radius so the avatar can't walk off the ground disc
+ // in non-AR mode. In AR there's no ground, so let it roam freely.
+ if (!arActive) {
+ const r = Math.hypot(avatarRig.position.x, avatarRig.position.z);
+ const max = GROUND_RADIUS - 0.5;
+ if (r > max) {
+ const k = max / r;
+ avatarRig.position.x *= k;
+ avatarRig.position.z *= k;
+ }
}
}
@@ -1617,6 +1648,46 @@ function tick() {
animationManager.crossfadeTo(CLIP_IDLE, 0.25);
}
+ // Physics movement — feed the frame's horizontal displacement plus an
+ // integrated vertical velocity to the kinematic character controller. It
+ // resolves wall slides, step-ups, ground contact, and shoves dynamic props,
+ // then hands back where the feet actually ended up. We step the world right
+ // after so the solver consumes the queued kinematic move in the same frame.
+ if (usePhysics && avatar) {
+ // On the first physics frame after boot/AR, snap the body to wherever the
+ // avatar currently is so the controller doesn't lurch from a stale pose.
+ if (!physicsActivePrev) {
+ character.setPosition(avatarRig.position);
+ verticalVel = 0;
+ physicsActivePrev = true;
+ }
+ const dispX = mag > 0.01 ? moveWorld.x : 0;
+ const dispZ = mag > 0.01 ? moveWorld.z : 0;
+ verticalVel += GRAVITY * dt;
+ if (verticalVel < -40) verticalVel = -40; // terminal velocity guard
+ const res = character.move({ x: dispX, y: verticalVel * dt, z: dispZ });
+ characterGrounded = res.grounded;
+ if (characterGrounded && verticalVel < 0) verticalVel = 0;
+
+ // Boundary safety — keep roaming inside the ground disc. Snap the body
+ // too so the controller's next query starts from the corrected spot.
+ let px = res.position.x;
+ let pz = res.position.z;
+ const r = Math.hypot(px, pz);
+ const maxR = GROUND_RADIUS - 0.5;
+ if (r > maxR) {
+ const k = maxR / r;
+ px *= k;
+ pz *= k;
+ character.setPosition({ x: px, y: res.position.y, z: pz });
+ }
+ avatarRig.position.set(px, res.position.y, pz);
+
+ physics.step(dt);
+ } else {
+ physicsActivePrev = false;
+ }
+
// Sync clip playback rate to actual ground speed so feet plant instead
// of skating. mixer.timeScale is a global multiplier on every action;
// when idle (speed≈0) we hold it at 1.0 so the breathing/sway cycle
@@ -2395,6 +2466,13 @@ let currentEnvIndex = 0;
const envPropsGroup = new Group();
scene.add(envPropsGroup);
+// Collider descriptors emitted by the prop builders for the current environment.
+// `worldObstacles` are static (trees/buildings); `worldDynamicProps` are the
+// kickable bodies whose meshes the physics solver drives each frame. Both are
+// rebuilt on every environment swap and consumed by rebuildPhysicsWorld().
+let worldObstacles = [];
+let worldDynamicProps = [];
+
// Restore saved environment
try {
const savedEnv = localStorage.getItem(ENV_KEY);
@@ -2429,10 +2507,16 @@ function applyEnvironment(index) {
child.material.dispose();
}
}
+ // Reset collider descriptors — the builders below repopulate them.
+ worldObstacles = [];
+ worldDynamicProps = [];
// Add environment props
if (env.name === 'park') buildParkProps();
else if (env.name === 'city') buildCityProps();
else if (env.name === 'beach') buildBeachProps();
+ buildDynamicProps(env.name);
+ // Sync the physics world to the new scenery (no-op until physics is ready).
+ rebuildPhysicsWorld();
try { localStorage.setItem(ENV_KEY, env.name); } catch {}
updateEnvIndicator();
}
@@ -2462,6 +2546,13 @@ function buildParkProps() {
dummy.position.y = 1.1 * scale;
dummy.updateMatrix();
foliageMesh.setMatrixAt(i, dummy.matrix);
+ // Solid trunk: a cylinder you can't walk through, sized to the canopy base.
+ worldObstacles.push({
+ type: 'cylinder',
+ position: { x, y: 0.9 * scale, z },
+ radius: 0.32 * scale,
+ halfHeight: 0.9 * scale,
+ });
}
envPropsGroup.add(trunkMesh);
envPropsGroup.add(foliageMesh);
@@ -2484,11 +2575,18 @@ function buildCityProps() {
const h = 1.5 + Math.random() * 4;
const w = 0.8 + Math.random() * 1.2;
const d = 0.8 + Math.random() * 1.2;
+ const rotationY = Math.random() * Math.PI;
dummy.position.set(x, h / 2, z);
dummy.scale.set(w, h, d);
- dummy.rotation.y = Math.random() * Math.PI;
+ dummy.rotation.y = rotationY;
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
+ worldObstacles.push({
+ type: 'box',
+ position: { x, y: h / 2, z },
+ halfExtents: { x: w / 2, y: h / 2, z: d / 2 },
+ rotationY,
+ });
}
envPropsGroup.add(mesh);
// Grid lines on ground
@@ -2536,11 +2634,61 @@ function buildBeachProps() {
dummy.position.y = 2.6;
dummy.updateMatrix();
palmLeaves.setMatrixAt(i, dummy.matrix);
+ worldObstacles.push({
+ type: 'cylinder',
+ position: { x, y: 1.25, z },
+ radius: 0.28,
+ halfHeight: 1.25,
+ });
}
envPropsGroup.add(palmTrunks);
envPropsGroup.add(palmLeaves);
}
+// Kickable physics props — beach balls and crates that fall, roll, and get
+// shoved when the avatar walks into them. Each prop builds its own mesh (added
+// to envPropsGroup so it's torn down on env change) and records a descriptor in
+// worldDynamicProps; rebuildPhysicsWorld() binds a rigid body to that mesh.
+const PROP_BALL_COLORS = [0xff5a5f, 0x2ec4b6, 0xffd166, 0x5a8dee];
+function buildDynamicProps(envName) {
+ const balls = envName === 'beach' ? 5 : 3;
+ const crates = envName === 'beach' ? 0 : 3;
+
+ for (let i = 0; i < balls; i++) {
+ const radius = 0.28 + Math.random() * 0.12;
+ const mesh = new Mesh(
+ new SphereGeometry(radius, 24, 16),
+ new MeshStandardMaterial({
+ color: PROP_BALL_COLORS[i % PROP_BALL_COLORS.length],
+ roughness: 0.35,
+ metalness: 0.05,
+ }),
+ );
+ const angle = (i / balls) * Math.PI * 2 + 0.6;
+ const r = 2.4 + Math.random() * 1.6;
+ mesh.position.set(Math.cos(angle) * r, radius + 0.05, Math.sin(angle) * r);
+ mesh.castShadow = true;
+ envPropsGroup.add(mesh);
+ worldDynamicProps.push({ kind: 'ball', mesh, radius });
+ }
+
+ for (let i = 0; i < crates; i++) {
+ const s = 0.4 + Math.random() * 0.18;
+ const mesh = new Mesh(
+ new BoxGeometry(s * 2, s * 2, s * 2),
+ new MeshStandardMaterial({ color: 0x9c6b3f, roughness: 0.85, metalness: 0.0 }),
+ );
+ const angle = (i / crates) * Math.PI * 2 - 0.8;
+ const r = 2.0 + Math.random() * 1.4;
+ mesh.position.set(Math.cos(angle) * r, s + 0.02, Math.sin(angle) * r);
+ mesh.rotation.y = Math.random() * Math.PI;
+ mesh.castShadow = true;
+ mesh.receiveShadow = true;
+ envPropsGroup.add(mesh);
+ worldDynamicProps.push({ kind: 'box', mesh, half: s });
+ }
+}
+
// Environment indicator
const envIndicator = (() => {
const el = document.createElement('div');
@@ -2925,6 +3073,45 @@ function showHelpOnFirstVisit() {
}, 6000);
}
+// ── Physics bring-up ────────────────────────────────────────────────────────
+// Rebuild the static + dynamic colliders to match the current scenery. Safe to
+// call before physics is ready (no-op) and on every environment swap.
+function rebuildPhysicsWorld() {
+ if (!physics || !physicsReady) return;
+ physics.clearObstacles();
+ physics.clearDynamics();
+ for (const o of worldObstacles) {
+ if (o.type === 'box') physics.addStaticBox(o);
+ else if (o.type === 'cylinder') physics.addStaticCylinder(o);
+ }
+ for (const p of worldDynamicProps) {
+ if (p.kind === 'ball') physics.addDynamicBall({ mesh: p.mesh, radius: p.radius });
+ else if (p.kind === 'box') physics.addDynamicBox({ mesh: p.mesh, halfExtents: { x: p.half, y: p.half, z: p.half } });
+ }
+}
+
+async function initWalkPhysics() {
+ try {
+ physics = await PhysicsWorld.create({ gravity: { x: 0, y: GRAVITY, z: 0 } });
+ physics.addGround(GROUND_Y, GROUND_RADIUS + 40);
+ character = physics.createCharacter({
+ position: { x: avatarRig.position.x, y: avatarRig.position.y, z: avatarRig.position.z },
+ radius: 0.3,
+ halfHeight: Math.max(0.3, (avatarHeight || 1.7) / 2 - 0.3),
+ });
+ physicsReady = true;
+ // Catch up to whatever environment is already showing.
+ rebuildPhysicsWorld();
+ } catch (err) {
+ // Solver failed to load — the legacy movement path keeps the scene fully
+ // playable, so degrade quietly rather than blocking the experience.
+ console.warn('[walk] physics unavailable, using legacy movement:', err);
+ physics = null;
+ physicsReady = false;
+ character = null;
+ }
+}
+
// ── Boot ──────────────────────────────────────────────────────────────────
loadAvatar()
.then(() => {
@@ -2932,6 +3119,8 @@ loadAvatar()
startNet();
// Apply saved environment
applyEnvironment(currentEnvIndex);
+ // Bring up the physics solver (async WASM); legacy movement runs until ready.
+ initWalkPhysics();
// Show camera mode if not default
if (cameraMode !== 'follow') {
if (avatar) avatar.visible = cameraMode !== 'firstperson';
diff --git a/tasks/iso-mmo/README.md b/tasks/iso-mmo/README.md
deleted file mode 100644
index 7ea5f77e8..000000000
--- a/tasks/iso-mmo/README.md
+++ /dev/null
@@ -1,97 +0,0 @@
-# Isometric MMO — Build Tasks
-
-This directory holds self-contained build prompts for the tile-based isometric
-multiplayer game served at `/play`. Each `task-NN-*.md` is an independent,
-end-to-end feature spec. Hand any one to an engineer (or agent) and it should be
-buildable to completion without further context.
-
-## The codebase you are working in
-
-**Authoritative game server** — Colyseus rooms (standalone Node process, not Vercel):
-- `multiplayer/src/rooms/GameRoom.js` — the room: validates every client intent, owns all state.
-- `multiplayer/src/rooms/realms.js` — realm/map definitions + geometry helpers (`inBounds`, `isBlocked`, `portalAt`, `inRect`, `realmLayout`).
-- `multiplayer/src/schemas/game.js` — `@colyseus/schema` state (`GameState`, `GamePlayer`, `Slot`, `ResourceNode`, `Mob`, `Tombstone`).
-- `multiplayer/src/index.js` — server entry; registers rooms (`game_mainland`, `walk_world`).
-
-**Game client** — vanilla JS + Three.js, built by Vite:
-- `src/game/iso-game.js` — renderer, HUD, input, scene build (`_buildRealm`), message handlers.
-- `src/game/game-net.js` — Colyseus client connection + message bus (`net.on(...)`, `net.send(...)`).
-- `src/game/iso-game.css` — game UI styles.
-- `public/play.html` / `dist/play.html` — the `/play` entry document.
-
-**Wallet / Solana** — `src/wallet-auth.js`, `src/wallet.js`, `src/solana.js`.
-
-**Backend HTTP** — Vercel functions in `api/` (use for persistence, token quotes,
-payment verification — anything that is not a live WebSocket concern).
-
-## Current baseline (already built — do not rebuild)
-
-Single realm only (Mainland). Working: click-to-walk movement with server-side
-walkability validation, camera zoom/rotate, 24-slot inventory + 6-slot hotbar
-with drag/swap/stack-to-999, resource gathering (tree/axe, rock/pickaxe, coal),
-melee combat vs. mobs, training dummies, skill XP + leveling (cap 99), fountain
-healing + passive regen, 48-slot bank, gold awarded on kills.
-
-Key constants in `GameRoom.js`: `INV_SIZE=24`, `HOTBAR_SIZE=6`, `BANK_SIZE=48`,
-`MAX_STACK=999`. Skills: `combat`, `woodcutting`, `mining`, `fishing`, `cooking`.
-
-## Engineering standards (apply to EVERY task)
-
-These are non-negotiable and override any urge to cut corners:
-
-1. **Real data and real integrations only.** No mocks, no fake/sample arrays, no
- stubbed responses, no `setTimeout` fake progress. Wire real RPC, real APIs,
- real on-chain calls, real persistence.
-2. **Server-authoritative.** The client sends intent; the server validates
- everything (bounds, adjacency, ownership, cooldowns, rate limits, balances)
- before mutating state. Never trust a client payload.
-3. **Wire it end-to-end.** Schema → server handler → network message → client
- handler → rendered UI → user-reachable control. A feature with no way to
- reach it in the UI is not done. No dead buttons, no orphan handlers.
-4. **Every state is designed.** Loading, empty, error, populated, overflow. Tell
- the user what to do next; never show a blank void or an unexplained failure.
-5. **No TODOs, no stubs, no commented-out code, no `throw "not implemented"`.**
- If you write it, finish it.
-6. **Match existing patterns.** Follow the rate-limit, cooldown, `priv`-map,
- `clean()`, `_addItem`, `_adjacent`, and message-naming conventions already in
- `GameRoom.js`. Follow `iso-game.js` conventions for scene groups and HUD.
-7. **Persistence-aware.** Anything the player earns or changes must survive a
- disconnect once Task 16 (persistence) lands. Until then, write through the
- same save interface that task defines — do not bake in in-memory-only assumptions.
-8. **Verify before claiming done.** Run the server + client, exercise the feature
- in a browser, confirm no console errors and real network traffic. State
- explicitly what you verified.
-
-## Build order (dependencies)
-
-Foundations first — several tasks unblock the rest:
-
-- **Task 01 (realm traversal)** unblocks 02, 03, 04, 05, 06, 08, 22, 23.
-- **Task 16 (persistence)** unblocks/needed-by 10, 12, 15, 17, 19, 20, 21, 23.
-- **Task 17 (wallet auth)** unblocks 18; **Task 18 (token)** unblocks 19, 20.
-
-| # | Task | Depends on |
-|----|------|-----------|
-| 01 | Multi-realm support & portal traversal | — |
-| 02 | Player death & tombstone death-bags | 01 |
-| 03 | Mob AI: roam, aggro, chase, contact damage | 01 |
-| 04 | PvP combat & safe-zone enforcement | 01, 03 |
-| 05 | Fishing | 01 |
-| 06 | Cooking & edible food healing | 01, 05 |
-| 07 | Building: firepit, shack & /pickup | 01 |
-| 08 | Mainland mine interior | 01 |
-| 09 | Mob loot drops & mounts | 02, 03 |
-| 10 | Quests: tutorial & daily quests | 16 |
-| 11 | Skills panel UI & progression feedback | — |
-| 12 | Hotbar number keys & rebindable keybindings | 16 |
-| 13 | Chat slash commands | 14 |
-| 14 | World chat: rate limit, length cap, mute | — |
-| 15 | Friends: requests, presence, direct messages | 16, 17 |
-| 16 | Account-keyed player persistence | 17 (account id) |
-| 17 | Wallet sign-in & token-balance gate | — |
-| 18 | On-chain token: treasury, burn, USD pricing | 17 |
-| 19 | Spinner wheel | 18 |
-| 20 | Marketplace: gold & gold-for-token listings | 16, 18 |
-| 21 | Cosmetics shop | 16 |
-| 22 | Additional realms & Arena (rollers, level-gated cave) | 01 |
-| 23 | Multi-server world instances | 16 |
diff --git a/tasks/iso-mmo/task-01-realm-traversal.md b/tasks/iso-mmo/task-01-realm-traversal.md
deleted file mode 100644
index a7c5b2fd8..000000000
--- a/tasks/iso-mmo/task-01-realm-traversal.md
+++ /dev/null
@@ -1,76 +0,0 @@
-# Task 01 — Multi-realm support & portal traversal
-
-## Context
-
-The game server only ever runs one map. `multiplayer/src/rooms/GameRoom.js`
-hardcodes `const MAINLAND = REALMS.mainland` and binds all geometry helpers to
-it. `multiplayer/src/index.js` registers a single room `game_mainland`. Yet
-`multiplayer/src/rooms/realms.js` already fully defines four realms — `mainland`,
-`wilderness`, `whisperwood`, `pond` — each with `spawn`, `safe`/`pvp`/`danger`
-flags, `blocked`, `bankZone`, `fountain`, `nodes`, `mobs`, `fishing`, `cooking`,
-`safeCamp`, and `portals` with `{x0,y0,x1,y1,to,toTx,toTy}` destinations. There is
-a `portalAt(realm, tx, ty)` helper and a `realmLayout(realm)` serializer, but
-**nothing calls them** and players can never leave Mainland.
-
-Note: `GameRoom.onJoin` hand-builds the `realm` client message and omits
-`fishing`, `cooking`, `safeCamp`, and `portals`. The client (`iso-game.js`
-`_buildRealm`) already reads `layout.fishing`, `layout.cooking`, and
-`layout.portals` — so it renders portals but the server never sends them.
-
-## Goal
-
-Make the game multi-realm. Players step onto a portal tile and arrive in the
-destination realm at its `toTx,toTy`, with the world (nodes, mobs, geometry,
-flags) fully swapped, and `safe`/`pvp`/`danger` rules applied per realm.
-
-## What to build
-
-1. **Parameterize `GameRoom` by realm.** Accept a realm name via room options /
- definition (e.g. `onCreate(options)` reads `options.realm`, default
- `mainland`). Replace the `MAINLAND` constant with `this.realm = REALMS[name]`
- and rebind `isBlocked`/`inBounds`/spawn/fountain/bankZone to it. `_seedWorld`,
- `onJoin`, healing, and respawn must all use `this.realm`.
-2. **Register every realm.** In `index.js`, register a room per realm
- (`game_mainland`, `game_wilderness`, `game_whisperwood`, `game_pond`) or one
- `game` definition filtered by `realm` so each realm is its own instance.
- Players in different realms must not see or affect each other.
-3. **Send the full layout on join.** Replace the hand-built `realm` message with
- `realmLayout(this.realm)` so `fishing`, `cooking`, `safeCamp`, `portals`,
- `safe`, `pvp`, `danger` all reach the client.
-4. **Portal detection on movement.** In `_handleStep`, after a valid step, call
- `portalAt(this.realm, p.tx, p.ty)`. If a portal is hit, transition the player:
- - Carry the player's full state (inventory, hotbar, gold, skills/XP, bank,
- hp, cosmetic) to the destination realm room. Use Colyseus seat reservation
- (`matchMaker.reserveSeatFor`) and send the client a `transfer` message with
- the destination room id + reservation + spawn tile, OR consolidate realms
- into one room that swaps the player's active realm + reseeds their view.
- Pick one approach and implement it completely — state must not be lost.
- - On arrival the player spawns at `toTx,toTy` of the destination realm.
-5. **Client transition.** `iso-game.js` / `game-net.js`: handle the `transfer`
- message by reconnecting/rejoining the destination room (or rebuilding the
- realm if single-room), preserving the camera and avatar. No flfrom-scratch
- reload, no flash of the wrong map. Show a brief, designed transition (fade or
- portal flash) — real, not a fake timer.
-6. **Per-realm rules wired now** (deeper behavior is owned by later tasks, but
- the flags must be respected and readable): expose `realm.safe/pvp/danger` to
- the systems that need them; ensure Mainland/Whisperwood/Pond stay safe and
- Wilderness is danger+pvp outside its `safeCamp`.
-
-## Definition of done
-
-- Walking onto each Mainland portal tile lands you in Wilderness / Whisperwood /
- Pond at the correct return tile, and the reverse portals bring you back.
-- Inventory, hotbar, gold, skills, bank, hp, and avatar are identical before and
- after a transition (verified by inspection).
-- Players in different realms are isolated (two browser sessions confirm it).
-- Client renders each realm's geometry, fishing/cooking tiles, safe camp, and
- portals from the server-sent layout. No console errors.
-- HUD realm label updates to the destination realm name.
-
-## Dependencies & follow-ons
-
-Foundation task — unblocks 02, 03, 04, 05, 06, 08, 22, 23. Additional realm data
-(Wilderness North/East, Arena) is added in Task 22 once traversal exists.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-02-death-tombstones.md b/tasks/iso-mmo/task-02-death-tombstones.md
deleted file mode 100644
index c59f95d98..000000000
--- a/tasks/iso-mmo/task-02-death-tombstones.md
+++ /dev/null
@@ -1,66 +0,0 @@
-# Task 02 — Player death & tombstone death-bags
-
-## Context
-
-`multiplayer/src/schemas/game.js` already defines a `Tombstone` schema
-(`id`, `owner`, `ownerName`, `tx`, `ty`, `items: [Slot]`, `expiresAt`) and
-`GameState.tombstones` is a `MapSchema`. `GamePlayer` has `dead` and `respawnAt`
-fields. The simulation tick in `GameRoom._tick` already respawns a dead player
-(`if (p.dead) { ... p.dead = false; ... }`). **But nothing ever sets
-`p.dead = true`** — there is no damage-to-players path and no tombstone is ever
-created. Players are effectively immortal. Realms carry a `danger` flag
-(`realms.js`): Wilderness is `danger: true`; Mainland/Whisperwood/Pond are not.
-
-## Goal
-
-When a player's HP reaches zero, they die: respawn at the realm's safe spawn
-after a delay, and — only in `danger` realms — drop a tombstone holding part of
-their inventory that they (and, after a grace window, anyone) can recover before
-it expires.
-
-## What to build
-
-1. **Death trigger.** Add a `_killPlayer(p)` path invoked whenever player HP hits
- 0 (from mob contact damage in Task 03, PvP in Task 04, or any future source).
- Set `p.dead = true`, `p.motion = 'idle'`, `p.respawnAt = now + RESPAWN_PLAYER_MS`,
- and broadcast a `died` notice to the client.
-2. **Tombstone drop (danger realms only).** On death in a `danger` realm, move a
- defined subset of the player's items into a new `Tombstone` at the death tile:
- - Decide and document the drop rule (e.g. equipped tools kept, stackable
- resources and non-tool items dropped). Keep it deterministic and fair.
- - Populate `items`, `owner`, `ownerName`, `tx/ty`, and
- `expiresAt = now + TOMBSTONE_TTL_MS`. Insert into `state.tombstones`.
- - In safe realms, no tombstone is created and no items are lost.
-3. **Per-realm isolation.** Because each realm is its own room (Task 01),
- tombstones already cannot collide across realms — confirm a death in one
- realm never affects another player's view elsewhere.
-4. **Recovery.** Add an `onMessage('tombLoot', ...)` handler: validate the player
- is adjacent to the tombstone, then transfer items back into their inventory
- (`_addItem`, respecting full-inventory leftover). Enforce ownership: only the
- `owner` may loot until a grace window passes (`now > expiresAt - GRACE_MS`),
- after which anyone adjacent may loot. Remove the tombstone when empty.
-5. **Expiry.** In `_tick`, delete tombstones past `expiresAt`.
-6. **Client.** Render tombstones in the object group (`iso-game.js`) as a
- distinct mesh/marker with the owner name. Clicking an adjacent tombstone sends
- `tombLoot` and opens a small recovery panel showing its contents. Designed
- empty state ("This bag is empty") and a clear "expires in Xs" countdown driven
- by `expiresAt` (real value, not a fake timer). Death shows a respawn overlay
- with the real countdown to `respawnAt`.
-
-## Definition of done
-
-- Dying in Wilderness drops a tombstone with the correct items; dying in a safe
- realm does not.
-- The owner can recover items by walking back and clicking; after the grace
- window others can; expired tombstones vanish server-side and client-side.
-- Respawn returns the player to the realm spawn with full HP after the delay.
-- Inventory math is exact (no item duplication or loss). No console errors.
-
-## Dependencies
-
-Requires Task 01 (realms + per-realm rooms). Damage sources that cause death are
-delivered by Task 03 (mobs) and Task 04 (PvP); build death/tombstone mechanics so
-those tasks only need to call `_killPlayer`.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-03-mob-ai.md b/tasks/iso-mmo/task-03-mob-ai.md
deleted file mode 100644
index 04f0f9569..000000000
--- a/tasks/iso-mmo/task-03-mob-ai.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Task 03 — Mob AI: roam, aggro, chase, contact damage
-
-## Context
-
-Mobs are static targets. `realms.js` defines mobs with `roam` and `aggro` flags
-(Wilderness has goblins/ogre with `roam: true, aggro: true`; Mainland has
-training dummies with both `false`). The `Mob` schema (`game.js`) has an
-`aggroId` field ("session id of the player this mob is chasing"). But
-`GameRoom._tick` only handles mob respawn — **mobs never move, never aggro, and
-never damage players.** Combat is one-directional (player hits mob).
-
-## Goal
-
-Give mobs server-authoritative behavior: roamers wander, aggressive mobs detect
-nearby players, chase them, and deal contact damage during a hit window —
-feeding the death/tombstone system (Task 02). Dummies stay inert for practice.
-
-## What to build
-
-1. **Carry behavior flags into state.** When seeding (`_seedWorld`), persist each
- mob's `roam`/`aggro` (off-schema in a server-side map, or add fields) plus a
- spawn/home tile for leashing. Add tuning constants (aggro radius, leash
- radius, move interval, contact damage, attack cooldown, mob HP regen).
-2. **Mob simulation in `_tick`** (or a dedicated faster mob tick):
- - **Roam:** idle mobs with `roam` occasionally step to a random adjacent
- walkable tile within a leash radius of home. Reuse the same walkability
- rules as players (`inBounds`, `isBlocked`, node/mob/player occupancy).
- - **Aggro acquisition:** an `aggro` mob with no target scans for the nearest
- living, non-dead player within aggro radius and in the same realm; set
- `aggroId`. Respect safe zones — a mob must not enter or aggro inside a
- `safeCamp` (`inRect`) or in a `safe` realm.
- - **Chase:** a mob with an `aggroId` steps one tile toward that player each
- move tick (greedy pathing around obstacles). Drop aggro and return home if
- the player dies, leaves the realm, enters the safe camp, or exceeds the
- leash radius.
- - **Contact damage:** when adjacent to its target and its attack cooldown is
- ready, deal damage to the player (`p.hp -= dmg`, clamp at 0). If HP hits 0,
- call `_killPlayer` (Task 02). Set a `hitTs`-style marker so the client can
- flash the player.
-3. **Mount/loot drops** are owned by Task 09 — leave a clean hook on mob death.
-4. **Client.** Mobs already render and tween position from synced `tx/ty`;
- confirm chasing reads smoothly. Show a damage flash + floating damage number
- when the local player is hit, and an aggro indicator on hostile mobs.
- Player HP bar reflects incoming damage in real time.
-
-## Definition of done
-
-- Goblins/ogre in Wilderness wander, notice a nearby player, chase, and deal
- damage; standing in the safe camp stops them at the fence.
-- Training dummies on Mainland never move or attack.
-- A player can be killed by mobs, triggering Task 02 death/tombstone in danger
- realms. Movement remains smooth; no teleporting mobs; no console errors.
-- Mob CPU cost is bounded (no O(players×mobs) blowups per frame — scans run on
- the sim tick, not the patch rate).
-
-## Dependencies
-
-Requires Task 01 (realms). Calls `_killPlayer` from Task 02. Leaves the kill hook
-for Task 09 (loot/mounts).
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-04-pvp-safezones.md b/tasks/iso-mmo/task-04-pvp-safezones.md
deleted file mode 100644
index aaf6e5b9f..000000000
--- a/tasks/iso-mmo/task-04-pvp-safezones.md
+++ /dev/null
@@ -1,60 +0,0 @@
-# Task 04 — PvP combat & safe-zone enforcement
-
-## Context
-
-`_handleAttack` in `GameRoom.js` only resolves attacks against mobs
-(`state.mobs.get(...)`). There is no player-vs-player combat. Realms carry the
-rules already: `realms.js` marks `pvp: true` on Wilderness (with a southern
-`safeCamp` rectangle that disables PvP) and `pvp: false` on Mainland,
-Whisperwood, and Pond. The `inRect` helper exists for safe-camp tests.
-
-## Goal
-
-Allow players to attack other players, but only where the realm rules permit:
-PvP enabled realms outside any safe camp. Safe realms and safe camps fully
-prevent player damage.
-
-## What to build
-
-1. **Target resolution.** Extend the attack path to accept a player target
- (e.g. `attack` payload distinguishes `{ kind: 'mob'|'player', id }`, or add a
- parallel `attackPlayer` message). Resolve the target player from
- `state.players`.
-2. **PvP gating (server-authoritative).** Permit a player hit only when ALL hold:
- - `this.realm.pvp === true`.
- - Neither attacker nor target is inside `this.realm.safeCamp`
- (`inRect(safeCamp, tx, ty)`), and the realm is not `safe`.
- - Attacker and target are adjacent (`_adjacent`), both alive, not the same
- player, and the attack cooldown is ready.
- Reject (with a client `notice`) in all other cases — including any attempt to
- hit a player on Mainland/Whisperwood/Pond.
-3. **Damage + death.** Apply damage using the existing damage formula (combat
- level + sword bonus + variance). On HP 0, call `_killPlayer` (Task 02) so the
- victim drops a tombstone in danger realms. Award the killer appropriately
- (define and document: e.g. combat XP; decide whether gold/loot transfers —
- keep it consistent with the tombstone model so loot flows through the bag, not
- a direct steal).
-4. **Anti-abuse.** Keep PvP under the same attack rate limit/cooldown as PvE.
- Prevent spawn-camping basics: brief post-respawn protection (a short
- invulnerability window where the player cannot deal or take player damage).
-5. **Client.** Make other players targetable (click) only where PvP is legal;
- show a clear affordance (e.g. hostile cursor / outline) when over an
- attackable player and a "safe zone" indicator where PvP is disabled. Floating
- damage numbers and HP bars for the involved players. A killfeed/notice on a
- PvP kill.
-
-## Definition of done
-
-- Two sessions can fight in Wilderness outside the camp; neither can damage the
- other inside the camp or in any safe realm (server rejects it, not just UI).
-- A PvP death drops the victim's tombstone (Task 02) and applies the documented
- reward to the killer. Respawn protection prevents instant re-kills.
-- No way to bypass the gate from a crafted client payload. No console errors.
-
-## Dependencies
-
-Requires Task 01 (realm flags/rooms) and Task 02 (`_killPlayer`/tombstones).
-Shares the damage model with Task 03.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-05-fishing.md b/tasks/iso-mmo/task-05-fishing.md
deleted file mode 100644
index 3fa52256b..000000000
--- a/tasks/iso-mmo/task-05-fishing.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# Task 05 — Fishing
-
-## Context
-
-The `fishing` skill exists on `GamePlayer` (`game.js`) and `realms.js` defines
-`fishing` tiles (shoreline coordinates) on Whisperwood and Pond, serialized to
-the client via `realmLayout`. The client `_buildRealm` already paints fishing
-spots. A `rod` tool is in the starter kit and `STACKABLE` already includes
-`'fish'`. **But there is no fishing handler** — no way to cast, no catch roll, no
-fish item awarded, and `priv.xp` doesn't even track `fishing` consistently
-(`onJoin` seeds `xp: { woodcutting, mining, fishing, combat }` — confirm fishing
-and add cooking where missing). Fishing XP is never granted anywhere.
-
-## Goal
-
-A complete fishing loop: equip the rod, stand next to fishable water, cast, and —
-after a real per-cast resolution — receive raw fish and fishing XP, scaled by
-skill and spot quality.
-
-## What to build
-
-1. **Cast handler.** `onMessage('fish', ...)`: validate the player is alive, the
- `rod` is on the active hotbar slot, the player is adjacent to a `fishing` tile
- of the current realm, and a fishing cooldown has elapsed. Rate-limit it
- (reuse the `gather` bucket pattern or add a `fish` limit).
-2. **Catch resolution.** Roll success against fishing skill + spot quality (define
- a clear curve — higher skill = higher catch rate and/or better yield). On
- success, `_addItem(p, 'fish', n)` (respect full-inventory leftover) and
- `_grantXp(sessionId, p, 'fishing', amount)`. On a miss, give a small XP trickle
- or none, and a "the fish got away" notice. Apply a per-cast cooldown so casting
- has cadence (real async resolution on the sim/cooldown clock — no fake timer).
-3. **Spot quality.** Allow tuning per realm/tile (e.g. Pond's open water richer
- than Whisperwood ponds). Keep data in `realms.js` if it needs to vary.
-4. **Client.** When the rod is equipped and the player clicks an adjacent fishing
- tile, send `fish` and show a cast animation/line + bobber, then resolve to a
- caught-fish toast or a miss toast. Disable casting (with a hint) when no rod is
- equipped or not adjacent to water. Update the fishing skill display on level-up.
-
-## Definition of done
-
-- Equipping the rod and clicking adjacent water in Whisperwood/Pond yields raw
- fish over repeated casts, with fishing XP and visible level-ups.
-- Casting is rejected (with a helpful notice) without a rod, away from water, or
- when the inventory is full. Catch rate visibly improves as fishing level rises.
-- No console errors; server validates every cast (no client-claimed catches).
-
-## Dependencies
-
-Requires Task 01 (realm layout incl. fishing tiles delivered to client). Feeds
-Task 06 (cooking consumes raw fish).
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-06-cooking-food.md b/tasks/iso-mmo/task-06-cooking-food.md
deleted file mode 100644
index aa2c50d75..000000000
--- a/tasks/iso-mmo/task-06-cooking-food.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# Task 06 — Cooking & edible food healing
-
-## Context
-
-The `cooking` skill exists on `GamePlayer`, and `realms.js` defines a `cooking`
-tile cluster on Pond labeled "the Roast Pit", serialized via `realmLayout` and
-painted by the client. There is **no cooking handler, no cooked-fish item, and no
-way to eat food to heal.** Note: `GameRoom.onJoin` seeds `priv.xp` without a
-`cooking` key — add it. Healing today is only the fountain + passive regen.
-
-## Goal
-
-Cook raw `fish` into `cookedFish` at the Roast Pit for cooking XP, and let players
-eat cooked fish (and other consumables) from inventory/hotbar to restore HP.
-
-## What to build
-
-1. **Cook handler.** `onMessage('cook', ...)`: validate alive, holding `fish`,
- and adjacent to a `cooking` tile of the current realm (the Roast Pit). Apply a
- cook cooldown + rate limit. Convert one (or a batch) `fish` → `cookedFish`:
- decrement the raw stack, `_addItem(p, 'cookedFish', n)`, grant cooking XP. Add
- a small burn-chance at low cooking levels that consumes the fish without a
- cooked result (improves with level) — keep it fair and documented. Add
- `cookedFish` to `STACKABLE`.
-2. **Eat/consume handler.** `onMessage('consume', ...)`: validate the referenced
- slot holds an edible item (`cookedFish`, and any `potion` items introduced by
- shop/loot later). Restore HP (`cookedFish` a fixed/level-scaled heal; potions
- their own values), consume one from the stack, apply a short consume cooldown.
- Never overheal past `maxHp`. Works from inventory or hotbar.
-3. **Item registry.** Introduce a small server-side item definition map (heal
- amount, edible flag, stackable flag) so consumables are data-driven, not
- hardcoded in branches. Use it from `consume` and from `_addItem`/`STACKABLE`.
-4. **Client.** At the Roast Pit, clicking with raw fish (or a "Cook" action)
- sends `cook` and shows a cooking animation + result toast; burned results are
- communicated honestly. Right-click / "Eat" on a cooked-fish or potion slot
- sends `consume` and animates the HP gain. Disable cooking away from a pit with
- a hint. Cooking skill display updates on level-up.
-
-## Definition of done
-
-- At the Pond Roast Pit, raw fish convert to cooked fish with cooking XP and
- visible level-ups; cooking elsewhere is rejected with a helpful notice.
-- Eating cooked fish restores HP (capped at max) from inventory and hotbar;
- potions consume correctly when present.
-- Burn chance falls as cooking level rises. No item dupe/loss. No console errors.
-
-## Dependencies
-
-Requires Task 01 (cooking tiles in layout) and Task 05 (raw fish supply). The
-consumable/item registry here is reused by Task 09 (loot), Task 20 (marketplace),
-and Task 21 (shop).
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-07-building-firepit-shack.md b/tasks/iso-mmo/task-07-building-firepit-shack.md
deleted file mode 100644
index 257bdedee..000000000
--- a/tasks/iso-mmo/task-07-building-firepit-shack.md
+++ /dev/null
@@ -1,61 +0,0 @@
-# Task 07 — Building: firepit, shack & /pickup
-
-## Context
-
-There is no building system. Players gather `wood`, `stone`, and `coal` but have
-nothing to spend them on beyond the bank. The world has a fountain for healing
-but no player-placed structures. Movement is tile-stepped and the client already
-has a scene object group for dynamic world objects.
-
-## Goal
-
-A complete placement system for two structures, plus pickup:
-- **Firepit** — costs 20 stone + 20 coal + 50 wood, lasts ~30s, heals players who
- stand adjacent (like the fountain), then decays. Placeable in allowed realms.
-- **Shack** — costs 500 wood + 200 stone, Whisperwood only, one per player,
- decorative landmark (no internal storage), persistent until picked up.
-- **/pickup** — removes a structure you own, freeing the shack's one-per-player
- slot for re-placement.
-
-## What to build
-
-1. **Schema.** Add a `Structure` schema (`id`, `kind: 'firepit'|'shack'`, `owner`,
- `ownerName`, `tx`, `ty`, `expiresAt` (0 = permanent), optional `locked`) and a
- `structures` `MapSchema` on `GameState`. Structures occupy/are solid on their
- tile (factor into `_isWalkable`).
-2. **Placement handler.** `onMessage('build', { kind, tx, ty })`: validate alive;
- target tile is in-bounds, walkable, adjacent to the player, and not on a
- portal/bank/fountain/resource tile; the realm allows that structure (shack →
- Whisperwood only; firepit → allowed realms); the player owns < the cap (shack
- one-per-player across realms); and the player has the exact material cost.
- Deduct materials atomically, create the structure, set `expiresAt` for firepit.
-3. **Firepit healing + decay.** In `_tick`, heal players adjacent to any firepit
- (reuse the fountain heal logic), and delete firepits past `expiresAt`.
-4. **Pickup + lock.** Implement `/pickup` (see Task 13 command routing, but the
- server action lives here): list/remove structures the caller owns; picking up
- a shack frees the slot. Implement `/lock` and `/unlock` to toggle a structure's
- `locked` flag so it ignores stray clicks.
-5. **Client build mode.** Add a build menu (from the hotbar/`B` key) listing
- buildable structures with their costs and whether the player can afford them.
- Entering build mode shows a ghost preview that snaps to tiles and turns
- red/green for invalid/valid placement; left-click places (sends `build`),
- right-click cancels; movement clicks are suppressed until exit. Render
- firepits (with a real countdown ring from `expiresAt`) and shacks in the
- object group. Designed empty/affordability states ("Need 200 more wood").
-
-## Definition of done
-
-- A firepit can be built only when you have 20 stone + 20 coal + 50 wood; it
- heals adjacent players and disappears after its lifetime.
-- A shack can be built only in Whisperwood, one per player; building a second is
- rejected until the first is picked up; `/pickup` frees the slot.
-- `/lock`/`/unlock` protect structures from mis-clicks. Materials are deducted
- exactly (no negative balances, no free builds). No console errors.
-
-## Dependencies
-
-Requires Task 01 (realm rules per structure). `/pickup` `/lock` `/unlock` routing
-comes from Task 13; implement the server-side actions here and expose them.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-08-mine-interior.md b/tasks/iso-mmo/task-08-mine-interior.md
deleted file mode 100644
index a3c385562..000000000
--- a/tasks/iso-mmo/task-08-mine-interior.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# Task 08 — Mainland mine interior
-
-## Context
-
-The world guide describes a mine entrance on the Mainland that leads to an
-interior mining area dense with rocks and coal. Today Mainland has only a handful
-of surface `rock`/`coal` nodes (`realms.js`), and there is no interior space.
-Realm traversal + portals now exist (Task 01), so an interior is just another
-realm reachable through an entrance tile.
-
-## Goal
-
-Add a mining interior reachable from a Mainland mine entrance: an enclosed cave
-map rich in rock and coal nodes, with a return portal to the Mainland entrance.
-
-## What to build
-
-1. **Define the interior realm** in `realms.js` (e.g. `mine`): an enclosed cave
- grid, `safe: true` (no PvP/death — it is a Mainland-side resource area unless
- you intentionally make it dangerous; default safe), walled `blocked` regions
- forming cave corridors, a spawn at the entrance, and a dense set of `rock` and
- `coal` nodes. No bank/fountain. A return portal to the Mainland mine entrance.
-2. **Mainland entrance.** Add a portal rectangle on Mainland (the mine entrance
- tile) with `to: 'mine'` and matching return coordinates, mirroring the existing
- portal pattern. Register the `mine` realm/room in `index.js` (Task 01 pattern).
-3. **Visuals.** Give the interior a cave look in the client (`iso-game.js`
- `_buildRealm` reads the layout; darker ground/walls, rock-textured blocks).
- Keep it readable and performant.
-4. **Balance.** Tune node counts and respawn timers so the mine is a meaningfully
- better mining spot than the surface without trivializing progression.
-
-## Definition of done
-
-- Walking onto the Mainland mine entrance transports the player into the cave
- interior; the return portal brings them back to the entrance tile.
-- The interior has working rock/coal nodes (pickaxe gathers them, mining XP
- granted) and renders as a distinct cave space. No console errors.
-- Players in the mine are isolated from the surface (separate room/instance).
-
-## Dependencies
-
-Requires Task 01 (multi-realm traversal + portals). Uses the existing gathering
-system unchanged.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-09-loot-mounts.md b/tasks/iso-mmo/task-09-loot-mounts.md
deleted file mode 100644
index 65da53fdf..000000000
--- a/tasks/iso-mmo/task-09-loot-mounts.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# Task 09 — Mob loot drops & mounts
-
-## Context
-
-When a mob dies in `_handleAttack`, the player gets gold + combat XP and the mob
-respawns — but no items drop. The world guide says mobs occasionally drop
-**mounts**, which players can ride for faster movement and leave with a
-`/dismount` command. There is currently no loot table, no mount item, and no
-mounted-movement system. Tasks 02/03/04 left a clean "mob death" hook.
-
-## Goal
-
-A loot system that drops items (notably mounts) from mob kills on a rolled
-chance, plus a mount system: equip a mount to move faster, and dismount on
-command.
-
-## What to build
-
-1. **Loot tables.** Add a data-driven drop table keyed by mob `kind` (e.g.
- goblin/ogre have a small mount-drop chance plus any other intended drops).
- Roll on mob death (both PvE and, if applicable, the mob-death hook from Task
- 03). Award items via `_addItem`; if the inventory is full, drop the loot into a
- ground bag (reuse the Task 02 tombstone/bag mechanics) rather than vanishing.
-2. **Mount item + state.** Define mount items in the item registry (Task 06).
- Add player mount state (e.g. `mounted` flag / `mount` id on `GamePlayer`).
- Equipping/using a mount item from the hotbar mounts the player.
-3. **Mounted movement.** While mounted, increase effective movement speed. Since
- movement is tile-stepped and server-validated, implement speed as a reduced
- step cooldown / higher step rate-limit headroom for mounted players — keep it
- server-authoritative (no client-claimed speed). Decide and document whether
- gathering/combat are restricted while mounted.
-4. **/dismount.** Wire the `/dismount` command (routing from Task 13; action
- here): clear mount state and return to normal speed. Also auto-dismount on
- death.
-5. **Client.** Render the mount under/around the avatar when mounted, animate
- faster locomotion, and show a mount indicator in the HUD. A kill that drops a
- mount shows a celebratory, honest notice ("The ogre dropped a mount!"). Mount
- from the hotbar; `/dismount` (or a HUD button) to get off.
-
-## Definition of done
-
-- Killing mobs occasionally yields real drops per the table; mounts can be
- obtained, equipped, and ridden for visibly faster travel; `/dismount` works and
- death auto-dismounts.
-- Loot never silently disappears on a full inventory (it bags on the ground).
-- Speed is enforced server-side. No console errors.
-
-## Dependencies
-
-Requires Task 03 (mob death hook) and Task 02 (ground-bag mechanics for overflow
-loot). Uses the item registry from Task 06. `/dismount` routing from Task 13.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-10-quests.md b/tasks/iso-mmo/task-10-quests.md
deleted file mode 100644
index 318608ea3..000000000
--- a/tasks/iso-mmo/task-10-quests.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# Task 10 — Quests: tutorial & daily quests
-
-## Context
-
-New players spawn with a starter kit (`onJoin` hands out axe/pickaxe/rod/sword)
-but there is **no guidance and no objectives system.** The world guide describes
-a tutorial NPC that walks new players through tools, bank, and the marketplace,
-plus daily quests with gather/combat objectives, gold/item/XP rewards, and a
-daily reset. None of this exists.
-
-## Goal
-
-Two complementary systems:
-- **Tutorial** — a first-session, step-by-step onboarding driven by a Mainland
- NPC that unlocks/teaches core actions (move, gather, hotbar, bank, marketplace)
- at the right pace and tracks completion per account.
-- **Daily quests** — a rotating set of objectives (chop X wood, mine X stone,
- catch X fish, kill X mobs in realm Y) that grant rewards and reset on a daily
- schedule.
-
-## What to build
-
-1. **NPC entity.** Add an NPC to Mainland (data in `realms.js` or an NPC table):
- a fixed, interactable character near spawn. Clicking/approaching opens a
- dialog. Render it client-side as a distinct character with a name tag and an
- "!" / "?" quest marker reflecting available/turn-in state.
-2. **Quest engine (server).** Define quests as data: `id`, `type`
- (`gather`/`combat`/`tutorial-step`), target item/mob/realm, count, and reward
- (gold, items, XP, optional badge). Track per-player progress server-side
- (`priv` and, once Task 16 lands, persisted). Increment progress from the real
- action hooks — gathering (`_handleGather`), kills (`_handleAttack`), fishing
- (Task 05) — not from client claims. Detect completion and allow turn-in for
- rewards (granted via `_addItem`/gold/`_grantXp`).
-3. **Tutorial flow.** A scripted ordered list of steps; advancing requires the
- player to actually perform the action (gather once, open the bank, open the
- marketplace, etc.). Persist tutorial completion so it does not repeat. Unlocks
- should feel paced, not dumped at once.
-4. **Daily quests.** Assign a daily set per account; reset on a fixed daily
- schedule (compute next-reset timestamp; expose it to the client for a real
- countdown). Rewards include gold/items/XP and sometimes a profile badge
- (badge stored on the account; surfaced wherever the profile renders).
-5. **Client quest UI.** A quest panel (HUD button + maybe `Q`) showing active
- tutorial step and daily quests with live progress bars, reward previews, a
- real reset countdown, and turn-in buttons. NPC dialog UI for accepting/turning
- in. Designed empty state ("All dailies complete — back tomorrow") and
- completion toasts.
-
-## Definition of done
-
-- A fresh account is guided through the core loop by the NPC; the tutorial does
- not replay after completion.
-- Daily quests track real progress from real actions, can be turned in for
- rewards, and reset on schedule with an accurate countdown.
-- Badges awarded by quests appear on the player profile. No console errors; no
- client-side progress spoofing possible.
-
-## Dependencies
-
-Requires Task 16 (persistence) so tutorial completion, daily assignment, progress,
-and badges survive sessions. Reads action hooks from gathering/combat/fishing.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-11-skills-ui.md b/tasks/iso-mmo/task-11-skills-ui.md
deleted file mode 100644
index 9efda98aa..000000000
--- a/tasks/iso-mmo/task-11-skills-ui.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# Task 11 — Skills panel UI & progression feedback
-
-## Context
-
-Progression works server-side: `_grantXp` accumulates per-skill XP in the `priv`
-map and `levelForXp` converts it to a level (cap 99), broadcasting only the
-integer level on `GamePlayer` (`combat`, `woodcutting`, `mining`, `fishing`,
-`cooking`). The client renders none of this as a dedicated surface — there is no
-skills panel, no XP bar, no level-up feedback, and the current level cap is not
-shown anywhere. Some content is meant to be skill-gated (e.g. a level-gated
-cave in Task 22; the spinner requires an average skill level — Task 19).
-
-## Goal
-
-A skills UI that shows each skill's level, progress to the next level, and the
-cap, with satisfying level-up feedback — plus a reusable "average skill level"
-read other systems can gate on.
-
-## What to build
-
-1. **Expose XP progress.** The schema broadcasts only levels (kept lean on
- purpose). Add a way for a player to see their own XP progress: send the
- requesting client its private XP map + the XP thresholds (e.g. an
- `onMessage('skills', ...)` that replies with current XP, XP for current and
- next level, and the cap). Do not broadcast XP to peers.
-2. **Level-up events.** When `_grantXp` raises a level, send the client a
- `levelup` notice ({ skill, level }) so the UI can celebrate it.
-3. **Average-skill helper.** Add a server helper computing the player's average
- skill level (used by Task 19's spin gate and any future gates). Expose it where
- needed; keep the computation authoritative.
-4. **Client skills panel.** A HUD-accessible panel (button + a key, e.g. `K`)
- listing all five skills with: level, an XP progress bar to next level (from the
- `skills` reply), and the level cap. Show total/average level. Live-update on
- `levelup`. Designed states for level 1 (fresh) through 99 (maxed: "Mastered").
-5. **Level-up feedback.** A non-intrusive celebratory toast/animation on
- `levelup` with the skill icon and new level. No fake numbers — driven by real
- server events.
-
-## Definition of done
-
-- The skills panel shows accurate levels, XP-to-next, and the cap for the local
- player, updating live as XP is earned.
-- Leveling a skill triggers a visible level-up celebration.
-- Peers cannot see each other's raw XP. The average-skill helper returns correct
- values for gating. No console errors.
-
-## Dependencies
-
-None hard; pairs with Task 19 (spin gate uses the average-skill helper) and Task
-22 (cave level gate). Persistence (Task 16) keeps levels across sessions.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-12-keybindings.md b/tasks/iso-mmo/task-12-keybindings.md
deleted file mode 100644
index 619d2c55b..000000000
--- a/tasks/iso-mmo/task-12-keybindings.md
+++ /dev/null
@@ -1,51 +0,0 @@
-# Task 12 — Hotbar number keys & rebindable keybindings
-
-## Context
-
-The client (`iso-game.js`) handles movement and camera input and has a 6-slot
-hotbar with an `equip` message, but **the number keys 1–6 are not wired to
-select hotbar slots**, and there is no keybindings settings UI. The world guide
-specifies defaults: `I` inventory, `M` map, `B` build, `C` chat, `F` friends,
-`R` rotate camera, `1–6` hotbar, `0` clear hotbar selection, `Esc` close top
-modal, `Enter` confirm. `R` rotate already exists; others are partial or missing.
-
-## Goal
-
-Wire all default keybindings, including hotbar 1–6 and 0-to-clear, and add a
-settings UI to rebind any action, persisted per account.
-
-## What to build
-
-1. **Central keybinding map.** Introduce a single source of truth for actions →
- keys (default to the spec above). Route all keydown handling through it instead
- of scattered literal key checks. Guard so bindings don't fire while typing in
- chat or an input field.
-2. **Hotbar keys.** `1`–`6` set `activeSlot` (send `equip`); `0` clears selection
- (`activeSlot = -1`). Reflect the active slot visually in the hotbar.
-3. **Panel toggles.** `I`/`M`/`B`/`C`/`F` open/close their panels (wire to the
- inventory, map, build (Task 07), chat (Task 14), friends (Task 15) surfaces as
- they exist; for not-yet-built panels, wire the toggle to the placeholder the
- owning task will fill — do not leave a dead key). `Esc` closes the top-most
- modal; `Enter` confirms the focused dialog. `R` keeps rotating the camera.
-4. **Rebinding UI.** A Settings → Controls panel listing every action and its
- current key, with a "click to rebind → press a key" capture flow. Detect and
- warn on conflicts; allow reset-to-defaults. Persist the custom map per account
- (Task 16; until then, persist to the same save interface).
-5. **Accessibility.** Visible focus states, keyboard navigability of the settings
- panel itself, and ARIA labels on the rebind controls.
-
-## Definition of done
-
-- Pressing 1–6 selects the matching hotbar slot and 0 clears it; the active slot
- is visually obvious and used by world clicks.
-- All default keys perform their action and none fire while typing in chat.
-- Rebinding any action works, conflicts are surfaced, reset-to-defaults works,
- and custom bindings persist across sessions. No console errors.
-
-## Dependencies
-
-Toggles connect to panels owned by Tasks 07/14/15; wire them as those land.
-Persistence of custom bindings uses Task 16.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-13-slash-commands.md b/tasks/iso-mmo/task-13-slash-commands.md
deleted file mode 100644
index 7ee9a6cb0..000000000
--- a/tasks/iso-mmo/task-13-slash-commands.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# Task 13 — Chat slash commands
-
-## Context
-
-There is no command system in the game. The world guide lists player commands:
-`/pickup` (pick up your firepit/shack), `/lock` and `/unlock` (protect structures
-from mis-clicks), `/dismount` (leave a mount), `/who` (list nearby players in your
-realm), and `/help` (list commands). Several of these have their action logic
-defined in other tasks (`/pickup` `/lock` `/unlock` → Task 07; `/dismount` →
-Task 09). This task builds the parser/router and the self-contained commands.
-
-## Context dependency
-
-Slash commands are entered through chat, so build on the world chat input from
-Task 14 (or, if building first, add a minimal command input that Task 14 absorbs).
-
-## What to build
-
-1. **Command router (server).** A single parser that receives chat input
- beginning with `/`, splits command + args, validates the command exists and
- the caller may run it, dispatches to a handler, and returns a result message
- to that client. Unknown commands return a helpful error. Rate-limit commands.
-2. **Wire the commands:**
- - `/pickup` — invoke the Task 07 structure-pickup action (list owned
- structures or pick up the targeted/nearest one; free the shack slot).
- - `/lock` / `/unlock` — toggle the Task 07 structure `locked` flag for the
- owner's adjacent structure.
- - `/dismount` — invoke the Task 09 dismount action.
- - `/who` — reply with the list of players currently in the caller's realm
- (real `state.players`, count + names), respecting any privacy/mute rules.
- - `/help` — reply with the list of available commands + one-line descriptions,
- generated from the command registry (never a hardcoded duplicate list).
-3. **Client.** Typing a `/command` in chat sends it through the command path;
- command replies render as system messages distinct from player chat.
- Autocomplete/hint for command names is a plus (show matching commands as the
- user types `/`). `/help` output is readable and scannable.
-
-## Definition of done
-
-- Each command runs its real action and returns accurate output; `/help` lists
- exactly the registered commands; `/who` reflects real realm occupancy.
-- Commands for actions the caller can't perform (no structure to pick up, not
- mounted) return a clear, honest message rather than failing silently.
-- Commands are rate-limited and validated server-side. No console errors.
-
-## Dependencies
-
-Requires Task 14 (chat input) and the action implementations in Task 07
-(`/pickup` `/lock` `/unlock`) and Task 09 (`/dismount`). `/who` and `/help` are
-self-contained here.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-14-world-chat.md b/tasks/iso-mmo/task-14-world-chat.md
deleted file mode 100644
index 9e6a3045a..000000000
--- a/tasks/iso-mmo/task-14-world-chat.md
+++ /dev/null
@@ -1,51 +0,0 @@
-# Task 14 — World chat: rate limit, length cap, mute
-
-## Context
-
-The game room (`GameRoom.js`) has no chat. The sibling room
-`multiplayer/src/rooms/WalkRoom.js` already implements a working chat (message
-handling around lines 191/346–351) with the patterns this game should reuse:
-sanitization, rate limiting, and broadcast. The world guide specifies world chat
-focused with `C`, messages to everyone online, per-window rate limits, rejection
-of overly long messages, and the ability to mute players.
-
-## Goal
-
-A world chat for the game realm: send/receive messages to everyone in the realm,
-rate-limited and length-capped, with client-side mute.
-
-## What to build
-
-1. **Server chat handler.** Add `onMessage('chat', ...)` to `GameRoom`: sanitize
- with the existing `clean()` helper, enforce a max length (reject longer
- messages with a notice), and rate-limit using the established bucket pattern
- (`_rateOk`, e.g. a `chat` limit). Broadcast accepted messages to the realm with
- sender id + name + sanitized text + server timestamp. Reuse `WalkRoom`'s
- approach so behavior is consistent across the two experiences.
-2. **Scope.** Chat is per-realm (each realm is its own room), matching player
- visibility. Do not leak messages across realms/instances.
-3. **Command passthrough.** Messages starting with `/` route to the command
- system (Task 13) instead of broadcasting.
-4. **Client chat UI.** A chat panel + input focused with `C` (Task 12 binding):
- scrollback of recent messages with sender names, send on `Enter`, auto-scroll,
- and an unobtrusive collapsed state. Show rejected-message feedback (too long /
- rate-limited) inline. Distinguish system/command replies from player messages.
-5. **Mute.** Let a player mute another (e.g. click a name → Mute). Muted senders'
- messages are hidden client-side. Persist the mute list per account (Task 16).
- Provide an unmute path and a view of who is muted.
-
-## Definition of done
-
-- Two sessions in the same realm see each other's messages in real time; sessions
- in different realms do not.
-- Over-length and flood messages are rejected server-side with clear feedback.
-- Muting hides a player's messages and persists; unmuting restores them.
-- `/` messages go to commands, not chat. No console errors.
-
-## Dependencies
-
-Reuses `WalkRoom` chat patterns. Feeds Task 13 (command input). Mute persistence
-uses Task 16.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-15-friends.md b/tasks/iso-mmo/task-15-friends.md
deleted file mode 100644
index 7863d4dc3..000000000
--- a/tasks/iso-mmo/task-15-friends.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# Task 15 — Friends: requests, presence, direct messages
-
-## Context
-
-There is no social graph. Players cannot add each other, see who is online, or
-message privately. The world guide describes a friends system: add by search or
-invite, mutual accept required, see who is online and which realm they are in,
-and send direct messages. (Parties and teleport-to-friend are explicitly NOT in
-scope — do not build those.)
-
-## Goal
-
-An account-level friends system: send/accept friend requests, see friends'
-online status and current realm, and exchange direct messages.
-
-## What to build
-
-1. **Account identity.** Friends are keyed to accounts (wallet address from Task
- 17), not ephemeral session ids — a friendship must survive reconnects and
- realm changes. Use the persistence layer (Task 16).
-2. **Friend graph API.** Backend endpoints (Vercel functions in `api/`, or a
- dedicated store) for: search users by display name, send a friend request,
- accept/decline, remove a friend, and list friends. Requests are pending until
- accepted; both directions stored consistently. Validate the requester owns the
- account (auth from Task 17). Guard against spam/self-add/duplicate requests.
-3. **Presence + location.** Track which accounts are online and their current
- realm. Since players connect to per-realm Colyseus rooms, publish presence
- from the server (a shared presence store — Redis presence is already wired in
- `index.js` when `REDIS_URI` is set; use it, or the persistence store) so a
- friend's online/offline + realm shows accurately across instances.
-4. **Direct messages.** Allow sending a DM to a friend whether or not they are in
- the same realm. Deliver in real time if online; queue + deliver on next login
- if offline (persisted). Respect the mute list (Task 14). Rate-limit + length-
- cap like world chat.
-5. **Client friends UI.** A friends panel (HUD + `F` binding from Task 12):
- incoming/outgoing requests with accept/decline, the friends list with live
- online/offline + realm badges, a search-to-add flow, and a DM thread view with
- unread indicators. Designed empty state ("No friends yet — search to add
- someone") and offline/error states.
-
-## Definition of done
-
-- A request can be sent, accepted, and the friendship appears for both accounts
- and persists across sessions.
-- Friends' online status and current realm display accurately, including across
- separate realm instances.
-- DMs deliver live when online and arrive on next login when offline; muted users
- are suppressed; spam is rate-limited. No console errors.
-
-## Dependencies
-
-Requires Task 16 (persistence) and Task 17 (account identity/auth). Uses presence
-infra referenced in `index.js`. Honors Task 14 mute list.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-16-persistence.md b/tasks/iso-mmo/task-16-persistence.md
deleted file mode 100644
index c9164c406..000000000
--- a/tasks/iso-mmo/task-16-persistence.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# Task 16 — Account-keyed player persistence
-
-## Context
-
-All game state is in-memory and lost on disconnect. `GameRoom.onJoin` builds a
-fresh `GamePlayer` every time (empty inventory + starter kit), and the per-player
-`priv` map (XP, bank, cooldowns) is created on join and deleted on leave
-(`onLeave`). Nothing is saved. The world guide promises that display name,
-inventory, hotbar, bank, gold, skills, tutorial progress, daily quests, placed
-structures, friends, cosmetics, and profile badge all save automatically. This
-is the foundation the economy and social systems depend on.
-
-## Goal
-
-Persist each player's full progression keyed to their account so a returning
-player resumes exactly where they left off, across realms and reconnects.
-
-## What to build
-
-1. **Account key.** Use the authenticated account id (wallet address from Task
- 17) as the persistence key. Before auth lands, key on a stable id from the
- join handshake, but design the interface around the account id so Task 17 is a
- drop-in.
-2. **Persistence store.** Choose and wire a real durable store reachable from the
- standalone multiplayer process (e.g. the same backend datastore the rest of
- the platform uses, exposed via `api/` endpoints the game server calls, or a
- direct DB/KV client). No local-only JSON files that die with the instance, no
- in-memory fakes. Must work across multiple server instances (Task 23).
-3. **Persisted profile shape.** Define a single serializable profile:
- `name`, `inv`, `hotbar`, `activeSlot`, `bank`, `gold`, skill XP (all five,
- including `cooking`), `hp/maxHp`, `cosmetic`/equipped cosmetics + owned
- cosmetics (Task 21), placed structures (Task 07), tutorial completion + daily
- quest state + badges (Task 10), friends + mute list (Tasks 14/15), keybindings
- (Task 12), and current realm + tile (so they resume in place, or at a safe
- spawn if that realm is unsafe to resume into).
-4. **Load on join / save on change.** On `onJoin`, load the profile (or create a
- new one with the starter kit on first ever login) and hydrate `GamePlayer` +
- `priv`. Save on meaningful mutations — debounced/throttled to avoid write
- storms (mirror the debounced-save pattern in `block-store.js` /
- `blockStore.flushAll()` used by `WalkRoom`), and flush on `onLeave`,
- `onDispose`, and server shutdown (`index.js` already calls
- `blockStore.flushAll()` on SIGTERM — hook the player store into the same path).
-5. **Cross-realm continuity.** When a player transitions realms (Task 01), their
- profile follows; persistence is account-scoped, not room-scoped.
-6. **Integrity.** Saves are atomic per account (no partial writes corrupting a
- profile). Concurrent logins of the same account are handled (reject the second,
- or hand off) so two sessions can't fork-and-clobber a profile.
-
-## Definition of done
-
-- Gather/earn/bank/level/build, disconnect, reconnect — everything is exactly as
- left, including across a server restart.
-- A brand-new account starts with the correct starter kit; an existing account
- never gets reset.
-- Saves are debounced under load and flushed on leave/shutdown; no write storms,
- no lost last-second changes. No console errors.
-
-## Dependencies
-
-Pairs with Task 17 (account id). Required by Tasks 10, 12, 14, 15, 19, 20, 21,
-23. Reuse the `block-store.js` debounced-save + flush conventions.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-17-wallet-auth.md b/tasks/iso-mmo/task-17-wallet-auth.md
deleted file mode 100644
index 29ebe8f3b..000000000
--- a/tasks/iso-mmo/task-17-wallet-auth.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# Task 17 — Wallet sign-in & token-balance gate
-
-## Context
-
-The `/play` entry (`public/play.html`) lets anyone in — there is no sign-in and
-no account identity beyond an ephemeral Colyseus session id. The platform already
-has wallet plumbing (`src/wallet-auth.js`, `src/wallet.js`, `src/solana.js`) and
-the multiplayer server has a holder-gate secret pattern (`HOLDER_PASS_SECRET` in
-`index.js`, `multiplayer/src/holder-pass.js`). The world guide specifies: sign in
-with a Solana wallet (the wallet address IS the account; no email/password), and
-hold at least 1 unit of the game token in the connected wallet to play.
-
-## Goal
-
-Gate `/play` behind a wallet sign-in that produces a verified account identity,
-and require a minimum token balance to enter, with the wallet address used as the
-persistence/account key everywhere.
-
-## What to build
-
-1. **Sign-in flow (client).** On `/play`, require connecting a Solana wallet and
- signing a login message (reuse `src/wallet-auth.js`/`wallet.js`). Sign a
- server-issued nonce so the signature can't be replayed. Surface connect /
- signing / signed states clearly; never ask for a seed phrase.
-2. **Signature verification (server/api).** Verify the signed nonce server-side
- to authenticate the wallet address. Issue a short-lived token/session the game
- server trusts (extend the existing holder-pass signing approach so the
- standalone Colyseus process can validate it — it already refuses to boot in
- prod without `HOLDER_PASS_SECRET`). The Colyseus `onAuth`/join must validate
- this and bind the verified wallet address to the session.
-3. **Token-balance gate.** Read the connected wallet's balance of the game token
- from a real Solana RPC (use the platform's existing RPC config). Require
- ≥ 1 token to play. Enforce on the server at join (not just client UI) so the
- gate can't be bypassed. Re-check on a sensible cadence, not just once, if you
- want to drop players who offload below the threshold — document the policy.
-4. **Account binding.** Pass the verified wallet address into the game as the
- account id, which Task 16 uses as the persistence key and Task 15 uses for the
- social graph. The displayed name maps to this account.
-5. **States.** Designed screens for: wallet not installed, not connected,
- signature rejected, balance too low (with a clear path to acquire the token /
- link to funding), and verifying. Honest errors, no dead ends.
-
-## Definition of done
-
-- Reaching `/play` requires connecting + signing; an unsigned or forged session
- cannot join the game room (server-enforced).
-- A wallet holding < 1 token is refused with a clear, actionable message; ≥ 1
- token gets in.
-- The verified wallet address is the account id used for persistence and friends.
- Balance is read from real RPC, not assumed. No console errors.
-
-## Dependencies
-
-Foundation for Task 16 (account key), Task 18 (token), and Task 15 (account
-identity). Reuses existing wallet/Solana modules + holder-pass secret.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-18-token-economy.md b/tasks/iso-mmo/task-18-token-economy.md
deleted file mode 100644
index 130b589cf..000000000
--- a/tasks/iso-mmo/task-18-token-economy.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# Task 18 — On-chain token: treasury, burn & USD pricing
-
-## Context
-
-The game references an on-chain token used for premium actions (paid wheel spins,
-token-priced marketplace sales) but there is **no token integration in the game
-code** — no mint config, no treasury wallet, no burn, no USD-based price quoting,
-no payment verification. The platform has Solana tooling (`src/solana.js`,
-`api/` functions, payment helpers under `api/payments/`) to build on. This task
-establishes the shared on-chain primitives that Tasks 19 and 20 consume.
-
-## Goal
-
-A reusable, real on-chain token layer: read the live token price, quote a USD
-amount as a token amount, build/verify payment transactions, and route proceeds
-to burn + treasury per the configured split.
-
-## What to build
-
-1. **Config.** Centralize the token mint address, decimals, treasury wallet
- address, and split policy in config/env (no hardcoded literals scattered
- around). Fail loudly if required values are missing in production, mirroring
- the `HOLDER_PASS_SECRET` boot guard.
-2. **Live price + USD quoting.** Fetch the token's live USD price from a real
- source (the price feed/oracle the platform already uses — e.g. the Pump.fun /
- market data path). Provide `quoteTokenForUsd(usd)` returning the token amount
- at current price, with a short server-side quote validity window so a quoted
- price can't be exploited after the market moves.
-3. **Payment build + verify.** Server issues a quote (amount, recipient split,
- nonce, expiry). Client wallet signs/sends one transaction. Server verifies the
- on-chain transaction: correct amount, correct destinations (burn address +
- treasury per split), confirmed on-chain, nonce unused, within expiry. Only a
- verified payment unlocks the paid action. Never trust a client "paid" claim.
-4. **Burn + treasury split.** Implement the split primitive (e.g. 50/50 for paid
- spins: half to the burn address, half to treasury; and the 95/5 seller/treasury
- split for marketplace token sales). Make the split a parameter so Tasks 19/20
- reuse the same verified-payment path with different ratios.
-5. **Auditability.** Record each settled payment (payer, amount, split, tx
- signature, purpose) in the persistence store for reconciliation. Expose a
- minimal internal read path; do not log secrets.
-
-## Definition of done
-
-- A USD amount quotes to a correct token amount at the live price, with an
- enforced quote expiry.
-- A real signed transaction is verified end-to-end (amount + burn/treasury
- destinations + confirmation) before the paid action is granted; replays and
- underpayments are rejected.
-- Burn and treasury receive the configured shares on a real transaction. Settled
- payments are recorded. No secrets logged. No console errors.
-
-## Dependencies
-
-Requires Task 17 (authenticated wallet). Consumed by Task 19 (paid spins) and
-Task 20 (token-priced listings). Uses existing Solana/payment infra + price feed.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-19-spinner-wheel.md b/tasks/iso-mmo/task-19-spinner-wheel.md
deleted file mode 100644
index 75b90d9fa..000000000
--- a/tasks/iso-mmo/task-19-spinner-wheel.md
+++ /dev/null
@@ -1,61 +0,0 @@
-# Task 19 — Spinner wheel
-
-## Context
-
-There is no spinner/prize-wheel feature anywhere in the game. The world guide
-describes a wheel on the Mainland (near a casino landmark): a 20-segment prize
-table, one free spin every 12 hours, and on-demand paid spins costing $3 USD
-worth of the game token (50% burned, 50% to treasury). Spinning requires an
-average skill level of 5. About 1 in 20 spins awards gold; the rest award wood,
-stone, or coal in varying amounts. The paid spin does not consume the free-spin
-timer.
-
-## Goal
-
-A complete spinner: a Mainland wheel object that opens a spin UI, with a gated
-free spin on a 12h cooldown and paid spins settled on-chain, both drawing from
-one server-authoritative prize table.
-
-## What to build
-
-1. **Wheel object + gate.** Place a wheel near the Mainland casino landmark
- (`realms.js`/object table); clicking it opens the spinner UI. Server-side,
- require the player's average skill level ≥ 5 (use the Task 11 average-skill
- helper) to spin; otherwise reject with a clear notice.
-2. **Prize table (authoritative).** Define the 20-segment table server-side with
- real probabilities (~1/20 gold; remainder wood/stone/coal in varying amounts).
- The SERVER rolls the outcome — the client animation must land on the
- server-decided segment, never decide the prize itself. Award via
- `_addItem`/gold (respect full-inventory leftover; bag overflow if needed).
-3. **Free spin.** One free spin per 12h per account. Track `nextFreeSpinAt` in the
- persisted profile (Task 16); expose it so the client shows a real countdown.
- Reject early free spins server-side.
-4. **Paid spin.** Cost = $3 USD worth of token via Task 18 `quoteTokenForUsd`.
- Flow: server issues a quote → client wallet signs one transaction → server
- verifies it (Task 18) with a 50/50 burn/treasury split → only then roll +
- award the prize. The paid spin does NOT alter the free-spin timer. Reject the
- spin if payment verification fails.
-5. **Client spinner UI.** A wheel with the 20 segments, a spin animation that
- resolves to the server's chosen segment, the free-spin countdown, and a
- "Paid spin ($3 in token)" button that runs the payment flow with clear pending/
- confirming/success/failure states. Prize result shown honestly (exact item +
- amount). Designed states for: not eligible (avg level < 5, with how-to),
- free-spin-not-ready, wallet/payment errors.
-
-## Definition of done
-
-- Players below average skill level 5 cannot spin (server-enforced).
-- The free spin works once per 12h with an accurate countdown and cannot be
- spun early.
-- Paid spins require a real verified on-chain payment ($3 in token, 50% burn /
- 50% treasury) before awarding; the animation always matches the server outcome;
- the free timer is untouched. Prizes match the table distribution over many
- spins. No console errors.
-
-## Dependencies
-
-Requires Task 11 (average-skill helper), Task 16 (free-spin timer persistence),
-and Task 18 (token quote + verified payment + split).
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-20-marketplace.md b/tasks/iso-mmo/task-20-marketplace.md
deleted file mode 100644
index 0b4608572..000000000
--- a/tasks/iso-mmo/task-20-marketplace.md
+++ /dev/null
@@ -1,61 +0,0 @@
-# Task 20 — Marketplace: gold & gold-for-token listings
-
-## Context
-
-Players earn gold (mob kills) and gather stacks of resources, but there is no way
-to trade with other players. The `api/marketplace*` endpoints in this repo are
-the platform's AGENT marketplace — unrelated to the in-game item economy; do not
-repurpose them. The world guide describes an in-game marketplace opened from a
-HUD button (cart icon), with Buy / Sell / My Listings tabs, two listing types:
-- **Gold listings** — trade items for gold; buyer pays gold, seller receives the
- full amount (no fee).
-- **Gold-for-token listings** — a seller lists in-game gold priced in USD; buyers
- pay on-chain with the game token. Payment splits 95% to seller / 5% to treasury.
-
-## Goal
-
-A full player-to-player marketplace with both listing types, server-authoritative
-escrow of listed goods, and on-chain settlement for token listings.
-
-## What to build
-
-1. **Listing store.** Persist listings (Task 16 store / `api/`): `id`, `seller`
- account, type (`gold` | `goldForToken`), the offered item(s) or gold amount,
- price (gold amount, or USD for token listings), status, timestamps. Listings
- are account-scoped and survive sessions/instances.
-2. **Escrow on list.** When a player lists, remove the offered item/gold from
- their inventory immediately (escrow) so they can't list-and-spend the same
- goods. Returning unsold goods on cancel restores them. No duplication.
-3. **Gold listings (buy).** A buyer with enough gold buys: atomically debit buyer
- gold, credit seller the full amount, deliver escrowed item(s) to the buyer
- (bag overflow if inventory full). No treasury cut.
-4. **Gold-for-token listings (buy).** Buyer pays on-chain via Task 18: server
- quotes the token amount from the listing's USD price, buyer's wallet sends one
- transaction, server verifies it with a 95/5 seller/treasury split, then
- delivers the escrowed in-game gold to the buyer and records the sale. Seller
- receives 95% of the token to their wallet; 5% to treasury. Reject on failed
- verification; never release goods before settlement.
-5. **Marketplace UI.** A HUD cart button (works anywhere, no need to stand at a
- building) opening tabs:
- - **Buy** — browse active listings (filter/sort by item, price), buy flow with
- gold or wallet payment per listing type.
- - **Sell** — pick inventory items / gold amount, set price + type, confirm.
- - **My Listings** — view/cancel own listings (cancel returns escrow).
- Designed loading/empty ("No listings yet — be the first to sell")/error states,
- and clear pending/confirming states for on-chain buys.
-
-## Definition of done
-
-- Listing escrows the goods; cancel returns them; nothing can be double-spent.
-- Gold purchases transfer item↔gold atomically with no fee and no dupe/loss.
-- Token purchases require a real verified on-chain payment with the 95/5 split
- before the gold is released; the seller is paid 95% and treasury 5%.
-- Two sessions can complete a real trade each way. No console errors.
-
-## Dependencies
-
-Requires Task 16 (persistence/escrow store) and Task 18 (token quote + verified
-payment + split). Distinct from the platform agent marketplace.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-21-cosmetics-shop.md b/tasks/iso-mmo/task-21-cosmetics-shop.md
deleted file mode 100644
index ceb91ab2a..000000000
--- a/tasks/iso-mmo/task-21-cosmetics-shop.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# Task 21 — Cosmetics shop
-
-## Context
-
-`GamePlayer` has a `cosmetic` field and players can set an avatar URL
-(`_handleAvatar`, validated by `cleanAvatarUrl`), but there is no shop and no
-catalog of purchasable looks. The world guide describes a cosmetic shop selling
-visual-only outfits/styles (no combat effect), with rotating daily and weekly
-offers, bought with gold, and equipped from the dashboard cosmetics page.
-
-## Goal
-
-A cosmetics shop where players spend gold on visual-only cosmetics from a rotating
-catalog, own them permanently, and equip/unequip them — with no gameplay effect.
-
-## What to build
-
-1. **Cosmetic catalog.** Define cosmetics as data: `id`, name, visual asset/style,
- gold price, rarity, and rotation window (daily/weekly). Keep it data-driven and
- extendable. Cosmetics are strictly visual — never touch combat/stats.
-2. **Rotation.** Compute the current daily and weekly offer sets from a fixed
- schedule (deterministic from the date, server-authoritative), exposing the next
- rotation time for a real countdown. Some cosmetics are always available; others
- only during their rotation.
-3. **Purchase (server).** A buy handler: validate the cosmetic is currently
- offered and the player has enough gold; debit gold; add the cosmetic to the
- account's owned-cosmetics set (persisted, Task 16). Reject duplicates (already
- owned) and insufficient gold with clear notices.
-4. **Equip/unequip.** Let the player equip an owned cosmetic (sets `cosmetic` /
- equipped-cosmetic state, broadcast so peers see it) or revert to default.
- Persist the equipped selection. Equipping affects only appearance.
-5. **Client UI.** A cosmetics shop surface (HUD/dashboard) showing the rotating
- catalog with prices, owned vs. buyable state, affordability, a real rotation
- countdown, and buy buttons; plus a cosmetics page to equip/unequip owned items
- with a live preview on the avatar. Designed empty ("You don't own any cosmetics
- yet"), affordability, and confirmation states.
-
-## Definition of done
-
-- The shop shows a correct rotating catalog with an accurate next-rotation
- countdown; offers change on schedule.
-- Buying debits gold, grants permanent ownership, prevents duplicate purchase,
- and rejects when gold is short.
-- Equipping an owned cosmetic changes the avatar's appearance for the player and
- peers, persists across sessions, and never alters gameplay. No console errors.
-
-## Dependencies
-
-Requires Task 16 (owned cosmetics + equipped selection persistence). Uses the
-existing avatar/cosmetic rendering path.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-22-additional-realms-arena.md b/tasks/iso-mmo/task-22-additional-realms-arena.md
deleted file mode 100644
index cc379fef2..000000000
--- a/tasks/iso-mmo/task-22-additional-realms-arena.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Task 22 — Additional realms & Arena (rollers, level-gated cave)
-
-## Context
-
-`realms.js` defines four realms (mainland, wilderness, whisperwood, pond) and
-Task 01 made traversal real. The world guide describes more areas not yet built:
-- **Wilderness North** — a smaller northern area reached from the top of the main
- Wilderness; PvP across the whole map (no safe camp); lower mob density; a
- level-gated cave at the far north requiring high enough combat skill to enter.
-- **Wilderness East** — a full-size wild area east of the main Wilderness, also
- reachable from the north edge of the Pond; PvP + mob danger like the Wilderness.
-- **Arena** — a dedicated PvP scene reached from a Mainland arena plaza (with a
- small practice boxing ring on the Mainland itself); has moving floor "rollers"
- that push players, plus spectator seating.
-
-## Goal
-
-Add these realms with their distinguishing mechanics, fully connected to the
-existing portal network and rule systems.
-
-## What to build
-
-1. **Wilderness North.** Define the realm (`pvp: true, danger: true`, no
- `safeCamp`, lower mob density). Add the portal pair connecting the top of the
- main Wilderness to its south return. At the far north, a **level-gated cave
- portal**: entry requires the player's combat level ≥ a threshold (use the Task
- 11 helper); server rejects under-level entry with a clear notice. Build the
- cave as its own realm/instance beyond the gate.
-2. **Wilderness East.** Define the realm (`pvp: true, danger: true`), with portal
- pairs to the east edge of the main Wilderness AND the north edge of the Pond
- (add the matching portals on those existing realms). Populate nodes/mobs to
- match Wilderness danger.
-3. **Arena + boxing ring.** Add an arena plaza area on the Mainland (a small
- walkable boxing ring for practice — visual + tile region, no death risk) and a
- portal into the full **Arena** realm. The Arena is a PvP scene (`pvp: true`)
- with:
- - **Rollers** — tiles that, on the sim tick, push a standing player one tile in
- the roller's direction (server-authoritative, respecting walkability). Learn-
- the-flow movement, not teleporting.
- - Spectator/seating tiles (non-combat zones) and a south return strip to the
- Mainland plaza.
-4. **Registration + client visuals.** Register all new realms/rooms (Task 01
- pattern in `index.js`). Give each a fitting look in `_buildRealm` (cave,
- wild-north, wild-east, arena with visible rollers + seating). Ensure portals
- render and the HUD realm label updates.
-
-## Definition of done
-
-- Wilderness North and East are reachable through real portals, enforce PvP+
- danger, and connect where the guide says (incl. Pond↔East).
-- The northern cave rejects under-combat-level players and admits qualified ones.
-- The Mainland boxing ring is walkable/safe; the Arena is reachable, PvP-enabled,
- and rollers push players server-side along their direction; the return strip
- works. No console errors.
-
-## Dependencies
-
-Requires Task 01 (traversal), Task 04 (PvP rules for the wild realms + arena),
-Task 02/03 (death + mobs in the wild realms), and Task 11 (combat-level gate).
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tasks/iso-mmo/task-23-multi-server.md b/tasks/iso-mmo/task-23-multi-server.md
deleted file mode 100644
index 7ec490de6..000000000
--- a/tasks/iso-mmo/task-23-multi-server.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# Task 23 — Multi-server world instances
-
-## Context
-
-The server runs as a single set of realm instances. The world guide describes two
-selectable world instances ("Server 1" and "Server 2") on the same host: a player
-picks one at login, their items and gold are shared between them (account-scoped),
-but players on one server cannot see players on the other. `multiplayer/src/index.js`
-already supports horizontal scaling via Redis driver + presence when `REDIS_URI`
-is set, and Colyseus room filtering (`filterBy`) is already used for `walk_world`.
-
-## Goal
-
-Let players choose between two (or N) independent world instances at login.
-Instances are fully isolated for presence/visibility but share one account-scoped
-profile, so progression is identical regardless of which server you join.
-
-## What to build
-
-1. **Server dimension on rooms.** Add a `server` (instance) key to game room
- matchmaking — e.g. `filterBy(['realm', 'server'])` so each (realm, server)
- pair is its own room and players only ever match within their chosen server.
- Mirror the existing `walk_world` filtering pattern.
-2. **Login selection.** On `/play` (after wallet sign-in, Task 17), present a
- server picker showing the available instances with live population counts
- (real, from presence/matchmaking — not faked). The choice is passed as a join
- option and pins all of that session's realm rooms to the chosen server.
-3. **Shared account profile.** Because persistence (Task 16) is account-scoped,
- the same profile loads on either server — items, gold, skills, bank, etc. are
- identical. Verify a player can earn on Server 1, switch to Server 2, and see
- the same inventory. Guard against the same account being live on both servers
- simultaneously in a way that could clobber the profile (single active session
- per account, per Task 16 integrity rule).
-4. **Isolation.** Players on different servers never appear in each other's
- realms, chat (Task 14), or `/who` (Task 13). Presence/friends (Task 15) should
- still show a friend's online status and which server+realm they're on.
-5. **Population display + balancing.** Show real per-server population at the
- picker; optionally recommend the less-full server. No fake numbers.
-
-## Definition of done
-
-- The login picker lists the servers with real population counts; choosing one
- pins the session to it.
-- Two sessions on different servers cannot see or interact with each other in any
- realm/chat/who, but the SAME account on either server has identical progression.
-- Friends presence reflects which server+realm a friend is on. No profile
- clobbering across servers. No console errors.
-
-## Dependencies
-
-Requires Task 16 (account-scoped persistence + single-active-session rule) and
-Task 17 (account identity). Uses the Redis driver/presence + `filterBy` infra
-already present in `index.js`. Interacts with Tasks 13/14/15 for isolation.
-
----
-Build to the standards in [README.md](./README.md): real data, server-authoritative, fully wired end-to-end, every state designed, no shortcuts.
diff --git a/tests/cooking.test.js b/tests/cooking.test.js
deleted file mode 100644
index c3c609d68..000000000
--- a/tests/cooking.test.js
+++ /dev/null
@@ -1,138 +0,0 @@
-// Task 06 — cooking & edible food. These cover the data-driven core the cooking
-// feature rests on: the item registry's edibility/heal/stack facts (which the
-// server's consume handler reads), the burn-chance curve (which the cook handler
-// rolls against), level-scaled healing, and the daily quest pool entries.
-import { describe, it, expect } from 'vitest';
-import {
- ITEMS, STACKABLE_ITEMS, isEdible, isStackable, healValue, scaledHeal, cookBurnChance, clientItemRegistry,
-} from '../multiplayer/src/items.js';
-import { DAILY_POOL, BADGES } from '../multiplayer/src/quests.js';
-
-describe('item registry — consumables', () => {
- it('cooked fish is a stackable, edible heal of 11', () => {
- expect(ITEMS.cookedFish).toMatchObject({ stackable: true, edible: true, heal: 11 });
- expect(isEdible('cookedFish')).toBe(true);
- expect(isStackable('cookedFish')).toBe(true);
- expect(healValue('cookedFish')).toBe(11);
- });
-
- it('health potion is edible with its own heal value', () => {
- expect(isEdible('healthPotion')).toBe(true);
- expect(healValue('healthPotion')).toBe(28);
- });
-
- it('raw fish and tools are not edible and heal nothing', () => {
- expect(isEdible('fish')).toBe(false);
- expect(isEdible('axe')).toBe(false);
- expect(healValue('fish')).toBe(0);
- expect(healValue('axe')).toBe(0);
- expect(healValue('nonexistent')).toBe(0);
- });
-
- it('STACKABLE_ITEMS includes cooked fish + raw fish but not tools', () => {
- expect(STACKABLE_ITEMS.has('cookedFish')).toBe(true);
- expect(STACKABLE_ITEMS.has('fish')).toBe(true);
- expect(STACKABLE_ITEMS.has('axe')).toBe(false);
- expect(STACKABLE_ITEMS.has('sword')).toBe(false);
- });
-});
-
-describe('cookBurnChance — fair, falling burn curve', () => {
- it('starts at 40% for a level-1 cook', () => {
- expect(cookBurnChance(1)).toBeCloseTo(0.4, 10);
- });
-
- it('never burns once trained, and stays clamped at high levels', () => {
- expect(cookBurnChance(40)).toBe(0);
- expect(cookBurnChance(99)).toBe(0);
- // Below-floor inputs are treated as level 1 (max burn), never negative.
- expect(cookBurnChance(0)).toBeLessThanOrEqual(0.4);
- expect(cookBurnChance(-5)).toBeLessThanOrEqual(0.4);
- });
-
- it('is monotonically non-increasing and bounded in [0, 0.4]', () => {
- let prev = Infinity;
- for (let lvl = 1; lvl <= 99; lvl++) {
- const c = cookBurnChance(lvl);
- expect(c).toBeGreaterThanOrEqual(0);
- expect(c).toBeLessThanOrEqual(0.4);
- expect(c).toBeLessThanOrEqual(prev + 1e-12);
- prev = c;
- }
- });
-
- it('reaches zero burn somewhere in the high 30s', () => {
- expect(cookBurnChance(30)).toBeGreaterThan(0);
- expect(cookBurnChance(38)).toBe(0);
- });
-});
-
-describe('scaledHeal — cooking level makes food better', () => {
- it('level 1 cook heals the base 11 HP', () => {
- expect(scaledHeal('cookedFish', 1)).toBe(11);
- });
-
- it('heal improves with cooking level', () => {
- expect(scaledHeal('cookedFish', 10)).toBeGreaterThan(scaledHeal('cookedFish', 1));
- expect(scaledHeal('cookedFish', 50)).toBeGreaterThan(scaledHeal('cookedFish', 10));
- expect(scaledHeal('cookedFish', 99)).toBeGreaterThan(scaledHeal('cookedFish', 50));
- });
-
- it('potions return their flat base value regardless of cooking level', () => {
- const base = healValue('healthPotion');
- expect(scaledHeal('healthPotion', 1)).toBe(base);
- expect(scaledHeal('healthPotion', 99)).toBe(base);
- });
-
- it('non-edibles and unknown items always return 0', () => {
- expect(scaledHeal('fish', 99)).toBe(0);
- expect(scaledHeal('axe', 99)).toBe(0);
- expect(scaledHeal('nonexistent', 10)).toBe(0);
- });
-
- it('below-floor levels clamp to level 1 (no negative bonuses)', () => {
- expect(scaledHeal('cookedFish', 0)).toBe(scaledHeal('cookedFish', 1));
- expect(scaledHeal('cookedFish', -5)).toBe(scaledHeal('cookedFish', 1));
- });
-});
-
-describe('clientItemRegistry — heal exposed to client', () => {
- it('edible items carry their base heal in the client registry', () => {
- const reg = clientItemRegistry();
- expect(reg.cookedFish.heal).toBe(11);
- expect(reg.healthPotion.heal).toBe(28);
- });
-
- it('non-edible items have no heal key', () => {
- const reg = clientItemRegistry();
- expect(reg.fish.heal).toBeUndefined();
- expect(reg.axe.heal).toBeUndefined();
- });
-});
-
-describe('daily quest pool — fishing and cooking quests exist', () => {
- it('pool contains at least one fishing quest', () => {
- const fishQuests = DAILY_POOL.filter((q) => q.type === 'fish');
- expect(fishQuests.length).toBeGreaterThan(0);
- for (const q of fishQuests) {
- expect(q.id).toBeTruthy();
- expect(q.item).toBe('fish');
- expect(q.count).toBeGreaterThan(0);
- expect(q.reward).toBeDefined();
- }
- });
-
- it('pool contains at least one cooking quest', () => {
- const cookQuests = DAILY_POOL.filter((q) => q.type === 'cook');
- expect(cookQuests.length).toBeGreaterThan(0);
- for (const q of cookQuests) {
- expect(q.item).toBe('cookedFish');
- expect(q.count).toBeGreaterThan(0);
- }
- });
-
- it('fishing and cooking badges are defined', () => {
- expect(BADGES.fisher).toBeDefined();
- expect(BADGES.pitcook).toBeDefined();
- });
-});
diff --git a/tests/cosmetics-hud.test.js b/tests/cosmetics-hud.test.js
deleted file mode 100644
index 1b451f1c2..000000000
--- a/tests/cosmetics-hud.test.js
+++ /dev/null
@@ -1,182 +0,0 @@
-// @vitest-environment jsdom
-//
-// Cosmetics shop HUD (Task 21) — the DOM half of the in-world shop the scene
-// drives. Verifies the gold readout, the buy/wardrobe tabs, affordability +
-// owned states, equip/unequip wiring, the rotation-section countdown, and the
-// empty wardrobe state, so the player-facing chrome is exercised without a
-// browser. Fed the same shapes the server sends (catalogue + shop board).
-
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-
-globalThis.self = globalThis;
-
-import { GameHud } from '../src/game/game-hud.js';
-import { clientCatalog, currentOffers, cosmeticById } from '../multiplayer/src/cosmetics.js';
-
-const CAT = clientCatalog();
-const T = Date.UTC(2026, 5, 1, 12, 0, 0);
-
-let hud;
-let calls;
-afterEach(() => { hud?.destroy(); hud = null; document.body.innerHTML = ''; });
-
-function mount() {
- calls = { buy: [], equip: [], unequip: 0, shopOpen: 0, preview: [], stop: 0 };
- hud = new GameHud({
- onShopOpen: () => calls.shopOpen++,
- onBuyCosmetic: (id) => calls.buy.push(id),
- onEquipCosmetic: (id) => calls.equip.push(id),
- onUnequipCosmetic: () => calls.unequip++,
- onPreviewCosmetic: (id) => calls.preview.push(id),
- onStopPreview: () => calls.stop++,
- });
- hud.setCosmeticCatalog(CAT.cosmetics, CAT.rarities);
- return hud;
-}
-
-// A shop board for instant T with a given purse / owned / equipped.
-function board({ gold = 1000, owned = [], equipped = '' } = {}) {
- return { offers: currentOffers(T), owned, equipped, gold };
-}
-
-// Every id currently on the board (all three buckets).
-function offeredIds() {
- const o = currentOffers(T);
- return [...o.daily, ...o.weekly, ...o.always];
-}
-
-describe('gold readout', () => {
- it('reflects setGold in the toolbar and shop header', () => {
- mount();
- hud.setGold(1234);
- expect(document.querySelector('#kq-gold-n').textContent).toBe('1,234');
- expect(document.querySelector('#kq-shop-gold').textContent).toBe('1,234');
- });
-});
-
-describe('shop tab — buy board', () => {
- it('opens, fetches a fresh board, and renders the rotating + always sections', () => {
- mount();
- hud.openShop();
- expect(calls.shopOpen).toBe(1); // open pulls a fresh board
- hud.setShop(board({ gold: 2000 }));
- const sections = document.querySelectorAll('#kq-shop-body .kq-shop-section');
- expect(sections.length).toBe(3); // daily, weekly, always
- // A live countdown is present for the rotating sections.
- expect(document.querySelector('#kq-shop-daily-reset')).toBeTruthy();
- expect(document.querySelector('#kq-shop-weekly-reset')).toBeTruthy();
- // Every offered card is rendered.
- const offers = currentOffers(T);
- const total = offers.daily.length + offers.weekly.length + offers.always.length;
- expect(document.querySelectorAll('#kq-shop-body .kq-cos-card').length).toBe(total);
- });
-
- it('a cheap affordable card buys on the first click', () => {
- mount();
- hud.openShop();
- hud.setShop(board({ gold: 100000 }));
- const cheap = offeredIds().find((id) => cosmeticById(id).price < 400);
- expect(cheap).toBeTruthy();
- document.querySelector(`#kq-shop-body [data-cos-id="${cheap}"] .kq-cos-buy`).click();
- expect(calls.buy).toEqual([cheap]);
- });
-
- it('a pricey card needs a confirming second click before it buys', () => {
- mount();
- hud.openShop();
- hud.setShop(board({ gold: 100000 }));
- const pricey = offeredIds().find((id) => cosmeticById(id).price >= 400);
- expect(pricey).toBeTruthy();
- const sel = `#kq-shop-body [data-cos-id="${pricey}"] .kq-cos-buy`;
- document.querySelector(sel).click(); // first click arms "Confirm?"
- expect(calls.buy.length).toBe(0);
- expect(document.querySelector(sel).textContent).toMatch(/confirm/i);
- document.querySelector(sel).click(); // second click commits
- expect(calls.buy).toEqual([pricey]);
- });
-
- it('disables buying when the purse is short and shows the shortfall', () => {
- mount();
- hud.openShop();
- hud.setShop(board({ gold: 0 }));
- const card = document.querySelector('#kq-shop-body .kq-cos-card.kq-cos--short');
- expect(card).toBeTruthy();
- const btn = card.querySelector('.kq-cos-buy');
- expect(btn.disabled).toBe(true);
- btn.click();
- expect(calls.buy.length).toBe(0); // a disabled button never fires
- });
-
- it('lets you equip an owned cosmetic straight from the shop tab', () => {
- mount();
- hud.openShop();
- const ownedId = currentOffers(T).always[0];
- hud.setShop(board({ gold: 5000, owned: [ownedId] }));
- const card = document.querySelector(`#kq-shop-body [data-cos-id="${ownedId}"]`);
- expect(card).toBeTruthy();
- expect(card.querySelector('.kq-cos-buy')).toBeNull(); // owned → no buy button
- const equip = card.querySelector('.kq-cos-equip');
- expect(equip).toBeTruthy();
- equip.click();
- expect(calls.equip).toEqual([ownedId]);
- });
-});
-
-describe('wardrobe tab — equip / unequip', () => {
- it('shows the empty state when nothing is owned', () => {
- mount();
- hud.openShop();
- hud.setShop(board({ owned: [] }));
- hud._setShopTab('wardrobe');
- expect(document.querySelector('#kq-shop-body .kq-shop-empty')).toBeTruthy();
- });
-
- it('lists owned cosmetics + a Default tile and equips on click', () => {
- mount();
- hud.openShop();
- const owned = currentOffers(T).always.slice(0, 1);
- hud.setShop(board({ owned, equipped: '' }));
- hud._setShopTab('wardrobe');
- // Default tile is equipped when nothing else is.
- const equippedTag = document.querySelector('#kq-shop-body .kq-cos--equipped');
- expect(equippedTag).toBeTruthy();
- // Equip the owned cosmetic.
- const equipBtn = document.querySelector('#kq-shop-body .kq-cos-equip');
- expect(equipBtn).toBeTruthy();
- equipBtn.click();
- expect(calls.equip).toEqual(owned);
- });
-
- it('the Default tile unequips when a cosmetic is equipped', () => {
- mount();
- hud.openShop();
- const owned = currentOffers(T).always.slice(0, 1);
- hud.setShop(board({ owned, equipped: owned[0] }));
- hud._setShopTab('wardrobe');
- // The equipped cosmetic shows "Equipped"; the Default tile offers Equip.
- const defaultCard = document.querySelector('#kq-shop-body .kq-cos--default');
- expect(defaultCard).toBeTruthy();
- defaultCard.querySelector('.kq-cos-equip').click();
- expect(calls.unequip).toBe(1);
- });
-});
-
-
-describe('collection tab', () => {
- it('lists the whole catalogue with a completion count and previews on click', () => {
- mount();
- hud.openShop();
- const ownedId = currentOffers(T).always[0];
- hud.setShop(board({ owned: [ownedId] }));
- hud._setShopTab('collection');
- const cards = document.querySelectorAll('#kq-shop-body .kq-cos-card');
- expect(cards.length).toBe(CAT.cosmetics.length);
- expect(document.querySelector('#kq-shop-body .kq-shop-sub').textContent).toMatch(/^1 \/ /);
- // The owned one reads as owned; a locked one shows price + source.
- expect(document.querySelector(`#kq-shop-body [data-cos-id="${ownedId}"] .kq-cos-owned`)).toBeTruthy();
- expect(document.querySelector('#kq-shop-body .kq-cos-src')).toBeTruthy();
- // Tapping any card previews it on the local avatar.
- document.querySelector(`#kq-shop-body [data-cos-id="${ownedId}"]`).click();
- expect(calls.preview).toEqual([ownedId]);
- });
-});
diff --git a/tests/cosmetics.test.js b/tests/cosmetics.test.js
deleted file mode 100644
index dfc733fee..000000000
--- a/tests/cosmetics.test.js
+++ /dev/null
@@ -1,214 +0,0 @@
-// Task 21 — cosmetics shop. These cover the data-driven core the buy/equip
-// handlers rest on: the catalogue's integrity (every cosmetic is purely visual,
-// priced, and rotation-tagged), the deterministic daily/weekly rotation (same
-// date ⇒ same offers, across processes), the next-rotation timestamps the client
-// counts down to, and the `isOffered` gate the purchase handler trusts. All live
-// in a dependency-free module so they assert without standing up a Colyseus room
-// — mirroring fishing.test.js / cooking.test.js.
-import { describe, it, expect } from 'vitest';
-import {
- COSMETICS, RARITIES, DAILY_OFFER_COUNT, WEEKLY_OFFER_COUNT,
- cosmeticById, currentOffers, isOffered, evaluatePurchase, clientCatalog,
- dailyKey, weekKey, nextDailyReset, nextWeeklyReset,
-} from '../multiplayer/src/cosmetics.js';
-
-// A fixed instant for deterministic assertions: Mon 2026-06-01 12:00 UTC.
-const T = Date.UTC(2026, 5, 1, 12, 0, 0);
-const DAY = 24 * 60 * 60 * 1000;
-
-describe('catalogue integrity — every cosmetic is visual-only, priced, rotation-tagged', () => {
- it('has a non-empty catalogue with unique ids', () => {
- expect(COSMETICS.length).toBeGreaterThan(0);
- const ids = COSMETICS.map((c) => c.id);
- expect(new Set(ids).size).toBe(ids.length);
- });
-
- it('every entry has a positive price, known rarity, and a valid rotation', () => {
- for (const c of COSMETICS) {
- expect(typeof c.id).toBe('string');
- expect(c.name).toBeTruthy();
- expect(Number.isInteger(c.price)).toBe(true);
- expect(c.price).toBeGreaterThan(0);
- expect(RARITIES[c.rarity]).toBeTruthy();
- expect(['always', 'daily', 'weekly']).toContain(c.rotation);
- }
- });
-
- it('every visual spec is strictly cosmetic — only tint / prop / aura keys', () => {
- const allowed = new Set(['tint', 'prop', 'anchor', 'aura']);
- for (const c of COSMETICS) {
- expect(c.visual && typeof c.visual === 'object').toBe(true);
- for (const key of Object.keys(c.visual)) expect(allowed.has(key)).toBe(true);
- // At least one renderable primitive — never an empty (no-op) cosmetic.
- expect(c.visual.tint || c.visual.prop || c.visual.aura).toBeTruthy();
- }
- });
-
- it('has enough rotating stock that a set genuinely changes each period', () => {
- const daily = COSMETICS.filter((c) => c.rotation === 'daily').length;
- const weekly = COSMETICS.filter((c) => c.rotation === 'weekly').length;
- expect(daily).toBeGreaterThan(DAILY_OFFER_COUNT);
- expect(weekly).toBeGreaterThan(WEEKLY_OFFER_COUNT);
- });
-
- it('cosmeticById resolves a real entry and rejects unknowns', () => {
- expect(cosmeticById(COSMETICS[0].id)).toBe(COSMETICS[0]);
- expect(cosmeticById('does-not-exist')).toBeNull();
- expect(cosmeticById('')).toBeNull();
- });
-});
-
-describe('currentOffers — deterministic rotation, correct bucket sizes', () => {
- it('offers exactly the configured count from each rotating pool', () => {
- const o = currentOffers(T);
- expect(o.daily).toHaveLength(DAILY_OFFER_COUNT);
- expect(o.weekly).toHaveLength(WEEKLY_OFFER_COUNT);
- expect(o.always.length).toBe(COSMETICS.filter((c) => c.rotation === 'always').length);
- });
-
- it('offered ids are distinct and drawn from the right pool', () => {
- const o = currentOffers(T);
- expect(new Set(o.daily).size).toBe(o.daily.length);
- for (const id of o.daily) expect(cosmeticById(id).rotation).toBe('daily');
- for (const id of o.weekly) expect(cosmeticById(id).rotation).toBe('weekly');
- for (const id of o.always) expect(cosmeticById(id).rotation).toBe('always');
- });
-
- it('is deterministic for a given instant (same date ⇒ same offers)', () => {
- const a = currentOffers(T);
- const b = currentOffers(T + 60 * 1000); // a minute later, same UTC day/week
- expect(b.daily).toEqual(a.daily);
- expect(b.weekly).toEqual(a.weekly);
- });
-
- it('the daily set rolls over across a UTC-day boundary', () => {
- // Compare two days far enough apart that the seeded shuffle differs. Some
- // neighbouring days can coincide, so assert change over a span of days.
- const today = currentOffers(T).daily.join(',');
- const later = currentOffers(T + 3 * DAY).daily.join(',');
- // Either the set or its order may shift; over 3 days at least one differs.
- const anyDiff = [1, 2, 3, 4, 5].some((d) => currentOffers(T + d * DAY).daily.join(',') !== today);
- expect(anyDiff || later !== today).toBe(true);
- });
-});
-
-describe('rotation keys + next-reset timestamps drive the client countdown', () => {
- it('dailyKey is the UTC date and nextDailyReset is the next UTC midnight', () => {
- expect(dailyKey(T)).toBe('2026-06-01');
- expect(nextDailyReset(T)).toBe(Date.UTC(2026, 5, 2));
- // Idempotent within the same day; advances to the next at the boundary.
- expect(nextDailyReset(T) - T).toBeLessThanOrEqual(DAY);
- expect(nextDailyReset(T)).toBeGreaterThan(T);
- });
-
- it('weekKey is the ISO-week Monday and nextWeeklyReset is the next Monday', () => {
- // 2026-06-01 is itself a Monday, so the week starts that day.
- expect(weekKey(T)).toBe('2026-06-01');
- const next = nextWeeklyReset(T);
- expect(next).toBe(Date.UTC(2026, 5, 8));
- expect(new Date(next).getUTCDay()).toBe(1); // Monday
- });
-
- it('mid-week still resolves to the same Monday + the same next reset', () => {
- const wed = T + 2 * DAY; // Wed 2026-06-03
- expect(weekKey(wed)).toBe('2026-06-01');
- expect(nextWeeklyReset(wed)).toBe(Date.UTC(2026, 5, 8));
- });
-});
-
-describe('isOffered — the purchase gate', () => {
- it('always-cosmetics are always buyable', () => {
- const always = COSMETICS.find((c) => c.rotation === 'always');
- expect(isOffered(always.id, T)).toBe(true);
- });
-
- it('matches the current rotating board exactly', () => {
- const o = currentOffers(T);
- for (const id of o.daily) expect(isOffered(id, T)).toBe(true);
- for (const id of o.weekly) expect(isOffered(id, T)).toBe(true);
- // A rotating cosmetic NOT in today's set is not offered.
- const offered = new Set([...o.daily, ...o.weekly]);
- const benched = COSMETICS.find((c) => c.rotation !== 'always' && !offered.has(c.id));
- if (benched) expect(isOffered(benched.id, T)).toBe(false);
- });
-
- it('rejects unknown ids', () => {
- expect(isOffered('nope', T)).toBe(false);
- });
-});
-
-describe('clientCatalog — what the client renders from', () => {
- it('exposes every cosmetic with the fields the shop/wardrobe need, plus rarities', () => {
- const cat = clientCatalog();
- expect(cat.rarities).toBe(RARITIES);
- expect(cat.cosmetics).toHaveLength(COSMETICS.length);
- for (const c of cat.cosmetics) {
- expect(c).toHaveProperty('id');
- expect(c).toHaveProperty('name');
- expect(c).toHaveProperty('rarity');
- expect(c).toHaveProperty('price');
- expect(c).toHaveProperty('rotation');
- expect(c).toHaveProperty('visual');
- }
- });
-});
-
-
-describe('evaluatePurchase — the shared buy rule', () => {
- const always = COSMETICS.find((c) => c.rotation === 'always');
- const benched = (() => {
- const o = currentOffers(T);
- const live = new Set([...o.daily, ...o.weekly]);
- return COSMETICS.find((c) => c.rotation !== 'always' && !live.has(c.id));
- })();
-
- it('rejects an unknown id', () => {
- const r = evaluatePurchase(99999, new Set(), 'nope', T);
- expect(r.ok).toBe(false);
- expect(r.reason).toBe('unknown');
- expect(r.cosmetic).toBeNull();
- });
-
- it('rejects a cosmetic the player already owns', () => {
- const r = evaluatePurchase(99999, new Set([always.id]), always.id, T);
- expect(r).toMatchObject({ ok: false, reason: 'owned' });
- expect(r.cosmetic.id).toBe(always.id);
- });
-
- it('rejects a cosmetic not in the current rotation', () => {
- if (!benched) return; // all rotating cosmetics happened to be offered
- const r = evaluatePurchase(99999, new Set(), benched.id, T);
- expect(r).toMatchObject({ ok: false, reason: 'not-offered' });
- });
-
- it('rejects when the purse is short', () => {
- const r = evaluatePurchase(always.price - 1, new Set(), always.id, T);
- expect(r).toMatchObject({ ok: false, reason: 'poor' });
- });
-
- it('allows an offered, unowned, affordable cosmetic', () => {
- const r = evaluatePurchase(always.price, new Set(), always.id, T);
- expect(r).toMatchObject({ ok: true, reason: 'ok' });
- expect(r.cosmetic.id).toBe(always.id);
- });
-
- it('accepts owned as either a Set or an array', () => {
- expect(evaluatePurchase(99999, [always.id], always.id, T).reason).toBe('owned');
- expect(evaluatePurchase(99999, new Set([always.id]), always.id, T).reason).toBe('owned');
- });
-});
-
-describe('worn props are bone-anchorable (hats + glasses)', () => {
- it('every prop cosmetic declares a head or face anchor', () => {
- for (const c of COSMETICS) {
- if (!c.visual.prop) continue;
- expect(['head', 'face']).toContain(c.visual.anchor);
- }
- });
-
- it('includes face-anchored glasses', () => {
- const glasses = COSMETICS.filter((c) => c.visual.prop && c.visual.anchor === 'face');
- expect(glasses.length).toBeGreaterThan(0);
- for (const g of glasses) expect(g.visual.prop).toMatch(/glasses/);
- });
-});
diff --git a/tests/fishing.test.js b/tests/fishing.test.js
deleted file mode 100644
index c434d9b6d..000000000
--- a/tests/fishing.test.js
+++ /dev/null
@@ -1,124 +0,0 @@
-// Task 05 — fishing. These cover the data-driven core the cast handler rests on:
-// the catch + double-haul curves (which the server rolls a single cast against)
-// and the realm fishing-spot data + adjacency helper (which gate a cast to shore
-// tiles beside water). All live in dependency-free modules so they can be
-// asserted without standing up a Colyseus room — mirroring cooking.test.js.
-import { describe, it, expect } from 'vitest';
-import { fishCatchChance, fishDoubleChance, STACKABLE_ITEMS } from '../multiplayer/src/items.js';
-import { REALMS, fishingSpotNear } from '../multiplayer/src/rooms/realms.js';
-
-describe('fishCatchChance — rises with skill + spot quality, capped', () => {
- it('starts at 40% for a level-1 angler on average water', () => {
- expect(fishCatchChance(1, 1)).toBeCloseTo(0.4, 10);
- });
-
- it('improves as fishing level rises (the core progression promise)', () => {
- expect(fishCatchChance(20, 1)).toBeGreaterThan(fishCatchChance(1, 1));
- expect(fishCatchChance(99, 1)).toBeGreaterThan(fishCatchChance(20, 1));
- });
-
- it('richer water catches more often than poor water at the same level', () => {
- // Pond (1.3) beats Whisperwood pools (0.9) for a given angler.
- expect(fishCatchChance(10, 1.3)).toBeGreaterThan(fishCatchChance(10, 0.9));
- });
-
- it('is monotonically non-decreasing in level and bounded in [0, 0.95]', () => {
- let prev = -Infinity;
- for (let lvl = 1; lvl <= 99; lvl++) {
- const c = fishCatchChance(lvl, 1);
- expect(c).toBeGreaterThanOrEqual(0);
- expect(c).toBeLessThanOrEqual(0.95);
- expect(c).toBeGreaterThanOrEqual(prev - 1e-12);
- prev = c;
- }
- });
-
- it('never guarantees a catch even on the best water at the cap', () => {
- expect(fishCatchChance(99, 1.3)).toBeLessThanOrEqual(0.95);
- expect(fishCatchChance(99, 5)).toBe(0.95); // absurd quality still clamps
- });
-
- it('treats below-floor levels and bad quality as level 1 / quality 1', () => {
- expect(fishCatchChance(0, 1)).toBeCloseTo(0.4, 10);
- expect(fishCatchChance(-5, 1)).toBeCloseTo(0.4, 10);
- expect(fishCatchChance(1, 0)).toBeCloseTo(0.4, 10);
- expect(fishCatchChance(1, -2)).toBeCloseTo(0.4, 10);
- });
-});
-
-describe('fishDoubleChance — a treat that scales, never the norm', () => {
- it('is zero at level 1 (no doubles for a raw beginner)', () => {
- expect(fishDoubleChance(1, 1)).toBe(0);
- });
-
- it('grows with level and quality but stays clamped at 45%', () => {
- expect(fishDoubleChance(10, 1)).toBeGreaterThan(0);
- expect(fishDoubleChance(50, 1.3)).toBeGreaterThan(fishDoubleChance(10, 1));
- for (let lvl = 1; lvl <= 99; lvl++) {
- expect(fishDoubleChance(lvl, 1.3)).toBeLessThanOrEqual(0.45);
- }
- });
-});
-
-describe('catch yield is a stackable item', () => {
- it('raw fish stacks so repeated casts fill one slot', () => {
- expect(STACKABLE_ITEMS.has('fish')).toBe(true);
- });
-});
-
-describe('realm fishing data — fishable shores beside water', () => {
- it('Pond is the richest water, Whisperwood the poorest of the fishable realms', () => {
- const pondQ = REALMS.pond.fishing[0].quality;
- const woodQ = REALMS.whisperwood.fishing[0].quality;
- const landQ = REALMS.mainland.fishing[0].quality;
- expect(pondQ).toBeGreaterThan(landQ);
- expect(landQ).toBeGreaterThan(woodQ);
- });
-
- it('every fishing spot carries a positive quality multiplier', () => {
- for (const realm of Object.values(REALMS)) {
- for (const spot of realm.fishing) {
- expect(spot.quality).toBeGreaterThan(0);
- expect(Number.isFinite(spot.tx)).toBe(true);
- expect(Number.isFinite(spot.ty)).toBe(true);
- }
- }
- });
-
- it('mine and wilderness have no fishing (dry/dangerous realms)', () => {
- expect(REALMS.mine.fishing).toHaveLength(0);
- expect(REALMS.wilderness.fishing).toHaveLength(0);
- });
-});
-
-describe('fishingSpotNear — 8-way adjacency gate, picks the richest reachable water', () => {
- const pond = REALMS.pond;
- const spot = pond.fishing[0]; // { tx: 13, ty: 14, quality: 1.3 }
-
- it('finds the spot when standing on it', () => {
- expect(fishingSpotNear(pond, spot.tx, spot.ty)).toBeTruthy();
- });
-
- it('finds the spot from a diagonally adjacent tile', () => {
- expect(fishingSpotNear(pond, spot.tx - 1, spot.ty - 1)).toBeTruthy();
- expect(fishingSpotNear(pond, spot.tx + 1, spot.ty + 1)).toBeTruthy();
- });
-
- it('returns null when two or more tiles away from any water', () => {
- expect(fishingSpotNear(pond, spot.tx + 3, spot.ty + 3)).toBeNull();
- expect(fishingSpotNear(pond, 0, 0)).toBeNull();
- });
-
- it('returns null in a realm with no fishing water', () => {
- expect(fishingSpotNear(REALMS.mine, 16, 28)).toBeNull();
- });
-
- it('prefers the higher-quality spot when two are in reach', () => {
- // Hand-built realm stub: a poor spot and a rich spot both within one tile.
- const realm = { fishing: [
- { tx: 5, ty: 5, quality: 0.5 },
- { tx: 6, ty: 5, quality: 1.5 },
- ] };
- expect(fishingSpotNear(realm, 5, 5).quality).toBe(1.5);
- });
-});
diff --git a/tests/marketplace-store.test.js b/tests/marketplace-store.test.js
deleted file mode 100644
index 1aaec1b9e..000000000
--- a/tests/marketplace-store.test.js
+++ /dev/null
@@ -1,123 +0,0 @@
-// Marketplace (Task 20) — the durable listing/payout store and the token quote
-// primitives the on-chain settlement depends on. The store is exercised against a
-// mocked @upstash/redis (same harness as player-store.test) so the durability +
-// no-dupe invariants are proven without real credentials, and the token layer's
-// quote sign/verify + 95/5 split are unit-checked.
-//
-// What matters for the task:
-// - a listing's escrow lives on the store, survives a simulated restart, and a
-// drained payout is removed atomically (delivered exactly once — no dupe/loss),
-// - a consumed on-chain signature is remembered so a token payment can't replay,
-// - a USD price quotes to a tamper-proof, expiring signed quote,
-// - the 95/5 split always sums back to the exact total.
-
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-
-const redis = vi.hoisted(() => ({ store: new Map(), pingFails: false }));
-
-vi.mock('@upstash/redis', () => ({
- Redis: class {
- async ping() { if (redis.pingFails) throw new Error('unreachable'); return 'PONG'; }
- async get(k) { return redis.store.has(k) ? redis.store.get(k) : null; }
- async set(k, v) { redis.store.set(k, v); return 'OK'; }
- async del(k) { return redis.store.delete(k) ? 1 : 0; }
- },
-}));
-
-async function freshStore({ durable = true } = {}) {
- vi.resetModules();
- if (durable) {
- process.env.UPSTASH_REDIS_REST_URL = 'http://mock-upstash';
- process.env.UPSTASH_REDIS_REST_TOKEN = 'mock-token';
- } else {
- delete process.env.UPSTASH_REDIS_REST_URL;
- delete process.env.UPSTASH_REDIS_REST_TOKEN;
- }
- return import('../multiplayer/src/marketplaceStore.js');
-}
-
-beforeEach(() => { redis.store.clear(); redis.pingFails = false; });
-
-describe('MarketplaceStore — listings + escrow', () => {
- it('creates active listings and surfaces them by recency + by seller', async () => {
- const { marketplaceStore: m } = await freshStore({ durable: false });
- const a = m.create({ seller: 'alice', sellerName: 'Alice', type: 'gold', item: 'wood', qty: 50, priceGold: 100 });
- const b = m.create({ seller: 'bob', sellerName: 'Bob', type: 'goldForToken', goldAmount: 1000, priceUsd: 1.5, sellerWallet: 'bob' });
- expect(a.status).toBe('active');
- expect(m.activeListings().map((l) => l.id)).toContain(a.id);
- expect(m.listingsBySeller('alice')).toHaveLength(1);
- // Closing one drops it from the active board but keeps it on the seller's list.
- m.update(a.id, { status: 'cancelled', closedAt: Date.now() });
- expect(m.activeListings().map((l) => l.id)).not.toContain(a.id);
- expect(m.listingsBySeller('alice')).toHaveLength(1);
- expect(m.get(b.id).status).toBe('active');
- });
-
- it('delivers a queued payout exactly once (no dupe, no loss)', async () => {
- const { marketplaceStore: m } = await freshStore({ durable: false });
- m.enqueuePayout('alice', { gold: 250, reason: 'sold wood' });
- m.enqueuePayout('alice', { gold: 50, reason: 'sold fish' });
- expect(m.hasPendingPayouts('alice')).toBe(true);
- const first = m.drainPayouts('alice');
- expect(first.reduce((s, p) => s + p.gold, 0)).toBe(300);
- // A second drain (e.g. a presence nudge racing the login) yields nothing.
- expect(m.drainPayouts('alice')).toEqual([]);
- expect(m.hasPendingPayouts('alice')).toBe(false);
- });
-
- it('remembers a consumed tx signature so a token payment cannot replay', async () => {
- const { marketplaceStore: m } = await freshStore({ durable: false });
- expect(m.isSettled('sigABC')).toBe(false);
- m.markSettled('sigABC');
- expect(m.isSettled('sigABC')).toBe(true);
- });
-});
-
-describe('MarketplaceStore (durable / Upstash)', () => {
- it('persists active listings + payouts across a simulated restart', async () => {
- const a = await freshStore();
- await a.marketplaceStore.ready();
- const rec = a.marketplaceStore.create({ seller: 'alice', sellerName: 'Alice', type: 'gold', item: 'coal', qty: 12, priceGold: 80 });
- a.marketplaceStore.enqueuePayout('bob', { gold: 999, reason: 'sale' });
- a.marketplaceStore.markSettled('sig1');
- await a.marketplaceStore.flushAll();
- expect(redis.store.has('market:listings')).toBe(true);
-
- // Process B (fresh store, same Redis) hydrates the board on boot.
- const b = await freshStore();
- await b.marketplaceStore.ready();
- expect(b.marketplaceStore.get(rec.id)?.priceGold).toBe(80);
- expect(b.marketplaceStore.activeListings().map((l) => l.id)).toContain(rec.id);
- expect(b.marketplaceStore.hasPendingPayouts('bob')).toBe(true);
- expect(b.marketplaceStore.isSettled('sig1')).toBe(true);
- });
-});
-
-describe('Game token — quote sign/verify + split', () => {
- it('splits a total 95/5 with no remainder lost', async () => {
- const { splitAmount } = await import('../multiplayer/src/game-token.js');
- for (const total of [1_000_000n, 999_999n, 7n, 123_456_789n]) {
- const { seller, treasury } = splitAmount(total, 500);
- expect(seller + treasury).toBe(total); // nothing created or lost
- expect(treasury).toBe((total * 500n) / 10000n); // exact 5%
- }
- });
-
- it('signs a quote that verifies and rejects tampering', async () => {
- const { signQuote, verifyQuote } = await import('../multiplayer/src/game-token.js');
- const token = signQuote({ listingId: 'lst_1', buyer: 'B', sellerWallet: 'S', usd: 2, total: '1000000', sellerRaw: '950000', treasuryRaw: '50000' });
- const ok = verifyQuote(token);
- expect(ok?.listingId).toBe('lst_1');
- expect(ok?.sellerRaw).toBe('950000');
- // Any byte flipped in the body or signature fails the HMAC.
- expect(verifyQuote(token.slice(0, -1) + (token.slice(-1) === 'a' ? 'b' : 'a'))).toBeNull();
- expect(verifyQuote('not-a-token')).toBeNull();
- });
-
- it('classifies wallet vs guest account ids', async () => {
- const { isWalletAddress } = await import('../multiplayer/src/game-token.js');
- expect(isWalletAddress('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump')).toBe(true);
- expect(isWalletAddress('g_abc123')).toBe(false);
- expect(isWalletAddress('')).toBe(false);
- });
-});
diff --git a/tests/mine-realm.test.js b/tests/mine-realm.test.js
deleted file mode 100644
index 952c240fd..000000000
--- a/tests/mine-realm.test.js
+++ /dev/null
@@ -1,208 +0,0 @@
-// Task 08 — Mainland mine interior. These cover the dependency-free core the
-// mine rests on: the realm geometry + portal wiring (which the GameRoom validates
-// movement and traversal against) and the realm-transfer token (which carries a
-// player's haul between realm rooms without trusting the client). Both live in
-// plain modules, so they assert without standing up a Colyseus room — mirroring
-// fishing.test.js / cooking.test.js.
-import { describe, it, expect } from 'vitest';
-import { REALMS, portalAt, isBlocked, inBounds } from '../multiplayer/src/rooms/realms.js';
-import { signTransfer, verifyTransfer, consumeTransferNonce } from '../multiplayer/src/rooms/realm-transfer.js';
-
-const MINE = REALMS.mine;
-const MAINLAND = REALMS.mainland;
-
-describe('mine realm — an enclosed, safe cave dense with ore', () => {
- it('exists and is a safe, non-pvp, non-danger resource area', () => {
- expect(MINE).toBeTruthy();
- expect(MINE.safe).toBe(true);
- expect(MINE.pvp).toBe(false);
- expect(MINE.danger).toBe(false);
- });
-
- it('has no bank or fountain — you carry the haul back up to the Mainland', () => {
- expect(MINE.fountain).toBeNull();
- expect(MINE.bankZone).toEqual([]);
- });
-
- it('is denser in ore than the Mainland surface (the whole point of the mine)', () => {
- const count = (realm, kind) => realm.nodes.filter((n) => n.kind === kind).length;
- const mineRock = count(MINE, 'rock'), mineCoal = count(MINE, 'coal');
- const surfRock = count(MAINLAND, 'rock'), surfCoal = count(MAINLAND, 'coal');
- expect(mineRock).toBeGreaterThan(surfRock);
- expect(mineCoal).toBeGreaterThan(surfCoal);
- // Only rock and coal grow down here — no trees in a cave.
- expect(MINE.nodes.every((n) => n.kind === 'rock' || n.kind === 'coal')).toBe(true);
- });
-
- it('keeps every node id unique and every node on a walkable, in-bounds tile', () => {
- const ids = MINE.nodes.map((n) => n.id);
- expect(new Set(ids).size).toBe(ids.length);
- for (const n of MINE.nodes) {
- expect(inBounds(MINE, n.tx, n.ty)).toBe(true);
- // A node may not sit inside a wall/ridge/pillar (it would be unreachable).
- expect(isBlocked(MINE, n.tx, n.ty)).toBe(false);
- }
- });
-
- it('spawns the player on a walkable interior tile, not in a wall', () => {
- expect(inBounds(MINE, MINE.spawn.tx, MINE.spawn.ty)).toBe(true);
- expect(isBlocked(MINE, MINE.spawn.tx, MINE.spawn.ty)).toBe(false);
- });
-
- it('walls its entire edge except the entrance mouth', () => {
- const g = MINE.grid;
- // Corners are always wall.
- for (const [x, y] of [[0, 0], [g - 1, 0], [0, g - 1], [g - 1, g - 1]]) {
- expect(isBlocked(MINE, x, y)).toBe(true);
- }
- // The south edge has a walkable gap (the entrance/return mouth) AND wall.
- let gap = 0, wall = 0;
- for (let x = 0; x < g; x++) (isBlocked(MINE, x, g - 1) ? wall++ : gap++);
- expect(gap).toBeGreaterThan(0);
- expect(wall).toBeGreaterThan(0);
- });
-
- it('permits no player building down a working mine', () => {
- expect(MINE.structures).toEqual([]);
- });
-});
-
-describe('mine portals — round-trip between the Mainland entrance and the cave', () => {
- it('Mainland has a mine entrance that targets the mine spawn area', () => {
- const entrance = MAINLAND.portals.find((p) => p.to === 'mine');
- expect(entrance).toBeTruthy();
- // The entrance tile is walkable so a player can actually step onto it.
- expect(isBlocked(MAINLAND, entrance.x0, entrance.y0)).toBe(false);
- // Its destination lands inside the mine, on a walkable tile.
- expect(inBounds(MINE, entrance.toTx, entrance.toTy)).toBe(true);
- expect(isBlocked(MINE, entrance.toTx, entrance.toTy)).toBe(false);
- });
-
- it('the mine has exactly one portal — a return to the Mainland', () => {
- expect(MINE.portals).toHaveLength(1);
- const ret = MINE.portals[0];
- expect(ret.to).toBe('mainland');
- expect(inBounds(MAINLAND, ret.toTx, ret.toTy)).toBe(true);
- expect(isBlocked(MAINLAND, ret.toTx, ret.toTy)).toBe(false);
- });
-
- it('return tile is clear of the entrance rect, so stepping out never bounces back in', () => {
- const entrance = MAINLAND.portals.find((p) => p.to === 'mine');
- const ret = MINE.portals[0];
- // Landing back on the Mainland must NOT be on a portal tile.
- expect(portalAt(MAINLAND, ret.toTx, ret.toTy)).toBeNull();
- // And the entrance's own destination must not sit on the mine's return rect.
- expect(portalAt(MINE, entrance.toTx, entrance.toTy)).toBeNull();
- });
-
- it('portalAt resolves the entrance rect and rejects ordinary tiles', () => {
- const entrance = MAINLAND.portals.find((p) => p.to === 'mine');
- expect(portalAt(MAINLAND, entrance.x0, entrance.y0)?.to).toBe('mine');
- expect(portalAt(MAINLAND, MAINLAND.spawn.tx, MAINLAND.spawn.ty)).toBeNull();
- });
-
- it('mine entrance portal carries toTx/toTy so the spawn can be verified', () => {
- const entrance = MAINLAND.portals.find((p) => p.to === 'mine');
- // The entrance arch on the Mainland is rendered at a portal that carries these
- // destination coords — confirm they agree with the mine's defined spawn.
- expect(Number.isFinite(entrance.toTx)).toBe(true);
- expect(Number.isFinite(entrance.toTy)).toBe(true);
- expect(entrance.toTx).toBe(MINE.spawn.tx);
- expect(entrance.toTy).toBe(MINE.spawn.ty);
- });
-});
-
-describe('realm-transfer token — the trust boundary for carrying a haul across realms', () => {
- const carry = {
- inv: [{ item: 'coal', qty: 17 }, { item: 'stone', qty: 9 }],
- hotbar: [{ item: 'pickaxe', qty: 1 }],
- activeSlot: 0,
- bank: [{ item: 'gold', qty: 250 }],
- gold: 1234,
- hp: 73,
- maxHp: 100,
- xp: { mining: 4200, combat: 0, woodcutting: 0, fishing: 0, cooking: 0 },
- mounted: false,
- mount: '',
- };
-
- it('round-trips a signed carry intact', () => {
- const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry, account: 'gs_abc123' });
- const out = verifyTransfer(token);
- expect(out).toBeTruthy();
- expect(out.to).toBe('mine');
- expect(out.tx).toBe(16);
- expect(out.ty).toBe(28);
- expect(out.carry).toEqual(carry);
- // The verified account rides along so the destination can re-bind it across the
- // passless handoff, and every token carries a unique single-use nonce.
- expect(out.account).toBe('gs_abc123');
- expect(typeof out.jti).toBe('string');
- expect(out.jti.length).toBeGreaterThan(0);
- });
-
- it('rejects a tampered payload (forged items can never ride in)', () => {
- const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry, account: 'gs_abc123' });
- const [body, sig] = token.split('.');
- const forged = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
- forged.carry.gold = 9_999_999;
- const rebody = Buffer.from(JSON.stringify(forged)).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
- expect(verifyTransfer(`${rebody}.${sig}`)).toBeNull();
- });
-
- it('rejects garbage, empty, and structurally-invalid tokens', () => {
- expect(verifyTransfer('')).toBeNull();
- expect(verifyTransfer('not-a-token')).toBeNull();
- expect(verifyTransfer('abc.def')).toBeNull();
- expect(verifyTransfer(null)).toBeNull();
- expect(verifyTransfer(undefined)).toBeNull();
- });
-
- it('rejects a token signed for a different destination (no cross-realm carry injection)', () => {
- const token = signTransfer({ to: 'wilderness', tx: 10, ty: 10, carry, account: 'gs_abc123' });
- const out = verifyTransfer(token);
- // The token itself verifies — it's not tampered. But the destination check in
- // onJoin (transfer.to === this.realm.name) will reject it if presented to the
- // wrong room. Confirm the `to` field is faithfully round-tripped.
- expect(out?.to).toBe('wilderness');
- expect(out?.to).not.toBe('mine');
- });
-
- it('a maximal carry (all slots filled, max qty, max gold, all skills maxed) round-trips correctly', () => {
- const maxCarry = {
- inv: Array.from({ length: 24 }, (_, i) => ({ item: i % 2 === 0 ? 'coal' : 'stone', qty: 999 })),
- hotbar: Array.from({ length: 6 }, () => ({ item: 'pickaxe', qty: 1 })),
- activeSlot: 2,
- bank: Array.from({ length: 48 }, () => ({ item: 'wood', qty: 999 })),
- gold: 4294967295, // uint32 max
- hp: 100, maxHp: 100,
- xp: { mining: 999999, combat: 999999, woodcutting: 999999, fishing: 999999, cooking: 999999 },
- mounted: true, mount: 'horse',
- };
- const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry: maxCarry, account: 'gs_abc123' });
- const out = verifyTransfer(token);
- expect(out?.carry).toEqual(maxCarry);
- });
-
- it('rejects a token with no account (a forged or pre-account token must not land)', () => {
- // Hand-build a structurally-valid, correctly-signed body that omits `account`.
- const now = Math.floor(Date.now() / 1000);
- const body = Buffer.from(JSON.stringify({ to: 'mine', tx: 1, ty: 1, carry, jti: 'x', iat: now, exp: now + 30 }))
- .toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
- // We can't re-sign without the module's secret, but verifyTransfer rejects on the
- // missing `account` before checking the (here-absent) valid signature path, so a
- // proper end-to-end account-less token is also covered by the signTransfer always
- // embedding one. Assert the field is mandatory via a signed-then-stripped token.
- const signed = signTransfer({ to: 'mine', tx: 1, ty: 1, carry, account: 'gs_abc123' });
- const [, sig] = signed.split('.');
- expect(verifyTransfer(`${body}.${sig}`)).toBeNull();
- });
-
- it('a nonce is single-use: the first consume wins, replays are rejected', () => {
- const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry, account: 'gs_abc123' });
- const out = verifyTransfer(token);
- expect(consumeTransferNonce(out.jti)).toBe(true); // first use applies the carry
- expect(consumeTransferNonce(out.jti)).toBe(false); // replay within TTL is rejected
- expect(consumeTransferNonce('')).toBe(false); // a falsy nonce never applies
- });
-});
diff --git a/tests/mob-ai.test.js b/tests/mob-ai.test.js
deleted file mode 100644
index b5319cb70..000000000
--- a/tests/mob-ai.test.js
+++ /dev/null
@@ -1,147 +0,0 @@
-// Task 03 — Mob AI: roam, aggro, chase, contact damage.
-//
-// These drive the real GameRoom mob simulation (`_mobTick` and its helpers)
-// against the real realm data. The simulation is server-authoritative and pure
-// w.r.t. the schema state, so we build a minimal GameRoom harness (a real
-// instance whose state maps and realm we populate via `_seedWorld`) and step the
-// tick by hand. No colyseus networking, no browser — the gameplay contract is:
-//
-// • hostile mobs in a danger realm acquire, chase, and deal contact damage;
-// • a player inside a safe camp is never aggroed;
-// • inert mobs (roam:false, aggro:false — e.g. Mainland dummies) never move;
-// • roamers wander but stay leashed near home and never stand on a player.
-
-import { describe, it, expect } from 'vitest';
-import { GameRoom } from '../multiplayer/src/rooms/GameRoom.js';
-import { REALMS, inRect } from '../multiplayer/src/rooms/realms.js';
-import { GamePlayer } from '../multiplayer/src/schemas/game.js';
-
-function makeRoom(realmName) {
- const room = Object.create(GameRoom.prototype);
- room.realm = REALMS[realmName];
- room.clients = [];
- room.priv = new Map();
- room.state = {
- players: new Map(),
- mobs: new Map(),
- nodes: new Map(),
- structures: new Map(),
- tombstones: new Map(),
- };
- room._seedWorld(); // seeds nodes + mobs + per-mob AI exactly like onCreate
- return room;
-}
-
-function addPlayer(room, sid, tx, ty, hp = 200) {
- const p = new GamePlayer();
- p.id = sid;
- p.name = sid;
- p.tx = tx;
- p.ty = ty;
- p.hp = p.maxHp = hp;
- p.dead = false;
- room.state.players.set(sid, p);
- return p;
-}
-
-// Find a walkable tile at (roughly) Chebyshev distance `dist` from (cx,cy) by
-// spiraling outward — keeps the tests robust to the realm's exact obstacle map.
-function walkableNear(room, cx, cy, dist) {
- for (let r = dist; r <= dist + 4; r++) {
- for (let dx = -r; dx <= r; dx++) {
- for (let dy = -r; dy <= r; dy++) {
- if (Math.max(Math.abs(dx), Math.abs(dy)) !== r) continue;
- const tx = cx + dx, ty = cy + dy;
- if (room._mobCanStand(tx, ty)) return { tx, ty };
- }
- }
- }
- return null;
-}
-
-describe('Mob AI — Wilderness goblins are hostile', () => {
- it('acquires, chases, and deals contact damage to a nearby player', () => {
- const room = makeRoom('wilderness');
- const g0 = room.state.mobs.get('g0'); // goblin, roam+aggro
- expect(g0).toBeTruthy();
-
- const spot = walkableNear(room, g0.tx, g0.ty, 3); // inside aggro radius (6)
- expect(spot).toBeTruthy();
- const p = addPlayer(room, 'p1', spot.tx, spot.ty);
- expect(inRect(room.realm.safeCamp, p.tx, p.ty)).toBe(false); // not sheltered
-
- let now = 1000;
- let reachedMelee = false;
- const startDist = room._cheb(g0, p);
- for (let i = 0; i < 40; i++) {
- now += 600;
- room._mobTick(now);
- expect(room._cheb(g0, p)).toBeGreaterThanOrEqual(1); // never stands ON the player
- if (room._cheb(g0, p) <= 1) { reachedMelee = true; break; }
- }
-
- expect(g0.aggroId).toBe('p1'); // acquired the target
- expect(reachedMelee).toBe(true); // closed the gap
- expect(startDist).toBeGreaterThan(1);
-
- const before = p.hp;
- now += MOB_ATTACK_GAP;
- room._mobTick(now);
- expect(p.hp).toBeLessThan(before); // took real contact damage
- });
-
- it('never aggros a player standing inside the safe camp', () => {
- const room = makeRoom('wilderness');
- const g0 = room.state.mobs.get('g0');
- const camp = room.realm.safeCamp;
- const safeTx = Math.floor((camp.x0 + camp.x1) / 2);
- const safeTy = Math.floor((camp.y0 + camp.y1) / 2);
- expect(inRect(camp, safeTx, safeTy)).toBe(true);
- addPlayer(room, 'safe', safeTx, safeTy);
-
- let now = 1000;
- for (let i = 0; i < 20; i++) { now += 600; room._mobTick(now); }
- for (const [, m] of room.state.mobs) expect(m.aggroId).toBe(''); // none locked on
- });
-});
-
-describe('Mob AI — inert mobs stay put', () => {
- it('Mainland dummies and tutorial goblins never move or aggro', () => {
- const room = makeRoom('mainland');
- // Drop a player right next to every mob.
- const homes = new Map();
- for (const [id, m] of room.state.mobs) {
- homes.set(id, { tx: m.tx, ty: m.ty });
- const spot = walkableNear(room, m.tx, m.ty, 1);
- if (spot) addPlayer(room, `near_${id}`, spot.tx, spot.ty);
- }
- let now = 1000;
- for (let i = 0; i < 25; i++) { now += 600; room._mobTick(now); }
- for (const [id, m] of room.state.mobs) {
- const h = homes.get(id);
- expect({ id, tx: m.tx, ty: m.ty }).toEqual({ id, tx: h.tx, ty: h.ty }); // never moved
- expect(m.aggroId).toBe(''); // never aggroed
- }
- });
-});
-
-describe('Mob AI — roamers wander but stay leashed', () => {
- it('a roamer stays within the roam radius of home with no players present', () => {
- const room = makeRoom('wilderness');
- const g0 = room.state.mobs.get('g0');
- const home = { tx: g0.tx, ty: g0.ty };
- let now = 1000;
- let everMoved = false;
- for (let i = 0; i < 200; i++) {
- now += 600;
- room._mobTick(now);
- if (g0.tx !== home.tx || g0.ty !== home.ty) everMoved = true;
- // Roam stays bounded — never exceeds the roam radius from home.
- expect(room._cheb(g0, home)).toBeLessThanOrEqual(4);
- }
- expect(everMoved).toBe(true); // it actually wandered (roam:true)
- });
-});
-
-// Mirrors MOB_ATTACK_COOLDOWN_MS in GameRoom — large enough to clear the gate.
-const MOB_ATTACK_GAP = 1100;
diff --git a/tests/realms-arena.test.js b/tests/realms-arena.test.js
deleted file mode 100644
index 3bd95e7ff..000000000
--- a/tests/realms-arena.test.js
+++ /dev/null
@@ -1,255 +0,0 @@
-// Task 22 — additional realms (Wilderness North/East, the gated Cave) and the
-// Arena (rollers + seating). These tests pin the realm DATA contract the server
-// and client both depend on: every realm is internally walkable, every portal is a
-// real two-way link that lands on solid ground (never inside a wall, a node, or a
-// return portal that would bounce you), the northern cave is combat-gated, and the
-// Arena's rollers + spectator stands carry the right shape + push semantics.
-
-import { describe, it, expect } from 'vitest';
-import {
- REALMS, isBlocked, inBounds, portalAt, inRect, inAnyRect,
- rollerAt, rollerDelta, inNoPvpZone, realmLayout,
-} from '../multiplayer/src/rooms/realms.js';
-
-// A tile is walkable on the server if it's in bounds, not blocked, and not sitting
-// under a resource node (nodes occupy their tile — see GameRoom._isWalkable).
-function nodeSet(realm) {
- return new Set((realm.nodes || []).map((n) => `${n.tx},${n.ty}`));
-}
-function walkable(realm, tx, ty, nodes = nodeSet(realm)) {
- return inBounds(realm, tx, ty) && !isBlocked(realm, tx, ty) && !nodes.has(`${tx},${ty}`);
-}
-
-const NEW = ['wilderness_north', 'wilderness_cave', 'wilderness_east', 'arena'];
-
-describe('new realms exist with the right rule flags', () => {
- it('all four are registered', () => {
- for (const name of NEW) expect(REALMS[name], name).toBeTruthy();
- });
-
- it('Wilderness North is PvP + danger with NO safe camp', () => {
- const r = REALMS.wilderness_north;
- expect(r.pvp).toBe(true);
- expect(r.danger).toBe(true);
- expect(r.safe).toBe(false);
- expect(r.safeCamp).toBeNull();
- });
-
- it('the Cave is a PvP + danger cavern (rendered enclosed)', () => {
- const r = REALMS.wilderness_cave;
- expect(r.pvp).toBe(true);
- expect(r.danger).toBe(true);
- expect(r.cave).toBe(true);
- });
-
- it('Wilderness East is a full PvP + danger realm, no safe camp', () => {
- const r = REALMS.wilderness_east;
- expect(r.pvp).toBe(true);
- expect(r.danger).toBe(true);
- expect(r.safeCamp).toBeNull();
- expect(r.grid).toBeGreaterThanOrEqual(40); // full-size, like the main Wilderness
- });
-
- it('the Arena is PvP but NOT danger (a sporting bout — no item loss)', () => {
- const r = REALMS.arena;
- expect(r.pvp).toBe(true);
- expect(r.danger).toBe(false);
- expect(r.rollers?.length).toBeGreaterThan(0);
- expect(r.seating?.length).toBeGreaterThan(0);
- });
-
- it('Wilderness North has a LOWER mob count than the main Wilderness', () => {
- expect(REALMS.wilderness_north.mobs.length).toBeLessThan(REALMS.wilderness.mobs.length);
- });
-});
-
-describe('every realm spawn stands on walkable ground', () => {
- for (const [name, r] of Object.entries(REALMS)) {
- it(`${name} spawn (${r.spawn.tx},${r.spawn.ty}) is walkable`, () => {
- expect(walkable(r, r.spawn.tx, r.spawn.ty)).toBe(true);
- });
- }
-});
-
-describe('portals are real two-way links that land on solid ground', () => {
- for (const [name, r] of Object.entries(REALMS)) {
- for (const p of r.portals) {
- it(`${name} → ${p.to} lands cleanly and is reciprocated`, () => {
- const dest = REALMS[p.to];
- expect(dest, `destination realm ${p.to} must exist`).toBeTruthy();
-
- // Landing tile is in bounds, not a wall, and not under a node.
- expect(walkable(dest, p.toTx, p.toTy), `landing (${p.toTx},${p.toTy}) in ${p.to} walkable`).toBe(true);
-
- // Landing tile is NOT inside a portal of the destination (no instant bounce).
- const bounced = portalAt(dest, p.toTx, p.toTy);
- expect(bounced, `landing in ${p.to} must not sit on a return portal`).toBeNull();
-
- // Some portal in the destination points back to this realm (a real round trip).
- const back = dest.portals.some((q) => q.to === name);
- expect(back, `${p.to} should have a portal back to ${name}`).toBe(true);
- });
- }
- }
-});
-
-describe('the guide-specified connectivity is wired', () => {
- const links = (from) => new Set(REALMS[from].portals.map((p) => p.to));
- it('Wilderness connects north and east', () => {
- expect(links('wilderness').has('wilderness_north')).toBe(true);
- expect(links('wilderness').has('wilderness_east')).toBe(true);
- });
- it('the Pond also reaches Wilderness East off its north shore', () => {
- expect(links('pond').has('wilderness_east')).toBe(true);
- });
- it('Wilderness North reaches the Cave; the Cave returns to the North', () => {
- expect(links('wilderness_north').has('wilderness_cave')).toBe(true);
- expect(links('wilderness_cave').has('wilderness_north')).toBe(true);
- });
- it('the Mainland plaza opens into the Arena and the Arena returns to it', () => {
- expect(links('mainland').has('arena')).toBe(true);
- expect(links('arena').has('mainland')).toBe(true);
- });
-});
-
-describe('the northern cave is combat-LEVEL gated', () => {
- const cavePortal = REALMS.wilderness_north.portals.find((p) => p.to === 'wilderness_cave');
-
- it('the cave portal carries a combat gate', () => {
- expect(cavePortal.gate).toBeTruthy();
- expect(cavePortal.gate.combat).toBeGreaterThan(1);
- });
-
- it('no OTHER portal in the world is gated (only the cave guards entry)', () => {
- const gated = [];
- for (const [name, r] of Object.entries(REALMS)) {
- for (const p of r.portals) if (p.gate) gated.push(`${name}->${p.to}`);
- }
- expect(gated).toEqual(['wilderness_north->wilderness_cave']);
- });
-
- // Mirrors GameRoom._meetsGate, the server's authoritative check.
- const meetsGate = (combat, gate) => !(gate && Number.isFinite(gate.combat) && combat < gate.combat);
-
- it('an under-level fighter is refused and a qualified one admitted', () => {
- const gate = cavePortal.gate;
- expect(meetsGate(gate.combat - 1, gate)).toBe(false);
- expect(meetsGate(gate.combat, gate)).toBe(true);
- expect(meetsGate(gate.combat + 5, gate)).toBe(true);
- });
-});
-
-describe('Arena rollers — direction + walkable footprint', () => {
- const arena = REALMS.arena;
-
- it('rollerDelta maps each compass direction to a unit step', () => {
- expect(rollerDelta('n')).toEqual([0, -1]);
- expect(rollerDelta('s')).toEqual([0, 1]);
- expect(rollerDelta('e')).toEqual([1, 0]);
- expect(rollerDelta('w')).toEqual([-1, 0]);
- expect(rollerDelta('?')).toEqual([0, 0]); // unknown never moves
- });
-
- it('every roller tile is itself walkable and uses a known direction', () => {
- const nodes = nodeSet(arena);
- for (const r of arena.rollers) {
- expect(['n', 's', 'e', 'w']).toContain(r.dir);
- for (let tx = r.x0; tx <= r.x1; tx++) {
- for (let ty = r.y0; ty <= r.y1; ty++) {
- expect(walkable(arena, tx, ty, nodes), `roller tile (${tx},${ty})`).toBe(true);
- expect(rollerAt(arena, tx, ty)).toBeTruthy();
- }
- }
- }
- });
-
- it('a push never shoves a player out of bounds (the strip stays inside the bowl)', () => {
- for (const r of arena.rollers) {
- const [dx, dy] = rollerDelta(r.dir);
- for (let tx = r.x0; tx <= r.x1; tx++) {
- for (let ty = r.y0; ty <= r.y1; ty++) {
- expect(inBounds(arena, tx + dx, ty + dy)).toBe(true);
- }
- }
- }
- });
-
- it('the four circuit corners all connect to the next strip (no broken corners)', () => {
- const corners = [
- { tx: 8, ty: 10, name: 'top-left' },
- { tx: 19, ty: 10, name: 'top-right' },
- { tx: 19, ty: 16, name: 'bot-right' },
- { tx: 8, ty: 16, name: 'bot-left' },
- ];
- for (const c of corners) {
- const r = rollerAt(arena, c.tx, c.ty);
- expect(r, `${c.name} (${c.tx},${c.ty}) must be on a roller`).toBeTruthy();
- const [dx, dy] = rollerDelta(r.dir);
- const next = rollerAt(arena, c.tx + dx, c.ty + dy);
- expect(next, `${c.name} push must land on the next strip, not dead floor`).toBeTruthy();
- }
- });
-
- it('a full circuit trace from the top-left returns to start (closed loop)', () => {
- const DELTA = { n: [0, -1], s: [0, 1], e: [1, 0], w: [-1, 0] };
- let tx = 8, ty = 10;
- for (let step = 0; step < 60; step++) {
- const r = rollerAt(arena, tx, ty);
- if (!r) throw new Error(`lost circuit at (${tx},${ty}) after ${step} steps`);
- const [dx, dy] = DELTA[r.dir];
- tx += dx; ty += dy;
- if (tx === 8 && ty === 10) return; // closed
- }
- throw new Error('circuit did not close within 60 steps');
- });
-
- it('rollerAt is null off the belts (the spawn floor is free)', () => {
- expect(rollerAt(arena, arena.spawn.tx, arena.spawn.ty)).toBeNull();
- });
-});
-
-describe('PvP-immune zones (safe camps + spectator stands)', () => {
- it('Arena seating is a no-PvP zone; the open floor is fair game', () => {
- const seat = REALMS.arena.seating[0];
- expect(inNoPvpZone(REALMS.arena, seat.x0, seat.y0)).toBe(true);
- expect(inNoPvpZone(REALMS.arena, REALMS.arena.spawn.tx, REALMS.arena.spawn.ty)).toBe(false);
- });
-
- it('the Wilderness safe camp is still a no-PvP zone', () => {
- const camp = REALMS.wilderness.safeCamp;
- expect(inNoPvpZone(REALMS.wilderness, camp.x0, camp.y0)).toBe(true);
- });
-
- it('seating tiles are walkable (spectators stand on them)', () => {
- for (const stand of REALMS.arena.seating) {
- expect(walkable(REALMS.arena, stand.x0, stand.y0)).toBe(true);
- }
- });
-});
-
-describe('realmLayout carries the new client-render fields', () => {
- it('the Arena layout exposes rollers (with dir), seating, and PvP flag', () => {
- const L = realmLayout(REALMS.arena);
- expect(L.pvp).toBe(true);
- expect(L.rollers.length).toBe(REALMS.arena.rollers.length);
- expect(L.rollers[0].dir).toBeTruthy();
- expect(L.seating.length).toBe(REALMS.arena.seating.length);
- });
-
- it('the cave layout is flagged for enclosed rendering', () => {
- expect(realmLayout(REALMS.wilderness_cave).cave).toBe(true);
- expect(realmLayout(REALMS.mainland).cave).toBe(false);
- });
-
- it('a gated portal forwards its gate to the client; an open one sends null', () => {
- const north = realmLayout(REALMS.wilderness_north);
- const gated = north.portals.find((p) => p.to === 'wilderness_cave');
- expect(gated.gate.combat).toBe(REALMS.wilderness_north.portals.find((p) => p.to === 'wilderness_cave').gate.combat);
- const open = realmLayout(REALMS.mainland).portals.find((p) => p.to === 'pond');
- expect(open.gate).toBeNull();
- });
-
- it('the Mainland layout exposes the practice boxing ring', () => {
- expect(realmLayout(REALMS.mainland).ring).toEqual(REALMS.mainland.ring);
- });
-});
diff --git a/vercel.json b/vercel.json
index 43b81eeb7..43215be03 100644
--- a/vercel.json
+++ b/vercel.json
@@ -433,6 +433,10 @@
"src": "/avatar-studio-demo/?",
"dest": "/avatar-studio-demo.html"
},
+ {
+ "src": "/forge/?",
+ "dest": "/forge.html"
+ },
{
"src": "/xr/?",
"dest": "/xr.html"
@@ -446,8 +450,9 @@
"dest": "/play.html"
},
{
- "src": "/game/?",
- "dest": "/game.html"
+ "src": "/game(/.*)?",
+ "status": 308,
+ "headers": { "Location": "/play" }
},
{
"src": "/walk/?",
diff --git a/vite.config.js b/vite.config.js
index 0d59b325a..83d65e981 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -239,6 +239,7 @@ const appConfig = {
launchpad: resolve(__dirname, 'pages/launchpad.html'),
start: resolve(__dirname, 'pages/start.html'),
create: resolve(__dirname, 'pages/create.html'),
+ forge: resolve(__dirname, 'pages/forge.html'),
'create-selfie': resolve(__dirname, 'pages/create-selfie.html'),
scan: resolve(__dirname, 'pages/scan.html'),
worlds: resolve(__dirname, 'pages/worlds.html'),
@@ -296,7 +297,6 @@ const appConfig = {
'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'),
club: resolve(__dirname, 'pages/club.html'),
skills: resolve(__dirname, 'pages/skills.html'),
@@ -310,6 +310,11 @@ const appConfig = {
// its inline modules (incl. pump-modals, agent-token-widget)
// instead of shipping /src/* refs that 404 in production.
'agent-token-page': resolve(__dirname, 'public/agent/index.html'),
+ // /login lives in public/ but its inline avatar module imports the
+ // bare `@three-ws/agent-ui` specifier. Registering it as an input
+ // bundles that module so the sign-in avatar renders in production
+ // instead of shipping an unresolvable bare import.
+ login: resolve(__dirname, 'public/login.html'),
// BEGIN:DISCOVER_ROUTE
'my-agents': resolve(__dirname, 'public/my-agents/index.html'),
discover: resolve(__dirname, 'public/discover/index.html'),
@@ -553,8 +558,6 @@ const appConfig = {
'/walk/': resolve(root, 'pages/walk.html'),
'/play': resolve(root, 'pages/play.html'),
'/play/': resolve(root, 'pages/play.html'),
- '/game': resolve(root, 'pages/game.html'),
- '/game/': resolve(root, 'pages/game.html'),
'/walk-embed': resolve(root, 'pages/walk-embed.html'),
'/walk-embed/': resolve(root, 'pages/walk-embed.html'),
'/demo': resolve(root, 'pages/demo-economy.html'),
@@ -1176,6 +1179,7 @@ const appConfig = {
closeBundle() {
const pairs = [
['dist/public/agent/index.html', 'dist/agent/index.html'],
+ ['dist/public/login.html', 'dist/login.html'],
['dist/public/demos/brain.html', 'dist/demos/brain.html'],
['dist/public/demos/lipsync-tts.html', 'dist/demos/lipsync-tts.html'],
['dist/public/demos/lipsync-mic.html', 'dist/demos/lipsync-mic.html'],