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: GTA-Online-style /play world — quests, combat, vehicles, districts, NPC life, HUD

nirholas24d1c50800db
diff --git a/.gitignore b/.gitignore
index 1ca10e906..8d2f82aed 100644
--- a/.gitignore
+++ b/.gitignore
@@ -175,3 +175,7 @@ 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
+
+# Snapshot day-exports — recoverable from git history, never commit
+snapshots/exported/
+docs/ibm.md
diff --git a/_shot.mjs b/_shot.mjs
new file mode 100644
index 000000000..58ae5b2a2
--- /dev/null
+++ b/_shot.mjs
@@ -0,0 +1,29 @@
+import puppeteer from 'puppeteer';
+const b = await puppeteer.launch({headless:'new', args:['--no-sandbox','--use-gl=swiftshader']});
+const p = await b.newPage();
+await p.setViewport({width:1400,height:800});
+const errs=[];
+p.on('console',m=>{if(m.type()==='error')errs.push(m.text());});
+p.on('pageerror',e=>errs.push('PAGEERR '+e.message));
+await p.goto('http://localhost:3000/tutorials',{waitUntil:'networkidle2',timeout:30000}).catch(e=>console.log('goto',e.message));
+await new Promise(r=>setTimeout(r,1500));
+const info = await p.evaluate(()=>{
+ const nav=document.querySelector('.nav');
+ const header=document.querySelector('.tut-page header')||document.querySelector('header');
+ const r=el=>el?el.getBoundingClientRect():null;
+ const cs=el=>el?getComputedStyle(el):{};
+ return {
+ navRect:r(nav), navInnerRect:r(document.querySelector('.nav-inner')),
+ headerRect:r(header),
+ navPos:cs(nav).position, navTop:cs(nav).top,
+ headerPos:cs(header).position, headerTop:cs(header).top, headerOverflow:cs(header).overflow,
+ bodyClass:document.body.className,
+ bodyOverflow:getComputedStyle(document.body).overflow,
+ htmlOverflow:getComputedStyle(document.documentElement).overflow,
+ scrollY:window.scrollY
+ };
+});
+console.log(JSON.stringify(info,null,2));
+console.log('ERRORS:',errs.slice(0,15));
+await p.screenshot({path:'/tmp/tut.png'});
+await b.close();
diff --git a/api/_lib/chat-models.js b/api/_lib/chat-models.js
new file mode 100644
index 000000000..efd0923e4
--- /dev/null
+++ b/api/_lib/chat-models.js
@@ -0,0 +1,39 @@
+// Canonical chat model + provider defaults — the single source of truth shared
+// by every LLM chat backend (api/chat.js, api/widgets, api/brain, ...).
+//
+// The platform default is OpenAI's GPT-OSS 120B served via OpenRouter's free
+// tier — the exact model the /chat app uses (chat/src/stores.js) and the one
+// we standardise on across every chat surface. Groq and OpenRouter free models
+// are the no-sign-in tier; paid providers (OpenAI, Anthropic) sit behind keys.
+
+/** OpenAI GPT-OSS 120B on OpenRouter, free tier. The platform-wide default. */
+export const DEFAULT_FREE_MODEL = 'openai/gpt-oss-120b:free';
+
+/** Default per-provider model when the caller doesn't name one. */
+export const PROVIDER_MODEL_DEFAULTS = {
+ anthropic: 'claude-sonnet-4-6',
+ openrouter: DEFAULT_FREE_MODEL,
+ groq: 'llama-3.3-70b-versatile',
+ openai: 'gpt-4o-mini',
+};
+
+/**
+ * Order to try providers in when none is explicitly requested ("auto").
+ * Free-first: GPT-OSS 120B on OpenRouter, then Groq, then paid keys. Keeps the
+ * unauthenticated/default experience on the free GPT-OSS model everywhere.
+ */
+export const DEFAULT_PROVIDER_ORDER = ['openrouter', 'groq', 'openai', 'anthropic'];
+
+/**
+ * OpenRouter sibling models for per-model rate-limit failover. OpenRouter's
+ * `:free` tier rate-limits per model, so a GPT-OSS burst degrades to Llama then
+ * Mistral (all free) before the chain moves to the next provider. GPT-OSS leads.
+ */
+export const OPENROUTER_SIBLINGS = [
+ DEFAULT_FREE_MODEL,
+ 'meta-llama/llama-3.3-70b-instruct:free',
+ 'mistralai/mistral-7b-instruct:free',
+];
+
+/** Providers an anonymous (unauthenticated) caller may use — free tiers only. */
+export const ANON_PROVIDER_LIST = ['openrouter', 'groq'];
diff --git a/api/_lib/crews-store.js b/api/_lib/crews-store.js
new file mode 100644
index 000000000..3b37c9549
--- /dev/null
+++ b/api/_lib/crews-store.js
@@ -0,0 +1,264 @@
+// Crews store — the durable crew (clan) graph for the /play world (W09). Every
+// function takes the authenticated account id (a users.id UUID) as its first
+// argument and keeps the roster + invites consistent. Presence (which member is
+// online / where) is volatile and lives in Redis (presence-store.js); only the
+// crew identity, roster, and pending invites live here.
+//
+// Mirrors the shape of friends-store.js so the two social systems read alike: a
+// lazily-built public-columns fragment, a toProfile() projector, and small
+// single-purpose queries the api/crews/* endpoints wrap thinly.
+
+import { sql } from './db.js';
+
+// Columns safe to expose for any account — never leak email, wallet, plan, or
+// admin flags through a crew roster. Built lazily so importing this module never
+// instantiates the Neon client (endpoints stay cold-start cheap without a DB).
+let _publicUserCols;
+const publicUserCols = () =>
+ (_publicUserCols ??= sql`u.id, u.display_name, u.username, u.avatar_url`);
+
+function toProfile(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ name: row.display_name || row.username || 'Anonymous',
+ username: row.username || null,
+ avatarUrl: row.avatar_url || null,
+ };
+}
+
+// A crew tag is a short clan badge: 2–6 chars, letters/digits only, upper-cased
+// for display. Returns '' for anything that can't be a tag so callers can reject.
+export function normalizeTag(raw) {
+ const t = String(raw || '').trim().toUpperCase().replace(/[^A-Z0-9]/g, '');
+ return t.length >= 2 && t.length <= 6 ? t : '';
+}
+
+function normalizeName(raw) {
+ return String(raw || '')
+ .replace(/[\x00-\x1f\x7f]+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, 32);
+}
+
+function err(message, status, code) {
+ return Object.assign(new Error(message), { status, code });
+}
+
+// ── lookups ──────────────────────────────────────────────────────────────────
+// The crew an account belongs to, as { id, tag, name, role, memberCount } — or
+// null if they're in no crew. This is the hot path the presence-ticket signer
+// calls on every sign-in, so it's one round-trip.
+export async function getMyCrew(accountId) {
+ const [row] = await sql`
+ select c.id, c.tag, c.name, c.owner_id, m.role,
+ (select count(*)::int from crew_members cm where cm.crew_id = c.id) as member_count
+ from crew_members m
+ join crews c on c.id = m.crew_id
+ where m.account_id = ${accountId}
+ limit 1
+ `;
+ if (!row) return null;
+ return {
+ id: row.id,
+ tag: row.tag,
+ name: row.name,
+ role: row.role,
+ isOwner: row.owner_id === accountId,
+ memberCount: row.member_count,
+ };
+}
+
+// Just the crew tag for an account — what the presence ticket embeds so the game
+// server can stamp a trustworthy tag over the avatar. Returns { tag, name } or null.
+export async function crewTagFor(accountId) {
+ const [row] = await sql`
+ select c.tag, c.name from crew_members m
+ join crews c on c.id = m.crew_id
+ where m.account_id = ${accountId}
+ limit 1
+ `;
+ return row ? { tag: row.tag, name: row.name } : null;
+}
+
+// Batch tag lookup for a set of accounts → { accountId: { tag, name } }. Used to
+// annotate rosters / search results with crew membership in one query.
+export async function crewTagsFor(accountIds) {
+ const ids = [...new Set((accountIds || []).filter(Boolean))];
+ if (!ids.length) return {};
+ const rows = await sql`
+ select m.account_id, c.tag, c.name from crew_members m
+ join crews c on c.id = m.crew_id
+ where m.account_id = any(${ids})
+ `;
+ const out = {};
+ for (const r of rows) out[r.account_id] = { tag: r.tag, name: r.name };
+ return out;
+}
+
+// The full roster for a crew, owner first then by join time. Each entry carries
+// the public profile + role; presence is merged at the endpoint layer (Redis).
+export async function listMembers(crewId) {
+ const rows = await sql`
+ select ${publicUserCols()}, m.role, m.joined_at
+ from crew_members m
+ join users u on u.id = m.account_id
+ where m.crew_id = ${crewId} and u.deleted_at is null
+ order by (m.role = 'owner') desc, m.joined_at asc
+ `;
+ return rows.map((r) => ({ ...toProfile(r), role: r.role, joinedAt: r.joined_at }));
+}
+
+// Public view of a crew by tag: identity + roster. Returns null if no such tag.
+export async function getCrewByTag(tag) {
+ const norm = normalizeTag(tag);
+ if (!norm) return null;
+ const [c] = await sql`
+ select id, tag, name, owner_id, created_at from crews where lower(tag) = lower(${norm}) limit 1
+ `;
+ if (!c) return null;
+ return {
+ id: c.id,
+ tag: c.tag,
+ name: c.name,
+ createdAt: c.created_at,
+ members: await listMembers(c.id),
+ };
+}
+
+// Pending invites addressed to an account → [{ crewId, tag, name, inviter, createdAt }].
+export async function listInvites(accountId) {
+ const rows = await sql`
+ select i.crew_id, i.created_at, c.tag, c.name,
+ inv.id as inviter_id, inv.display_name as inviter_name, inv.username as inviter_username
+ from crew_invites i
+ join crews c on c.id = i.crew_id
+ join users inv on inv.id = i.inviter_id
+ where i.invitee_id = ${accountId}
+ order by i.created_at desc
+ `;
+ return rows.map((r) => ({
+ crewId: r.crew_id,
+ tag: r.tag,
+ name: r.name,
+ inviter: { id: r.inviter_id, name: r.inviter_name || r.inviter_username || 'Someone' },
+ createdAt: r.created_at,
+ }));
+}
+
+// ── mutations ────────────────────────────────────────────────────────────────
+// Found a new crew. The founder becomes the owner and first member. Guards a
+// duplicate tag and an account that's already in a crew (one-crew-per-account).
+export async function createCrew(accountId, rawTag, rawName) {
+ const tag = normalizeTag(rawTag);
+ if (!tag) throw err('Tag must be 2–6 letters or digits.', 400, 'bad_tag');
+ const name = normalizeName(rawName) || tag;
+ if (name.length < 2) throw err('Crew name is too short.', 400, 'bad_name');
+
+ if (await getMyCrew(accountId)) {
+ throw err('Leave your current crew before founding a new one.', 409, 'already_in_crew');
+ }
+ const [clash] = await sql`select 1 from crews where lower(tag) = lower(${tag}) limit 1`;
+ if (clash) throw err('That tag is taken.', 409, 'tag_taken');
+
+ const [crew] = await sql`
+ insert into crews (tag, name, owner_id) values (${tag}, ${name}, ${accountId})
+ returning id, tag, name
+ `;
+ await sql`
+ insert into crew_members (crew_id, account_id, role) values (${crew.id}, ${accountId}, 'owner')
+ `;
+ return { id: crew.id, tag: crew.tag, name: crew.name, role: 'owner', isOwner: true, memberCount: 1 };
+}
+
+// Invite an account to my crew. I must be a member; the target must exist, not be
+// muted-irrelevant here, not already be in a crew, and not already invited. Returns
+// the invitee's public profile so the caller can fire a live toast.
+export async function invite(accountId, targetId) {
+ if (targetId === accountId) throw err('You cannot invite yourself.', 400, 'self_invite');
+ const crew = await getMyCrew(accountId);
+ if (!crew) throw err('You are not in a crew.', 400, 'no_crew');
+
+ const [target] = await sql`select ${publicUserCols()} from users u where u.id = ${targetId} and u.deleted_at is null`;
+ if (!target) throw err('User not found.', 404, 'not_found');
+
+ const [member] = await sql`select 1 from crew_members where account_id = ${targetId} limit 1`;
+ if (member) throw err('They are already in a crew.', 409, 'target_in_crew');
+
+ await sql`
+ insert into crew_invites (crew_id, inviter_id, invitee_id) values (${crew.id}, ${accountId}, ${targetId})
+ on conflict (crew_id, invitee_id) do nothing
+ `;
+ return { crew, invitee: toProfile(target) };
+}
+
+// Accept an invite to a crew. Validates the invite exists for me and that I'm not
+// already in a crew (an invite I accept after joining elsewhere is rejected, then
+// cleaned up). Inserts membership and clears every invite I had pending.
+export async function acceptInvite(accountId, crewId) {
+ const [inv] = await sql`
+ select 1 from crew_invites where crew_id = ${crewId} and invitee_id = ${accountId} limit 1
+ `;
+ if (!inv) throw err('No pending invite from that crew.', 404, 'no_invite');
+ if (await getMyCrew(accountId)) {
+ await sql`delete from crew_invites where crew_id = ${crewId} and invitee_id = ${accountId}`;
+ throw err('Leave your current crew first.', 409, 'already_in_crew');
+ }
+ const [crew] = await sql`select id, tag, name from crews where id = ${crewId} limit 1`;
+ if (!crew) {
+ await sql`delete from crew_invites where invitee_id = ${accountId}`;
+ throw err('That crew no longer exists.', 404, 'not_found');
+ }
+ await sql`
+ insert into crew_members (crew_id, account_id, role) values (${crewId}, ${accountId}, 'member')
+ `;
+ // Clear all of my pending invites — I've made my choice.
+ await sql`delete from crew_invites where invitee_id = ${accountId}`;
+ return { id: crew.id, tag: crew.tag, name: crew.name, role: 'member', isOwner: false };
+}
+
+export async function declineInvite(accountId, crewId) {
+ await sql`delete from crew_invites where crew_id = ${crewId} and invitee_id = ${accountId}`;
+ return { ok: true };
+}
+
+// Leave my crew. If I'm the owner, ownership passes to the longest-tenured
+// remaining member; if I was the last member, the crew is deleted outright (its
+// invites cascade away). Keeps a crew from ever being orphaned with no owner.
+export async function leaveCrew(accountId) {
+ const crew = await getMyCrew(accountId);
+ if (!crew) throw err('You are not in a crew.', 400, 'no_crew');
+
+ await sql`delete from crew_members where crew_id = ${crew.id} and account_id = ${accountId}`;
+
+ const remaining = await sql`
+ select account_id from crew_members where crew_id = ${crew.id}
+ order by joined_at asc limit 1
+ `;
+ if (!remaining.length) {
+ await sql`delete from crews where id = ${crew.id}`; // cascades members + invites
+ return { ok: true, disbanded: true };
+ }
+ if (crew.isOwner) {
+ const heir = remaining[0].account_id;
+ await sql`update crews set owner_id = ${heir} where id = ${crew.id}`;
+ await sql`update crew_members set role = 'owner' where crew_id = ${crew.id} and account_id = ${heir}`;
+ }
+ return { ok: true, disbanded: false };
+}
+
+// Owner-only: remove another member from the crew. The owner can't kick themselves
+// (they leave instead, which hands off ownership).
+export async function kickMember(accountId, targetId) {
+ const crew = await getMyCrew(accountId);
+ if (!crew) throw err('You are not in a crew.', 400, 'no_crew');
+ if (!crew.isOwner) throw err('Only the crew owner can remove members.', 403, 'not_owner');
+ if (targetId === accountId) throw err('Use leave to step down as owner.', 400, 'self_kick');
+ const rows = await sql`
+ delete from crew_members where crew_id = ${crew.id} and account_id = ${targetId}
+ returning account_id
+ `;
+ if (!rows.length) throw err('They are not in your crew.', 404, 'not_member');
+ return { ok: true };
+}
diff --git a/api/_lib/feed.js b/api/_lib/feed.js
index e9cef9931..686ff55fc 100644
--- a/api/_lib/feed.js
+++ b/api/_lib/feed.js
@@ -20,9 +20,10 @@
// actor — short, already-sanitized display label (truncated wallet, player
// name, agent name). NEVER a raw secret or full address we wouldn't
// show publicly — this list is world-readable.
-// coin-buy → { mint, sol, network }
-// agent-deploy → { agentId, name }
-// level-up → { skill, level, coin }
+// coin-buy → { mint, sol, network }
+// agent-deploy → { agentId, name } — new agent joined the registry (off-chain)
+// agent-onchain → { agentId, name, chain } — agent verified on-chain
+// level-up → { skill, level, coin }
// world-join → { coin, coinName }
// jackpot → { reward, coin }
//
@@ -39,6 +40,7 @@ const MAX_EVENTS = 200; // capped list — the widget shows ~30; we keep headroo
export const ALLOWED_TYPES = new Set([
'coin-buy',
'agent-deploy',
+ 'agent-onchain',
'level-up',
'world-join',
'jackpot',
diff --git a/api/_lib/migrations/2026-06-05-crews.sql b/api/_lib/migrations/2026-06-05-crews.sql
new file mode 100644
index 000000000..331eab954
--- /dev/null
+++ b/api/_lib/migrations/2026-06-05-crews.sql
@@ -0,0 +1,57 @@
+-- Migration: crews (clans) — persistent, account-keyed player groups for the
+-- /play world (W09). A crew is a named group with a short tag shown over members'
+-- avatars and on their profiles. Membership is keyed to accounts (users.id), not
+-- ephemeral session ids, so a crew and its roster survive reconnects, realm
+-- changes, and server restarts — exactly like the friends graph it sits beside.
+--
+-- Presence (which member is online / where) is volatile and already lives in
+-- Redis (api/_lib/presence-store.js); only the durable crew identity, roster, and
+-- pending invites live here.
+
+begin;
+
+-- A crew. `tag` is the short badge ("3WS", "NOVA") rendered in-world and on
+-- profiles; it is unique case-insensitively so "nova" and "NOVA" can't collide.
+-- `owner_id` is the founder; ownership can pass to another member on leave (see
+-- crews-store.leaveCrew) so a crew is never orphaned while it still has members.
+create table if not exists crews (
+ id uuid primary key default gen_random_uuid(),
+ tag text not null,
+ name text not null,
+ owner_id uuid not null references users(id) on delete cascade,
+ created_at timestamptz not null default now(),
+ constraint crews_tag_len check (char_length(tag) between 2 and 6),
+ constraint crews_name_len check (char_length(name) between 2 and 32)
+);
+-- Case-insensitive uniqueness on the tag without depending on the citext
+-- extension — a plain functional unique index over lower(tag).
+create unique index if not exists crews_tag_lower_uniq on crews (lower(tag));
+
+-- Crew membership. One row per (crew, account). An account belongs to at most one
+-- crew at a time — enforced by a unique index on account_id (a member can't sit
+-- in two crews). `role` is 'owner' | 'member'; the owner row mirrors crews.owner_id.
+create table if not exists crew_members (
+ crew_id uuid not null references crews(id) on delete cascade,
+ account_id uuid not null references users(id) on delete cascade,
+ role text not null default 'member' check (role in ('owner', 'member')),
+ joined_at timestamptz not null default now(),
+ primary key (crew_id, account_id)
+);
+-- "what crew is this account in" (one) + the in-world tag lookup at ticket-sign
+-- time both key off account_id, and the unique-ness enforces one-crew-per-account.
+create unique index if not exists crew_members_account_uniq on crew_members (account_id);
+
+-- A pending invite from a crew (sent by `inviter_id`, an existing member) to
+-- `invitee_id`. Accepting inserts a crew_members row and deletes the invite;
+-- declining just deletes it. Unique per (crew, invitee) so an invite can't stack.
+create table if not exists crew_invites (
+ crew_id uuid not null references crews(id) on delete cascade,
+ inviter_id uuid not null references users(id) on delete cascade,
+ invitee_id uuid not null references users(id) on delete cascade,
+ created_at timestamptz not null default now(),
+ primary key (crew_id, invitee_id)
+);
+-- "my pending crew invites" keys off the invitee.
+create index if not exists crew_invites_invitee_idx on crew_invites (invitee_id);
+
+commit;
diff --git a/api/_lib/presence-store.js b/api/_lib/presence-store.js
index c43d732db..87d6bbd46 100644
--- a/api/_lib/presence-store.js
+++ b/api/_lib/presence-store.js
@@ -72,16 +72,30 @@ function safeParse(s) {
// ── presence tickets ──────────────────────────────────────────────────────
// A presence ticket proves to the multiplayer server that the bearer is a
// specific authenticated account, without that server needing to read our
-// session cookie or call back to verify. Format: base64url(JSON{uid,exp}).base64url(hmac).
+// session cookie or call back to verify. The crew tag (W09) rides inside the
+// signed payload too, so the game server can stamp a TRUSTWORTHY crew badge over
+// the avatar without a DB of its own and without trusting a client option.
+// Format: base64url(JSON{uid,exp,crew,crewName}).base64url(hmac).
export async function signPresenceTicket(userId) {
const exp = Math.floor(Date.now() / 1000) + TICKET_TTL_SEC;
- const payload = base64url(JSON.stringify({ uid: userId, exp }));
+ // Fold in the bearer's crew tag if they're in one. Defensive: a missing crews
+ // table (pre-migration) or any lookup error must never break ticket minting —
+ // friends presence has to keep working regardless of the crew feature.
+ let crew = '';
+ let crewName = '';
+ try {
+ const c = await crewTagFor(userId);
+ if (c) { crew = c.tag; crewName = c.name; }
+ } catch { /* crew is optional metadata; presence works without it */ }
+ const payload = base64url(JSON.stringify({ uid: userId, exp, crew, crewName }));
const sig = await hmacSha256(env.MULTIPLAYER_SHARED_SECRET, payload);
return { token: `${payload}.${sig}`, expiresIn: TICKET_TTL_SEC };
}
-// Verify a ticket and return its userId, or null. Mirrored byte-for-byte on the
-// multiplayer side (multiplayer/src/presence-token.js); keep the two in sync.
+// Verify a ticket and return { uid, crew, crewName }, or null. Mirrored
+// byte-for-byte on the multiplayer side (multiplayer/src/presence-token.js); keep
+// the two in sync. (No API caller today — the multiplayer server is the verifier;
+// this stays here as the canonical reference implementation.)
export async function verifyPresenceTicket(token) {
if (typeof token !== 'string' || !token.includes('.')) return null;
const [payload, sig] = token.split('.');
@@ -91,7 +105,7 @@ export async function verifyPresenceTicket(token) {
const data = safeParse(Buffer.from(payload, 'base64url').toString('utf8'));
if (!data || !data.uid || !data.exp) return null;
if (data.exp < Math.floor(Date.now() / 1000)) return null;
- return data.uid;
+ return { uid: data.uid, crew: data.crew || '', crewName: data.crewName || '' };
}
function base64url(s) {
diff --git a/api/agents/onchain/[action].js b/api/agents/onchain/[action].js
index bcb849be3..b3c7afbaf 100644
--- a/api/agents/onchain/[action].js
+++ b/api/agents/onchain/[action].js
@@ -32,6 +32,7 @@ import { parse } from '../../_lib/validate.js';
import { randomToken } from '../../_lib/crypto.js';
import { r2, publicUrl } from '../../_lib/r2.js';
import { env } from '../../_lib/env.js';
+import { publishFeedEvent } from '../../_lib/feed.js';
import {
buildAgentManifest,
buildAgentOnchainAttributes,
@@ -584,6 +585,25 @@ async function handleConfirm(req, res) {
// Cleanup prep
await sql`delete from agent_registrations_pending where id = ${prep.id}`;
+ // Announce the genuine on-chain deployment on the site-wide ticker. This is
+ // the ONLY truthful "deployed on-chain" feed event — fired here, after the tx
+ // is verified and the onchain block is persisted, never at plain creation.
+ // Fire-and-forget; the feed is a delight layer and must never block confirm.
+ const chainLabel =
+ onchain.family === 'solana'
+ ? 'Solana'
+ : { '1': 'Ethereum', '8453': 'Base', '137': 'Polygon', '42161': 'Arbitrum', '10': 'Optimism' }[
+ String(onchain.chain).split(':')[1]
+ ] || 'EVM';
+ publishFeedEvent({
+ type: 'agent-onchain',
+ ts: Date.now(),
+ actor: agent.name,
+ agentId: agent.id,
+ name: agent.name,
+ chain: chainLabel,
+ }).catch(() => {});
+
return json(res, 201, {
ok: true,
agent: {
diff --git a/api/agents/register/[action].js b/api/agents/register/[action].js
index bede6326c..1e8bd548f 100644
--- a/api/agents/register/[action].js
+++ b/api/agents/register/[action].js
@@ -10,6 +10,7 @@ import { limits, clientIp } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
import { r2, publicUrl } from '../../_lib/r2.js';
import { SERVER_CHAIN_META } from '../../_lib/onchain.js';
+import { publishFeedEvent } from '../../_lib/feed.js';
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { AbiCoder, getAddress, keccak256, toUtf8Bytes } from 'ethers';
import { z } from 'zod';
@@ -161,6 +162,16 @@ async function handleConfirm(req, res) {
if (agentURI !== prep.metadata_uri) return error(res, 409, 'conflict', `metadata URI mismatch: expected ${prep.metadata_uri} got ${agentURI}`);
const [updated] = await sql`insert into agent_identities (user_id, name, description, avatar_id, chain_id, erc8004_agent_id, erc8004_registry, registration_cid) values (${session.id}, ${(prep.payload.name || 'Unnamed Agent').slice(0, 255)}, ${(prep.payload.description || '').slice(0, 1000)}, null, ${body.chainId}, ${String(body.agentId)}, ${chainMeta.registry}, ${prep.cid}) on conflict (user_id) do update set name=excluded.name, description=excluded.description, chain_id=excluded.chain_id, erc8004_agent_id=excluded.erc8004_agent_id, erc8004_registry=excluded.erc8004_registry, registration_cid=excluded.registration_cid, updated_at=now() returning id`;
await sql`delete from agent_registrations_pending where id = ${body.prepId}`;
+ // Truthful "deployed on-chain" ticker event — only after the ERC-8004 tx is
+ // verified and the agent row carries its on-chain id. Fire-and-forget.
+ publishFeedEvent({
+ type: 'agent-onchain',
+ ts: Date.now(),
+ actor: prep.payload.name || 'An agent',
+ agentId: updated.id,
+ name: prep.payload.name || 'An agent',
+ chain: chainMeta.name || 'EVM',
+ }).catch(() => {});
return json(res, 200, { ok: true, agentId: updated.id });
}
diff --git a/api/brain/chat.js b/api/brain/chat.js
index 9772eb444..5a5f7b63e 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -21,6 +21,17 @@ import { watsonxConfig, watsonxChatRequest } from '../_lib/watsonx.js';
export const maxDuration = 120;
const PROVIDERS = {
+ 'gpt-oss-120b': {
+ label: 'GPT-OSS 120B',
+ network: 'OpenAI · OpenRouter',
+ tier: 'balanced',
+ maxOutput: 8192,
+ description: "OpenAI's open-weight 120B. Fast, capable, free tier. Platform default.",
+ build: () => {
+ if (env.OPENROUTER_API_KEY) return openrouter()('openai/gpt-oss-120b:free');
+ return null;
+ },
+ },
'claude-opus-4-7': {
label: 'Claude Opus 4.7',
network: 'Anthropic',
@@ -302,7 +313,7 @@ export default wrap(async function handler(req, res) {
return error(res, e.status || 400, 'bad_request', e.message);
}
- const providerKey = String(body.provider || 'claude-sonnet-4-6');
+ const providerKey = String(body.provider || 'gpt-oss-120b');
const spec = PROVIDERS[providerKey];
if (!spec) {
return error(res, 400, 'unknown_provider', `unknown provider: ${providerKey}`, {
diff --git a/api/chat.js b/api/chat.js
index d535a7b9b..8bb9fe93d 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -31,19 +31,28 @@ import { loadUserProviderKeys } from './_lib/provider-keys.js';
import { watsonxConfig, watsonxAuthHeaders } from './_lib/watsonx.js';
import { orchestrateConfig } from './_lib/orchestrate.js';
import { guardianConfig, governSend, sendCapUsd } from './_lib/granite-guardian.js';
+import {
+ DEFAULT_FREE_MODEL,
+ PROVIDER_MODEL_DEFAULTS,
+ DEFAULT_PROVIDER_ORDER,
+ OPENROUTER_SIBLINGS,
+ ANON_PROVIDER_LIST,
+} from './_lib/chat-models.js';
import { z } from 'zod';
// Providers anonymous (unauthenticated) callers may use. Groq and OpenRouter
// free-tier models are exposed without sign-in — paid keys stay gated behind auth.
-const ANON_PROVIDERS = new Set(['groq', 'openrouter']);
+const ANON_PROVIDERS = new Set(ANON_PROVIDER_LIST);
export const maxDuration = 60;
const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';
-const DEFAULT_ANTHROPIC_MODEL = 'claude-sonnet-4-6';
-const DEFAULT_OPENROUTER_MODEL = 'meta-llama/llama-3.3-70b-instruct:free';
-const DEFAULT_GROQ_MODEL = 'llama-3.3-70b-versatile';
-const DEFAULT_OPENAI_MODEL = 'gpt-4o-mini';
+const DEFAULT_ANTHROPIC_MODEL = PROVIDER_MODEL_DEFAULTS.anthropic;
+// GPT-OSS 120B on OpenRouter — the platform-wide default chat model (same one
+// the /chat app uses). See api/_lib/chat-models.js.
+const DEFAULT_OPENROUTER_MODEL = PROVIDER_MODEL_DEFAULTS.openrouter;
+const DEFAULT_GROQ_MODEL = PROVIDER_MODEL_DEFAULTS.groq;
+const DEFAULT_OPENAI_MODEL = PROVIDER_MODEL_DEFAULTS.openai;
const DEFAULT_MAX_TOKENS = 1024;
const HARD_MAX_TOKENS = 4096;
@@ -312,15 +321,21 @@ export default wrap(async (req, res) => {
if (!rl.success) {
return error(res, 429, 'rate_limited', 'too many anonymous chat requests, try again shortly');
}
- if (!process.env.GROQ_API_KEY) {
+ const hasOpenRouter = !!process.env.OPENROUTER_API_KEY;
+ const hasGroq = !!process.env.GROQ_API_KEY;
+ if (!hasOpenRouter && !hasGroq) {
return error(res, 401, 'unauthorized', 'sign in to chat with the agent');
}
if (body.provider && !ANON_PROVIDERS.has(body.provider)) {
return error(res, 401, 'unauthorized', 'sign in to use this model');
}
- // Honor an explicitly-requested free-tier provider (groq/openrouter);
- // only default to groq when the caller didn't pick one.
- if (!body.provider) body.provider = 'groq';
+ // Honor an explicitly-requested free-tier provider (groq/openrouter).
+ // Otherwise default to GPT-OSS 120B on OpenRouter — the platform-wide
+ // default model — and fall back to Groq when OpenRouter isn't configured.
+ if (!body.provider) {
+ body.provider = hasOpenRouter ? 'openrouter' : 'groq';
+ if (!body.model && body.provider === 'openrouter') body.model = DEFAULT_FREE_MODEL;
+ }
anonymous = true;
}
@@ -640,7 +655,7 @@ async function governActions(actions, userMessage) {
function pickProvider(requested, model, userKeys = {}) {
const order = requested
? [requested, ...Object.keys(PROVIDERS).filter((p) => p !== requested)]
- : ['groq', 'openrouter', 'openai', 'anthropic'];
+ : DEFAULT_PROVIDER_ORDER;
for (const name of order) {
const cfg = PROVIDERS[name];
@@ -674,11 +689,7 @@ function pickProvider(requested, model, userKeys = {}) {
// from a single upstream burst without paying. Last resort is paid Anthropic
// so the user still gets a response.
const FALLBACK_SIBLINGS = {
- openrouter: [
- 'meta-llama/llama-3.3-70b-instruct:free',
- 'meta-llama/llama-3.2-3b-instruct:free',
- 'mistralai/mistral-7b-instruct:free',
- ],
+ openrouter: OPENROUTER_SIBLINGS,
groq: ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant'],
anthropic: ['claude-sonnet-4-6', 'claude-haiku-4-5-20251001'],
openai: ['gpt-4o-mini'],
diff --git a/api/crews/[tag].js b/api/crews/[tag].js
new file mode 100644
index 000000000..342173290
--- /dev/null
+++ b/api/crews/[tag].js
@@ -0,0 +1,38 @@
+// GET /api/crews/:tag
+// Public view of a crew by its tag: identity + roster (public profile subset) +
+// live presence per member. Used by the inspect card's crew link and any crew
+// landing surface. Auth-optional — a crew roster is public, like the agent
+// gallery, but never leaks private member state (handled in crews-store).
+
+import { cors, error, json, method, wrap } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { readPresence } from '../_lib/presence-store.js';
+import { getCrewByTag, normalizeTag } from '../_lib/crews-store.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const raw = url.searchParams.get('tag') || url.pathname.split('/').pop() || '';
+ const tag = normalizeTag(decodeURIComponent(raw));
+ if (!tag) return error(res, 400, 'bad_tag', 'invalid crew tag');
+
+ let crew;
+ try {
+ crew = await getCrewByTag(tag);
+ } catch (err) {
+ if (err?.message?.includes('relation') || err?.message?.includes('does not exist')) {
+ return error(res, 404, 'not_found', 'no such crew');
+ }
+ throw err;
+ }
+ if (!crew) return error(res, 404, 'not_found', 'no such crew');
+
+ const presence = await readPresence(crew.members.map((m) => m.id));
+ crew.members = crew.members.map((m) => ({ ...m, ...(presence[m.id] || { online: false, realm: null, server: null }) }));
+ return json(res, 200, { data: { crew } });
+});
diff --git a/api/crews/index.js b/api/crews/index.js
new file mode 100644
index 000000000..5059d592b
--- /dev/null
+++ b/api/crews/index.js
@@ -0,0 +1,114 @@
+// /api/crews
+// GET — the caller's crew (with roster + live presence) and pending crew
+// invites. Empty crew/invites when they belong to none.
+// POST — crew mutations via { action, ... }:
+// create { tag, name } found a new crew (founder becomes owner)
+// invite { userId } invite an account to my crew
+// accept { crewId } accept an invite to a crew
+// decline { crewId } decline an invite
+// leave {} leave my crew (owner hands off / disbands)
+// kick { userId } owner-only: remove a member
+//
+// Validates the caller owns the account (session or bearer); the store layer
+// guards self-invite, duplicates, one-crew-per-account, and ownership. Rate-
+// limited per account. Mirrors api/friends/index.js.
+
+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { resolveAccount } from '../_lib/account-auth.js';
+import { readPresence, notifyMultiplayer } from '../_lib/presence-store.js';
+import {
+ getMyCrew,
+ listMembers,
+ listInvites,
+ createCrew,
+ invite,
+ acceptInvite,
+ declineInvite,
+ leaveCrew,
+ kickMember,
+} from '../_lib/crews-store.js';
+
+function isUuid(v) {
+ return typeof v === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);
+}
+
+const EMPTY = { crew: null, members: [], invites: [] };
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = await resolveAccount(req, res);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ const me = auth.userId;
+
+ if (req.method === 'GET') {
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+ return json(res, 200, { data: await crewWithPresence(me) });
+ }
+
+ // POST — a crew mutation. 40 actions/min per account (shared chat limiter).
+ const rl = await limits.chatUser(me);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'slow down');
+
+ const body = await readJson(req).catch(() => ({}));
+ const action = String(body.action || '');
+ try {
+ switch (action) {
+ case 'create': {
+ const crew = await createCrew(me, body.tag, body.name);
+ return json(res, 200, { data: { crew } });
+ }
+ case 'invite': {
+ if (!isUuid(body.userId)) return error(res, 400, 'bad_target', 'invalid user id');
+ const { crew, invitee } = await invite(me, body.userId);
+ notifyMultiplayer('crew_invite', body.userId, { crew, from: me });
+ return json(res, 200, { data: { ok: true, invitee } });
+ }
+ case 'accept': {
+ if (!isUuid(body.crewId)) return error(res, 400, 'bad_target', 'invalid crew id');
+ const crew = await acceptInvite(me, body.crewId);
+ return json(res, 200, { data: { crew } });
+ }
+ case 'decline': {
+ if (!isUuid(body.crewId)) return error(res, 400, 'bad_target', 'invalid crew id');
+ return json(res, 200, { data: await declineInvite(me, body.crewId) });
+ }
+ case 'leave':
+ return json(res, 200, { data: await leaveCrew(me) });
+ case 'kick': {
+ if (!isUuid(body.userId)) return error(res, 400, 'bad_target', 'invalid user id');
+ return json(res, 200, { data: await kickMember(me, body.userId) });
+ }
+ default:
+ return error(res, 400, 'bad_action', 'unknown action');
+ }
+ } catch (e) {
+ // Store layer throws typed errors ({ status, code }); surface them cleanly.
+ if (e?.status && e?.code) return error(res, e.status, e.code, e.message);
+ throw e;
+ }
+});
+
+async function crewWithPresence(me) {
+ let crew;
+ let invites;
+ try {
+ crew = await getMyCrew(me);
+ invites = await listInvites(me);
+ } catch (err) {
+ // Crew tables may not be migrated yet — return an empty view rather than 500.
+ if (err?.message?.includes('relation') || err?.message?.includes('does not exist')) {
+ return EMPTY;
+ }
+ throw err;
+ }
+ if (!crew) return { crew: null, members: [], invites: invites || [] };
+
+ const members = await listMembers(crew.id);
+ const presence = await readPresence(members.map((m) => m.id));
+ const annotated = members.map((m) => ({ ...m, ...(presence[m.id] || { online: false, realm: null, server: null }) }));
+ return { crew, members: annotated, invites: invites || [] };
+}
diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].js
index 213e2b89e..24a9d5ee3 100644
--- a/api/widgets/[id]/[action].js
+++ b/api/widgets/[id]/[action].js
@@ -15,6 +15,7 @@ import { limits, clientIp } from '../../_lib/rate-limit.js';
import { captureException } from '../../_lib/sentry.js';
import { isDemoWidgetId, getDemoWidget } from '../_demo-fixtures.js';
import { decorate } from '../index.js';
+import { PROVIDER_MODEL_DEFAULTS, DEFAULT_PROVIDER_ORDER } from '../../_lib/chat-models.js';
import { redactPii } from '../../_lib/pii.js';
import { embed, cosine, embeddingsConfigured } from '../../_lib/embeddings.js';
import { watsonxConfig, watsonxToken } from '../../_lib/watsonx.js';
@@ -60,7 +61,8 @@ const PROVIDERS = {
},
openrouter: {
envKey: 'OPENROUTER_API_KEY',
- defaultModel: 'meta-llama/llama-3.3-70b-instruct:free',
+ // GPT-OSS 120B (free) — the platform-wide default; see api/_lib/chat-models.js.
+ defaultModel: PROVIDER_MODEL_DEFAULTS.openrouter,
url: 'https://openrouter.ai/api/v1/chat/completions',
style: 'openai',
extraHeaders: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws widget' },
@@ -293,7 +295,7 @@ function pickProvider(requested, requestedModel) {
const order =
requested && requested !== 'auto'
? [requested, ...Object.keys(PROVIDERS).filter((p) => p !== requested)]
- : ['anthropic', 'openrouter', 'groq', 'openai'];
+ : DEFAULT_PROVIDER_ORDER;
for (const name of order) {
const cfg = PROVIDERS[name];
diff --git a/data/pages.json b/data/pages.json
index 52b18cd36..e05067228 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -17,7 +17,7 @@
{
"path": "/",
"title": "Home",
- "description": "Landing page. Pitch, live agent demos, and the front door to every flow.",
+ "description": "Landing page. 3D AI agents that think on IBM watsonx.ai (Granite) — the pitch, live agent demos, and the front door to every flow.",
"priority": 1,
"changefreq": "weekly"
},
diff --git a/docs/ibm.md b/docs/ibm.md
index 9b2a52aee..e59c108fb 100644
--- a/docs/ibm.md
+++ b/docs/ibm.md
@@ -20,6 +20,13 @@ Three things are deliberately kept distinct, and the docs say so plainly:
Do not describe the connector or the public demos as an official IBM release or partnership deliverable. Do describe the platform integration as built on IBM watsonx.ai.
+### Press & coverage
+
+Outside coverage of three.ws and its work on IBM watsonx.ai. These are third-party press and syndicated releases — link to them as coverage, and keep the distinctions above intact when you cite them. Do not let a headline upgrade the careful framing on this page.
+
+- [three.ws and IBM announce strategic partnership to advance AI-powered 3D agent technology](https://markets.businessinsider.com/news/stocks/three-ws-and-ibm-announce-strategic-partnership-to-advance-ai-powered-3d-agent-technology-1036222181) — Business Insider (syndicated release)
+- [IBM extends its AI narrative to three.ws](https://finance.yahoo.com/sectors/technology/articles/ibm-extends-ai-narrative-three-010650764.html) — Yahoo Finance
+
---
## The Granite models we run
diff --git a/multiplayer/src/combat.js b/multiplayer/src/combat.js
new file mode 100644
index 000000000..7f94f0f09
--- /dev/null
+++ b/multiplayer/src/combat.js
@@ -0,0 +1,123 @@
+// Combat math — the pure, server-authoritative core of the /play combat system
+// (W07). Targeting geometry, damage + armor resolution, and the wanted/heat meter
+// all live here as side-effect-light functions so the WalkRoom can stay a thin
+// validator-and-replicator and every rule is unit-testable in isolation.
+//
+// Nothing here touches the network, the schema, or world geometry: the room feeds
+// in authoritative positions (which it already holds from validated `move`s),
+// weapon defs from items.js, and zone decisions from world-features.js, then
+// applies the results. The client NEVER computes damage or picks hits — it only
+// renders what these functions, run on the server, produce.
+//
+// Angle convention matches the client's avatar facing: yaw is measured as
+// atan2(forwardX, forwardZ), so a player's forward vector is (sin yaw, cos yaw).
+
+// Smallest signed difference between two angles, normalised to (-π, π].
+export function angleDiff(a, b) {
+ let d = a - b;
+ while (d > Math.PI) d -= Math.PI * 2;
+ while (d < -Math.PI) d += Math.PI * 2;
+ return d;
+}
+
+// Bearing from one point to another in the yaw convention above.
+export function bearing(from, to) {
+ return Math.atan2(to.x - from.x, to.z - from.z);
+}
+
+export function dist2d(a, b) {
+ return Math.hypot(a.x - b.x, a.z - b.z);
+}
+
+// The authoritative target picker. Given the attacker's pose ({x, z, yaw}), the
+// weapon def (from items.js WEAPONS), and the candidate entities (players + mobs,
+// each {x, z, ...}), return the single entity the swing/shot lands on, or null.
+//
+// melee — candidate must be within `range` AND inside the frontal cone `arc`
+// (so you can't sword someone behind you).
+// ranged — candidate must be within `range` AND within `aimTol` of where the
+// attacker is facing (a light aim-assist on the hitscan line).
+//
+// Among all candidates that pass, the NEAREST is chosen — melee favours the foe in
+// your face, ranged favours the first thing down your sights. Candidates the
+// caller already excluded (self, dead, wrong zone) simply aren't passed in, so the
+// gating policy stays in the room while the geometry stays here.
+export function selectTarget(attacker, weapon, candidates) {
+ if (!weapon || !Array.isArray(candidates)) return null;
+ const isMelee = weapon.kind === 'melee';
+ const tol = isMelee ? (weapon.arc || 0) / 2 : (weapon.aimTol || 0);
+ let best = null;
+ let bestDist = Infinity;
+ for (const c of candidates) {
+ const d = dist2d(attacker, c);
+ if (d > weapon.range) continue;
+ // A target essentially on top of the attacker has an unstable bearing —
+ // always count it as in-arc rather than letting noise reject a point-blank hit.
+ if (d > 0.05) {
+ const off = Math.abs(angleDiff(bearing(attacker, c), attacker.yaw));
+ if (off > tol) continue;
+ }
+ if (d < bestDist) { best = c; bestDist = d; }
+ }
+ return best;
+}
+
+// Roll a weapon's damage for one hit: base, scaled gently by the attacker's combat
+// level (+1%/level so the skill matters without trivialising fights) and a ±15%
+// swing for texture. `rng` is injectable so the room's roll is honest and this
+// stays deterministic under test, mirroring items.js's roll helpers. Always ≥ 1.
+export function rollDamage(weapon, combatLevel = 1, rng = Math.random) {
+ const base = weapon?.dmg || 0;
+ if (base <= 0) return 0;
+ const lvl = Math.max(1, combatLevel | 0);
+ const scaled = base * (1 + 0.01 * (lvl - 1));
+ const varied = scaled * (0.85 + rng() * 0.30);
+ return Math.max(1, Math.round(varied));
+}
+
+// Apply `dmg` to a target's vitals. Armor is a second health bar that absorbs
+// damage 1:1 until depleted; the remainder spills into HP. Mutates the target
+// ({hp, armor}) in place — server entities are plain mutable objects — and returns
+// a breakdown for the hit feedback. `killed` is true when HP reaches 0.
+export function applyDamage(target, dmg) {
+ const d = Math.max(0, Math.round(dmg));
+ const armor = Math.max(0, target.armor || 0);
+ const armorAbsorbed = Math.min(armor, d);
+ target.armor = armor - armorAbsorbed;
+ const hpLost = d - armorAbsorbed;
+ target.hp = Math.max(0, (target.hp || 0) - hpLost);
+ return { dealt: d, armorAbsorbed, hpLost, killed: target.hp <= 0 };
+}
+
+// ---------------------------------------------------------------------------
+// Wanted / heat (W07 v1)
+// ---------------------------------------------------------------------------
+//
+// A lightweight crime meter. Attacking another player is a "crime" that raises
+// heat; killing one raises it more. Heat decays over time, and faster while you
+// lie low in a safe zone. The meter maps to 0–5 wanted stars peers can see (and,
+// in W08, NPC enforcers will react to). Mob fights never raise heat — clearing the
+// wilds is the intended, lawful loop.
+export const MAX_HEAT = 5;
+export const HEAT_PER_ATTACK = 0.5;
+export const HEAT_PER_KILL = 1.5;
+export const HEAT_DECAY_DANGER = 0.12; // heat/sec out in the wilds
+export const HEAT_DECAY_SAFE = 0.5; // heat/sec while lying low in town
+
+// Heat to add for a hostile act against another player. A kill is the bigger
+// crime; a plain hit still nudges the meter. Clamps the running total to MAX_HEAT.
+export function addHeat(heat, { killed = false } = {}) {
+ const add = killed ? HEAT_PER_KILL : HEAT_PER_ATTACK;
+ return Math.min(MAX_HEAT, Math.max(0, heat || 0) + add);
+}
+
+// Decay heat over `dtMs`, faster in a safe zone. Pure; clamps at 0.
+export function decayHeat(heat, dtMs, inSafe) {
+ const rate = inSafe ? HEAT_DECAY_SAFE : HEAT_DECAY_DANGER;
+ return Math.max(0, (heat || 0) - rate * (dtMs / 1000));
+}
+
+// The 0–5 star level shown for a heat value. 0 heat → not wanted.
+export function heatStars(heat) {
+ return Math.max(0, Math.min(MAX_HEAT, Math.ceil(heat || 0)));
+}
diff --git a/multiplayer/src/cosmetics-catalog.js b/multiplayer/src/cosmetics-catalog.js
new file mode 100644
index 000000000..7498648e1
--- /dev/null
+++ b/multiplayer/src/cosmetics-catalog.js
@@ -0,0 +1,133 @@
+// Cosmetics catalog — the single source of truth for every wearable in the
+// world, shared verbatim by the authoritative server (WalkRoom validates equips
+// and ownership against it) and the client (the creator wardrobe renders it, and
+// every player's rig applies it). Keep it dependency-free so both the Node server
+// and the Vite client import the exact same table — a cosmetic that exists on one
+// side but not the other would let a player wear something peers can't render.
+//
+// A cosmetic is purely visual (see cosmetics-visual.js): it never touches a
+// gameplay value. Each entry carries a `visual` spec the renderer turns into
+// Three.js objects:
+// tint — recolour the body (a dye), { tint:'#rrggbb' }
+// prop — a GLB worn on the head/face, { prop:'/url.glb', anchor:'head'|'face' }
+// aura — a glowing ground ring, { aura:'#rrggbb' }
+//
+// Slots are exclusive: a player wears at most one cosmetic per slot. The `none`
+// entry in each slot is the bare default everyone owns — equipping it clears the
+// slot. Props reference the real GLBs already shipped in public/accessories/, so
+// nothing here points at an asset that 404s.
+
+// Ordered so the wardrobe renders slots top-to-bottom in a sensible grooming flow.
+export const SLOTS = ['dye', 'headwear', 'eyewear', 'aura'];
+
+export const SLOT_LABELS = {
+ dye: 'Body color',
+ headwear: 'Headwear',
+ eyewear: 'Eyewear',
+ aura: 'Aura',
+};
+
+// tier: 'free' is owned by everyone implicitly; 'premium' must be unlocked
+// (W04's shop grants it into the account's owned list). `price` is the $THREE
+// cost the shop will charge — surfaced here so the wardrobe can show it, but W03
+// never sells (it only exposes the unlock hook).
+export const COSMETICS = [
+ // ── Body color (dye) ──────────────────────────────────────────────────────
+ { id: 'dye-none', name: 'Natural', slot: 'dye', rarity: 'common', tier: 'free', price: 0, visual: null, swatch: '#d8d8e0' },
+ { id: 'dye-crimson', name: 'Crimson', slot: 'dye', rarity: 'common', tier: 'free', price: 0, visual: { tint: '#c0392b' }, swatch: '#c0392b' },
+ { id: 'dye-azure', name: 'Azure', slot: 'dye', rarity: 'common', tier: 'free', price: 0, visual: { tint: '#2980b9' }, swatch: '#2980b9' },
+ { id: 'dye-emerald', name: 'Emerald', slot: 'dye', rarity: 'common', tier: 'free', price: 0, visual: { tint: '#1e9e5a' }, swatch: '#1e9e5a' },
+ { id: 'dye-gold', name: 'Midas', slot: 'dye', rarity: 'rare', tier: 'premium', price: 250, visual: { tint: '#e6b422' }, swatch: '#e6b422' },
+ { id: 'dye-violet', name: 'Amethyst', slot: 'dye', rarity: 'rare', tier: 'premium', price: 250, visual: { tint: '#8e44ad' }, swatch: '#8e44ad' },
+
+ // ── Headwear (prop, anchored to the head bone) ────────────────────────────
+ { id: 'head-none', name: 'None', slot: 'headwear', rarity: 'common', tier: 'free', price: 0, visual: null },
+ { id: 'hat-beanie', name: 'Beanie', slot: 'headwear', rarity: 'common', tier: 'free', price: 0, visual: { prop: '/accessories/hat-beanie.glb', anchor: 'head' }, thumb: '/accessories/thumbs/hat-beanie.png' },
+ { id: 'hat-baseball', name: 'Ball cap', slot: 'headwear', rarity: 'common', tier: 'free', price: 0, visual: { prop: '/accessories/hat-baseball.glb', anchor: 'head' }, thumb: '/accessories/thumbs/hat-baseball.png' },
+ { id: 'hat-cowboy', name: 'Stetson', slot: 'headwear', rarity: 'rare', tier: 'premium', price: 400, visual: { prop: '/accessories/hat-cowboy.glb', anchor: 'head' }, thumb: '/accessories/thumbs/hat-cowboy.png' },
+
+ // ── Eyewear (prop, anchored at the eye line) ──────────────────────────────
+ { id: 'eye-none', name: 'None', slot: 'eyewear', rarity: 'common', tier: 'free', price: 0, visual: null },
+ { id: 'glasses-round', name: 'Round frames', slot: 'eyewear', rarity: 'common', tier: 'free', price: 0, visual: { prop: '/accessories/glasses-round.glb', anchor: 'face' }, thumb: '/accessories/thumbs/glasses-round.png' },
+ { id: 'glasses-shades', name: 'Shades', slot: 'eyewear', rarity: 'rare', tier: 'premium', price: 350, visual: { prop: '/accessories/glasses-shades.glb', anchor: 'face' }, thumb: '/accessories/thumbs/glasses-shades.png' },
+
+ // ── Aura (glowing ground ring) ────────────────────────────────────────────
+ { id: 'aura-none', name: 'None', slot: 'aura', rarity: 'common', tier: 'free', price: 0, visual: null },
+ { id: 'aura-gold', name: 'Golden halo', slot: 'aura', rarity: 'epic', tier: 'premium', price: 600, visual: { aura: '#e6b422' }, swatch: '#e6b422' },
+ { id: 'aura-cyan', name: 'Cyan pulse', slot: 'aura', rarity: 'epic', tier: 'premium', price: 600, visual: { aura: '#00e5ff' }, swatch: '#00e5ff' },
+ { id: 'aura-magenta', name: 'Magenta pulse', slot: 'aura', rarity: 'epic', tier: 'premium', price: 600, visual: { aura: '#ff2d95' }, swatch: '#ff2d95' },
+];
+
+export const COSMETICS_BY_ID = new Map(COSMETICS.map((c) => [c.id, c]));
+
+export function getCosmetic(id) {
+ return COSMETICS_BY_ID.get(id) || null;
+}
+
+// The bare default loadout: each slot's `none`/first-free entry. Everyone starts
+// here, owning nothing premium.
+export const DEFAULT_LOADOUT = Object.freeze({
+ dye: 'dye-none',
+ headwear: 'head-none',
+ eyewear: 'eye-none',
+ aura: 'aura-none',
+});
+
+// Is this id a free cosmetic anyone may wear without owning it? (The `none`
+// defaults are free, as are the starter colours/hats.)
+export function isFreeCosmetic(id) {
+ const c = getCosmetic(id);
+ return !!c && c.tier === 'free';
+}
+
+// Can `account` (an owned-id set, or array) wear `id`? Free cosmetics are always
+// allowed; premium ones only when explicitly owned. Unknown ids are rejected.
+export function canWear(id, owned) {
+ const c = getCosmetic(id);
+ if (!c) return false;
+ if (c.tier === 'free') return true;
+ if (!owned) return false;
+ return owned instanceof Set ? owned.has(id) : Array.isArray(owned) && owned.includes(id);
+}
+
+// Coerce an arbitrary equipped map (from a client or a persisted blob) into a
+// valid, slot-correct loadout the wearer is actually allowed to use. Anything
+// invalid, in the wrong slot, or unowned falls back to that slot's default — so a
+// tampered payload can never put an unowned cosmetic on a player.
+export function sanitizeLoadout(equipped, owned) {
+ const out = { ...DEFAULT_LOADOUT };
+ if (equipped && typeof equipped === 'object') {
+ for (const slot of SLOTS) {
+ const id = equipped[slot];
+ const c = getCosmetic(id);
+ if (c && c.slot === slot && canWear(id, owned)) out[slot] = id;
+ }
+ }
+ return out;
+}
+
+// Compact wire form for the Player schema field peers read: the equipped ids in
+// slot order, comma-joined, dropping the `none` defaults (they render nothing).
+// Bounded length so the schema diff stays tiny.
+export function serializeLoadout(equipped) {
+ const ids = [];
+ for (const slot of SLOTS) {
+ const id = equipped?.[slot];
+ const c = getCosmetic(id);
+ if (c && c.visual) ids.push(id);
+ }
+ return ids.join(',');
+}
+
+// Parse the wire string back into the list of catalog entries to render. Tolerant
+// of unknown/empty ids (a peer on a newer catalog) — they're simply skipped.
+export function parseLoadout(str) {
+ if (!str || typeof str !== 'string') return [];
+ return str.split(',').map((id) => getCosmetic(id.trim())).filter((c) => c && c.visual);
+}
+
+// The ids a brand-new account implicitly owns (every free cosmetic). Used so the
+// wardrobe can show owned vs. locked without a round-trip.
+export function freeCosmeticIds() {
+ return COSMETICS.filter((c) => c.tier === 'free').map((c) => c.id);
+}
diff --git a/multiplayer/src/economy.js b/multiplayer/src/economy.js
index a75ae35e9..e5b4d5499 100644
--- a/multiplayer/src/economy.js
+++ b/multiplayer/src/economy.js
@@ -15,19 +15,29 @@
// same account-keyed playerStore.
import {
- STACKABLE_ITEMS, isEdible, scaledHeal,
+ STACKABLE_ITEMS, isEdible, scaledHeal, armorValue,
} from './items.js';
+import {
+ DEFAULT_LOADOUT, SLOTS, getCosmetic, canWear, sanitizeLoadout, freeCosmeticIds,
+} from './cosmetics-catalog.js';
export const INV_SIZE = 24;
export const HOTBAR_SIZE = 6;
export const MAX_STACK = 999;
export const LEVEL_CAP = 99;
export const SKILLS = ['combat', 'woodcutting', 'mining', 'fishing', 'cooking'];
+// The armor layer's ceiling — a vest tops you up to here, and incoming damage eats
+// armor before HP (see combat.js applyDamage). One capped bar, so it reads cleanly.
+export const MAX_ARMOR = 100;
// Starter kit handed to a brand-new player so the loop is exercisable the moment
-// they land: a fishing rod (cast at any pond) plus the gathering tools and a sword
-// the later phases (woodcutting/mining/combat) will use. Tools occupy the hotbar.
-const STARTER_HOTBAR = ['rod', 'axe', 'pickaxe', 'sword'];
+// they land: a fishing rod (cast at any pond), the gathering tools, and BOTH a
+// melee (sword) and ranged (pistol) weapon so the W07 combat loop — swing, shoot,
+// heal, re-armor — is playable on arrival. Tools occupy the hotbar.
+const STARTER_HOTBAR = ['rod', 'axe', 'pickaxe', 'sword', 'pistol'];
+// Backpack seed so a new player can fire and survive their first fight without a
+// shop run: a clip of pistol ammo and one body-armor vest.
+const STARTER_INV = [{ item: 'ammo', qty: 24 }, { item: 'vest', qty: 1 }];
// XP curve — the canonical progression for the platform: level n needs
// 50 * n^1.8 cumulative XP, capped at LEVEL_CAP.
@@ -54,19 +64,63 @@ function emptySlots(n) {
export function newProfile(playerId = '') {
const hotbar = emptySlots(HOTBAR_SIZE);
STARTER_HOTBAR.forEach((item, i) => { hotbar[i] = { item, qty: 1 }; });
+ const inv = emptySlots(INV_SIZE);
+ STARTER_INV.forEach((seed, i) => { inv[i] = { item: seed.item, qty: seed.qty }; });
return {
playerId,
gold: 0,
+ bank: 0, // banked cash — protected on death (carried `gold` drops). W04 extends.
hp: 100,
maxHp: 100,
- inv: emptySlots(INV_SIZE),
+ armor: 0, // armor layer that absorbs damage before HP; refilled by a vest.
+ maxArmor: MAX_ARMOR,
+ heat: 0, // wanted/heat meter (0..MAX_HEAT) — raised by crimes, decays over time.
+ inv,
hotbar,
activeSlot: 0, // the rod, ready to cast
xp: Object.fromEntries(SKILLS.map((s) => [s, 0])),
levels: Object.fromEntries(SKILLS.map((s) => [s, 1])),
+ // Cosmetic identity (W03), purely visual. `owned` lists the premium ids this
+ // account has unlocked (free cosmetics are implicitly owned by everyone, so
+ // they're never stored here); `equipped` is the per-slot loadout peers render.
+ cosmetics: { owned: [], equipped: { ...DEFAULT_LOADOUT } },
};
}
+// Premium ids this profile may wear: its unlocked set plus every free cosmetic.
+// Returned as a Set for O(1) canWear checks on the equip hot path.
+export function ownedCosmeticSet(profile) {
+ const owned = new Set(freeCosmeticIds());
+ const list = profile?.cosmetics?.owned;
+ if (Array.isArray(list)) for (const id of list) if (getCosmetic(id)) owned.add(id);
+ return owned;
+}
+
+// Grant a premium cosmetic into an account's owned list (the W04 unlock hook:
+// the shop calls this after a $THREE payment settles). Idempotent; ignores free
+// or unknown ids. Returns true when it newly unlocked something.
+export function grantCosmetic(profile, id) {
+ const c = getCosmetic(id);
+ if (!c || c.tier !== 'premium') return false;
+ if (!profile.cosmetics) profile.cosmetics = { owned: [], equipped: { ...DEFAULT_LOADOUT } };
+ if (!Array.isArray(profile.cosmetics.owned)) profile.cosmetics.owned = [];
+ if (profile.cosmetics.owned.includes(id)) return false;
+ profile.cosmetics.owned.push(id);
+ return true;
+}
+
+// Equip `id` into its slot if the profile is allowed to wear it. Returns the new
+// equipped map on success, or null when the id is unknown or unowned (the server
+// then rejects the equip). Mutates profile.cosmetics.equipped.
+export function equipCosmetic(profile, id) {
+ const c = getCosmetic(id);
+ if (!c) return null;
+ if (!canWear(id, ownedCosmeticSet(profile))) return null;
+ if (!profile.cosmetics) profile.cosmetics = { owned: [], equipped: { ...DEFAULT_LOADOUT } };
+ profile.cosmetics.equipped = { ...profile.cosmetics.equipped, [c.slot]: id };
+ return profile.cosmetics.equipped;
+}
+
// Rebuild a profile from a persisted blob (playerStore `profile` field). Tolerant
// of partial/legacy/missing data — every field is clamped and defaulted so a
// corrupt save can never crash a join; missing → a fresh starter profile.
@@ -84,8 +138,12 @@ export function restoreProfile(saved, playerId = '') {
if (Array.isArray(saved.hotbar)) fill(base.hotbar, saved.hotbar);
if (Number.isFinite(saved.activeSlot)) base.activeSlot = Math.max(-1, Math.min(HOTBAR_SIZE - 1, saved.activeSlot | 0));
if (Number.isFinite(saved.gold)) base.gold = Math.max(0, Math.min(0xffffffff, saved.gold | 0));
+ if (Number.isFinite(saved.bank)) base.bank = Math.max(0, Math.min(0xffffffff, saved.bank | 0));
if (Number.isFinite(saved.maxHp) && saved.maxHp > 0) base.maxHp = saved.maxHp | 0;
if (Number.isFinite(saved.hp)) base.hp = Math.max(0, Math.min(base.maxHp, saved.hp | 0));
+ if (Number.isFinite(saved.maxArmor) && saved.maxArmor > 0) base.maxArmor = saved.maxArmor | 0;
+ if (Number.isFinite(saved.armor)) base.armor = Math.max(0, Math.min(base.maxArmor, saved.armor | 0));
+ if (Number.isFinite(saved.heat)) base.heat = Math.max(0, Math.min(99, saved.heat));
if (saved.xp && typeof saved.xp === 'object') {
for (const skill of SKILLS) {
const v = Number.isFinite(saved.xp[skill]) ? Math.max(0, saved.xp[skill]) : 0;
@@ -93,6 +151,16 @@ export function restoreProfile(saved, playerId = '') {
base.levels[skill] = levelForXp(v);
}
}
+ // Cosmetics: keep only premium ids that still exist in the catalog as owned,
+ // then sanitize the equipped loadout against what this account may actually
+ // wear (drops anything unowned/renamed to the slot default).
+ if (saved.cosmetics && typeof saved.cosmetics === 'object') {
+ const owned = Array.isArray(saved.cosmetics.owned)
+ ? saved.cosmetics.owned.filter((id) => { const c = getCosmetic(id); return c && c.tier === 'premium'; })
+ : [];
+ base.cosmetics.owned = [...new Set(owned)];
+ base.cosmetics.equipped = sanitizeLoadout(saved.cosmetics.equipped, ownedCosmeticSet(base));
+ }
return base;
}
@@ -104,9 +172,17 @@ export function serializeProfile(profile) {
hotbar: slots(profile.hotbar),
activeSlot: profile.activeSlot,
gold: profile.gold,
+ bank: profile.bank,
hp: profile.hp,
maxHp: profile.maxHp,
+ armor: profile.armor,
+ maxArmor: profile.maxArmor,
+ heat: profile.heat,
xp: { ...profile.xp },
+ cosmetics: {
+ owned: [...(profile.cosmetics?.owned || [])],
+ equipped: { ...(profile.cosmetics?.equipped || DEFAULT_LOADOUT) },
+ },
};
}
@@ -153,6 +229,30 @@ export function addItem(profile, item, qty) {
return left;
}
+// Total quantity of `item` held across the backpack (hotbar tools aren't counted —
+// resources and food live in the pack). Used to gate cooking ("any raw fish?").
+export function countItem(profile, item) {
+ let n = 0;
+ for (const s of profile.inv) if (s.item === item) n += s.qty;
+ return n;
+}
+
+// Remove up to `qty` of `item` from the backpack, draining stacks until satisfied or
+// the item runs out. Returns the quantity actually removed (≤ qty). Used by cooking
+// (consume raw fish) and any future recipe/sink. Mutates the profile.
+export function removeItem(profile, item, qty) {
+ let need = qty;
+ for (const s of profile.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;
+}
+
// Resolve a client slot reference { zone:'inv'|'hotbar', i } to the live slot
// object, or null when out of range. Validated server-side so a
// crafted index can never read outside the arrays.
@@ -198,25 +298,94 @@ export function profileSnapshot(profile) {
}
return {
gold: profile.gold,
+ bank: profile.bank,
hp: profile.hp,
maxHp: profile.maxHp,
+ armor: profile.armor,
+ maxArmor: profile.maxArmor,
+ heat: profile.heat,
inv: profile.inv.map((s) => ({ item: s.item, qty: s.qty })),
hotbar: profile.hotbar.map((s) => ({ item: s.item, qty: s.qty })),
activeSlot: profile.activeSlot,
skills,
cap: LEVEL_CAP,
+ // Cosmetic loadout + unlocked set, so the owner's wardrobe shows what they
+ // own and have equipped without a second round-trip.
+ cosmetics: {
+ owned: [...(profile.cosmetics?.owned || [])],
+ equipped: { ...(profile.cosmetics?.equipped || DEFAULT_LOADOUT) },
+ },
};
}
-// Eat the edible in `slot`, healing scaled by cooking level. Returns the HP gained
-// (0 when nothing happened: not edible, already full, or empty). Mutates profile.
+// Use the item in `slot`: eat an edible to restore HP (scaled by cooking level), or
+// don a vest to refill the armor layer. Returns what happened so the room can toast
+// it. Mutates the profile; consumes one of the item on success.
export function consumeSlot(profile, slot) {
- if (!slot || !slot.item || !isEdible(slot.item)) return { ok: false, reason: 'inedible' };
+ if (!slot || !slot.item) return { ok: false, reason: 'inedible' };
+
+ // Body armor — refill the armor bar instead of HP.
+ const armorPts = armorValue(slot.item);
+ if (armorPts > 0) {
+ const cap = profile.maxArmor || MAX_ARMOR;
+ if (profile.armor >= cap) return { ok: false, reason: 'armorFull' };
+ const before = profile.armor;
+ profile.armor = Math.min(cap, profile.armor + armorPts);
+ const gained = profile.armor - before;
+ slot.qty -= 1;
+ if (slot.qty <= 0) { slot.item = ''; slot.qty = 0; }
+ return { ok: true, kind: 'armor', gained };
+ }
+
+ if (!isEdible(slot.item)) return { ok: false, reason: 'inedible' };
if (profile.hp >= profile.maxHp) return { ok: false, reason: 'full' };
const before = profile.hp;
profile.hp = Math.min(profile.maxHp, profile.hp + scaledHeal(slot.item, profile.levels.cooking || 1));
const gained = profile.hp - before;
slot.qty -= 1;
if (slot.qty <= 0) { slot.item = ''; slot.qty = 0; }
- return { ok: true, gained };
+ return { ok: true, kind: 'heal', gained };
+}
+
+// --- Death, banking & vitals (W07) ----------------------------------------
+
+// Strip the carried valuables a tombstone inherits when this player dies: all
+// carried cash (`gold`) plus everything in the BACKPACK. Equipped hotbar tools and
+// weapons are kept so a respawn isn't toothless, and BANKED cash is untouched —
+// that's the whole risk/reward point of banking. Mutates the profile (zeroing the
+// dropped slice) and returns { gold, items:[{item,qty}] } for the tombstone.
+export function dropCarried(profile) {
+ const gold = profile.gold | 0;
+ profile.gold = 0;
+ const items = [];
+ for (const s of profile.inv) {
+ if (s.item && s.qty > 0) items.push({ item: s.item, qty: s.qty });
+ s.item = ''; s.qty = 0;
+ }
+ return { gold, items };
+}
+
+// Restore a player to fighting shape after respawn: full HP and a cleared armor bar
+// (you lose your vest on death — re-armor from the pack or a vendor).
+export function reviveProfile(profile) {
+ profile.hp = profile.maxHp;
+ profile.armor = 0;
+}
+
+// Move cash between the carried purse and the protected bank. `amount > 0` deposits
+// (purse → bank); `amount < 0` withdraws. Clamps to what's actually available so it
+// can never mint or strand cash. Returns the signed amount actually moved.
+export function bankTransfer(profile, amount) {
+ const amt = amount | 0;
+ if (amt > 0) {
+ const moved = Math.min(amt, profile.gold | 0);
+ profile.gold -= moved; profile.bank += moved;
+ return moved;
+ }
+ if (amt < 0) {
+ const moved = Math.min(-amt, profile.bank | 0);
+ profile.bank -= moved; profile.gold += moved;
+ return -moved;
+ }
+ return 0;
}
diff --git a/multiplayer/src/items.js b/multiplayer/src/items.js
index 40be49b56..8d3ec752b 100644
--- a/multiplayer/src/items.js
+++ b/multiplayer/src/items.js
@@ -27,7 +27,24 @@ export const ITEMS = {
pickaxe: { tool: true, stackable: false, icon: '⛏️', label: 'Pickaxe' },
rod: { tool: true, stackable: false, icon: '🎣', label: 'Fishing rod' },
hammer: { tool: true, stackable: false, icon: '🔨', label: 'Hammer' },
- sword: { tool: true, stackable: false, icon: '⚔️', label: 'Sword' },
+
+ // Weapons — non-stackable tools that occupy the active slot. Their combat
+ // tuning (damage, range, rate, ammo) lives in WEAPONS below; this entry is just
+ // the inventory presence so they equip like any other tool. (W07)
+ sword: { tool: true, weapon: true, stackable: false, icon: '⚔️', label: 'Sword' },
+ bat: { tool: true, weapon: true, stackable: false, icon: '🏏', label: 'Bat' },
+ pistol: { tool: true, weapon: true, stackable: false, icon: '🔫', label: 'Pistol' },
+ bow: { tool: true, weapon: true, stackable: false, icon: '🏹', label: 'Bow' },
+
+ // Ammunition — stackable consumables a ranged weapon burns one of per shot
+ // (W04 consumable; spent server-side on a validated fire). (W07)
+ ammo: { stackable: true, ammo: true, icon: '🔸', label: 'Ammo' },
+ arrow: { stackable: true, ammo: true, icon: '🔹', label: 'Arrows' },
+
+ // Body armor — a stackable consumable that, when worn, refills the armor layer
+ // that absorbs damage before HP. Worn via the `consume` intent like a potion,
+ // but tops up armor instead of health. (W07)
+ vest: { stackable: true, armorValue: 50, icon: '🦺', label: 'Body armor' },
// Gathered resources — stackable.
wood: { stackable: true, icon: '🪵', label: 'Wood' },
@@ -102,6 +119,73 @@ export function itemLabel(item) {
return ITEMS[item]?.label || item;
}
+export function isEquippableWeapon(item) {
+ return !!ITEMS[item]?.weapon;
+}
+
+export function isAmmo(item) {
+ return !!ITEMS[item]?.ammo;
+}
+
+// Armor points a wearable item restores when worn (0 for non-armor items).
+export function armorValue(item) {
+ return ITEMS[item]?.armorValue || 0;
+}
+
+// ---------------------------------------------------------------------------
+// Combat — weapons (W07)
+// ---------------------------------------------------------------------------
+//
+// The authoritative weapon tuning table. The WalkRoom reads THIS to validate an
+// attack intent (right tool equipped? target in range/arc? off cooldown? ammo?)
+// and to roll damage — so balance lives in one data-driven place, never inline in
+// the handler. Each entry:
+// kind — 'melee' (range + frontal arc) or 'ranged' (hitscan line + ammo).
+// dmg — base damage per hit, before the small combat-level scaling and
+// the ±15% variance the room rolls.
+// range — max metres from attacker to a valid target.
+// arc — melee only: full frontal cone (radians) a target must sit within.
+// aimTol — ranged only: angular tolerance (radians) between aim (yaw) and
+// the bearing to a target — a light aim-assist on the hitscan.
+// cooldownMs — server-enforced floor between swings/shots with this weapon.
+// ammo — ranged only: the item id consumed one-per-shot.
+export const WEAPONS = {
+ sword: { kind: 'melee', dmg: 18, range: 2.7, arc: 1.5, cooldownMs: 620 },
+ bat: { kind: 'melee', dmg: 12, range: 2.5, arc: 1.7, cooldownMs: 460 },
+ pistol: { kind: 'ranged', dmg: 20, range: 34, aimTol: 0.22, cooldownMs: 430, ammo: 'ammo' },
+ bow: { kind: 'ranged', dmg: 28, range: 42, aimTol: 0.16, cooldownMs: 880, ammo: 'arrow' },
+};
+
+export function weaponDef(item) {
+ return WEAPONS[item] || null;
+}
+
+// ---------------------------------------------------------------------------
+// Combat — mobs (W07/W08)
+// ---------------------------------------------------------------------------
+//
+// PvE enemy tuning. Mobs spawn in danger zones, chase the nearest player, and
+// fight through the SAME authoritative damage path players do. `kind` keys both
+// this table and the LOOT_TABLES below, so a kill's rewards and its stats stay in
+// lockstep. Each entry:
+// hp/dmg — pool it spawns with / damage per landed swing (0 = harmless).
+// speed — chase speed in m/s.
+// aggro — metres at which it notices and pursues a player.
+// atkRange — metres at which it can land a hit; atkCd — ms between its swings.
+// xp/gold — combat XP and cash awarded to the killer.
+// scale/color — render hints for the client mesh.
+// hostile — false for non-aggressive targets that never chase.
+export const MOB_STATS = {
+ dummy: { hp: 60, dmg: 0, speed: 0, aggro: 0, atkRange: 0, atkCd: 0, xp: 8, gold: 0, scale: 1.0, color: 0x9aa3b2, hostile: false },
+ goblin: { hp: 42, dmg: 6, speed: 2.7, aggro: 15, atkRange: 1.9, atkCd: 1150, xp: 26, gold: 4, scale: 0.9, color: 0x5f8a3a, hostile: true },
+ ogre: { hp: 95, dmg: 14, speed: 2.0, aggro: 17, atkRange: 2.5, atkCd: 1650, xp: 62, gold: 12, scale: 1.35, color: 0x8a6a3a, hostile: true },
+ troll: { hp: 165, dmg: 22, speed: 1.8, aggro: 19, atkRange: 2.9, atkCd: 2000, xp: 128, gold: 28, scale: 1.7, color: 0x4a6a6a, hostile: true },
+};
+
+export function mobStats(kind) {
+ return MOB_STATS[kind] || null;
+}
+
// ---------------------------------------------------------------------------
// Mounts
// ---------------------------------------------------------------------------
@@ -169,6 +253,38 @@ export function rollLoot(kind, rng = Math.random) {
return out;
}
+// ---------------------------------------------------------------------------
+// Gathering (woodcutting & mining) — W06
+// ---------------------------------------------------------------------------
+
+// Chance a single chop/strike yields a resource: 45% at level 1 on a difficulty-1
+// node, rising +0.6%/level and divided by the node's difficulty (hardwood/dense rock
+// gives up its goods less often). Clamped 5%–97%. Pure, mirroring fishCatchChance.
+export function gatherChance(level, difficulty = 1) {
+ const lvl = Math.max(1, level | 0);
+ const d = difficulty > 0 ? difficulty : 1;
+ const c = (0.45 + 0.006 * (lvl - 1)) / d;
+ return Math.max(0.05, Math.min(0.97, c));
+}
+
+// Chance a successful gather yields two resources instead of one. Zero at level 1,
+// growing with level and easing on tougher nodes, clamped at 40%. Mirrors
+// fishDoubleChance.
+export function gatherDoubleChance(level, difficulty = 1) {
+ const lvl = Math.max(1, level | 0);
+ const d = difficulty > 0 ? difficulty : 1;
+ return Math.max(0, Math.min(0.4, (0.018 * (lvl - 1)) / d));
+}
+
+// Chance a successful mine ALSO surfaces a lump of coal alongside the stone, scaled
+// by the seam's coal weight and the miner's level. Capped at 55% on the richest seam.
+export function coalBonusChance(level, coalWeight = 1) {
+ const lvl = Math.max(1, level | 0);
+ const w = coalWeight > 0 ? coalWeight : 1;
+ const c = (0.10 + 0.004 * (lvl - 1)) * w;
+ return Math.max(0, Math.min(0.55, c));
+}
+
// ---------------------------------------------------------------------------
// Client view
// ---------------------------------------------------------------------------
@@ -221,10 +337,12 @@ export function clientItemRegistry() {
out[id] = {
label: it.label || id,
icon: it.icon || '📦',
- kind: it.mount ? 'mount' : it.tool ? 'tool' : it.edible ? 'food' : 'resource',
+ kind: it.mount ? 'mount' : it.weapon ? 'weapon' : it.tool ? 'tool' : it.armorValue ? 'armor' : it.ammo ? 'ammo' : it.edible ? 'food' : 'resource',
stackable: !!it.stackable,
};
if (it.edible) out[id].heal = it.heal || 0;
+ if (it.armorValue) out[id].armorValue = it.armorValue;
+ if (it.weapon && WEAPONS[id]) out[id].weapon = { ...WEAPONS[id] };
if (it.mount) out[id].mount = { ...it.mount };
}
return out;
diff --git a/multiplayer/src/quest-zones.js b/multiplayer/src/quest-zones.js
new file mode 100644
index 000000000..069648e28
--- /dev/null
+++ b/multiplayer/src/quest-zones.js
@@ -0,0 +1,65 @@
+// Quest zones (W05) — the named world locations missions reference for goto /
+// interact objectives, waypoints, and the heist district.
+//
+// This is the ONE source of truth for those positions, imported by BOTH the server
+// (WalkRoom — validates "are you actually at the dock / vault?") and the client
+// (quest-systems — renders the markers and gates the interact prompt), so the
+// playable world and the authoritative world can never drift. It sits alongside
+// world-features.js (fishing/gather positions) rather than inside it so the quest
+// layer stays self-contained and conflict-free. Coordinates are world metres in the
+// XZ plane; the ground sits at y = 0.
+//
+// `kind` tags how a zone is used:
+// 'goto' — a survey/patrol point you reach (drives an enter-zone objective)
+// 'interact' — a quest object you act at (pickup/dropoff/terminal/crack)
+// `r` is the trigger radius. Two survey points reuse the pond centres (see
+// world-features.FISHING_SPOTS) so a survey also reveals where the fishing is. The
+// vault district sits out east, clear of the spawn ring, the totem (0,0,-12) and the
+// trade screen (0,0,-30), all within the world disc (radius ≈ 60).
+
+export const QUEST_ZONES = [
+ // Survey lookouts (Grounds Survey daily).
+ { id: 'pond-east', kind: 'goto', x: 30, z: 8, r: 5, label: 'East Pond' },
+ { id: 'pond-west', kind: 'goto', x: -28, z: 16, r: 5, label: 'West Pond' },
+ { id: 'lookout-north', kind: 'goto', x: 0, z: 44, r: 4.5, label: 'North Lookout' },
+
+ // Courier run: pick up at the dock, deliver to the market.
+ { id: 'dock-east', kind: 'interact', action: 'pickup', x: 34, z: 0, r: 3.0, label: 'East Dock', glyph: '📦' },
+ { id: 'market-stall', kind: 'interact', action: 'dropoff', x: -16, z: -22, r: 3.0, label: 'Market Stall', glyph: '🏷️' },
+
+ // Vault heist district: two alarm terminals flanking the vault door.
+ { id: 'vault-terminal-a', kind: 'interact', action: 'terminal', x: 50, z: 16, r: 2.8, label: 'Alarm Terminal A', glyph: '🖥️' },
+ { id: 'vault-terminal-b', kind: 'interact', action: 'terminal', x: 50, z: -16, r: 2.8, label: 'Alarm Terminal B', glyph: '🖥️' },
+ { id: 'vault-door', kind: 'interact', action: 'crack', x: 54, z: 0, r: 3.4, label: 'The Vault', glyph: '🏦' },
+];
+
+const QUEST_ZONE_BY_ID = new Map(QUEST_ZONES.map((z) => [z.id, z]));
+
+// Reach beyond a zone's radius that still counts as "at" it — a little margin so the
+// prompt feels reliable as you walk up (mirrors FISH_REACH for activities).
+export const ZONE_REACH = 1.6;
+
+export function questZone(id) {
+ return QUEST_ZONE_BY_ID.get(id) || null;
+}
+
+// Which quest zone (if any) the point (x,z) is inside, including the reach margin.
+// Nearest centre wins on overlap. The single check the server trusts for both
+// zone-entry (goto) and the interact gate, mirrored by the client for waypoints and
+// the interact prompt — same function, no drift.
+export function zoneAt(x, z) {
+ let best = null;
+ let bestD = Infinity;
+ for (const zone of QUEST_ZONES) {
+ const d = Math.hypot(x - zone.x, z - zone.z);
+ if (d <= zone.r + ZONE_REACH && d < bestD) { best = zone; bestD = d; }
+ }
+ return best;
+}
+
+// Server-side gate for an interact at the player's position: the 'interact' zone
+// they're standing in, or null (a goto lookout isn't something you "act" at).
+export function interactZoneInRange(x, z) {
+ const zone = zoneAt(x, z);
+ return zone && zone.kind === 'interact' ? zone : null;
+}
diff --git a/multiplayer/src/quests.js b/multiplayer/src/quests.js
new file mode 100644
index 000000000..59a5a164b
--- /dev/null
+++ b/multiplayer/src/quests.js
@@ -0,0 +1,536 @@
+// Quest engine — jobs, missions & heists for the /play coin worlds (W05).
+//
+// A mission is DATA, not code: a spec of ordered objectives + a reward. The same
+// engine drives one-tap daily jobs, repeatable courier runs, and multi-stage
+// co-op heists — authoring new content is adding an entry to MISSIONS, never
+// writing a new handler. This mirrors how items.js is the one source of truth for
+// items and economy.js for the pack/purse: rooms read THIS instead of branching on
+// mission ids inline.
+//
+// Authority is server-side. The WalkRoom owns a player's quest state OFF the synced
+// WalkState schema (it's private, like the pack/purse), feeds real gameplay events
+// (a fish caught, a zone entered, a terminal activated) into applyEvent(), and grants
+// rewards only when the engine — not the client — says an objective is done. A client
+// claiming "I finished" advances nothing; only the event it actually produced does.
+//
+// Objective vocabulary (every mission is expressible in these, all backed by a REAL
+// server handler that emits the matching event — no objective is un-completable):
+// collect — gather N of an item (emitted by the fishing handler)
+// goto — enter a named world zone (emitted by movement zone-entry)
+// interact — act at a quest object/zone (emitted by the questInteract handler)
+// Heists compose these as a SHARED instance (see WalkRoom): the same objective shape,
+// advanced by any crew member, finishing only when the party is assembled at the finale.
+
+import { SKILLS } from './economy.js';
+
+// ---------------------------------------------------------------------------
+// Mission registry — the single source of truth for what missions exist.
+// ---------------------------------------------------------------------------
+//
+// Fields:
+// id stable key (persisted; never reuse for a different mission).
+// title human name shown on the board + tracker.
+// giver in-world quest-giver label (W08 NPCs hook this; today it's flavour).
+// summary one-line pitch on the jobs board.
+// kind 'job' (solo) | 'heist' (co-op, server-managed shared instance).
+// repeat 'daily' (once per UTC day, rotated) | 'repeatable' (any time) |
+// 'once' (a one-shot the account completes a single time, ever).
+// party minimum crew size to FINISH (1 for solo; ≥2 for a heist finale).
+// objectives ordered list — complete one to advance to the next.
+// reward { gold, xp?: { skill, amount } } granted server-side on completion.
+// Heist gold is the TOTAL pot, split evenly among the crew at payout.
+// prereq mission ids that must be completed before this one is offered.
+//
+// In-world spendable currency is "gold" (a game resource, per the program rules) —
+// never an on-chain token. The only coin that ever exists is $THREE, and missions
+// never mint or reference it.
+export const MISSIONS = {
+ // — Daily collect job (the Kintara retention mechanic): cheap, once/day, fishing. —
+ 'daily-anglers-haul': {
+ id: 'daily-anglers-haul',
+ title: "Angler's Daily Haul",
+ giver: 'Dockmaster Reyes',
+ summary: 'Land 5 fish from the community ponds before the day is out.',
+ kind: 'job',
+ repeat: 'daily',
+ party: 1,
+ objectives: [
+ { type: 'collect', item: 'fish', count: 5, label: 'Catch 5 fish at the ponds' },
+ ],
+ reward: { gold: 140, xp: { skill: 'fishing', amount: 120 } },
+ },
+
+ // — Daily survey job: a movement loop that teaches the map. One tap to accept,
+ // finished by simply touring the landmarks. —
+ 'daily-grounds-survey': {
+ id: 'daily-grounds-survey',
+ title: 'Grounds Survey',
+ giver: 'Warden Okoro',
+ summary: 'Patrol the three lookouts and report the grounds secure.',
+ kind: 'job',
+ repeat: 'daily',
+ party: 1,
+ objectives: [
+ { type: 'goto', zone: 'pond-east', label: 'Reach the East Pond' },
+ { type: 'goto', zone: 'lookout-north', label: 'Reach the North Lookout' },
+ { type: 'goto', zone: 'pond-west', label: 'Reach the West Pond' },
+ ],
+ reward: { gold: 90 },
+ },
+
+ // — Repeatable collect: a bigger fishing contract for grinders. —
+ 'stock-the-kitchen': {
+ id: 'stock-the-kitchen',
+ title: 'Stock the Kitchen',
+ giver: 'Cook Mara',
+ summary: 'The roast pit is running low — bring in 12 fresh fish.',
+ kind: 'job',
+ repeat: 'repeatable',
+ party: 1,
+ objectives: [
+ { type: 'collect', item: 'fish', count: 12, label: 'Catch 12 fish' },
+ ],
+ reward: { gold: 260, xp: { skill: 'fishing', amount: 220 } },
+ },
+
+ // — Repeatable courier run: pick up at the dock, deliver to the market. A
+ // two-stage go-there / act, then go-there / act loop — the spine of every
+ // GTA-style delivery mission. (Vehicles, W02, will make the legs faster; on
+ // foot it already plays.) —
+ 'harbor-courier': {
+ id: 'harbor-courier',
+ title: 'Harbor Courier',
+ giver: 'Foreman Dell',
+ summary: 'Grab the sealed crate at the East Dock and run it to the Market.',
+ kind: 'job',
+ repeat: 'repeatable',
+ party: 1,
+ objectives: [
+ { type: 'interact', zone: 'dock-east', action: 'pickup', label: 'Collect the crate at the East Dock' },
+ { type: 'interact', zone: 'market-stall', action: 'dropoff', label: 'Deliver the crate to the Market' },
+ ],
+ reward: { gold: 180 },
+ },
+
+ // — One-shot intro mission: first taste of the loop, unlocks nothing but pays a
+ // welcome purse and points the player at the board. —
+ 'welcome-to-work': {
+ id: 'welcome-to-work',
+ title: 'First Day on the Job',
+ giver: 'Foreman Dell',
+ summary: 'Catch your first fish and find your footing in the world.',
+ kind: 'job',
+ repeat: 'once',
+ party: 1,
+ objectives: [
+ { type: 'collect', item: 'fish', count: 1, label: 'Catch your first fish' },
+ ],
+ reward: { gold: 60, xp: { skill: 'fishing', amount: 40 } },
+ },
+
+ // — Co-op heist: the flagship multi-stage crew job. Stage 1 disables both alarm
+ // terminals (either crew member can tap either terminal — SHARED progress);
+ // the finale cracks the vault and only completes with the full crew assembled
+ // at the door. The pot is split evenly at payout. Repeatable so a crew can run
+ // it again. —
+ 'vault-job': {
+ id: 'vault-job',
+ title: 'The Vault Job',
+ giver: 'The Fixer',
+ summary: 'Two-crew heist: kill the alarms, then crack the vault together for a big split.',
+ kind: 'heist',
+ repeat: 'repeatable',
+ party: 2,
+ objectives: [
+ {
+ type: 'interact', action: 'terminal', count: 2, shared: true,
+ zones: ['vault-terminal-a', 'vault-terminal-b'],
+ label: 'Disable both alarm terminals',
+ },
+ {
+ type: 'interact', action: 'crack', zone: 'vault-door', shared: true, finale: true,
+ label: 'Crack the vault — full crew at the door',
+ },
+ ],
+ // 900 gold total, split among the crew (e.g. 450 each for a duo).
+ reward: { gold: 900, xp: { skill: 'combat', amount: 200 } },
+ },
+};
+
+// The pool of mission ids eligible for the rotating daily board. A deterministic
+// subset is offered each UTC day so the board feels fresh without authoring a
+// calendar. Only 'daily' missions belong here.
+export const DAILY_POOL = Object.values(MISSIONS)
+ .filter((m) => m.repeat === 'daily')
+ .map((m) => m.id);
+
+// How many daily jobs to surface per day. Capped to the pool size.
+export const DAILY_COUNT = 2;
+
+export function missionDef(id) {
+ return MISSIONS[id] || null;
+}
+
+export function isHeist(id) {
+ return MISSIONS[id]?.kind === 'heist';
+}
+
+// The default count for an objective (most are a single action).
+function objCount(obj) {
+ return Math.max(1, obj?.count | 0 || 1);
+}
+
+// ---------------------------------------------------------------------------
+// Daily rotation — deterministic per UTC day, so every player and every room
+// instance offers the same daily set, and it changes exactly at the UTC midnight
+// boundary with no scheduler.
+// ---------------------------------------------------------------------------
+
+export function utcDayKey(ts = Date.now()) {
+ const d = new Date(ts);
+ const y = d.getUTCFullYear();
+ const m = String(d.getUTCMonth() + 1).padStart(2, '0');
+ const day = String(d.getUTCDate()).padStart(2, '0');
+ return `${y}-${m}-${day}`;
+}
+
+function hashStr(s) {
+ let h = 2166136261 >>> 0;
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ return h >>> 0;
+}
+
+// The daily job ids for a given UTC day — a stable shuffle of DAILY_POOL seeded by
+// the day, then the first DAILY_COUNT. Pure: same day in → same ids out, anywhere.
+export function dailyJobIds(dayKey, count = DAILY_COUNT) {
+ const pool = [...DAILY_POOL];
+ if (pool.length <= count) return pool;
+ let seed = hashStr(String(dayKey)) || 1;
+ const rng = () => {
+ // LCG (Numerical Recipes constants) — deterministic, no Math.random.
+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
+ return seed / 0x100000000;
+ };
+ for (let i = pool.length - 1; i > 0; i--) {
+ const j = Math.floor(rng() * (i + 1));
+ [pool[i], pool[j]] = [pool[j], pool[i]];
+ }
+ return pool.slice(0, Math.min(count, pool.length));
+}
+
+// ---------------------------------------------------------------------------
+// Per-player quest state — lives on the player's profile (off-schema), persisted
+// through the account-keyed player store alongside the pack/purse.
+// active: { [missionId]: run } in-progress missions
+// completed: { [missionId]: { count, ts } } lifetime completions (for one-shots
+// + board state + UI badges)
+// daily: { day, done: [missionId] } which dailies were finished today
+// A `run` is { id, stage, counts: { [stageIndex]: n }, startedAt, day }.
+// ---------------------------------------------------------------------------
+
+export function newQuestState(dayKey = utcDayKey()) {
+ return {
+ active: {},
+ completed: {},
+ daily: { day: dayKey, done: [] },
+ };
+}
+
+// Rebuild from a persisted blob, tolerant of partial/legacy/missing data — a
+// corrupt save can never crash a join; it degrades to a fresh quest log. Stale
+// daily state is rolled over to the current day on load (yesterday's completions
+// don't block today's offers).
+export function restoreQuestState(saved, dayKey = utcDayKey()) {
+ const base = newQuestState(dayKey);
+ if (!saved || typeof saved !== 'object') return base;
+
+ if (saved.active && typeof saved.active === 'object') {
+ for (const [id, run] of Object.entries(saved.active)) {
+ const mission = MISSIONS[id];
+ if (!mission || !run || typeof run !== 'object') continue;
+ // Heists are ephemeral, room-scoped shared instances — never restored as a
+ // solo active run (you re-join the crew live), so drop any persisted heist.
+ if (mission.kind === 'heist') continue;
+ const stage = Math.max(0, Math.min(mission.objectives.length - 1, run.stage | 0));
+ const counts = {};
+ if (run.counts && typeof run.counts === 'object') {
+ for (const [k, v] of Object.entries(run.counts)) {
+ const idx = k | 0;
+ if (idx >= 0 && idx < mission.objectives.length && Number.isFinite(v)) {
+ counts[idx] = Math.max(0, v | 0);
+ }
+ }
+ }
+ base.active[id] = { id, stage, counts, startedAt: Number(run.startedAt) || 0, day: typeof run.day === 'string' ? run.day : dayKey };
+ }
+ }
+
+ if (saved.completed && typeof saved.completed === 'object') {
+ for (const [id, rec] of Object.entries(saved.completed)) {
+ if (!MISSIONS[id]) continue;
+ const count = Number.isFinite(rec?.count) ? Math.max(0, rec.count | 0) : 1;
+ base.completed[id] = { count, ts: Number(rec?.ts) || 0 };
+ }
+ }
+
+ // Daily completions only count for the current UTC day; a new day clears them.
+ if (saved.daily && saved.daily.day === dayKey && Array.isArray(saved.daily.done)) {
+ base.daily = { day: dayKey, done: saved.daily.done.filter((id) => !!MISSIONS[id]) };
+ }
+
+ return base;
+}
+
+export function serializeQuestState(state) {
+ if (!state) return newQuestState();
+ const active = {};
+ for (const [id, run] of Object.entries(state.active || {})) {
+ // Don't persist heist runs (ephemeral shared instances).
+ if (MISSIONS[id]?.kind === 'heist') continue;
+ active[id] = { id: run.id, stage: run.stage, counts: { ...run.counts }, startedAt: run.startedAt, day: run.day };
+ }
+ return {
+ active,
+ completed: { ...(state.completed || {}) },
+ daily: { day: state.daily?.day || utcDayKey(), done: [...(state.daily?.done || [])] },
+ };
+}
+
+// Roll the daily log over to `dayKey` if it's stale. Call on each board read so a
+// player who stayed online across UTC midnight sees the new day's offers and may
+// re-run today's dailies. Returns true if it rolled (the caller may re-offer).
+export function rolloverDaily(state, dayKey = utcDayKey()) {
+ if (!state.daily || state.daily.day !== dayKey) {
+ state.daily = { day: dayKey, done: [] };
+ return true;
+ }
+ return false;
+}
+
+// ---------------------------------------------------------------------------
+// Offers — which missions the board may show this player right now.
+// ---------------------------------------------------------------------------
+
+function prereqMet(state, mission) {
+ if (!Array.isArray(mission.prereq) || !mission.prereq.length) return true;
+ return mission.prereq.every((pid) => (state.completed[pid]?.count | 0) > 0);
+}
+
+// Is `mission` acceptable by this player right now? (Not already active, prereqs
+// met, and the repeat rule satisfied: a one-shot not yet done, a daily not yet
+// done today, a repeatable always.)
+export function canAccept(state, mission, dayKey = utcDayKey()) {
+ if (!mission) return false;
+ if (state.active[mission.id]) return false;
+ if (!prereqMet(state, mission)) return false;
+ if (mission.repeat === 'once') return !(state.completed[mission.id]?.count > 0);
+ if (mission.repeat === 'daily') return !state.daily.done.includes(mission.id);
+ return true; // repeatable
+}
+
+// The board: the missions this player can accept now, plus any in-progress runs,
+// shaped for the client. Daily offers are the day's rotated subset; the rest are
+// the always-available repeatable/one-shot jobs. Heists are surfaced too (the
+// client shows a "needs a crew" hint).
+export function boardOffers(state, dayKey = utcDayKey()) {
+ rolloverDaily(state, dayKey);
+ const dailyIds = new Set(dailyJobIds(dayKey));
+ const offers = [];
+ for (const mission of Object.values(MISSIONS)) {
+ if (mission.repeat === 'daily' && !dailyIds.has(mission.id)) continue; // not in today's rotation
+ if (state.active[mission.id]) continue; // already accepted
+ if (!canAccept(state, mission, dayKey)) continue;
+ offers.push(offerView(mission, state));
+ }
+ return offers;
+}
+
+function offerView(mission, state) {
+ return {
+ id: mission.id,
+ title: mission.title,
+ giver: mission.giver,
+ summary: mission.summary,
+ kind: mission.kind,
+ repeat: mission.repeat,
+ party: mission.party || 1,
+ reward: { ...mission.reward },
+ objectives: mission.objectives.map((o) => ({ type: o.type, label: o.label, count: objCount(o) })),
+ completedCount: state.completed[mission.id]?.count | 0,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Accept / abandon
+// ---------------------------------------------------------------------------
+
+export function acceptMission(state, id, dayKey = utcDayKey()) {
+ const mission = MISSIONS[id];
+ if (!mission) return { ok: false, reason: 'unknown' };
+ rolloverDaily(state, dayKey);
+ if (state.active[id]) return { ok: false, reason: 'active' };
+ if (!canAccept(state, mission, dayKey)) {
+ const reason = mission.repeat === 'daily' ? 'daily-done'
+ : mission.repeat === 'once' ? 'done'
+ : 'locked';
+ return { ok: false, reason };
+ }
+ const run = { id, stage: 0, counts: {}, startedAt: Date.now(), day: dayKey };
+ state.active[id] = run;
+ return { ok: true, run, mission };
+}
+
+export function abandonMission(state, id) {
+ if (!state.active[id]) return { ok: false };
+ delete state.active[id];
+ return { ok: true };
+}
+
+// ---------------------------------------------------------------------------
+// Progress — feed a real gameplay event into a run.
+// ---------------------------------------------------------------------------
+
+// Does objective `obj` match gameplay `event`?
+// collect: { type:'collect', item, qty }
+// goto: { type:'enter-zone', zone }
+// interact: { type:'interact', zone, action }
+// `event.qty` (collect) defaults to 1.
+export function objectiveMatches(obj, event) {
+ if (!obj || !event) return false;
+ if (obj.type === 'collect') {
+ return event.type === 'collect' && event.item === obj.item;
+ }
+ if (obj.type === 'goto') {
+ return event.type === 'enter-zone' && event.zone === obj.zone;
+ }
+ if (obj.type === 'interact') {
+ if (event.type !== 'interact') return false;
+ if (obj.action && event.action !== obj.action) return false;
+ // A multi-zone objective (e.g. two terminals) matches any of its zones.
+ if (Array.isArray(obj.zones)) return obj.zones.includes(event.zone);
+ return !obj.zone || event.zone === obj.zone;
+ }
+ return false;
+}
+
+// Apply an event to a run (or a shared heist instance — same shape). Mutates the
+// run's stage/counts. Returns:
+// { matched, objComplete, missionComplete, stage }
+// `progressed` runs carry an optional `seen` Set on shared multi-zone objectives so
+// the same terminal can't be tapped twice for two ticks.
+export function applyEvent(run, mission, event) {
+ const result = { matched: false, objComplete: false, missionComplete: false, stage: run.stage };
+ if (!mission) return result;
+ const obj = mission.objectives[run.stage];
+ if (!obj) return result;
+ if (!objectiveMatches(obj, event)) return result;
+
+ // Multi-zone objectives count distinct zones, not repeat taps of one zone.
+ if (Array.isArray(obj.zones)) {
+ if (!run.seen) run.seen = {};
+ const seenKey = String(run.stage);
+ const seen = (run.seen[seenKey] = run.seen[seenKey] || []);
+ if (seen.includes(event.zone)) return result; // already counted this terminal
+ seen.push(event.zone);
+ }
+
+ result.matched = true;
+ const need = objCount(obj);
+ const inc = obj.type === 'collect' ? Math.max(1, event.qty | 0 || 1) : 1;
+ run.counts[run.stage] = Math.min(need, (run.counts[run.stage] | 0) + inc);
+
+ if (run.counts[run.stage] >= need) {
+ result.objComplete = true;
+ run.stage += 1;
+ if (run.stage >= mission.objectives.length) {
+ result.missionComplete = true;
+ }
+ }
+ result.stage = run.stage;
+ return result;
+}
+
+// Mark a mission completed in the player's lifetime + daily log. Returns the new
+// completion count.
+export function recordCompletion(state, mission, dayKey = utcDayKey()) {
+ const prev = state.completed[mission.id]?.count | 0;
+ state.completed[mission.id] = { count: prev + 1, ts: Date.now() };
+ delete state.active[mission.id];
+ if (mission.repeat === 'daily') {
+ rolloverDaily(state, dayKey);
+ if (!state.daily.done.includes(mission.id)) state.daily.done.push(mission.id);
+ }
+ return prev + 1;
+}
+
+// ---------------------------------------------------------------------------
+// Reward shaping + validation (used by the room when granting).
+// ---------------------------------------------------------------------------
+
+// The reward a solo mission grants. Heists split the pot, computed by the room.
+export function missionReward(mission) {
+ const r = mission?.reward || {};
+ const out = { gold: Math.max(0, r.gold | 0) };
+ if (r.xp && SKILLS.includes(r.xp.skill) && r.xp.amount > 0) {
+ out.xp = { skill: r.xp.skill, amount: r.xp.amount | 0 };
+ }
+ return out;
+}
+
+// Split a heist pot across `n` crew members — even split, remainder to the first
+// member so no gold is lost to rounding. Returns an array of per-member gold.
+export function splitPot(totalGold, n) {
+ const count = Math.max(1, n | 0);
+ const base = Math.floor(totalGold / count);
+ const rem = totalGold - base * count;
+ return Array.from({ length: count }, (_, i) => base + (i < rem ? 1 : 0));
+}
+
+// ---------------------------------------------------------------------------
+// Client snapshots
+// ---------------------------------------------------------------------------
+
+// One active run shaped for the client tracker: the mission's objective list with
+// per-objective progress and which one is current.
+export function runView(run, mission) {
+ const objectives = mission.objectives.map((o, i) => ({
+ type: o.type,
+ label: o.label,
+ count: objCount(o),
+ progress: Math.min(objCount(o), run.counts[i] | 0),
+ done: i < run.stage,
+ current: i === run.stage,
+ zone: o.zone || (Array.isArray(o.zones) ? o.zones[0] : null),
+ zones: Array.isArray(o.zones) ? [...o.zones] : null,
+ action: o.action || null,
+ }));
+ return {
+ id: mission.id,
+ title: mission.title,
+ giver: mission.giver,
+ kind: mission.kind,
+ party: mission.party || 1,
+ reward: { ...mission.reward },
+ stage: run.stage,
+ objectives,
+ };
+}
+
+// The full quest payload sent to a client (board offers + active runs). Heist runs
+// are layered on by the room (shared-instance progress), so this covers solo runs;
+// the room merges any live heist run before sending.
+export function questSnapshot(state, dayKey = utcDayKey()) {
+ const active = [];
+ for (const [id, run] of Object.entries(state.active)) {
+ const mission = MISSIONS[id];
+ if (mission) active.push(runView(run, mission));
+ }
+ return {
+ offers: boardOffers(state, dayKey),
+ active,
+ day: dayKey,
+ };
+}
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index 657f35160..21f51b32a 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -8,7 +8,12 @@
import { Room } from '@colyseus/core';
-import { Player, Block, WalkState } from '../schemas.js';
+import { Player, Block, Vehicle, WalkState } from '../schemas.js';
+import {
+ VEHICLE_SPAWNS, vehicleSpec, isVehicleType,
+ VEHICLE_WORLD_RADIUS_M, VEHICLE_ENTER_RANGE_M,
+ vehicleMaxStepM, vehicleMaxSpeedMps,
+} from '../vehicles.js';
import { cleanAvatarUrl } from '../avatar-url.js';
import { blockStore } from '../block-store.js';
import { verifyHolderPass } from '../holder-pass.js';
@@ -18,10 +23,23 @@ import { verifyPlayPass } from '../play-pass.js';
import {
restoreProfile, serializeProfile, profileSnapshot,
addItem, hasRoomFor, resolveSlot, grantXp, consumeSlot,
+ countItem, removeItem,
HOTBAR_SIZE,
} from '../economy.js';
-import { itemLabel, fishCatchChance, fishDoubleChance } from '../items.js';
-import { fishingSpotInRange } from '../world-features.js';
+import {
+ itemLabel, fishCatchChance, fishDoubleChance,
+ gatherChance, gatherDoubleChance, coalBonusChance, cookBurnChance,
+} from '../items.js';
+import {
+ fishingSpotInRange, treeInRange, rockInRange, firepitInRange,
+} from '../world-features.js';
+import { interactZoneInRange, zoneAt } from '../quest-zones.js';
+import {
+ missionDef, isHeist, utcDayKey,
+ restoreQuestState, serializeQuestState,
+ acceptMission, abandonMission, applyEvent, recordCompletion,
+ missionReward, splitPot, questSnapshot, runView, objectiveMatches,
+} from '../quests.js';
import { hydratePlayer, loadPlayer, savePlayer, flushPlayer } from '../playerStore.js';
import { publishFeedEvent } from '../feed.js';
@@ -65,12 +83,24 @@ const EDITS_PER_SEC_LIMIT = 20;
// headroom for packet timing jitter.
const MAX_STEP_M = 1.2;
-// World bounds — match the ground disc radius in src/walk.js so the visual
-// ground and the authoritative area stay aligned. In AR mode the client lets
-// the avatar roam freely, but we still clamp on the server so a malicious
-// client can't broadcast nonsense positions.
+// Legacy disc radius — still used as the fallback drop clamp when a driver steps
+// out of a vehicle (vehicles carry their own VEHICLE_WORLD_RADIUS_M bound).
const WORLD_RADIUS_M = 60;
+// Open-world district bounds (W01). The /play world is no longer the 60 m disc:
+// it's a square district the client renders streets/buildings across. These
+// mirror DISTRICT.half in src/game/world-zones.js — keep the two in sync so the
+// authoritative bounds and the rendered ground agree. The anti-teleport MAX_STEP
+// clamp above is independent and still applies on every move.
+const WORLD_HALF_M = 200;
+const WORLD_BOUND_M = WORLD_HALF_M - 2; // small margin so an edge-pressed avatar never clips the rim
+
+// Authoritative day/night clock. One full day every DAY_LENGTH_MS, derived from
+// the wall clock so every room (and every client in it) agrees on the time of
+// day without us syncing a phase. Broadcast once a second as state.worldTime (a
+// [0,1) day fraction); clients advance it smoothly between updates.
+const DAY_LENGTH_MS = 600_000; // 10-minute day → a visible cycle, not a frantic one
+
// Rate limit incoming 'move' messages per client to twice the expected rate
// so legitimate jitter passes but a flooding client gets dropped.
const MOVES_PER_SEC_LIMIT = PATCH_RATE_HZ * 2;
@@ -85,8 +115,13 @@ const MOTION_VALUES = new Set(['idle', 'walk', 'run']);
// This keeps the shared /walk schema untouched and peers' wire cost at zero.
const FISH_COOLDOWN_MS = 1500; // per-cast reel time (cadence on the real clock)
const CONSUME_COOLDOWN_MS = 1100; // pace between bites — no instant heal-spam
+const CHOP_COOLDOWN_MS = 1300; // per-swing axe cadence
+const MINE_COOLDOWN_MS = 1500; // per-strike pickaxe cadence (ore is slower)
+const COOK_COOLDOWN_MS = 900; // pace between fish on the fire
// Per-action rate ceilings (messages/sec/client) — a flooding client is dropped.
-const ACTION_RATES = { fish: 6, consume: 6, equip: 30 };
+// vsync rides at the same 15Hz the move netcode uses; allow 2× for jitter, like
+// MOVES_PER_SEC_LIMIT. enter/exit are deliberate, rare actions.
+const ACTION_RATES = { fish: 6, consume: 6, equip: 30, chop: 6, mine: 6, cook: 8, vsync: PATCH_RATE_HZ * 2, venter: 4, vexit: 4, quest: 8, questInteract: 6 };
// Spatial voice signaling. The room only relays SDP/ICE between two peers (the
// audio itself flows peer-to-peer over WebRTC), so the cap just has to clear a
@@ -205,6 +240,10 @@ export class WalkRoom extends Room {
// stable persistence id + per-action cooldowns). Never synced to peers.
this.econ = new Map();
this._actionCounters = new Map(); // sessionId → { [action]: { windowStart, count } }
+ // Co-op heist instances live on the room, not on a profile: a SHARED run a
+ // crew advances together. Keyed by mission id (one live instance per heist per
+ // world). Each value: { missionId, members:Set<sessionId>, run, done:Set<zone> }.
+ this.heists = new Map();
}
async onCreate(options) {
@@ -252,9 +291,25 @@ export class WalkRoom extends Room {
// Economy & activities (off-schema). The owning client drives these and
// receives the authoritative result via profile/inv/xpgain/levelup/notice.
this.onMessage('fish', (client) => this._handleFish(client));
+ this.onMessage('chop', (client) => this._handleChop(client));
+ this.onMessage('mine', (client) => this._handleMine(client));
+ this.onMessage('cook', (client) => this._handleCook(client));
this.onMessage('equip', (client, payload) => this._handleEquip(client, payload));
this.onMessage('consume', (client, payload) => this._handleConsume(client, payload));
this.onMessage('profileReq', (client) => this._sendProfile(client));
+ // Quests, jobs & heists (W05, off-schema). The board, accepting/abandoning a
+ // mission, and acting at a quest object all flow through here; the server is the
+ // sole authority for objective progress and reward grants.
+ this.onMessage('questReq', (client) => this._sendQuests(client));
+ this.onMessage('questAccept', (client, payload) => this._handleQuestAccept(client, payload));
+ this.onMessage('questAbandon', (client, payload) => this._handleQuestAbandon(client, payload));
+ this.onMessage('questInteract', (client) => this._handleQuestInteract(client));
+ // Vehicles. The driver streams 'vsync' (the Rapier-simulated transform); the
+ // server validates per-type speed/bounds and relays. 'venter'/'vexit' take and
+ // release the wheel, gated by proximity and single-occupancy.
+ this.onMessage('venter', (client, payload) => this._handleVehicleEnter(client, payload));
+ this.onMessage('vexit', (client, payload) => this._handleVehicleExit(client, payload));
+ this.onMessage('vsync', (client, payload) => this._handleVehicleSync(client, payload));
this._emoteCooldowns = new Map();
this._editCounters = new Map(); // sessionId → { windowStart, count }
this._voiceCounters = new Map(); // sessionId → { windowStart, count }
@@ -280,6 +335,13 @@ export class WalkRoom extends Room {
await blockStore.ready();
this.state.persistent = blockStore.durable;
+ // Seed this world's drivable fleet. Vehicles are world entities (everyone sees
+ // them) so they ride on the synced state, parked until someone takes the wheel.
+ // Spawned for every coin world — driving is a core verb, not a flagship-only
+ // affordance. v1 fleet is ephemeral per room (re-spawned fresh each time the
+ // room is created); persistence of parked vehicles is a later concern.
+ this._seedVehicles();
+
// Re-check policy for the token gate. The game server has no RPC of its own,
// so "still holding the token" is re-proven by the client minting a fresh
// play pass (which re-reads the chain) before the current one's 10-min TTL
@@ -342,9 +404,14 @@ export class WalkRoom extends Room {
if (!this.state.players.has(client.sessionId)) return;
const saved = loadPlayer(playerId);
const profile = restoreProfile(saved?.profile, playerId);
- profile.cd = { fish: 0, consume: 0 }; // per-action cooldown clocks (runtime only)
+ profile.cd = { fish: 0, consume: 0, chop: 0, mine: 0, cook: 0 }; // per-action cooldown clocks (runtime only)
+ // Quest log (W05): the player's accepted/completed missions + daily state,
+ // persisted alongside the pack/purse. Stale dailies roll over to today on load.
+ profile.quests = restoreQuestState(saved?.profile?.quests, utcDayKey());
+ profile._zone = null; // last quest zone the player was inside (enter-zone edge detect)
this.econ.set(client.sessionId, profile);
this._sendProfile(client);
+ this._sendQuests(client);
const tierTag = this.state.tier === 'holders' ? ' tier=holders' : '';
console.log(
@@ -368,6 +435,12 @@ export class WalkRoom extends Room {
onLeave(client) {
if (client.userData?.accountUid) socialHub.unregister(client.userData.accountUid, client);
+ // Free any vehicle this player was driving so it parks where it was left and
+ // becomes available again — otherwise a disconnect would lock a car forever.
+ this._releaseVehicleOf(client.sessionId);
+ // Drop the player from any co-op heist instance they were in, so the shared run
+ // doesn't hold a phantom crew member (and disposes when the last one leaves).
+ this._leaveHeists(client.sessionId);
// Persist the final economy state and arm a durable flush so progress survives
// the disconnect and the room being torn down when the last player leaves.
const profile = this.econ.get(client.sessionId);
@@ -441,20 +514,34 @@ export class WalkRoom extends Room {
return;
}
- // World bounds clamp.
- const r = Math.hypot(x, z);
- if (r > WORLD_RADIUS_M) {
- const k = WORLD_RADIUS_M / r;
- player.x = x * k;
- player.z = z * k;
- } else {
- player.x = x;
- player.z = z;
- }
+ // World bounds clamp — the square open-world district (W01).
+ player.x = Math.max(-WORLD_BOUND_M, Math.min(WORLD_BOUND_M, x));
+ player.z = Math.max(-WORLD_BOUND_M, Math.min(WORLD_BOUND_M, z));
player.y = Math.max(-10, Math.min(10, y)); // keep avatars near the ground plane
player.yaw = yaw;
if (MOTION_VALUES.has(motion)) player.motion = motion;
player.tsServer = Date.now();
+
+ // Quest progress: detect entering a NEW quest zone (edge-triggered off the
+ // authoritative position, so a "goto" objective can't be faked from the client).
+ this._checkZoneEntry(client);
+ }
+
+ // Edge-detect quest-zone entry on the server's authoritative position. Emits a
+ // single 'enter-zone' event when the player crosses into a zone they weren't in
+ // last tick — never per-frame while standing in it — so survey/patrol objectives
+ // advance exactly once per visit. Cheap (a handful of zones); only does work when
+ // the current zone actually changed.
+ _checkZoneEntry(client) {
+ const profile = this.econ.get(client.sessionId);
+ if (!profile) return;
+ const player = this.state.players.get(client.sessionId);
+ if (!player) return;
+ const zone = zoneAt(player.x, player.z);
+ const id = zone ? zone.id : null;
+ if (id === profile._zone) return; // no transition
+ profile._zone = id;
+ if (id) this._questEvent(client, profile, { type: 'enter-zone', zone: id });
}
_handleRename(client, payload) {
@@ -640,6 +727,8 @@ export class WalkRoom extends Room {
this._grantXp(client, profile, 'fishing', xp);
this._sendInv(client, profile);
client.send('notice', { kind: 'fish', caught, text: caught > 1 ? `Caught ${caught} ${itemLabel('fish').toLowerCase()}!` : `Caught a ${itemLabel('fish').toLowerCase()}.` });
+ // Quest progress: a real catch advances any active "collect fish" objective.
+ this._questEvent(client, profile, { type: 'collect', item: 'fish', qty: caught });
} else {
this._grantXp(client, profile, 'fishing', 2);
client.send('notice', { kind: 'fish', caught: 0, text: 'The fish got away.' });
@@ -691,10 +780,181 @@ export class WalkRoom extends Room {
...prev,
name: player?.name || prev.name,
gold: profile.gold,
- profile: serializeProfile(profile),
+ // Fold the quest log into the persisted profile blob so accepted jobs +
+ // daily state survive a disconnect (economy.js round-trips it opaquely).
+ profile: { ...serializeProfile(profile), quests: serializeQuestState(profile.quests) },
});
}
+ // --- Vehicles ------------------------------------------------------------
+
+ // Seed the parked fleet from the shared spawn registry. Colors come from each
+ // type's signature color so the world reads consistently across clients.
+ _seedVehicles() {
+ for (const spawn of VEHICLE_SPAWNS) {
+ if (!isVehicleType(spawn.type)) continue;
+ const spec = vehicleSpec(spawn.type);
+ const v = new Vehicle();
+ v.id = spawn.id;
+ v.type = spawn.type;
+ v.color = Number.isInteger(spawn.color) ? spawn.color : spec.color;
+ v.x = spawn.x;
+ v.y = 0;
+ v.z = spawn.z;
+ // Resting heading → quaternion about the up axis.
+ const half = (spawn.yaw || 0) / 2;
+ v.qx = 0; v.qy = Math.sin(half); v.qz = 0; v.qw = Math.cos(half);
+ v.speed = 0;
+ v.driver = '';
+ v.health = 100;
+ v.tsServer = Date.now();
+ this.state.vehicles.set(v.id, v);
+ }
+ }
+
+ // Take the wheel of a parked vehicle. Gated by: the vehicle exists, it isn't
+ // already occupied, and the player is standing within range of it. A player can
+ // only drive one vehicle, so any prior one is released first. The grant is the
+ // authoritative `driver` field flipping to this session — the client waits for
+ // that echo (plus a targeted ack) before it starts simulating.
+ _handleVehicleEnter(client, payload) {
+ const player = this.state.players.get(client.sessionId);
+ if (!player) return;
+ if (!this._actionOk(client.sessionId, 'venter')) return;
+ const id = typeof payload?.id === 'string' ? payload.id : '';
+ const v = this.state.vehicles.get(id);
+ if (!v) { client.send('vehicle', { event: 'deny', id, reason: 'gone' }); return; }
+ if (v.driver && v.driver !== client.sessionId) {
+ client.send('vehicle', { event: 'deny', id, reason: 'occupied' });
+ return;
+ }
+ // Proximity gate — can't claim a car from across the map.
+ const dist = Math.hypot(player.x - v.x, player.z - v.z);
+ if (dist > VEHICLE_ENTER_RANGE_M) {
+ client.send('vehicle', { event: 'deny', id, reason: 'range' });
+ return;
+ }
+ this._releaseVehicleOf(client.sessionId, id); // give up any other car first
+ v.driver = client.sessionId;
+ v.tsServer = Date.now();
+ client.send('vehicle', { event: 'enter', id });
+ }
+
+ // Leave the wheel. The client sends its final resting transform; the server
+ // parks the car there, clears the driver, and authors the player's drop point
+ // beside the door so the next ordinary 'move' is continuous (no teleport
+ // rejection). The drop is server-computed and bounds-clamped — a client can't
+ // use exit to warp.
+ _handleVehicleExit(client, payload) {
+ const player = this.state.players.get(client.sessionId);
+ if (!player) return;
+ if (!this._actionOk(client.sessionId, 'vexit')) return;
+ const v = this._vehicleDrivenBy(client.sessionId);
+ if (!v) return;
+ // Accept the final transform through the same validation as a sync so the car
+ // can't be parked somewhere impossible on the way out.
+ this._applyVehicleTransform(v, payload, /* park */ true);
+ v.driver = '';
+ v.speed = 0;
+ v.tsServer = Date.now();
+
+ // Drop the avatar just left of the car (chassis-left), clamped to the world.
+ const yaw = this._vehicleYaw(v);
+ const off = (vehicleSpec(v.type).dims.w / 2) + 0.6;
+ let dx = v.x + Math.cos(yaw) * off;
+ let dz = v.z - Math.sin(yaw) * off;
+ const r = Math.hypot(dx, dz);
+ if (r > WORLD_RADIUS_M) { const k = WORLD_RADIUS_M / r; dx *= k; dz *= k; }
+ player.x = dx;
+ player.z = dz;
+ player.y = 0;
+ player.motion = 'idle';
+ player.tsServer = Date.now();
+ client.send('vehicle', { event: 'exit', id: v.id, x: dx, z: dz });
+ }
+
+ // Adopt the driver's streamed transform. Server-authoritative validation: only
+ // the seated driver may write; reject NaNs; reject a jump larger than the type's
+ // top speed allows over the send window (teleport) and an implausible reported
+ // speed (speed hack). A rejected position is simply not applied — the car holds
+ // its last authoritative transform, which the cheating client then sees snap back.
+ _handleVehicleSync(client, payload) {
+ if (!this._actionOk(client.sessionId, 'vsync')) return;
+ const v = this._vehicleDrivenBy(client.sessionId);
+ if (!v) return;
+ if (!this._applyVehicleTransform(v, payload, /* park */ false)) return;
+
+ // Carry the driver's avatar with the car so peers render them in the seat and
+ // stepping out is continuous. The avatar sits at the seat height above the
+ // chassis; ordinary move validation is bypassed here because the vehicle's own
+ // speed clamp already policed this displacement.
+ const player = this.state.players.get(client.sessionId);
+ if (player) {
+ player.x = v.x;
+ player.z = v.z;
+ player.y = Math.max(0, Math.min(3, v.y + vehicleSpec(v.type).seat.y));
+ player.motion = 'idle';
+ player.tsServer = v.tsServer;
+ }
+ }
+
+ // Validate + write a transform onto a vehicle. Returns false (and leaves the
+ // vehicle untouched) when the update is malformed or fails an anti-cheat clamp.
+ _applyVehicleTransform(v, payload, park) {
+ if (!payload || typeof payload !== 'object') return false;
+ const { x, y, z, qx, qy, qz, qw, speed } = payload;
+ const nums = [x, y, z, qx, qy, qz, qw];
+ if (nums.some((n) => typeof n !== 'number' || !Number.isFinite(n))) return false;
+
+ // Teleport clamp: reject a step larger than top speed could cover this window.
+ const dx = x - v.x, dz = z - v.z;
+ if (Math.hypot(dx, dz) > vehicleMaxStepM(v.type)) return false;
+ // Speed-hack clamp on the reported forward speed.
+ const sp = typeof speed === 'number' && Number.isFinite(speed) ? speed : 0;
+ if (Math.abs(sp) > vehicleMaxSpeedMps(v.type)) return false;
+
+ // World bounds — keep the car inside the visible arena (scale x/z together so
+ // a clamp doesn't change heading).
+ const r = Math.hypot(x, z);
+ if (r > VEHICLE_WORLD_RADIUS_M) {
+ const k = VEHICLE_WORLD_RADIUS_M / r;
+ v.x = x * k; v.z = z * k;
+ } else {
+ v.x = x; v.z = z;
+ }
+ v.y = Math.max(-2, Math.min(8, y));
+ // Normalize the quaternion defensively so a denormalized client value can't
+ // poison every peer's renderer.
+ const ql = Math.hypot(qx, qy, qz, qw) || 1;
+ v.qx = qx / ql; v.qy = qy / ql; v.qz = qz / ql; v.qw = qw / ql;
+ v.speed = park ? 0 : sp;
+ v.tsServer = Date.now();
+ return true;
+ }
+
+ _vehicleDrivenBy(sessionId) {
+ for (const [, v] of this.state.vehicles) {
+ if (v.driver === sessionId) return v;
+ }
+ return null;
+ }
+
+ // Release any vehicle driven by this session (except `keepId`, when re-claiming).
+ _releaseVehicleOf(sessionId, keepId = null) {
+ for (const [, v] of this.state.vehicles) {
+ if (v.driver === sessionId && v.id !== keepId) {
+ v.driver = '';
+ v.speed = 0;
+ v.tsServer = Date.now();
+ }
+ }
+ }
+
+ // Heading (radians about the up axis) extracted from a vehicle's quaternion.
+ _vehicleYaw(v) {
+ return Math.atan2(2 * (v.qw * v.qy + v.qx * v.qz), 1 - 2 * (v.qy * v.qy + v.qx * v.qx));
+ }
+
// Per-action sliding-window rate limit (messages/sec/client). A flooding client
// is silently dropped for the offending action; legitimate cadence passes.
_actionOk(sessionId, action) {
diff --git a/multiplayer/src/schemas.js b/multiplayer/src/schemas.js
index 73ebe5cf4..dabf8749d 100644
--- a/multiplayer/src/schemas.js
+++ b/multiplayer/src/schemas.js
@@ -33,6 +33,13 @@ export class Player extends Schema {
// player persists under and is known by in the social graph. Empty in the
// open (un-gated) world; set from the play pass when the token gate is on.
this.account = '';
+ // Combat (W07). HP/armor stay PRIVATE (off-schema, streamed only to the
+ // owner) so peers can't read exact vitals, but two states MUST be visible to
+ // everyone: whether you're downed (peers render the ragdoll + skip you as a
+ // target) and your wanted level (0–5 stars peers can see to bounty you). Both
+ // are tiny and authoritative — set only by the server's combat resolution.
+ this.dead = false;
+ this.heat = 0; // wanted/heat stars (0–5), derived from the private heat meter
}
}
// IMPORTANT: append-only. Field indices are positional in @colyseus/schema's
@@ -55,6 +62,9 @@ defineTypes(Player, {
voice: 'boolean',
tsServer: 'float64',
account: 'string',
+ // Append-only (W07): downed state + wanted stars. See the constructor note.
+ dead: 'boolean',
+ heat: 'uint8',
});
// A single placed voxel in a coin's world. Keyed in the blocks MapSchema by its
@@ -71,6 +81,111 @@ defineTypes(Block, {
t: 'uint8',
});
+// A drivable vehicle living in the shared world. Unlike a player's private
+// economy (off-schema), a vehicle is a world entity everyone must see, so it
+// rides on the synced state. The driver's client simulates it with Rapier and
+// streams the authoritative transform (full quaternion — cars pitch/roll over
+// the ground, a single yaw can't express that); the server validates per-type
+// speed/bounds and relays. `driver` is the sessionId at the wheel ('' = parked),
+// the field that gates who is allowed to write this vehicle's transform.
+export class Vehicle extends Schema {
+ constructor() {
+ super();
+ this.id = '';
+ this.type = 'sedan'; // VEHICLE_TYPES key — picks the mesh + handling profile
+ this.color = 0xffffff;
+ this.x = 0;
+ this.y = 0;
+ this.z = 0;
+ // Orientation as a quaternion so peers reproduce body tilt, not just heading.
+ this.qx = 0;
+ this.qy = 0;
+ this.qz = 0;
+ this.qw = 1;
+ this.speed = 0; // signed forward speed (m/s) — drives wheel spin + audio
+ this.driver = ''; // sessionId at the wheel; '' when parked
+ this.health = 100; // damage hooks for W07 (combat); full here
+ this.tsServer = 0; // last authoritative update (epoch ms) for interpolation
+ }
+}
+defineTypes(Vehicle, {
+ id: 'string',
+ type: 'string',
+ color: 'uint32',
+ x: 'float32',
+ y: 'float32',
+ z: 'float32',
+ qx: 'float32',
+ qy: 'float32',
+ qz: 'float32',
+ qw: 'float32',
+ speed: 'float32',
+ driver: 'string',
+ health: 'float32',
+ tsServer: 'float64',
+});
+
+// A PvE enemy in the shared world (W07). Unlike a player's private vitals, a mob
+// is a world entity everyone must see and fight, so it rides on the synced state.
+// The SERVER owns every field — spawns it, runs its AI, applies damage — so a
+// client can never move, heal, or kill a mob by writing state; it only renders
+// what the room replicates. Keyed in the mobs MapSchema by its id.
+export class Mob extends Schema {
+ constructor() {
+ super();
+ this.id = '';
+ this.kind = 'goblin'; // MOB_STATS key — picks stats, mesh, loot table
+ this.x = 0;
+ this.y = 0;
+ this.z = 0;
+ this.yaw = 0;
+ this.hp = 1;
+ this.maxHp = 1;
+ this.state = 'idle'; // 'idle' | 'chase' | 'attack' | 'dead'
+ this.tsServer = 0; // last authoritative update (epoch ms) for interpolation
+ }
+}
+defineTypes(Mob, {
+ id: 'string',
+ kind: 'string',
+ x: 'float32',
+ y: 'float32',
+ z: 'float32',
+ yaw: 'float32',
+ hp: 'uint16',
+ maxHp: 'uint16',
+ state: 'string',
+ tsServer: 'float64',
+});
+
+// A death-drop marker (W07). When a player or mob dies in a danger zone its carried
+// cash + items spill into a lootable tombstone the killer and others can claim. The
+// synced fields are only what peers must SEE to find and read it (where it is, how
+// much cash, how many item lines, whose it was); the actual item manifest stays
+// off-schema on the room so the wire stays cheap and contents can't be inspected
+// without walking up and looting. Keyed in the tombstones MapSchema by its id.
+export class Tombstone extends Schema {
+ constructor() {
+ super();
+ this.id = '';
+ this.x = 0;
+ this.z = 0;
+ this.gold = 0; // carried cash inside (display + claim)
+ this.count = 0; // number of item lines inside (for the "N items" pip)
+ this.owner = ''; // display name of who dropped it
+ this.ts = 0; // epoch ms it was created (clients fade it as it ages)
+ }
+}
+defineTypes(Tombstone, {
+ id: 'string',
+ x: 'float32',
+ z: 'float32',
+ gold: 'uint32',
+ count: 'uint8',
+ owner: 'string',
+ ts: 'float64',
+});
+
export class WalkState extends Schema {
constructor() {
super();
@@ -97,6 +212,20 @@ export class WalkState extends Schema {
// but not a full server restart. The client surfaces this so builders know
// whether their creation is saved for keeps.
this.persistent = false;
+ // Drivable vehicles in this world, keyed by vehicle id. Seeded on room create
+ // from the vehicle spawn registry; transforms driven by whoever is at the
+ // wheel and validated server-side.
+ this.vehicles = new MapSchema();
+ // Authoritative time of day for the open-world day/night cycle, as a day
+ // fraction in [0,1): 0 = midnight, 0.25 = sunrise, 0.5 = noon, 0.75 = sunset.
+ // The server advances it (see WalkRoom) so every client in the world renders
+ // the same sky and two players always agree on whether it's night.
+ this.worldTime = 0;
+ // Combat world entities (W07), both server-owned: roaming PvE mobs in the
+ // danger zones, and death-drop tombstones anyone can loot. Kept at the end of
+ // the schema (append-only) so an older client isn't shifted off the format.
+ this.mobs = new MapSchema();
+ this.tombstones = new MapSchema();
}
}
defineTypes(WalkState, {
@@ -109,4 +238,10 @@ defineTypes(WalkState, {
holderMinUsd: 'float32',
blocks: { map: Block },
persistent: 'boolean',
+ // Append-only: keep new collections at the end so a still-running older client
+ // (pre-vehicles) isn't shifted off the wire format mid-deploy.
+ vehicles: { map: Vehicle },
+ worldTime: 'float32',
+ mobs: { map: Mob },
+ tombstones: { map: Tombstone },
});
diff --git a/multiplayer/src/vehicles.js b/multiplayer/src/vehicles.js
new file mode 100644
index 000000000..6d4affc35
--- /dev/null
+++ b/multiplayer/src/vehicles.js
@@ -0,0 +1,138 @@
+// Vehicle spec — the single source of truth for drivable vehicles, shared by the
+// authoritative server (WalkRoom) and the client (VehicleManager + physics).
+//
+// Why it lives in multiplayer/: the client already imports the schemas from here,
+// so co-locating the handling table and spawn registry keeps one canonical
+// definition. The server reads it to seed the fleet and to validate driver
+// updates (speed/teleport clamps per type); the client reads the same numbers to
+// tune its Rapier raycast vehicle, so a car drives identically to how the server
+// polices it — no drift between "feels fast" and "rejected as cheating".
+//
+// Driving model (Notblox-style, matching how /play already nets movement): the
+// driver simulates the vehicle with Rapier locally and streams the authoritative
+// transform; the server validates bounds + per-type speed and relays it. The
+// server stays the gate — it never trusts a transform that implies impossible
+// speed, and it owns who is allowed to drive which vehicle.
+
+// Handling profiles. Lengths in metres, mass in kg, forces in Newtons, speeds in
+// m/s, angles in radians. Each type has a distinct feel:
+// coupe — low, fast, light, twitchy steering, less grip (slides)
+// sedan — the balanced everyday car
+// pickup — heavy, slower, planted, wide turning, lots of grip
+// buggy — light off-roader, high grip + stiff suspension, nimble
+export const VEHICLE_TYPES = {
+ coupe: {
+ id: 'coupe',
+ label: 'Coupe',
+ mass: 1100,
+ topSpeed: 28, // ~100 km/h
+ engineForce: 5200, // forward drive force per powered axle
+ brakeForce: 110,
+ reverseForce: 2600,
+ steerMax: 0.52, // max front-wheel steer angle
+ steerSpeed: 3.2, // how fast steering approaches the target (per second)
+ grip: 1.9, // wheel friction slip — lower = looser tail
+ dims: { l: 4.1, w: 1.85, h: 1.05 },
+ wheel: { radius: 0.34, halfWidth: 0.18, inset: 0.16, frontZ: 1.35, rearZ: -1.3 },
+ suspension: { rest: 0.32, stiffness: 26, travel: 0.16, compression: 0.82, relax: 0.88 },
+ seat: { x: -0.42, y: 0.62, z: -0.2 }, // driver seat offset in chassis space
+ color: 0xc8402f,
+ },
+ sedan: {
+ id: 'sedan',
+ label: 'Sedan',
+ mass: 1350,
+ topSpeed: 24,
+ engineForce: 4600,
+ brakeForce: 120,
+ reverseForce: 2400,
+ steerMax: 0.5,
+ steerSpeed: 2.6,
+ grip: 2.3,
+ dims: { l: 4.4, w: 1.9, h: 1.25 },
+ wheel: { radius: 0.36, halfWidth: 0.19, inset: 0.16, frontZ: 1.45, rearZ: -1.4 },
+ suspension: { rest: 0.36, stiffness: 24, travel: 0.18, compression: 0.85, relax: 0.9 },
+ seat: { x: -0.44, y: 0.72, z: -0.1 },
+ color: 0x2f6fc8,
+ },
+ pickup: {
+ id: 'pickup',
+ label: 'Pickup',
+ mass: 1950,
+ topSpeed: 21,
+ engineForce: 6200,
+ brakeForce: 150,
+ reverseForce: 3000,
+ steerMax: 0.46,
+ steerSpeed: 2.1,
+ grip: 2.7,
+ dims: { l: 5.0, w: 2.05, h: 1.5 },
+ wheel: { radius: 0.42, halfWidth: 0.22, inset: 0.14, frontZ: 1.6, rearZ: -1.55 },
+ suspension: { rest: 0.42, stiffness: 22, travel: 0.22, compression: 0.85, relax: 0.9 },
+ seat: { x: -0.5, y: 0.92, z: 0.35 },
+ color: 0x2b2f36,
+ },
+ buggy: {
+ id: 'buggy',
+ label: 'Buggy',
+ mass: 850,
+ topSpeed: 25,
+ engineForce: 4200,
+ brakeForce: 100,
+ reverseForce: 2200,
+ steerMax: 0.6,
+ steerSpeed: 3.6,
+ grip: 3.0,
+ dims: { l: 3.4, w: 1.8, h: 1.0 },
+ wheel: { radius: 0.4, halfWidth: 0.24, inset: 0.06, frontZ: 1.2, rearZ: -1.15 },
+ suspension: { rest: 0.46, stiffness: 28, travel: 0.26, compression: 0.8, relax: 0.86 },
+ seat: { x: -0.4, y: 0.66, z: -0.1 },
+ color: 0xe0a52e,
+ },
+};
+
+export const VEHICLE_TYPE_IDS = Object.keys(VEHICLE_TYPES);
+
+export function isVehicleType(t) {
+ return typeof t === 'string' && Object.prototype.hasOwnProperty.call(VEHICLE_TYPES, t);
+}
+
+export function vehicleSpec(type) {
+ return VEHICLE_TYPES[type] || VEHICLE_TYPES.sedan;
+}
+
+// The fleet every world spawns with. Parked in a row near the spawn point, facing
+// into the plaza, clear of the totem (0,0,-12), the jumbotron (0,0,-30) and the
+// Agent Exchange (8,0,-6). yaw is the resting heading (radians, 0 = +z).
+export const VEHICLE_SPAWNS = [
+ { id: 'v-coupe-1', type: 'coupe', x: -10, z: 9, yaw: Math.PI },
+ { id: 'v-sedan-1', type: 'sedan', x: -4, z: 9.5, yaw: Math.PI },
+ { id: 'v-pickup-1', type: 'pickup', x: 3, z: 9.5, yaw: Math.PI },
+ { id: 'v-buggy-1', type: 'buggy', x: 9, z: 9, yaw: Math.PI },
+ { id: 'v-coupe-2', type: 'coupe', x: 14, z: 4, yaw: Math.PI * 0.5 },
+ { id: 'v-sedan-2', type: 'sedan', x: -15, z: 3, yaw: -Math.PI * 0.5 },
+];
+
+// --- Anti-cheat limits (server-enforced) ----------------------------------
+
+// World bounds must match WalkRoom's player clamp so a car can't be driven past
+// the visible arena.
+export const VEHICLE_WORLD_RADIUS_M = 60;
+
+// How close a player must stand to a parked vehicle to take the wheel.
+export const VEHICLE_ENTER_RANGE_M = 3.4;
+
+// A driver streams the transform at the same 15Hz the move netcode uses, but
+// packets jitter, so validate the per-update displacement against the type's top
+// speed over a generous window (handles a dropped packet or two) before rejecting
+// it as a teleport. Above 1.6× top speed is always rejected outright.
+const VSYNC_WINDOW_S = 0.22; // ~3 dropped 15Hz frames of headroom
+const SPEED_CHEAT_FACTOR = 1.6; // hard ceiling on reported/derived speed
+
+export function vehicleMaxStepM(type) {
+ return vehicleSpec(type).topSpeed * SPEED_CHEAT_FACTOR * VSYNC_WINDOW_S;
+}
+
+export function vehicleMaxSpeedMps(type) {
+ return vehicleSpec(type).topSpeed * SPEED_CHEAT_FACTOR;
+}
diff --git a/multiplayer/src/world-features.js b/multiplayer/src/world-features.js
index adafbe7f8..26e963ff2 100644
--- a/multiplayer/src/world-features.js
+++ b/multiplayer/src/world-features.js
@@ -47,3 +47,126 @@ export function fishingSpotInRange(x, z) {
const near = nearestFishingSpot(x, z);
return near && near.gap <= 0 ? near.spot : null;
}
+
+// ---------------------------------------------------------------------------
+// Gather & craft stations — woodcutting, mining, cooking (W06)
+// ---------------------------------------------------------------------------
+//
+// The gather→craft loop's fixed world stations, the chop/mine/cook counterpart to
+// the fishing ponds above. All sited in the SAFE town (clear of the W07 danger
+// zones), so the gather economy stays peaceful — you fight foes in the wilds, you
+// gather and cook at home. Generalised over `nearestNode` so the range rule the
+// server trusts and the client renders the button from is byte-identical to fishing.
+
+// Generic proximity: distance from (x,z) to the nearest usable edge of a node list,
+// where each node is { x, z, r } and `reach` is how far beyond the body radius a
+// player may stand and still act. Returns { node, gap, dist } for the nearest (gap ≤
+// 0 = in range) or null when the list is empty.
+export function nearestNode(x, z, nodes, reach) {
+ let best = null;
+ for (const node of nodes) {
+ const dist = Math.hypot(x - node.x, z - node.z);
+ const gap = dist - (node.r + reach);
+ if (!best || gap < best.gap) best = { node, gap, dist };
+ }
+ return best;
+}
+
+function nodeInRange(x, z, nodes, reach) {
+ const near = nearestNode(x, z, nodes, reach);
+ return near && near.gap <= 0 ? near.node : null;
+}
+
+// Trees, chopped with an axe. `difficulty` scales the chop curve (a hardwood is
+// slower). A grove west of the totem, clear of the ponds and the danger zones.
+export const TREES = [
+ { id: 'tree-1', x: -36, z: -6, r: 0.9, difficulty: 1 },
+ { id: 'tree-2', x: -39, z: -11, r: 0.9, difficulty: 1.2 },
+ { id: 'tree-3', x: -33, z: -14, r: 0.9, difficulty: 1 },
+ { id: 'tree-4', x: -41, z: -4, r: 0.9, difficulty: 1.4 },
+ { id: 'tree-5', x: -35, z: -20, r: 0.9, difficulty: 1.2 },
+];
+export const CHOP_REACH = 2.6;
+export function nearestTree(x, z) { return nearestNode(x, z, TREES, CHOP_REACH); }
+export function treeInRange(x, z) { return nodeInRange(x, z, TREES, CHOP_REACH); }
+
+// Ore rocks, mined with a pickaxe. `difficulty` slows the strike; `coal` is the
+// bonus-coal weight (denser seams give up coal more readily). A quarry east of the
+// totem, away from the grove, the ponds and the danger zones.
+export const ROCKS = [
+ { id: 'rock-1', x: 36, z: -16, r: 1.1, difficulty: 1, coal: 1 },
+ { id: 'rock-2', x: 40, z: -21, r: 1.1, difficulty: 1.3, coal: 1.4 },
+ { id: 'rock-3', x: 33, z: -24, r: 1.1, difficulty: 1.2, coal: 1.2 },
+ { id: 'rock-4', x: 42, z: -13, r: 1.1, difficulty: 1.5, coal: 1.6 },
+];
+export const MINE_REACH = 2.8;
+export function nearestRock(x, z) { return nearestNode(x, z, ROCKS, MINE_REACH); }
+export function rockInRange(x, z) { return nodeInRange(x, z, ROCKS, MINE_REACH); }
+
+// Roast pits — cook raw fish into edible cooked fish. Sited beside the ponds so the
+// catch→cook→eat loop is a short walk, not a trek.
+export const FIREPITS = [
+ { id: 'fire-east', x: 23, z: 13, r: 1.0 },
+ { id: 'fire-west', x: -22, z: 20, r: 1.0 },
+];
+export const COOK_REACH = 2.6;
+export function nearestFirepit(x, z) { return nearestNode(x, z, FIREPITS, COOK_REACH); }
+export function firepitInRange(x, z) { return nodeInRange(x, z, FIREPITS, COOK_REACH); }
+
+// ---------------------------------------------------------------------------
+// Safe vs danger zones — opt-in PvP by location (W07)
+// ---------------------------------------------------------------------------
+//
+// GTA / Kintara-style risk geography: the whole built-up town (spawn, totem,
+// trading screen, and the gather/fish stations) is SAFE — no player may damage
+// another there and no roaming mob enters it. Combat tension is confined to a
+// handful of named WILDERNESS pockets sited in the open ground away from those
+// landmarks: inside one, PvP is on and PvE mobs roam and drop the better loot.
+// Naming the danger zones (rather than carving the map by radius) keeps the dense
+// town peaceful, gives each red zone a sign to put over the crossing, and leaves
+// the gather economy undisturbed.
+//
+// This is the ONE source of truth for the boundary, imported by BOTH the server
+// (WalkRoom — gates every attack, confines + seeds mobs, picks death-drop rules)
+// and the client (PlayCombat — paints the danger ground ring, signposts the
+// crossing, gates the attack button). A circle test is exact, cheap and trivially
+// unit-testable; W01 can later refine these into full districts.
+export const DANGER_ZONES = [
+ { id: 'southern-wilds', name: 'Southern Wilds', x: 0, z: -46, r: 13 },
+ { id: 'western-marches', name: 'Western Marches', x: -46, z: 28, r: 11 },
+ { id: 'eastern-marches', name: 'Eastern Marches', x: 46, z: 8, r: 11 },
+];
+
+export const WORLD_RADIUS = 60; // matches WalkRoom's authoritative clamp
+export const SPAWN_POINT = { x: 0, z: 0 }; // where the dead respawn — always safe
+
+// The danger zone a world point sits inside, or null when it's in safe town.
+export function dangerZoneAt(x, z) {
+ for (const zone of DANGER_ZONES) {
+ if (Math.hypot(x - zone.x, z - zone.z) <= zone.r) return zone;
+ }
+ return null;
+}
+
+// The zone kind a world point falls in. Pure and shared so client signposting and
+// server gating agree to the metre.
+export function zoneAt(x, z) {
+ return dangerZoneAt(x, z) ? 'danger' : 'safe';
+}
+
+export function isSafeZone(x, z) {
+ return !dangerZoneAt(x, z);
+}
+
+export function isDangerZone(x, z) {
+ return !!dangerZoneAt(x, z);
+}
+
+// A random point inside a given danger zone (kept a little in from its edge so a
+// spawn never lands straddling the boundary). `rng` is injectable so spawn
+// placement is deterministic under test, mirroring the loot/fish roll helpers.
+export function randomPointInZone(zone, rng = Math.random) {
+ const rr = Math.max(0, zone.r - 1.5) * Math.sqrt(rng()); // uniform over the disc
+ const a = rng() * Math.PI * 2;
+ return { x: zone.x + Math.cos(a) * rr, z: zone.z + Math.sin(a) * rr };
+}
diff --git a/package.json b/package.json
index 4389f2b10..6c3f9bd63 100644
--- a/package.json
+++ b/package.json
@@ -60,6 +60,7 @@
"build:pages": "node scripts/build-page-index.mjs",
"audit:pages": "node scripts/audit-page-index.mjs",
"audit:web": "node scripts/page-audit.mjs",
+ "snapshot": "node scripts/page-snapshot.mjs",
"build:news": "node scripts/build-news.mjs",
"prebuild": "(node scripts/build-news.mjs & node scripts/build-skill-metadata.mjs & node scripts/build-local-skill-packs.mjs & npm run build:club-assets & wait) && (node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs)",
"build": "NODE_OPTIONS='--no-deprecation --max-old-space-size=6144' vite build && node scripts/strip-sw-from-embeds.mjs",
diff --git a/pages/home.html b/pages/home.html
index 97d5c1b56..92efd6838 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -4,7 +4,7 @@
<meta charset="utf-8" />
<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="Make a 3D AI agent from a selfie in 60 seconds. Drop one HTML tag to embed it on any website. Optionally charge per chat with built-in micropayments." />
+ <meta name="description" content="Make a 3D AI agent from a selfie in 60 seconds. Drop one HTML tag to embed it on any website. Agents think on IBM watsonx.ai (Granite); optionally charge per chat with built-in micropayments." />
<link rel="canonical" href="https://three.ws/" />
<link rel="alternate" type="application/rss+xml" title="three.ws announcements" href="https://three.ws/rss/announcements.xml" />
<meta name="theme-color" content="#050505" />
@@ -14,7 +14,7 @@
<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="Make a living 3D AI agent from a selfie — embed it on any website in 60 seconds. Voice, memory, and payments built in." />
+ <meta property="og:description" content="Make a living 3D AI agent from a selfie — embed it on any website in 60 seconds. Voice, memory, payments, and an IBM watsonx.ai (Granite) brain built in." />
<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" />
@@ -24,7 +24,7 @@
<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="Make a living 3D AI agent from a selfie — embed it on any website in 60 seconds. Voice, memory, and payments built in." />
+ <meta name="twitter:description" content="Make a living 3D AI agent from a selfie — embed it on any website in 60 seconds. Voice, memory, payments, and an IBM watsonx.ai (Granite) brain built in." />
<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" />
@@ -388,6 +388,37 @@
}
.logo-row .logo:hover { opacity: 1; }
+ /* ── PRESS / LISTINGS ────────────────────────────────────── */
+ .press-strip { padding: 64px 0; border-bottom: 1px solid var(--hairline); }
+ .press-cap {
+ font-family: var(--font-mono); font-size: 10.5px;
+ letter-spacing: 0.2em; text-transform: uppercase;
+ color: var(--text-4); text-align: center; margin-bottom: 22px;
+ }
+ .press-row {
+ display: flex; flex-wrap: wrap; justify-content: center;
+ gap: 14px; align-items: stretch; max-width: 920px; margin: 0 auto;
+ }
+ .press-chip {
+ display: inline-flex; align-items: center; gap: 8px;
+ padding: 10px 16px; border: 1px solid var(--hairline);
+ border-radius: 10px; background: var(--surface-2, rgba(255,255,255,0.03));
+ font-family: var(--font-display); font-size: 14px; font-weight: 500;
+ letter-spacing: -0.01em; color: var(--text-3); text-decoration: none;
+ transition: color 0.15s, border-color 0.15s, background 0.15s, transform 0.15s;
+ }
+ .press-chip:hover { color: var(--text); border-color: var(--text-3); transform: translateY(-2px); }
+ .press-chip:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; }
+ .press-chip .press-arrow { font-size: 11px; opacity: 0.5; }
+ .press-divider { height: 30px; }
+ .press-ca {
+ margin: 26px auto 0; text-align: center;
+ font-family: var(--font-mono); font-size: 11px; color: var(--text-4);
+ word-break: break-all; max-width: 520px; line-height: 1.5;
+ }
+ .press-ca code { color: var(--text-3); }
+ @media (max-width: 720px) { .press-strip { padding: 48px 0; } }
+
/* ── SECTION FRAME ───────────────────────────────────────── */
section.block { padding: 112px 0; border-top: 1px solid var(--hairline); }
@media (max-width: 720px) { section.block { padding: 72px 0; } }
@@ -2841,6 +2872,31 @@
</div>
</div>
+<!-- ── PRESS / LISTINGS ──────────────────────────────────────────── -->
+<!-- Coinbase + CoinGecko route to our own listings post on purpose: their public
+ pages can surface a non-canonical mint, so we keep the destination on a page
+ we control that shows the canonical $three contract. -->
+<section class="press-strip" id="press" aria-label="Press coverage and exchange listings">
+ <div class="wrap-1280">
+ <div class="press-cap">In the press</div>
+ <div class="press-row">
+ <a class="press-chip" href="https://markets.businessinsider.com/news/stocks/three-ws-and-ibm-announce-strategic-partnership-to-advance-ai-powered-3d-agent-technology-1036222181" target="_blank" rel="noopener noreferrer">Business Insider <span class="press-arrow" aria-hidden="true">↗</span></a>
+ <a class="press-chip" href="https://finance.yahoo.com/sectors/technology/articles/ibm-extends-ai-narrative-three-010650764.html" target="_blank" rel="noopener noreferrer">Yahoo Finance <span class="press-arrow" aria-hidden="true">↗</span></a>
+ </div>
+ <div class="press-divider"></div>
+ <div class="press-cap">Trading $three</div>
+ <div class="press-row">
+ <a class="press-chip" href="/blog/three-token-listings.html">Coinbase</a>
+ <a class="press-chip" href="/blog/three-token-listings.html">CoinGecko</a>
+ <a class="press-chip" href="https://announcements.bybit.com/en/article/three-is-now-live-on-bybit-alpha-bltc04fc471efada919/" target="_blank" rel="noopener noreferrer">Bybit <span class="press-arrow" aria-hidden="true">↗</span></a>
+ <a class="press-chip" href="https://www.kucoin.com/news/flash/solana-meme-coin-three-surges-104-in-two-hours-reaches-16m-market-cap" target="_blank" rel="noopener noreferrer">KuCoin <span class="press-arrow" aria-hidden="true">↗</span></a>
+ <a class="press-chip" href="https://www.mexc.com/exchange/THREE_USDT" target="_blank" rel="noopener noreferrer">MEXC <span class="press-arrow" aria-hidden="true">↗</span></a>
+ <a class="press-chip" href="https://www.tradingview.com/news/coinmarketcal:f0996d63c094b:0-three-ws-three-kucoin-listing-02-june-2026/" target="_blank" rel="noopener noreferrer">TradingView <span class="press-arrow" aria-hidden="true">↗</span></a>
+ </div>
+ <p class="press-ca">$three contract · <code>FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump</code></p>
+ </div>
+</section>
+
<!-- ── PLAYGROUND ──────────────────────────────────────────────────── -->
<section class="block" id="embed">
<div class="wrap-1280">
diff --git a/public/feed.js b/public/feed.js
index 6ed8a3407..edb7658b3 100644
--- a/public/feed.js
+++ b/public/feed.js
@@ -91,7 +91,15 @@
'agent-deploy': {
icon: '✦',
href: function (e) { return e.agentId ? '/agent/' + encodeURIComponent(e.agentId) : '/discover'; },
- parts: function (e) { return [bold(e.name || e.actor || 'A new agent'), ' just deployed on-chain']; },
+ parts: function (e) { return [bold(e.name || e.actor || 'A new agent'), ' just joined three.ws']; },
+ },
+ 'agent-onchain': {
+ icon: '⛓',
+ href: function (e) { return e.agentId ? '/agent/' + encodeURIComponent(e.agentId) : '/discover'; },
+ parts: function (e) {
+ var who = bold(e.name || e.actor || 'An agent');
+ return e.chain ? [who, ' deployed on-chain on ', bold(e.chain)] : [who, ' just deployed on-chain'];
+ },
},
'level-up': {
icon: '⬆',
diff --git a/public/nav.css b/public/nav.css
index b4b94d0b6..4ef859c4c 100644
--- a/public/nav.css
+++ b/public/nav.css
@@ -104,6 +104,14 @@
@media (max-width: 1080px) {
.nav-search-label { display: none; }
.nav-search-hint { display: none; }
+ /* Collapse to a square icon button that matches the notifications bell,
+ instead of a wide pill wrapping a tiny off-balance icon. */
+ .nav-search-btn {
+ width: 36px; height: 36px; padding: 0;
+ justify-content: center; border-radius: 8px;
+ border-color: transparent;
+ }
+ .nav-search-ico { width: 16px; height: 16px; }
}
/* ── Notifications bell button ───────────────────────────────── */
diff --git a/public/studio/studio.css b/public/studio/studio.css
index fb0a18969..b06ef4654 100644
--- a/public/studio/studio.css
+++ b/public/studio/studio.css
@@ -524,7 +524,7 @@ a:hover {
align-items: center;
justify-content: center;
background: var(--accent);
- color: #fff;
+ color: #000;
border-radius: 50%;
font-size: 0.58rem;
font-weight: 800;
@@ -850,7 +850,7 @@ a:hover {
.studio-right-tab[aria-selected='true'] {
background: var(--accent);
- color: #fff;
+ color: #000;
}
.config-form {
@@ -963,14 +963,14 @@ a:hover {
.btn-primary {
background: var(--accent);
- color: #fff;
+ color: #000;
border-color: var(--accent);
box-shadow: 0 2px 12px rgba(255, 255, 255, 0.15);
}
.btn-primary:hover {
- background: var(--ink);
- border-color: var(--ink);
+ background: var(--accent-strong);
+ border-color: var(--accent-strong);
box-shadow: 0 4px 20px rgba(255, 255, 255, 0.25);
transform: translateY(-1px);
}
diff --git a/scripts/page-snapshot.mjs b/scripts/page-snapshot.mjs
new file mode 100644
index 000000000..096780974
--- /dev/null
+++ b/scripts/page-snapshot.mjs
@@ -0,0 +1,352 @@
+#!/usr/bin/env node
+/**
+ * page-snapshot.mjs — daily visual snapshot of every page on the site.
+ *
+ * Drives a real Chromium across every public page (sourced from data/pages.json,
+ * the same manifest that powers /sitemap, llms.txt and page-audit) in a desktop
+ * and a mobile viewport, and saves a full-page screenshot of each. The result is
+ * a complete picture of how the site looked on a given day — a design memory you
+ * can flip back to after any drastic change.
+ *
+ * ── Storage model: stable paths + git history as the time machine ─────────────
+ * Screenshots are written to STABLE filenames (snapshots/current/<viewport>/<slug>.jpg),
+ * overwritten on every run. Each day's `git commit` of snapshots/ is the archive:
+ *
+ * • Browse today: open snapshots/current/index.html
+ * • See a page's past: git log --follow -- snapshots/current/desktop/home.jpg
+ * • Recover any day: git checkout <sha> -- snapshots/current (or git show <sha>:<path> > old.jpg)
+ * • Export a full day: scripts/snapshot-export-day.sh <YYYY-MM-DD> (see that script)
+ *
+ * This keeps the working tree at ~one day's size (~tens of MB) while git history
+ * holds every prior day in full — no unbounded snapshots/<date>/ folder bloat.
+ *
+ * ── Target ────────────────────────────────────────────────────────────────────
+ * BASE_URL=https://three.ws (default — the live, deployed design)
+ * BASE_URL=http://localhost:3000 (vite/vercel dev)
+ *
+ * ── Usage ─────────────────────────────────────────────────────────────────────
+ * node scripts/page-snapshot.mjs # full snapshot, desktop + mobile
+ * node scripts/page-snapshot.mjs / /pay /ibm # only these routes
+ * node scripts/page-snapshot.mjs --desktop-only # skip the mobile viewport
+ * node scripts/page-snapshot.mjs --mobile-only # skip the desktop viewport
+ * node scripts/page-snapshot.mjs --concurrency 4 # parallel pages per viewport (default 3)
+ * node scripts/page-snapshot.mjs --settle 5000 # ms to wait after load for 3D/animations
+ * node scripts/page-snapshot.mjs --quality 80 # JPEG quality (default 72)
+ *
+ * Note: headless Chromium renders WebGL via SWANGLE/SwiftShader. Most 3D heroes
+ * render, but some heavy GPU scenes (and backdrop-filter) may come out dark. The
+ * full-page layout, type, copy and imagery are always captured faithfully — that
+ * is the design record. Raise --settle if a page's data loads slowly.
+ */
+import { chromium, devices } from 'playwright';
+import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, statSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const BASE_URL = (process.env.BASE_URL || 'https://three.ws').replace(/\/$/, '');
+const OUT_DIR = resolve(ROOT, 'snapshots/current');
+
+// ── CLI parsing ───────────────────────────────────────────────────────────────
+const argv = process.argv.slice(2);
+const flag = (name) => argv.includes(`--${name}`);
+const opt = (name, fallback) => {
+ const i = argv.indexOf(`--${name}`);
+ return i !== -1 && argv[i + 1] ? argv[i + 1] : fallback;
+};
+const DESKTOP_ONLY = flag('desktop-only');
+const MOBILE_ONLY = flag('mobile-only');
+const CONCURRENCY = Math.max(1, Number(opt('concurrency', 3)) || 3);
+const SETTLE_MS = Math.max(0, Number(opt('settle', 3500)) || 3500);
+const QUALITY = Math.min(100, Math.max(30, Number(opt('quality', 72)) || 72));
+const explicitRoutes = argv.filter((a) => a.startsWith('/'));
+
+// ── Route discovery ────────────────────────────────────────────────────────────
+// Public, user-discoverable pages from the manifest that drives /sitemap and
+// llms.txt — the single source of truth. Machine-readable endpoints (.xml/.txt/
+// .json, .well-known) and parameterised routes are skipped: they have no design.
+function manifestPages() {
+ const pages = JSON.parse(readFileSync(resolve(ROOT, 'data/pages.json'), 'utf8'));
+ const out = [];
+ const seen = new Set();
+ for (const s of pages.sections || []) {
+ if (s.id === 'machine') continue;
+ for (const p of s.pages || []) {
+ const path = p.path;
+ if (!path || !path.startsWith('/') || /[:*]/.test(path)) continue;
+ if (/\.(xml|txt|json)$/.test(path) || path.startsWith('/.well-known')) continue;
+ if (seen.has(path)) continue;
+ seen.add(path);
+ out.push({ path, title: p.title || path, section: s.title || s.id, auth: p.auth || null });
+ }
+ }
+ return out;
+}
+
+// Map a route to a filesystem-safe slug: '/' → 'home', '/docs/api' → 'docs-api'.
+function slugFor(path) {
+ if (path === '/') return 'home';
+ return path.replace(/^\//, '').replace(/\/$/, '').replace(/[^a-zA-Z0-9._-]+/g, '-') || 'home';
+}
+
+// ── Snapshot one route in one viewport ──────────────────────────────────────────
+async function snapshotRoute(ctx, page, route, viewport) {
+ const slug = slugFor(route);
+ const file = resolve(OUT_DIR, viewport, `${slug}.jpg`);
+ let navStatus = 0;
+ let title = '';
+ try {
+ const resp = await page
+ .goto(`${BASE_URL}${route}`, { waitUntil: 'networkidle', timeout: 45000 })
+ .catch(async () => {
+ // networkidle never settles on pages with long-poll/SSE — fall back.
+ return page.goto(`${BASE_URL}${route}`, { waitUntil: 'domcontentloaded', timeout: 45000 });
+ });
+ navStatus = resp ? resp.status() : 0;
+ } catch (e) {
+ return { route, viewport, slug, ok: false, navStatus, error: String(e).slice(0, 160) };
+ }
+ // Let data, fonts, lazy images and 3D scenes settle before the shot.
+ await page.waitForTimeout(SETTLE_MS);
+ await page.evaluate(() => window.scrollTo(0, 0)).catch(() => {});
+ title = (await page.title().catch(() => '')) || '';
+ mkdirSync(dirname(file), { recursive: true });
+ try {
+ await page.screenshot({ path: file, fullPage: true, type: 'jpeg', quality: QUALITY });
+ } catch {
+ // Some pages are taller than the GPU surface limit — clip to a tall viewport shot.
+ await page.screenshot({ path: file, fullPage: false, type: 'jpeg', quality: QUALITY });
+ }
+ const bytes = existsSync(file) ? statSync(file).size : 0;
+ return { route, viewport, slug, ok: bytes > 0, navStatus, title, bytes };
+}
+
+// Bounded-concurrency pool, one shared-context page per worker.
+async function runPool(ctx, routes, viewport, onResult) {
+ const queue = [...routes];
+ const results = [];
+ const worker = async () => {
+ const page = await ctx.newPage();
+ // Silence page console so a noisy site doesn't drown the run log.
+ page.on('console', () => {});
+ page.on('pageerror', () => {});
+ while (queue.length) {
+ const route = queue.shift();
+ const r = await snapshotRoute(ctx, page, route, viewport).catch((e) => ({
+ route,
+ viewport,
+ slug: slugFor(route),
+ ok: false,
+ error: String(e).slice(0, 160),
+ }));
+ results.push(r);
+ onResult(r);
+ }
+ await page.close();
+ };
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, routes.length) }, worker));
+ return results;
+}
+
+// ── Gallery (self-contained: data is inlined so file:// works without a server) ──
+function writeGallery(meta, byRoute) {
+ const data = {
+ capturedAt: meta.capturedAt,
+ date: meta.date,
+ baseUrl: meta.baseUrl,
+ viewports: meta.viewports,
+ pages: byRoute,
+ };
+ const html = `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>three.ws — site snapshot ${meta.date}</title>
+<style>
+ :root { --bg:#0a0a0b; --panel:#141416; --line:#26262b; --fg:#f4f4f5; --mut:#9a9aa3; --accent:#e8e8ea; }
+ * { box-sizing: border-box; }
+ body { margin:0; background:var(--bg); color:var(--fg); font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Inter,sans-serif; }
+ header { position:sticky; top:0; z-index:10; background:rgba(10,10,11,.85); backdrop-filter:blur(12px); border-bottom:1px solid var(--line); padding:18px 24px; display:flex; align-items:baseline; gap:16px; flex-wrap:wrap; }
+ header h1 { font-size:16px; margin:0; letter-spacing:-.01em; }
+ header .meta { color:var(--mut); font-size:13px; }
+ header .spacer { flex:1; }
+ .toggle { display:inline-flex; border:1px solid var(--line); border-radius:8px; overflow:hidden; }
+ .toggle button { background:transparent; color:var(--mut); border:0; padding:6px 14px; font:inherit; cursor:pointer; }
+ .toggle button[aria-pressed="true"] { background:var(--accent); color:#0a0a0b; font-weight:600; }
+ input[type=search] { background:var(--panel); border:1px solid var(--line); color:var(--fg); border-radius:8px; padding:7px 12px; font:inherit; min-width:220px; }
+ main { padding:24px; }
+ .section-title { color:var(--mut); text-transform:uppercase; letter-spacing:.08em; font-size:11px; margin:28px 0 12px; }
+ .grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(280px,1fr)); gap:18px; }
+ .card { background:var(--panel); border:1px solid var(--line); border-radius:12px; overflow:hidden; transition:border-color .15s, transform .15s; }
+ .card:hover { border-color:#3a3a42; transform:translateY(-2px); }
+ .card a.shot { display:block; aspect-ratio:16/10; overflow:hidden; background:#000; border-bottom:1px solid var(--line); }
+ .card a.shot img { width:100%; height:100%; object-fit:cover; object-position:top center; display:block; }
+ .card .body { padding:11px 13px; }
+ .card .t { font-weight:600; font-size:13px; margin:0 0 2px; }
+ .card .p { color:var(--mut); font-size:12px; font-family:ui-monospace,SFMono-Regular,Menlo,monospace; }
+ .card.missing a.shot { display:flex; align-items:center; justify-content:center; color:var(--mut); font-size:12px; aspect-ratio:16/10; }
+ .empty { color:var(--mut); padding:40px; text-align:center; }
+</style>
+</head>
+<body>
+<header>
+ <h1>three.ws site snapshot</h1>
+ <span class="meta" id="meta"></span>
+ <span class="spacer"></span>
+ <input type="search" id="q" placeholder="Filter pages…" aria-label="Filter pages" />
+ <div class="toggle" role="group" aria-label="Viewport">
+ <button id="vp-desktop" aria-pressed="true">Desktop</button>
+ <button id="vp-mobile" aria-pressed="false">Mobile</button>
+ </div>
+</header>
+<main id="main"></main>
+<script>
+const DATA = ${JSON.stringify(data)};
+let viewport = DATA.viewports.includes('desktop') ? 'desktop' : 'mobile';
+let query = '';
+const main = document.getElementById('main');
+document.getElementById('meta').textContent =
+ DATA.pages.length + ' pages · ' + DATA.baseUrl + ' · captured ' + new Date(DATA.capturedAt).toLocaleString();
+
+function bySection() {
+ const m = new Map();
+ for (const p of DATA.pages) {
+ if (query && !(p.path.toLowerCase().includes(query) || (p.title||'').toLowerCase().includes(query))) continue;
+ if (!m.has(p.section)) m.set(p.section, []);
+ m.get(p.section).push(p);
+ }
+ return m;
+}
+function render() {
+ const groups = bySection();
+ if (!groups.size) { main.innerHTML = '<div class="empty">No pages match "' + query + '".</div>'; return; }
+ let html = '';
+ for (const [section, pages] of groups) {
+ html += '<div class="section-title">' + section + ' · ' + pages.length + '</div><div class="grid">';
+ for (const p of pages) {
+ const shot = p.shots && p.shots[viewport];
+ const src = shot ? viewport + '/' + p.slug + '.jpg' : '';
+ html += '<div class="card' + (shot ? '' : ' missing') + '">'
+ + (shot
+ ? '<a class="shot" href="' + src + '" target="_blank" rel="noopener"><img loading="lazy" src="' + src + '" alt="' + (p.title||p.path) + '"></a>'
+ : '<a class="shot">not captured</a>')
+ + '<div class="body"><p class="t">' + (p.title||p.path) + '</p><p class="p">' + p.path + '</p></div></div>';
+ }
+ html += '</div>';
+ }
+ main.innerHTML = html;
+}
+function setVp(v) {
+ viewport = v;
+ document.getElementById('vp-desktop').setAttribute('aria-pressed', String(v==='desktop'));
+ document.getElementById('vp-mobile').setAttribute('aria-pressed', String(v==='mobile'));
+ render();
+}
+document.getElementById('vp-desktop').onclick = () => setVp('desktop');
+document.getElementById('vp-mobile').onclick = () => setVp('mobile');
+if (!DATA.viewports.includes('desktop')) document.getElementById('vp-desktop').disabled = true;
+if (!DATA.viewports.includes('mobile')) document.getElementById('vp-mobile').disabled = true;
+document.getElementById('q').oninput = (e) => { query = e.target.value.trim().toLowerCase(); render(); };
+render();
+</script>
+</body>
+</html>`;
+ writeFileSync(resolve(OUT_DIR, 'index.html'), html);
+}
+
+// ── Main ────────────────────────────────────────────────────────────────────────
+async function main() {
+ const pages = explicitRoutes.length
+ ? explicitRoutes.map((p) => ({ path: p, title: p, section: 'Selected', auth: null }))
+ : manifestPages();
+ // Public design record: skip auth-gated pages unless explicitly requested.
+ const targets = pages.filter((p) => explicitRoutes.length || !p.auth);
+ const routes = targets.map((p) => p.path);
+
+ const viewports = MOBILE_ONLY ? ['mobile'] : DESKTOP_ONLY ? ['desktop'] : ['desktop', 'mobile'];
+
+ // `date` is the local calendar day this run belongs to — stamped into the
+ // manifest and gallery so a committed set is self-describing.
+ const now = new Date();
+ const date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
+
+ console.log(`■ Snapshotting ${routes.length} pages at ${BASE_URL}`);
+ console.log(` viewports: ${viewports.join(', ')} · concurrency: ${CONCURRENCY} · settle: ${SETTLE_MS}ms · jpeg q${QUALITY}`);
+
+ // Clear stale shots so a removed/renamed page never lingers in the committed set.
+ for (const vp of viewports) {
+ const dir = resolve(OUT_DIR, vp);
+ if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
+ mkdirSync(dir, { recursive: true });
+ }
+
+ const browser = await chromium.launch({
+ args: [
+ '--no-sandbox',
+ '--disable-dev-shm-usage',
+ // Maximise the odds WebGL 3D heroes render under headless Chromium.
+ '--ignore-gpu-blocklist',
+ '--enable-unsafe-swiftshader',
+ '--use-gl=angle',
+ '--use-angle=swiftshader',
+ ],
+ });
+
+ const byRoute = new Map(targets.map((p) => [p.path, { ...p, slug: slugFor(p.path), shots: {} }]));
+ let done = 0;
+ const total = routes.length * viewports.length;
+
+ for (const viewport of viewports) {
+ const ctxOpts =
+ viewport === 'mobile'
+ ? { ...devices['iPhone 13'] }
+ : { viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 };
+ const ctx = await browser.newContext(ctxOpts);
+ ctx.setDefaultTimeout(45000);
+ console.log(`── ${viewport} ──`);
+ await runPool(ctx, routes, viewport, (r) => {
+ done++;
+ const entry = byRoute.get(r.route);
+ if (entry && r.ok) entry.shots[viewport] = { bytes: r.bytes, navStatus: r.navStatus };
+ const mark = r.ok ? '✓' : '✗';
+ const size = r.ok ? `${Math.round(r.bytes / 1024)}kb` : r.error || `HTTP ${r.navStatus}`;
+ console.log(` ${mark} [${String(done).padStart(3)}/${total}] ${viewport} ${r.route} ${size}`);
+ });
+ await ctx.close();
+ }
+ await browser.close();
+
+ // ── Manifest + gallery ──────────────────────────────────────────────────────
+ const pageList = [...byRoute.values()].map((p) => ({
+ path: p.path,
+ title: p.title,
+ section: p.section,
+ slug: p.slug,
+ shots: p.shots,
+ }));
+ const captured = pageList.filter((p) => Object.keys(p.shots).length).length;
+ const meta = {
+ capturedAt: now.toISOString(),
+ date,
+ baseUrl: BASE_URL,
+ viewports,
+ pageCount: pageList.length,
+ capturedCount: captured,
+ };
+ writeFileSync(resolve(OUT_DIR, 'manifest.json'), JSON.stringify({ ...meta, pages: pageList }, null, 2));
+ writeGallery(meta, pageList);
+
+ console.log(`\n■ Done. ${captured}/${pageList.length} pages captured for ${date}.`);
+ console.log(` Gallery: snapshots/current/index.html`);
+ console.log(` Manifest: snapshots/current/manifest.json`);
+ if (captured < pageList.length) {
+ const missing = pageList.filter((p) => !Object.keys(p.shots).length).map((p) => p.path);
+ console.log(` Missing: ${missing.join(', ')}`);
+ }
+}
+
+main().catch((e) => {
+ console.error(e);
+ process.exit(1);
+});
diff --git a/scripts/snapshot-export-day.sh b/scripts/snapshot-export-day.sh
new file mode 100755
index 000000000..52022f9b4
--- /dev/null
+++ b/scripts/snapshot-export-day.sh
@@ -0,0 +1,43 @@
+#!/usr/bin/env bash
+# snapshot-export-day.sh — recover a full daily snapshot set from git history.
+#
+# The daily snapshots live at stable paths (snapshots/current/) that are
+# overwritten each run, so the working tree only ever holds the latest day.
+# Every prior day is preserved in git history via that day's commit. This
+# script checks out the snapshot set as it existed on (or just before) a given
+# date and copies it to snapshots/exported/<date>/ so you can browse it.
+#
+# Usage: scripts/snapshot-export-day.sh 2026-06-05
+#
+set -euo pipefail
+
+DATE="${1:-}"
+if [[ -z "$DATE" ]]; then
+ echo "usage: $0 <YYYY-MM-DD>" >&2
+ exit 2
+fi
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "$ROOT"
+
+# Last commit that touched the snapshot set on or before end-of-day DATE.
+SHA="$(git log -1 --format=%H --before="${DATE} 23:59:59" -- snapshots/current || true)"
+if [[ -z "$SHA" ]]; then
+ echo "No snapshot commit found on or before ${DATE}." >&2
+ exit 1
+fi
+
+OUT="snapshots/exported/${DATE}"
+rm -rf "$OUT"
+mkdir -p "$OUT"
+
+# Materialise every snapshot file from that commit into the export dir.
+git ls-tree -r --name-only "$SHA" -- snapshots/current | while read -r path; do
+ rel="${path#snapshots/current/}"
+ mkdir -p "$OUT/$(dirname "$rel")"
+ git show "${SHA}:${path}" > "$OUT/$rel"
+done
+
+COMMIT_DATE="$(git show -s --format=%ci "$SHA")"
+echo "Exported snapshot from commit ${SHA:0:10} (${COMMIT_DATE})"
+echo " → ${OUT}/index.html"
diff --git a/snapshots/README.md b/snapshots/README.md
new file mode 100644
index 000000000..b24603cec
--- /dev/null
+++ b/snapshots/README.md
@@ -0,0 +1,45 @@
+# Site snapshots
+
+A daily visual record of how every page on three.ws looks, so we can always see
+what a page looked like before a drastic redesign.
+
+## Capture a snapshot
+
+```bash
+node scripts/page-snapshot.mjs # all public pages, desktop + mobile, against https://three.ws
+node scripts/page-snapshot.mjs --desktop-only
+node scripts/page-snapshot.mjs / /ibm /pay # just a few routes
+BASE_URL=http://localhost:3000 node scripts/page-snapshot.mjs # snapshot a local build
+```
+
+or `npm run snapshot`.
+
+Pages come from [`data/pages.json`](../data/pages.json) — the same manifest that
+drives `/sitemap`, `llms.txt`, and the page audit. Add a page there and it's
+snapshotted automatically. Auth-gated pages are skipped unless named explicitly.
+
+## How it's stored (and why)
+
+Screenshots are written to **stable paths** under `current/` and overwritten on
+every run:
+
+```
+current/
+ index.html ← open this: a browsable gallery of the latest set
+ manifest.json ← machine-readable index, stamped with the capture date
+ desktop/<slug>.jpg
+ mobile/<slug>.jpg
+```
+
+The **archive is git history**. Committing `snapshots/` each day captures that
+day; the working tree stays at ~one day's size instead of growing forever.
+
+- Browse today: open `current/index.html`
+- A page's history: `git log --follow -- snapshots/current/desktop/home.jpg`
+- Recover a past day: `scripts/snapshot-export-day.sh 2026-06-05`
+ (writes `exported/<date>/` — gitignored, just for viewing)
+
+## Daily run
+
+The capture script is wired and tested. The daily trigger (GitHub Action cron or
+a scheduled agent) is added separately once the output is confirmed.
diff --git a/snapshots/current/desktop/ibm.jpg b/snapshots/current/desktop/ibm.jpg
new file mode 100644
index 000000000..a7353e9d4
Binary files /dev/null and b/snapshots/current/desktop/ibm.jpg differ
diff --git a/snapshots/current/index.html b/snapshots/current/index.html
new file mode 100644
index 000000000..09be4e8cb
--- /dev/null
+++ b/snapshots/current/index.html
@@ -0,0 +1,95 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>three.ws — site snapshot 2026-06-05</title>
+<style>
+ :root { --bg:#0a0a0b; --panel:#141416; --line:#26262b; --fg:#f4f4f5; --mut:#9a9aa3; --accent:#e8e8ea; }
+ * { box-sizing: border-box; }
+ body { margin:0; background:var(--bg); color:var(--fg); font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Inter,sans-serif; }
+ header { position:sticky; top:0; z-index:10; background:rgba(10,10,11,.85); backdrop-filter:blur(12px); border-bottom:1px solid var(--line); padding:18px 24px; display:flex; align-items:baseline; gap:16px; flex-wrap:wrap; }
+ header h1 { font-size:16px; margin:0; letter-spacing:-.01em; }
+ header .meta { color:var(--mut); font-size:13px; }
+ header .spacer { flex:1; }
+ .toggle { display:inline-flex; border:1px solid var(--line); border-radius:8px; overflow:hidden; }
+ .toggle button { background:transparent; color:var(--mut); border:0; padding:6px 14px; font:inherit; cursor:pointer; }
+ .toggle button[aria-pressed="true"] { background:var(--accent); color:#0a0a0b; font-weight:600; }
+ input[type=search] { background:var(--panel); border:1px solid var(--line); color:var(--fg); border-radius:8px; padding:7px 12px; font:inherit; min-width:220px; }
+ main { padding:24px; }
+ .section-title { color:var(--mut); text-transform:uppercase; letter-spacing:.08em; font-size:11px; margin:28px 0 12px; }
+ .grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(280px,1fr)); gap:18px; }
+ .card { background:var(--panel); border:1px solid var(--line); border-radius:12px; overflow:hidden; transition:border-color .15s, transform .15s; }
+ .card:hover { border-color:#3a3a42; transform:translateY(-2px); }
+ .card a.shot { display:block; aspect-ratio:16/10; overflow:hidden; background:#000; border-bottom:1px solid var(--line); }
+ .card a.shot img { width:100%; height:100%; object-fit:cover; object-position:top center; display:block; }
+ .card .body { padding:11px 13px; }
+ .card .t { font-weight:600; font-size:13px; margin:0 0 2px; }
+ .card .p { color:var(--mut); font-size:12px; font-family:ui-monospace,SFMono-Regular,Menlo,monospace; }
+ .card.missing a.shot { display:flex; align-items:center; justify-content:center; color:var(--mut); font-size:12px; aspect-ratio:16/10; }
+ .empty { color:var(--mut); padding:40px; text-align:center; }
+</style>
+</head>
+<body>
+<header>
+ <h1>three.ws site snapshot</h1>
+ <span class="meta" id="meta"></span>
+ <span class="spacer"></span>
+ <input type="search" id="q" placeholder="Filter pages…" aria-label="Filter pages" />
+ <div class="toggle" role="group" aria-label="Viewport">
+ <button id="vp-desktop" aria-pressed="true">Desktop</button>
+ <button id="vp-mobile" aria-pressed="false">Mobile</button>
+ </div>
+</header>
+<main id="main"></main>
+<script>
+const DATA = {"capturedAt":"2026-06-05T08:31:41.751Z","date":"2026-06-05","baseUrl":"https://three.ws","viewports":["desktop"],"pages":[{"path":"/","title":"/","section":"Selected","slug":"home","shots":{}},{"path":"/ibm","title":"/ibm","section":"Selected","slug":"ibm","shots":{"desktop":{"bytes":700364,"navStatus":200}}},{"path":"/pay","title":"/pay","section":"Selected","slug":"pay","shots":{}},{"path":"/three-live","title":"/three-live","section":"Selected","slug":"three-live","shots":{}},{"path":"/docs","title":"/docs","section":"Selected","slug":"docs","shots":{}}]};
+let viewport = DATA.viewports.includes('desktop') ? 'desktop' : 'mobile';
+let query = '';
+const main = document.getElementById('main');
+document.getElementById('meta').textContent =
+ DATA.pages.length + ' pages · ' + DATA.baseUrl + ' · captured ' + new Date(DATA.capturedAt).toLocaleString();
+
+function bySection() {
+ const m = new Map();
+ for (const p of DATA.pages) {
+ if (query && !(p.path.toLowerCase().includes(query) || (p.title||'').toLowerCase().includes(query))) continue;
+ if (!m.has(p.section)) m.set(p.section, []);
+ m.get(p.section).push(p);
+ }
+ return m;
+}
+function render() {
+ const groups = bySection();
+ if (!groups.size) { main.innerHTML = '<div class="empty">No pages match "' + query + '".</div>'; return; }
+ let html = '';
+ for (const [section, pages] of groups) {
+ html += '<div class="section-title">' + section + ' · ' + pages.length + '</div><div class="grid">';
+ for (const p of pages) {
+ const shot = p.shots && p.shots[viewport];
+ const src = shot ? viewport + '/' + p.slug + '.jpg' : '';
+ html += '<div class="card' + (shot ? '' : ' missing') + '">'
+ + (shot
+ ? '<a class="shot" href="' + src + '" target="_blank" rel="noopener"><img loading="lazy" src="' + src + '" alt="' + (p.title||p.path) + '"></a>'
+ : '<a class="shot">not captured</a>')
+ + '<div class="body"><p class="t">' + (p.title||p.path) + '</p><p class="p">' + p.path + '</p></div></div>';
+ }
+ html += '</div>';
+ }
+ main.innerHTML = html;
+}
+function setVp(v) {
+ viewport = v;
+ document.getElementById('vp-desktop').setAttribute('aria-pressed', String(v==='desktop'));
+ document.getElementById('vp-mobile').setAttribute('aria-pressed', String(v==='mobile'));
+ render();
+}
+document.getElementById('vp-desktop').onclick = () => setVp('desktop');
+document.getElementById('vp-mobile').onclick = () => setVp('mobile');
+if (!DATA.viewports.includes('desktop')) document.getElementById('vp-desktop').disabled = true;
+if (!DATA.viewports.includes('mobile')) document.getElementById('vp-mobile').disabled = true;
+document.getElementById('q').oninput = (e) => { query = e.target.value.trim().toLowerCase(); render(); };
+render();
+</script>
+</body>
+</html>
\ No newline at end of file
diff --git a/snapshots/current/manifest.json b/snapshots/current/manifest.json
new file mode 100644
index 000000000..28d9ccb85
--- /dev/null
+++ b/snapshots/current/manifest.json
@@ -0,0 +1,52 @@
+{
+ "capturedAt": "2026-06-05T08:31:41.751Z",
+ "date": "2026-06-05",
+ "baseUrl": "https://three.ws",
+ "viewports": [
+ "desktop"
+ ],
+ "pageCount": 5,
+ "capturedCount": 1,
+ "pages": [
+ {
+ "path": "/",
+ "title": "/",
+ "section": "Selected",
+ "slug": "home",
+ "shots": {}
+ },
+ {
+ "path": "/ibm",
+ "title": "/ibm",
+ "section": "Selected",
+ "slug": "ibm",
+ "shots": {
+ "desktop": {
+ "bytes": 700364,
+ "navStatus": 200
+ }
+ }
+ },
+ {
+ "path": "/pay",
+ "title": "/pay",
+ "section": "Selected",
+ "slug": "pay",
+ "shots": {}
+ },
+ {
+ "path": "/three-live",
+ "title": "/three-live",
+ "section": "Selected",
+ "slug": "three-live",
+ "shots": {}
+ },
+ {
+ "path": "/docs",
+ "title": "/docs",
+ "section": "Selected",
+ "slug": "docs",
+ "shots": {}
+ }
+ ]
+}
\ No newline at end of file
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 4c736dc74..63dfd54ca 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -1258,7 +1258,12 @@ function normalize(rec, avatar) {
id: rec.id,
name: rec.name || 'Unnamed agent',
assetKind: rec.is_registered ? 'Core Asset' : 'Off-chain',
- active: !!rec.is_registered,
+ // "Active" is a liveness signal, NOT an on-chain one. An agent is live as
+ // long as it isn't an unpublished draft — off-chain agents are fully usable
+ // and must not read as dead. On-chain status is carried separately by the
+ // asset-kind label + the on-chain badge. `is_published` is only present in
+ // the owner view; public viewers (undefined) always see a live agent.
+ active: rec.is_published !== false,
avatar: avatar?.image_url || avatar?.thumbnail_url || avatar?.preview_url || null,
description: rec.description || '',
trust,
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 1be9e5c8b..ec03ca7ce 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -58,7 +58,13 @@ let selectedModelId = 'auto';
// Model choices surfaced in the chat dropdown. `auto` lets the server pick
// based on which keys are configured (Anthropic → OpenRouter → Groq → OpenAI).
const MODEL_OPTIONS = [
- { id: 'auto', label: 'Auto', provider: null, model: null },
+ { id: 'auto', label: 'Auto (GPT-OSS 120B)', provider: null, model: null },
+ {
+ id: 'openrouter:gpt-oss',
+ label: 'GPT-OSS 120B (free)',
+ provider: 'openrouter',
+ model: 'openai/gpt-oss-120b:free',
+ },
{ id: 'anthropic:sonnet', label: 'Claude Sonnet 4.6', provider: 'anthropic', model: 'claude-sonnet-4-6' },
{
id: 'openrouter:llama-70b',
@@ -66,12 +72,6 @@ const MODEL_OPTIONS = [
provider: 'openrouter',
model: 'meta-llama/llama-3.3-70b-instruct:free',
},
- {
- id: 'openrouter:gpt-oss',
- label: 'GPT-OSS 120B (free)',
- provider: 'openrouter',
- model: 'openai/gpt-oss-120b:free',
- },
{
id: 'openrouter:hermes',
label: 'Hermes 3 405B (free)',
diff --git a/src/brain.js b/src/brain.js
index b00241925..fdfb0fb76 100644
--- a/src/brain.js
+++ b/src/brain.js
@@ -4,6 +4,7 @@ import { sanitizeUrl } from './shared/sanitize-url.js';
// ── Provider registry ────────────────────────────────────────────────────────
const PROVIDERS = [
+ { key: 'gpt-oss-120b', label: 'GPT-OSS 120B', short: 'GPT-OSS', network: 'OpenAI · OpenRouter', color: '#a5b4fc', ctx: '128K', tier: 'Default' },
{ key: 'claude-opus-4-7', label: 'Claude Opus 4.7', short: 'Opus 4.7', network: 'Anthropic', color: '#c8a96e', ctx: '200K', tier: 'Flagship' },
{ key: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6', short: 'Sonnet 4.6', network: 'Anthropic', color: '#d4b87a', ctx: '200K', tier: 'Balanced' },
{ key: 'claude-haiku-4-5', label: 'Claude Haiku 4.5', short: 'Haiku 4.5', network: 'Anthropic', color: '#e0c88a', ctx: '200K', tier: 'Fast' },
@@ -54,8 +55,8 @@ const state = {
authed: isAuthedHint(),
playMode: 'compare',
- focusKey: 'groq-llama',
- active: new Set(['groq-llama', 'claude-sonnet-4-6', 'gpt-4o-mini', 'deepseek-r1']),
+ focusKey: 'gpt-oss-120b',
+ active: new Set(['gpt-oss-120b', 'groq-llama', 'claude-sonnet-4-6', 'gpt-4o-mini']),
sessions: [],
currentId: null,
streaming: false,
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 8694c351d..5cf465d39 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -22,7 +22,7 @@ import {
import { AnimationManager } from '../animation-manager.js';
import { CommunityNet } from './community-net.js';
import { CommunityUI } from './coincommunities-ui.js';
-import { createWorldEnvironment } from './world-env.js';
+import { createWorldEnvironment, seedFromString } from './world-env.js';
import { createChartScreen } from './chart-screen.js';
import { mountOracleRibbon } from './oracle-ribbon.js';
import { MarketReactor } from './market-reactor.js';
@@ -35,6 +35,7 @@ import {
import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';
import { HOME_TOWN, isHomeTown } from './home-town.js';
import { AgentCommerce } from './agent-commerce.js';
+import { WorldLife } from './npc/world-life.js';
import { VoiceChat, voiceSupported } from './voice-chat.js';
import { requestHolderPass, signInWithX, ensureSolanaWallet, relinkSolanaWallet, getSession } from '../community/town-auth.js';
import { ensurePlayAccess } from './play-gate.js';
@@ -794,6 +795,21 @@ export class CoinCommunities {
ui: this.ui,
});
}
+ // Living world (W08): ambient pedestrians + traffic, interactive vendor /
+ // quest / flavor NPCs, and (gated behind W07) hostile mobs — all on a
+ // deterministic nav graph so every client sees the same crowd without
+ // syncing it. Built for every world; the Agent Exchange above stays the
+ // home town's special NPC. Torn down in leave().
+ this.worldLife = new WorldLife({
+ scene: this.scene,
+ camera: this.camera,
+ renderer: this.renderer,
+ getPlayer: () => this.localPos,
+ ui: this.ui,
+ net: this.net,
+ world: { mint: coin.mint, seed: seedFromString(coin.mint) >>> 0, biome: this.env?.biome },
+ radius: WORLD_RADIUS - 4,
+ });
// Start the silent pass-refresh cycle. The play pass has a 10-min server
// TTL; the server sweeps expired passes every minute. We refresh 2 min early
// so a player in a long session is never evicted mid-build. The refresh
@@ -1007,6 +1023,7 @@ export class CoinCommunities {
if (this.net) { this.net.destroy(); this.net = null; }
if (this.playSystems) { this.playSystems.dispose(); this.playSystems = null; }
if (this.agentCommerce) { this.agentCommerce.dispose(); this.agentCommerce = null; }
+ if (this.worldLife) { this.worldLife.dispose(); this.worldLife = null; }
if (this._onboard) { this._onboard.dispose(); this._onboard = null; }
for (const [, r] of this.remotes) r.dispose();
this.remotes.clear();
@@ -1142,9 +1159,11 @@ export class CoinCommunities {
}
// E watches the Agent Exchange round when standing near the agents in
// the home town (no-op elsewhere). Not while building.
- if (k === 'e' && !this.buildHud.active && this.agentCommerce) {
+ if (k === 'e' && !this.buildHud.active) {
e.preventDefault();
- this.agentCommerce.interact();
+ // Talk to the nearest townsperson (vendor/quest/flavor); if none is
+ // in range, fall through to the home town's Agent Exchange.
+ if (!this.worldLife?.interact()) this.agentCommerce?.interact();
return;
}
// F casts a line when standing by a pond (no-op elsewhere). Not while
@@ -1191,6 +1210,7 @@ export class CoinCommunities {
if (this.phase === 'world' && this.buildHud.active) { this._buildAt(e.clientX, e.clientY, false); return; }
// Tap the agents (or their exchange ring) to watch a live payment — the
// touch-native equivalent of pressing E. Checked before the chart screen.
+ if (this.worldLife?.tryActivateAt(e.clientX, e.clientY)) return;
if (this.agentCommerce?.tryActivateAt(this._pointerRay(e.clientX, e.clientY))) return;
if (this._raycastScreen(e.clientX, e.clientY)) this._chartScreen.openExternal();
});
@@ -1474,6 +1494,7 @@ export class CoinCommunities {
this._updateVoice();
this.playSystems?.tick(dt);
this.agentCommerce?.tick(dt);
+ if (this.worldLife) { this.worldLife.setRealPeers(this.remotes.size); this.worldLife.tick(dt); }
if (this.net) this.net.sendMove({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z, yaw: this.localYaw, motion: this.motion });
}
this._tickEnv(dt);
diff --git a/src/game/community-net.js b/src/game/community-net.js
index daa15db6e..56988256b 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -129,6 +129,7 @@ export class CommunityNet {
xpgain: new Set(), // ({skill, amount, xp, level, levelXp, nextXp})
levelup: new Set(), // ({skill, level})
notice: new Set(), // ({kind, text, ...}) — activity result toast (fish/eat/tool/full)
+ combat: new Set(), // ({node, kind, mobHp, mobMaxHp, playerHp, playerMaxHp, dealt, dead, ...}) — combat-lite exchange
};
this.ping = null; // smoothed RTT in ms, null until the first echo
this._pingSentAt = 0; // perf-clock stamp of the last move awaiting an echo
@@ -241,6 +242,7 @@ export class CommunityNet {
this.room.onMessage('xpgain', (msg) => this._emit('xpgain', msg || {}));
this.room.onMessage('levelup', (msg) => this._emit('levelup', msg || {}));
this.room.onMessage('notice', (msg) => this._emit('notice', msg || {}));
+ this.room.onMessage('combat', (msg) => this._emit('combat', msg || {}));
const $ = getStateCallbacks(this.room);
const $state = $(this.room.state);
@@ -380,6 +382,10 @@ export class CommunityNet {
// Activities & economy. Server-authoritative: these only request the action; the
// result arrives via the profile/inv/xpgain/levelup/notice events above.
fish() { this.room?.send('fish'); }
+ chop() { this.room?.send('chop'); }
+ mine() { this.room?.send('mine'); }
+ cook() { this.room?.send('cook'); }
+ attack() { this.room?.send('attack'); }
equip(slot) { this.room?.send('equip', { slot }); }
consume(ref) { this.room?.send('consume', { slot: ref }); }
requestProfile() { this.room?.send('profileReq'); }
diff --git a/src/game/day-night.js b/src/game/day-night.js
new file mode 100644
index 000000000..add8213b6
--- /dev/null
+++ b/src/game/day-night.js
@@ -0,0 +1,120 @@
+// Day/night cycle — a real time-of-day that drives the sun, sky, fog and the
+// city's lights (W01: open-world foundation).
+//
+// world-env.js gives each biome a single, fixed sun. This module replaces that
+// frozen noon with a moving day: the sun rises in the east, arcs overhead and
+// sets in the west, the sky graduates night → dawn → day → dusk, fog closes in
+// after dark, and the district's windows and streetlamps come up at dusk. It is
+// driven by an authoritative world time the server broadcasts, so every client
+// in a world sees the EXACT same sky — two players always agree on whether it's
+// night.
+//
+// It owns no scene objects of its own: it reads the biome's daytime values as
+// the bright end of every range and writes through the handles world-env and the
+// district expose. `setTime(t)` takes a day fraction in [0, 1): 0 = midnight,
+// 0.25 = sunrise, 0.5 = noon, 0.75 = sunset.
+
+import { Color, MathUtils } from 'three';
+
+const TWO_PI = Math.PI * 2;
+
+// Sky keyframes for the dark and dusk ends; the bright end is the biome's own
+// `sky` palette, so midday still looks like the coin's world.
+const NIGHT_SKY = ['#05060f', '#0a0f24', '#16223c'];
+const DUSK_SKY = ['#1b2a52', '#6a4a72', '#e8995a'];
+const DAWN_WARM = new Color('#ff7a3a');
+
+function smoothstep(edge0, edge1, x) {
+ const t = Math.max(0, Math.min(1, (x - edge0) / (edge1 - edge0)));
+ return t * t * (3 - 2 * t);
+}
+
+function lerpHex(a, b, t, out) {
+ return out.set(a).lerp(typeof b === 'string' ? new Color(b) : b, t);
+}
+
+/**
+ * @param {object} env world-env handle exposing { biome, lights, setSky, setBaseSun, setBaseFog }
+ * @param {object} [district] district handle exposing setNight(k) (optional)
+ */
+export function createDayNightCycle(env, district = null) {
+ const biome = env.biome;
+ const { sunLight, sun, hemi, ambient } = env.lights;
+
+ // Bright-end (daytime) anchors, straight from the biome.
+ const dayHemi = biome.hemi[2];
+ const dayAmbient = biome.ambient;
+ const dayFogNear = biome.fogNear;
+ const dayFogFar = biome.fogFar;
+ const daySunI = biome.sun.intensity;
+ const biomeSunColor = new Color(biome.sun.color);
+ const azR = MathUtils.degToRad(biome.sun.azimuth);
+
+ // Scratch colours so setTime allocates nothing per frame.
+ const _sunC = new Color();
+ const _top = new Color(), _mid = new Color(), _hor = new Color();
+ const _fog = new Color();
+ let _lastSkyP = -1;
+
+ function setTime(t) {
+ const frac = ((t % 1) + 1) % 1; // wrap into [0,1)
+ const sunAngle = (frac - 0.25) * TWO_PI; // 0.25→sunrise, 0.5→noon, 0.75→sunset
+ const alt = Math.sin(sunAngle); // sun altitude, -1..1
+ const horiz = Math.cos(sunAngle); // east(+) … west(−)
+ const day = smoothstep(-0.10, 0.18, alt); // 0 night … 1 full day
+ const night = 1 - day;
+
+ // --- Sun position + colour ---------------------------------------------
+ sun.set(Math.cos(azR) * horiz, Math.max(alt, -0.25), Math.sin(azR) * horiz).normalize();
+ sunLight.position.copy(sun).multiplyScalar(120);
+ sunLight.target.position.set(0, 0, 0);
+ // Warm and dim near the horizon, neutral-bright high in the sky.
+ const warmth = Math.max(0, Math.min(1, 1 - alt * 1.8));
+ _sunC.copy(biomeSunColor).lerp(DAWN_WARM, warmth * 0.75);
+ sunLight.color.copy(_sunC);
+
+ // --- Light levels (biome bright end → a low, cool night) ----------------
+ env.setBaseSun(daySunI * day);
+ hemi.intensity = MathUtils.lerp(0.1, dayHemi, day);
+ ambient.intensity = MathUtils.lerp(0.05, dayAmbient, day);
+
+ // --- Fog: closes in and darkens after dark -----------------------------
+ env.setBaseFog(
+ MathUtils.lerp(dayFogNear * 0.55, dayFogNear, day),
+ MathUtils.lerp(dayFogFar * 0.6, dayFogFar, day),
+ );
+
+ // --- Sky gradient (throttled — only rebuild when it has shifted) --------
+ if (Math.abs(day - _lastSkyP) > 0.01) {
+ _lastSkyP = day;
+ if (day < 0.5) {
+ const k = day / 0.5; // night → dusk
+ lerpHex(NIGHT_SKY[0], DUSK_SKY[0], k, _top);
+ lerpHex(NIGHT_SKY[1], DUSK_SKY[1], k, _mid);
+ lerpHex(NIGHT_SKY[2], DUSK_SKY[2], k, _hor);
+ } else {
+ const k = (day - 0.5) / 0.5; // dusk → day (biome palette)
+ lerpHex(DUSK_SKY[0], biome.sky[0], k, _top);
+ lerpHex(DUSK_SKY[1], biome.sky[1], k, _mid);
+ lerpHex(DUSK_SKY[2], biome.sky[2], k, _hor);
+ }
+ _fog.copy(_hor);
+ env.setSky(
+ `#${_top.getHexString()}`,
+ `#${_mid.getHexString()}`,
+ `#${_hor.getHexString()}`,
+ `#${_fog.getHexString()}`,
+ );
+ }
+
+ // --- City lights -------------------------------------------------------
+ district?.setNight(night);
+
+ return { day, alt, night };
+ }
+
+ return {
+ setTime,
+ dispose() { /* owns no scene objects; handles belong to env/district */ },
+ };
+}
diff --git a/src/game/district.js b/src/game/district.js
new file mode 100644
index 000000000..e9e0700b6
--- /dev/null
+++ b/src/game/district.js
@@ -0,0 +1,264 @@
+// District — the drivable open-world block grid that turns the bare plaza into a
+// coherent little city (W01: open-world foundation).
+//
+// The original Downtown plaza (the centre circle the totem, market screens and
+// ponds live on) is kept clear; everything this module builds rings it: an
+// asphalt street grid, raised sidewalk blocks, building shells, streetlights and
+// planters, out to the district bounds. It's themeable per coin — colours are
+// pulled from the same biome palette world-env.js uses — and deterministic from
+// the coin's seed, so every client renders the IDENTICAL city (a requirement for
+// two players to agree on where the walls are).
+//
+// Performance is built in: buildings, sidewalks, streetlights and planters are
+// each a single InstancedMesh (one draw call apiece), geometry is shared, and the
+// whole grid is a few thousand triangles. The returned `colliders` feed the
+// shared Rapier PhysicsWorld so the buildings are solid; `setNight()` lets the
+// day/night cycle switch the windows and lamps on after dusk.
+
+import {
+ Group, Color, Object3D, Mesh,
+ InstancedMesh, BoxGeometry, CylinderGeometry, IcosahedronGeometry,
+ MeshStandardMaterial, MeshBasicMaterial,
+ Shape, Path, ShapeGeometry,
+ CanvasTexture, RepeatWrapping, SRGBColorSpace,
+} from 'three';
+
+import { DISTRICT } from './world-zones.js';
+
+// Deterministic LCG — identical seed → identical city on every client.
+function rng(seed) {
+ let s = (seed >>> 0) || 0x9e3779b9;
+ return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 0xffffffff; };
+}
+
+// A tiled facade: a dark wall with a grid of window cells, some lit. Used as both
+// the diffuse `map` (a believable building skin by day) and the `emissiveMap`
+// (only the bright window cells glow when the night intensity is raised), so a
+// whole skyline lights up at dusk for the cost of one shared texture.
+function facadeTexture(rand) {
+ const c = document.createElement('canvas');
+ c.width = 128; c.height = 128;
+ const x = c.getContext('2d');
+ x.fillStyle = '#23272f'; x.fillRect(0, 0, 128, 128);
+ const cols = 4, rows = 4, pad = 6, gap = 6;
+ const cw = (128 - pad * 2 - gap * (cols - 1)) / cols;
+ const ch = (128 - pad * 2 - gap * (rows - 1)) / rows;
+ for (let r = 0; r < rows; r++) {
+ for (let col = 0; col < cols; col++) {
+ // Window cells: mostly pale glass, ~1 in 4 dark (lights off / blind).
+ x.fillStyle = rand() > 0.25 ? '#cdd8e6' : '#3a3f49';
+ x.fillRect(pad + col * (cw + gap), pad + r * (ch + gap), cw, ch);
+ }
+ }
+ const tex = new CanvasTexture(c);
+ tex.colorSpace = SRGBColorSpace;
+ tex.wrapS = tex.wrapT = RepeatWrapping;
+ tex.repeat.set(2, 3);
+ return tex;
+}
+
+/**
+ * Build the district into `scene`.
+ * @param {import('three').Scene} scene
+ * @param {{ seed?: number, biome?: object, playRadius?: number }} opts
+ * @returns {{ root: Group, colliders: Array, setNight(k:number):void, dispose():void }}
+ */
+export function createDistrict(scene, { seed = 0, biome = {}, playRadius = DISTRICT.plazaRadius } = {}) {
+ const root = new Group();
+ root.name = 'district';
+ scene.add(root);
+
+ const rand = rng(seed);
+ const { half, blockSize, roadWidth } = DISTRICT;
+ const pitch = blockSize + roadWidth;
+ // Keep the grid clear of Downtown and its ring boulevard; a frontier town also
+ // rings the plaza, so leave it more room when the biome flags one.
+ const clearR = Math.max(playRadius + roadWidth + 6, biome.town ? 98 : playRadius + 14);
+ const colliders = [];
+
+ // --- Asphalt: a square slab with Downtown punched out so the plaza shows ----
+ const outer = new Shape();
+ outer.moveTo(-half, -half); outer.lineTo(half, -half);
+ outer.lineTo(half, half); outer.lineTo(-half, half); outer.lineTo(-half, -half);
+ const hole = new Path();
+ hole.absarc(0, 0, playRadius, 0, Math.PI * 2, true);
+ outer.holes.push(hole);
+ const asphalt = new Mesh(
+ new ShapeGeometry(outer),
+ new MeshStandardMaterial({ color: new Color(biome.grid || 0x2a2e36).multiplyScalar(0.5), roughness: 0.95, metalness: 0 }),
+ );
+ asphalt.rotation.x = -Math.PI / 2; asphalt.position.y = 0.006; asphalt.receiveShadow = true;
+ root.add(asphalt);
+
+ // --- Lane markings on the two main cross avenues ----------------------------
+ const laneMat = new MeshBasicMaterial({ color: 0xe8e2c8, transparent: true, opacity: 0.55 });
+ const laneGeo = new BoxGeometry(2.2, 0.02, 0.5);
+ const dashCount = Math.floor((half - playRadius) / 6);
+ const lanes = new InstancedMesh(laneGeo, laneMat, dashCount * 4);
+ {
+ const o = new Object3D();
+ let i = 0;
+ for (const axis of ['x', 'z']) {
+ for (const sign of [-1, 1]) {
+ for (let d = 0; d < dashCount; d++) {
+ const along = playRadius + 4 + d * 6;
+ if (axis === 'x') o.position.set(sign * along, 0.02, 0);
+ else { o.position.set(0, 0.02, sign * along); o.rotation.set(0, Math.PI / 2, 0); }
+ o.updateMatrix(); lanes.setMatrixAt(i++, o.matrix); o.rotation.set(0, 0, 0);
+ }
+ }
+ }
+ lanes.count = i;
+ }
+ root.add(lanes);
+
+ // --- Collect the block layout ----------------------------------------------
+ // Walk the grid; every cell whose centre clears Downtown and fits the bounds
+ // becomes a block: a raised sidewalk slab carrying 1–3 building shells.
+ const reach = Math.floor((half - blockSize / 2) / pitch);
+ const slabs = []; // { x, z }
+ const buildings = []; // { x, z, w, d, h, tint }
+ // Building palette tinted from the biome so each coin's city reads differently.
+ const tints = [
+ new Color(biome.plaza || 0x9aa0aa),
+ new Color(biome.hill || 0x8a909a).lerp(new Color(0x9aa6b6), 0.4),
+ new Color(biome.ground || 0x808890).lerp(new Color(0xb8c2d0), 0.5),
+ new Color(biome.ring || 0x6f8fbf).lerp(new Color(0xffffff), 0.35), // glass accent
+ ];
+ for (let gx = -reach; gx <= reach; gx++) {
+ for (let gz = -reach; gz <= reach; gz++) {
+ const cx = gx * pitch, cz = gz * pitch;
+ if (Math.hypot(cx, cz) < clearR) continue; // Downtown + boulevard
+ if (Math.max(Math.abs(cx), Math.abs(cz)) > half - blockSize / 2) continue; // bounds
+ slabs.push({ x: cx, z: cz });
+
+ // Taller toward the centre (a real skyline), shorter out in the wilds.
+ const distN = Math.min(1, Math.hypot(cx, cz) / half);
+ const count = 1 + Math.floor(rand() * 3); // 1..3 shells per block
+ const inset = 3.2; // sidewalk margin
+ const cell = (blockSize - inset * 2) / Math.ceil(Math.sqrt(count));
+ let placed = 0;
+ for (let k = 0; k < count; k++) {
+ const w = cell * (0.55 + rand() * 0.35);
+ const d = cell * (0.55 + rand() * 0.35);
+ const baseH = 8 + rand() * 16;
+ const h = baseH * (1.6 - distN) + (rand() > 0.82 ? 18 * (1.2 - distN) : 0);
+ // Offset within the block so shells don't all stack on the centre.
+ const ox = (rand() - 0.5) * (blockSize - inset * 2 - w);
+ const oz = (rand() - 0.5) * (blockSize - inset * 2 - d);
+ const bx = cx + ox, bz = cz + oz;
+ buildings.push({ x: bx, z: bz, w, d, h, tint: tints[Math.floor(rand() * tints.length)] });
+ placed++;
+ }
+ void placed;
+ }
+ }
+
+ // --- Sidewalk slabs (one draw call) -----------------------------------------
+ const slabMat = new MeshStandardMaterial({ color: new Color(biome.plaza || 0xc9c2b2).lerp(new Color(0x9a9a9a), 0.3), roughness: 1, metalness: 0 });
+ const slabGeo = new BoxGeometry(blockSize, 0.12, blockSize);
+ const slabMesh = new InstancedMesh(slabGeo, slabMat, slabs.length);
+ slabMesh.receiveShadow = true;
+ {
+ const o = new Object3D();
+ slabs.forEach((s, i) => { o.position.set(s.x, 0.06, s.z); o.updateMatrix(); slabMesh.setMatrixAt(i, o.matrix); });
+ }
+ root.add(slabMesh);
+
+ // --- Building shells (one draw call, per-instance tint + lit windows) -------
+ const facade = facadeTexture(rand);
+ const buildMat = new MeshStandardMaterial({
+ map: facade, emissiveMap: facade, emissive: new Color(0xffd9a0),
+ emissiveIntensity: 0, roughness: 0.82, metalness: 0.05,
+ });
+ const buildGeo = new BoxGeometry(1, 1, 1);
+ const buildMesh = new InstancedMesh(buildGeo, buildMat, buildings.length);
+ buildMesh.castShadow = true; buildMesh.receiveShadow = true;
+ {
+ const o = new Object3D();
+ buildings.forEach((b, i) => {
+ const cyl = 0.12 + b.h / 2; // sit on the sidewalk slab top
+ o.position.set(b.x, cyl, b.z);
+ o.scale.set(b.w, b.h, b.d);
+ o.rotation.set(0, 0, 0);
+ o.updateMatrix();
+ buildMesh.setMatrixAt(i, o.matrix);
+ buildMesh.setColorAt(i, b.tint);
+ colliders.push({
+ position: { x: b.x, y: cyl, z: b.z },
+ halfExtents: { x: b.w / 2, y: b.h / 2, z: b.d / 2 },
+ rotationY: 0,
+ });
+ });
+ }
+ if (buildMesh.instanceColor) buildMesh.instanceColor.needsUpdate = true;
+ root.add(buildMesh);
+
+ // --- Streetlights at the grid intersections (poles + glowing lamps) ---------
+ const lights = [];
+ for (let gx = -reach; gx <= reach; gx++) {
+ for (let gz = -reach; gz <= reach; gz++) {
+ const ix = gx * pitch + pitch / 2, iz = gz * pitch + pitch / 2;
+ if (Math.hypot(ix, iz) < clearR) continue;
+ if (Math.max(Math.abs(ix), Math.abs(iz)) > half - 2) continue;
+ lights.push({ x: ix, z: iz });
+ }
+ }
+ const poleMat = new MeshStandardMaterial({ color: 0x2b2f36, roughness: 0.7, metalness: 0.4 });
+ const poleGeo = new CylinderGeometry(0.12, 0.16, 5.2, 6);
+ const poleMesh = new InstancedMesh(poleGeo, poleMat, lights.length);
+ poleMesh.castShadow = true;
+ const lampMat = new MeshBasicMaterial({ color: 0xffe6b0 });
+ const lampGeo = new IcosahedronGeometry(0.28, 0);
+ const lampMesh = new InstancedMesh(lampGeo, lampMat, lights.length);
+ {
+ const o = new Object3D();
+ lights.forEach((p, i) => {
+ o.position.set(p.x, 2.6, p.z); o.updateMatrix(); poleMesh.setMatrixAt(i, o.matrix);
+ o.position.set(p.x, 5.3, p.z); o.updateMatrix(); lampMesh.setMatrixAt(i, o.matrix);
+ });
+ }
+ root.add(poleMesh, lampMesh);
+
+ // --- Planters dotted along the sidewalks (life + a touch of green) ----------
+ const planterMat = new MeshStandardMaterial({ color: new Color(biome.leafA || 0x4f8a49), roughness: 1, metalness: 0, flatShading: true });
+ const planterGeo = new IcosahedronGeometry(0.9, 0);
+ const planterMesh = new InstancedMesh(planterGeo, planterMat, slabs.length);
+ {
+ const o = new Object3D();
+ slabs.forEach((s, i) => {
+ const a = rand() * Math.PI * 2, rr = blockSize / 2 - 1.5;
+ o.position.set(s.x + Math.cos(a) * rr, 0.9, s.z + Math.sin(a) * rr);
+ o.scale.setScalar(0.7 + rand() * 0.5);
+ o.updateMatrix(); planterMesh.setMatrixAt(i, o.matrix); o.scale.setScalar(1);
+ });
+ }
+ planterMesh.castShadow = true;
+ root.add(planterMesh);
+
+ // The lamp glow as a baseline so it reads even before the cycle runs.
+ const baseLamp = 1;
+
+ return {
+ root,
+ colliders,
+ // Switch the city over to night. k = 0 (full day) … 1 (deep night): windows
+ // and streetlamps come up as k rises. Called by the day/night cycle.
+ setNight(k) {
+ const n = Math.max(0, Math.min(1, k));
+ buildMat.emissiveIntensity = n * 1.15;
+ lampMat.color.setRGB(1, 0.9, 0.7).multiplyScalar(baseLamp * (0.35 + n * 0.65));
+ },
+ dispose() {
+ scene.remove(root);
+ facade.dispose();
+ root.traverse((o) => {
+ if (o.isMesh || o.isInstancedMesh) {
+ o.geometry?.dispose?.();
+ const ms = Array.isArray(o.material) ? o.material : [o.material];
+ for (const m of ms) m?.dispose?.();
+ }
+ });
+ },
+ };
+}
diff --git a/src/game/hud/camera-rig.js b/src/game/hud/camera-rig.js
new file mode 100644
index 000000000..0b73cb655
--- /dev/null
+++ b/src/game/hud/camera-rig.js
@@ -0,0 +1,168 @@
+// CameraRig — the third-person camera for /play, upgraded into a proper GTA-style
+// rig: smooth collision-aware follow, a vehicle chase cam, an over-the-shoulder
+// aim cam, an optional first-person toggle, FOV kick on speed/sprint, and a
+// trauma-based shake for impacts. Modes blend automatically because every mode
+// just retargets the same eased params (distance / height / shoulder / fov), so
+// switching cameras is a smooth interpolation, never a cut.
+//
+// The host owns the *input* yaw/pitch/dist (drag + wheel, also used for movement
+// basis); the rig eases its own *render* yaw/pitch/dist toward those and writes
+// the final transform onto the three camera each frame.
+
+import { Vector3, Raycaster } from 'three';
+
+const MODES = {
+ follow: { distMul: 1.0, height: 1.45, shoulder: 0.0, fov: 0, posLerp: 0.16, lookHeight: 1.4 },
+ vehicle: { distMul: 1.55, height: 2.0, shoulder: 0.0, fov: 6, posLerp: 0.10, lookHeight: 1.2 },
+ aim: { distMul: 0.55, height: 1.55, shoulder: 0.65, fov: -8, posLerp: 0.28, lookHeight: 1.5 },
+ first: { distMul: 0.0, height: 0.0, shoulder: 0.0, fov: 4, posLerp: 0.5, lookHeight: 0.0 },
+};
+
+const lerp = (a, b, t) => a + (b - a) * t;
+
+export class CameraRig {
+ constructor(camera, { baseFov = 50 } = {}) {
+ this.camera = camera;
+ this.baseFov = baseFov;
+ this.mode = 'follow';
+ this._prevMode = 'follow'; // mode to fall back to when leaving first-person
+ // Eased render state.
+ this.yaw = 0.6; this.pitch = 0.5; this.dist = 9;
+ this.fov = baseFov;
+ this._pos = new Vector3();
+ this._look = new Vector3();
+ this._inited = false;
+ // FOV kick + shake.
+ this._fovKick = 0;
+ this._trauma = 0; // 0..1, decays each frame; shake ∝ trauma²
+ this._shakeT = 0;
+ this._ray = new Raycaster();
+ this._dir = new Vector3();
+ this._desired = new Vector3();
+ }
+
+ setMode(mode) {
+ if (!MODES[mode] || mode === this.mode) return;
+ if (this.mode !== 'first') this._prevMode = this.mode;
+ this.mode = mode;
+ }
+
+ // First-person toggle (V): drop into the eyes, or back to the prior chase cam.
+ toggleFirstPerson() { this.setMode(this.mode === 'first' ? this._prevMode : 'first'); }
+ isFirstPerson() { return this.mode === 'first'; }
+
+ // Add camera trauma (0..1). Stacks; decays in update(). Use for damage, hard
+ // landings, explosions — the game-feel layer calls this.
+ shake(amount = 0.4) { this._trauma = Math.min(1, this._trauma + amount); }
+
+ /**
+ * @param {number} dt
+ * @param {object} ctx
+ * @param {{x,y,z}} ctx.target avatar ground position
+ * @param {number} ctx.yaw input yaw (camera orbit)
+ * @param {number} ctx.pitch input pitch
+ * @param {number} ctx.dist input distance
+ * @param {number} [ctx.speed] current move speed (m/s) for FOV kick
+ * @param {boolean} [ctx.sprinting]
+ * @param {number} [ctx.headHeight] avatar head height (m)
+ * @param {Object3D[]} [ctx.colliders] meshes the camera shouldn't clip through
+ * @param {number} [ctx.autoYaw] when set (vehicles), bias yaw to trail heading
+ */
+ update(dt, ctx) {
+ const m = MODES[this.mode];
+ const head = ctx.headHeight || 1.7;
+ // Snap on first frame so we don't sling in from the origin.
+ const k = this._inited ? 1 - Math.pow(1 - m.posLerp, Math.max(1, dt * 60)) : 1;
+
+ // Vehicles gently trail behind the heading unless the player is steering the
+ // camera; the host supplies autoYaw as the vehicle's facing.
+ let targetYaw = ctx.yaw;
+ if (ctx.autoYaw != null && this.mode === 'vehicle') {
+ let d = ctx.autoYaw - this.yaw;
+ while (d > Math.PI) d -= Math.PI * 2;
+ while (d < -Math.PI) d += Math.PI * 2;
+ targetYaw = this.yaw + d * 0.04;
+ }
+ this.yaw = this._inited ? this.yaw + shortestArc(this.yaw, targetYaw) * k : targetYaw;
+ this.pitch = this._inited ? lerp(this.pitch, ctx.pitch, k) : ctx.pitch;
+ const wantDist = (ctx.dist || 9) * m.distMul;
+ this.dist = this._inited ? lerp(this.dist, wantDist, k) : wantDist;
+
+ // Eased look target at the avatar's chest/head.
+ const tx = ctx.target.x, ty = ctx.target.y, tz = ctx.target.z;
+ const cp = Math.cos(this.pitch), sp = Math.sin(this.pitch);
+ const fwdX = Math.sin(this.yaw), fwdZ = Math.cos(this.yaw);
+ const rightX = Math.cos(this.yaw), rightZ = -Math.sin(this.yaw);
+
+ // Desired eye position behind + above the target, offset to the shoulder.
+ const ox = fwdX * cp * this.dist - rightX * m.shoulder;
+ const oz = fwdZ * cp * this.dist - rightZ * m.shoulder;
+ const oy = sp * this.dist + m.height;
+ this._desired.set(tx - ox, ty + oy, tz - oz);
+
+ // Collision: pull the camera in if a wall/building sits between it and the
+ // head, so the chase cam never clips into geometry. One ray, cheap.
+ const originX = tx, originY = ty + head * 0.9, originZ = tz;
+ if (this.mode !== 'first' && ctx.colliders && ctx.colliders.length) {
+ this._dir.set(this._desired.x - originX, this._desired.y - originY, this._desired.z - originZ);
+ const want = this._dir.length();
+ if (want > 0.01) {
+ this._dir.multiplyScalar(1 / want);
+ this._ray.set({ x: originX, y: originY, z: originZ }, this._dir);
+ this._ray.far = want;
+ const hits = this._ray.intersectObjects(ctx.colliders, true);
+ if (hits.length) {
+ const safe = Math.max(0.6, hits[0].distance - 0.35);
+ this._desired.set(originX + this._dir.x * safe, originY + this._dir.y * safe, originZ + this._dir.z * safe);
+ }
+ }
+ }
+
+ if (!this._inited) { this._pos.copy(this._desired); this._inited = true; }
+ else this._pos.lerp(this._desired, k);
+
+ // Look point: ahead of the eyes in first-person, at the avatar otherwise.
+ if (this.mode === 'first') {
+ const ex = tx, ey = ty + head * 0.94, ez = tz;
+ this._pos.set(ex + fwdX * 0.12, ey, ez + fwdZ * 0.12);
+ this._look.set(ex + fwdX * cp, ey - sp, ez + fwdZ * cp);
+ } else {
+ const lookTarget = this._tmpLook || (this._tmpLook = new Vector3());
+ lookTarget.set(tx + rightX * m.shoulder, ty + m.lookHeight, tz + rightZ * m.shoulder);
+ if (this._inited) this._look.lerp(lookTarget, k);
+ else this._look.copy(lookTarget);
+ }
+
+ // FOV: base + per-mode bias + a speed/sprint kick, all eased.
+ const speed = ctx.speed || 0;
+ const kickTarget = m.fov + (ctx.sprinting ? 4 : 0) + Math.min(10, speed * 0.7);
+ this._fovKick = lerp(this._fovKick, kickTarget, 1 - Math.pow(0.001, dt));
+ this.fov = this.baseFov + this._fovKick;
+
+ // Trauma shake: decays fast; offsets position + a roll, scaled by trauma².
+ let shakeX = 0, shakeY = 0, roll = 0;
+ if (this._trauma > 0.0001) {
+ this._trauma = Math.max(0, this._trauma - dt * 1.6);
+ this._shakeT += dt * 40;
+ const s = this._trauma * this._trauma;
+ shakeX = Math.sin(this._shakeT * 1.7) * s * 0.5;
+ shakeY = Math.sin(this._shakeT * 2.3 + 1.3) * s * 0.5;
+ roll = Math.sin(this._shakeT * 1.1) * s * 0.05;
+ }
+
+ this.camera.position.set(this._pos.x + rightX * shakeX, this._pos.y + shakeY, this._pos.z + rightZ * shakeX);
+ this.camera.lookAt(this._look.x, this._look.y, this._look.z);
+ if (roll) this.camera.rotateZ(roll);
+ if (Math.abs(this.camera.fov - this.fov) > 0.01) { this.camera.fov = this.fov; this.camera.updateProjectionMatrix(); }
+ }
+
+ reset() { this._inited = false; this._trauma = 0; this._fovKick = 0; }
+}
+
+// Smallest signed angular step a→b, wrapped to (−π, π].
+function shortestArc(a, b) {
+ let d = b - a;
+ while (d > Math.PI) d -= Math.PI * 2;
+ while (d < -Math.PI) d += Math.PI * 2;
+ return d;
+}
diff --git a/src/game/hud/game-feel.css b/src/game/hud/game-feel.css
new file mode 100644
index 000000000..4fb27b504
--- /dev/null
+++ b/src/game/hud/game-feel.css
@@ -0,0 +1,88 @@
+/* GameFeel — full-screen feedback overlays + floating chips. Non-interactive. */
+
+.wh-feel {
+ position: fixed;
+ inset: 0;
+ z-index: 55;
+ pointer-events: none;
+ overflow: hidden;
+}
+
+/* Damage vignette: red edges that flare then fade. --feel-vig scales intensity. */
+.wh-feel-vignette {
+ --feel-vig: 0.6;
+ position: absolute;
+ inset: 0;
+ opacity: 0;
+ box-shadow: inset 0 0 140px 30px rgba(190, 20, 20, 0.85);
+ background: radial-gradient(ellipse at center, transparent 56%, rgba(150, 10, 10, 0.35) 100%);
+}
+.wh-feel-vignette.is-hit { animation: wh-feel-hit 0.5s ease-out; }
+@keyframes wh-feel-hit {
+ 0% { opacity: 0; }
+ 18% { opacity: var(--feel-vig); }
+ 100% { opacity: 0; }
+}
+
+/* Screen flash. */
+.wh-feel-flash {
+ position: absolute;
+ inset: 0;
+ opacity: 0;
+ background: rgba(255, 255, 255, 0.5);
+}
+.wh-feel-flash.is-on { animation: wh-feel-flash 0.32s ease-out; }
+@keyframes wh-feel-flash { 0% { opacity: 0.7; } 100% { opacity: 0; } }
+
+/* Floating money chip. */
+.wh-feel-money {
+ position: fixed;
+ z-index: 56;
+ transform: translate(-50%, 0);
+ font: 800 16px/1 ui-sans-serif, system-ui, sans-serif;
+ font-variant-numeric: tabular-nums;
+ text-shadow: 0 2px 6px rgba(0, 0, 0, 0.8);
+ pointer-events: none;
+ opacity: 0;
+ transition: transform 1s cubic-bezier(0.1, 0.7, 0.2, 1), opacity 1s ease;
+}
+.wh-feel-money.is-up { color: #8effa6; }
+.wh-feel-money.is-down { color: #ff9b9b; }
+.wh-feel-money.is-go { opacity: 1; transform: translate(-50%, -34px); }
+
+/* Level-up / achievement flourish. */
+.wh-feel-flourish {
+ position: fixed;
+ left: 50%;
+ top: 38%;
+ z-index: 57;
+ transform: translate(-50%, -50%) scale(0.86);
+ text-align: center;
+ padding: 14px 30px;
+ border-radius: var(--cc-radius, 4px);
+ background: var(--cc-panel, rgba(12, 12, 14, 0.82));
+ border: 1px solid var(--cc-edge-hi, rgba(255, 255, 255, 0.5));
+ box-shadow: var(--cc-glow, 0 0 14px rgba(255, 255, 255, 0.35)), var(--cc-shadow, 0 16px 50px rgba(0, 0, 0, 0.7));
+ -webkit-backdrop-filter: blur(10px);
+ backdrop-filter: blur(10px);
+ opacity: 0;
+ pointer-events: none;
+}
+.wh-feel-flourish.is-show { animation: wh-feel-flourish 0.42s cubic-bezier(0.2, 0.9, 0.25, 1) forwards; }
+@keyframes wh-feel-flourish {
+ from { opacity: 0; transform: translate(-50%, -50%) scale(0.86); }
+ to { opacity: 1; transform: translate(-50%, -50%) scale(1); }
+}
+.wh-feel-flourish:not(.is-show) { transition: opacity 0.4s ease, transform 0.4s ease; }
+.wh-feel-flourish-title {
+ font: 800 22px/1.1 ui-sans-serif, system-ui, sans-serif;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--cc-text, #fff);
+}
+.wh-feel-flourish-sub { margin-top: 4px; font-size: 14px; color: var(--cc-dim, #9a9aa2); }
+
+@media (prefers-reduced-motion: reduce) {
+ .wh-feel-vignette.is-hit, .wh-feel-flash.is-on, .wh-feel-flourish.is-show { animation-duration: 0.01s; }
+ .wh-feel-money { transition: opacity 0.3s ease; }
+}
diff --git a/src/game/hud/game-feel.js b/src/game/hud/game-feel.js
new file mode 100644
index 000000000..31fca16e8
--- /dev/null
+++ b/src/game/hud/game-feel.js
@@ -0,0 +1,151 @@
+// GameFeel — the polish layer: screen feedback (damage vignette, money pops,
+// level-up flourish, hit flash), a tiny procedural WebAudio SFX kit (no asset
+// files — synthesised envelopes), and haptics. Other systems call into it so the
+// world *feels* responsive: the HUD pops cash, the camera rig shakes, menus tick.
+//
+// Audio is opt-in-safe: the AudioContext is created lazily on the first real
+// gesture and respects a persisted mute toggle. Everything degrades silently
+// where a capability is missing (no vibrate, no WebAudio).
+
+import './game-feel.css';
+
+const MUTE_KEY = 'wh-sfx-muted';
+
+export class GameFeel {
+ constructor() {
+ this._muted = (() => { try { return localStorage.getItem(MUTE_KEY) === '1'; } catch { return false; } })();
+ this._ctx = null;
+ this._master = null;
+ this._buildOverlay();
+ // Unlock audio on the first gesture so menu ticks aren't swallowed by the
+ // browser autoplay policy.
+ const unlock = () => { this._ensureAudio(); window.removeEventListener('pointerdown', unlock); window.removeEventListener('keydown', unlock); };
+ window.addEventListener('pointerdown', unlock, { once: true });
+ window.addEventListener('keydown', unlock, { once: true });
+ }
+
+ _buildOverlay() {
+ const o = document.createElement('div');
+ o.className = 'wh-feel';
+ o.setAttribute('aria-hidden', 'true');
+ this.vignette = document.createElement('div'); this.vignette.className = 'wh-feel-vignette';
+ this.flash = document.createElement('div'); this.flash.className = 'wh-feel-flash';
+ o.append(this.vignette, this.flash);
+ document.body.appendChild(o);
+ this.root = o;
+ }
+
+ // ------------------------------------------------------------------- audio
+ _ensureAudio() {
+ if (this._ctx || this._muted) return this._ctx;
+ const AC = window.AudioContext || window.webkitAudioContext;
+ if (!AC) return null;
+ try {
+ this._ctx = new AC();
+ this._master = this._ctx.createGain();
+ this._master.gain.value = 0.18;
+ this._master.connect(this._ctx.destination);
+ } catch { this._ctx = null; }
+ return this._ctx;
+ }
+
+ setMuted(m) {
+ this._muted = !!m;
+ try { localStorage.setItem(MUTE_KEY, this._muted ? '1' : '0'); } catch { /* ignore */ }
+ if (this._master) this._master.gain.value = this._muted ? 0 : 0.18;
+ }
+ isMuted() { return this._muted; }
+
+ // One synthesised blip. `type` shapes a short envelope; tuned to feel like a
+ // clean UI kit rather than a beep.
+ sfx(type = 'select') {
+ if (this._muted) return;
+ const ctx = this._ensureAudio();
+ if (!ctx) return;
+ if (ctx.state === 'suspended') ctx.resume().catch(() => {});
+ const now = ctx.currentTime;
+ const voices = {
+ open: { f: 520, f2: 720, dur: 0.12, wave: 'sine', gain: 0.5 },
+ select: { f: 660, f2: 660, dur: 0.05, wave: 'square', gain: 0.28 },
+ confirm: { f: 540, f2: 880, dur: 0.16, wave: 'triangle', gain: 0.6 },
+ back: { f: 420, f2: 300, dur: 0.1, wave: 'sine', gain: 0.4 },
+ error: { f: 200, f2: 150, dur: 0.18, wave: 'sawtooth', gain: 0.4 },
+ cash: { f: 880, f2: 1320, dur: 0.14, wave: 'triangle', gain: 0.5 },
+ level: { f: 660, f2: 1320, dur: 0.32, wave: 'triangle', gain: 0.7 },
+ damage: { f: 160, f2: 90, dur: 0.22, wave: 'sawtooth', gain: 0.55 },
+ tick: { f: 1200, f2: 1200, dur: 0.025, wave: 'square', gain: 0.18 },
+ };
+ const v = voices[type] || voices.select;
+ const osc = ctx.createOscillator();
+ const g = ctx.createGain();
+ osc.type = v.wave;
+ osc.frequency.setValueAtTime(v.f, now);
+ osc.frequency.exponentialRampToValueAtTime(Math.max(40, v.f2), now + v.dur);
+ g.gain.setValueAtTime(0.0001, now);
+ g.gain.exponentialRampToValueAtTime(v.gain, now + 0.008);
+ g.gain.exponentialRampToValueAtTime(0.0001, now + v.dur);
+ osc.connect(g); g.connect(this._master);
+ osc.start(now); osc.stop(now + v.dur + 0.02);
+ }
+
+ // ----------------------------------------------------------------- haptics
+ haptic(pattern = 12) {
+ try { if (navigator.vibrate) navigator.vibrate(pattern); } catch { /* ignore */ }
+ }
+
+ // ---------------------------------------------------------------- feedback
+ // Red edge-vignette pulse for taking damage. `intensity` 0..1.
+ damage(intensity = 0.6) {
+ const v = Math.max(0.15, Math.min(1, intensity));
+ this.vignette.style.setProperty('--feel-vig', String(v));
+ this.vignette.classList.remove('is-hit');
+ void this.vignette.offsetWidth;
+ this.vignette.classList.add('is-hit');
+ this.sfx('damage');
+ this.haptic([18, 30, 18]);
+ }
+
+ // Quick white screen flash (pickup, teleport, photo).
+ flashScreen(color = 'rgba(255,255,255,0.5)') {
+ this.flash.style.background = color;
+ this.flash.classList.remove('is-on');
+ void this.flash.offsetWidth;
+ this.flash.classList.add('is-on');
+ }
+
+ // Floating "+$120" / "−$40" near an anchor element (the cash readout).
+ moneyPop(delta, anchorEl) {
+ const d = Math.round(Number(delta) || 0);
+ if (!d) return;
+ const chip = document.createElement('div');
+ chip.className = 'wh-feel-money ' + (d > 0 ? 'is-up' : 'is-down');
+ chip.textContent = (d > 0 ? '+$' : '−$') + Math.abs(d).toLocaleString();
+ const r = anchorEl?.getBoundingClientRect();
+ if (r) { chip.style.left = `${r.left + r.width / 2}px`; chip.style.top = `${r.bottom + 4}px`; }
+ else { chip.style.right = '16px'; chip.style.top = '140px'; }
+ document.body.appendChild(chip);
+ requestAnimationFrame(() => chip.classList.add('is-go'));
+ setTimeout(() => chip.remove(), 1100);
+ this.sfx('cash');
+ }
+
+ // Center-screen level-up / achievement flourish.
+ flourish(title, sub = '') {
+ const card = document.createElement('div');
+ card.className = 'wh-feel-flourish';
+ const t = document.createElement('div'); t.className = 'wh-feel-flourish-title'; t.textContent = title;
+ card.appendChild(t);
+ if (sub) { const s = document.createElement('div'); s.className = 'wh-feel-flourish-sub'; s.textContent = sub; card.appendChild(s); }
+ document.body.appendChild(card);
+ requestAnimationFrame(() => card.classList.add('is-show'));
+ setTimeout(() => { card.classList.remove('is-show'); setTimeout(() => card.remove(), 420); }, 2200);
+ this.sfx('level');
+ this.haptic([10, 40, 10, 40, 20]);
+ }
+
+ dispose() {
+ this.root?.remove();
+ document.querySelectorAll('.wh-feel-money, .wh-feel-flourish').forEach((n) => n.remove());
+ try { this._ctx?.close(); } catch { /* ignore */ }
+ }
+}
diff --git a/src/game/hud/index.js b/src/game/hud/index.js
new file mode 100644
index 000000000..09aab3f8f
--- /dev/null
+++ b/src/game/hud/index.js
@@ -0,0 +1,134 @@
+// WorldHudSystem — the W10 layer composed into one object the /play client owns.
+//
+// It bundles the unified HUD (cash/health/wanted/objective/minimap/speedo), the
+// camera rig (follow/vehicle/aim/first-person + collision + shake), the radial
+// interaction menu ("M") and weapon/emote wheels, and the game-feel layer
+// (vignette/money pops/flourish/SFX/haptics) — and wires the menus to real host
+// actions. Sibling briefs push data through `system.hud`; the host drives the
+// camera + minimap each frame and routes input through the open-menu guards.
+
+import { WorldHud } from './world-hud.js';
+import { CameraRig } from './camera-rig.js';
+import { GameFeel } from './game-feel.js';
+import { RadialMenu } from './radial-menu.js';
+
+export class WorldHudSystem {
+ /**
+ * @param {import('three').PerspectiveCamera} camera
+ * @param {object} opts
+ * @param {object} opts.actions host action callbacks (only wired items appear)
+ * @param {() => Array} [opts.getEmotes] () => [{ name, icon, label }]
+ * @param {() => Array} [opts.getHotbar] () => [{ slot, glyph, name, qty, active, empty }]
+ */
+ constructor(camera, { actions = {}, getEmotes, getHotbar } = {}) {
+ this.actions = actions;
+ this.getEmotes = getEmotes || (() => []);
+ this.getHotbar = getHotbar || (() => []);
+
+ this.feel = new GameFeel();
+ this.hud = new WorldHud();
+ this.camera = new CameraRig(camera, { baseFov: camera.fov });
+
+ // One radial component per role. They share chrome but differ in open style.
+ this.interaction = new RadialMenu({
+ id: 'wh-interaction', title: 'Interaction', mode: 'toggle',
+ onSelect: (it) => { this.feel.sfx('confirm'); it.action?.(); },
+ onClose: () => this.feel.sfx('back'),
+ });
+ this.weaponWheel = new RadialMenu({
+ id: 'wh-weapon', title: 'Weapons', mode: 'hold',
+ onSelect: (it) => { this.feel.sfx('confirm'); it.action?.(); },
+ });
+ this.emoteWheel = new RadialMenu({
+ id: 'wh-emotes', title: 'Emotes', mode: 'hold',
+ onSelect: (it) => { this.feel.sfx('confirm'); it.action?.(); },
+ });
+
+ // Tick a soft SFX as focus moves across any wheel.
+ for (const menu of [this.interaction, this.weaponWheel, this.emoteWheel]) {
+ const orig = menu._setFocus.bind(menu);
+ menu._setFocus = (i) => { if (i !== menu.focus && i >= 0) this.feel.sfx('tick'); orig(i); };
+ }
+ }
+
+ // --------------------------------------------------------------- menu state
+ isInteractionOpen() { return this.interaction.isOpen; }
+ isWheelOpen() { return this.weaponWheel.isOpen || this.emoteWheel.isOpen; }
+ isMenuOpen() { return this.isInteractionOpen() || this.isWheelOpen(); }
+
+ closeMenus() { this.interaction.close(); this.weaponWheel.close(); this.emoteWheel.close(); }
+
+ // ------------------------------------------------------------ interaction M
+ toggleInteraction() {
+ if (this.interaction.isOpen) { this.interaction.close(); return; }
+ this.weaponWheel.close(); this.emoteWheel.close();
+ this.feel.sfx('open');
+ this.feel.haptic(10);
+ this.interaction.open(this._interactionItems());
+ }
+
+ _interactionItems() {
+ const a = this.actions;
+ const items = [];
+ if (a.openCharacter) items.push({ id: 'character', icon: '🧍', label: 'Character', short: 'Character', action: a.openCharacter });
+ if (a.openMissions) items.push({ id: 'missions', icon: '🎯', label: 'Missions', short: 'Missions', action: a.openMissions });
+ if (a.openCrew) items.push({ id: 'crew', icon: '👥', label: 'Crew', short: 'Crew', action: a.openCrew });
+ if (this.getEmotes().length) items.push({ id: 'emotes', icon: '😄', label: 'Emotes', short: 'Emotes', action: () => this.openEmoteWheel() });
+ items.push({
+ id: 'camera', icon: '🎥',
+ label: this.camera.isFirstPerson() ? 'Camera: First-person' : 'Camera: Third-person',
+ short: 'Camera', action: () => { this.camera.toggleFirstPerson(); this.feel.sfx('select'); },
+ });
+ items.push({
+ id: 'sound', icon: this.feel.isMuted() ? '🔇' : '🔊',
+ label: this.feel.isMuted() ? 'Sound: Off' : 'Sound: On',
+ short: 'Sound', action: () => { this.feel.setMuted(!this.feel.isMuted()); if (!this.feel.isMuted()) this.feel.sfx('select'); },
+ });
+ if (a.openSettings) items.push({ id: 'settings', icon: '⚙️', label: 'Settings', short: 'Settings', action: a.openSettings });
+ if (a.leave) items.push({ id: 'leave', icon: '🚪', label: 'Leave world', short: 'Leave', color: '#ff7a7a', action: a.leave });
+ return items;
+ }
+
+ // ----------------------------------------------------------- weapon wheel Q
+ openWeaponWheel() {
+ if (this.isMenuOpen()) return;
+ const items = this._hotbarItems();
+ if (!items.length) return; // nothing to quick-select — stay silent
+ this.feel.sfx('open');
+ this.weaponWheel.open(items);
+ }
+ releaseWeaponWheel() { this.weaponWheel.release(); }
+
+ _hotbarItems() {
+ const hb = this.getHotbar() || [];
+ return hb.map((s, i) => ({
+ id: 'slot' + i, icon: s.empty ? '·' : (s.glyph || '▢'),
+ label: s.empty ? 'Empty' : (s.name || 'Item'),
+ short: s.empty ? '—' : (s.name || ''),
+ hint: s.qty > 1 ? `×${s.qty}` : '',
+ disabled: s.empty,
+ action: () => this.actions.equipSlot?.(i),
+ }));
+ }
+
+ // ------------------------------------------------------------- emote wheel
+ openEmoteWheel() {
+ const emotes = this.getEmotes() || [];
+ if (!emotes.length) return;
+ this.interaction.close();
+ this.feel.sfx('open');
+ this.emoteWheel.open(emotes.slice(0, 8).map((e) => ({
+ id: 'emote-' + e.name, icon: e.icon || '🙂', label: e.label || e.name, short: e.label || e.name,
+ action: () => this.actions.emote?.(e.name),
+ })));
+ }
+ releaseEmoteWheel() { this.emoteWheel.release(); }
+
+ dispose() {
+ this.interaction.dispose();
+ this.weaponWheel.dispose();
+ this.emoteWheel.dispose();
+ this.hud.dispose();
+ this.feel.dispose();
+ }
+}
diff --git a/src/game/hud/minimap.js b/src/game/hud/minimap.js
new file mode 100644
index 000000000..629b426ba
--- /dev/null
+++ b/src/game/hud/minimap.js
@@ -0,0 +1,137 @@
+// Minimap — a rotating GTA-style radar drawn on a canvas. The map turns under a
+// fixed player arrow (player faces "up"), with a compass N marker, the world
+// boundary ring, and live blips for peers / POIs / waypoints pushed by the host.
+//
+// All data is real: the viewer pose comes from the local avatar each frame and
+// the blips from actual peer positions + world features. Nothing is invented.
+
+const TAU = Math.PI * 2;
+
+export class Minimap {
+ constructor() {
+ this.size = 184; // CSS px; canvas backing scales by DPR
+ this.range = 70; // world metres from centre to edge
+ this.viewer = { x: 0, z: 0, yaw: 0 };
+ this.blips = [];
+ this.boundary = 58; // world radius ring (0 = none)
+ this._build();
+ }
+
+ _build() {
+ this.root = document.createElement('div');
+ this.root.className = 'wh-minimap';
+ this.root.setAttribute('role', 'img');
+ this.root.setAttribute('aria-label', 'Minimap');
+ this.canvas = document.createElement('canvas');
+ this.canvas.className = 'wh-minimap-canvas';
+ this.ctx = this.canvas.getContext('2d');
+ // Compass cardinal, painted as DOM so it stays crisp text.
+ this.north = document.createElement('span');
+ this.north.className = 'wh-minimap-n';
+ this.north.textContent = 'N';
+ this.root.append(this.canvas, this.north);
+ this._resize();
+ }
+
+ _resize() {
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
+ this.canvas.width = this.size * dpr;
+ this.canvas.height = this.size * dpr;
+ this.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ }
+
+ setRange(m) { this.range = Math.max(20, m); }
+ setBoundary(r) { this.boundary = Number(r) || 0; }
+ setViewer(v) { if (v) this.viewer = { x: v.x || 0, z: v.z || 0, yaw: v.yaw || 0 }; }
+ // Blips: [{ x, z, kind:'peer'|'poi'|'waypoint'|'party', label?, color? }]
+ setBlips(list) { this.blips = Array.isArray(list) ? list : []; }
+
+ // Project a world point to map space with the player facing screen-up. Returns
+ // {sx, sy, inside} where inside is false past the map edge (drawn as a rim arrow).
+ _project(x, z) {
+ const dx = x - this.viewer.x, dz = z - this.viewer.z;
+ const y = this.viewer.yaw;
+ const cos = Math.cos(y), sin = Math.sin(y);
+ // forward (sin y, cos y) → up; right of forward → screen-right.
+ const mx = dx * cos - dz * sin;
+ const my = -(dx * sin + dz * cos);
+ const ppm = (this.size / 2) / this.range;
+ return { sx: mx * ppm, sy: my * ppm };
+ }
+
+ tick() {
+ const ctx = this.ctx;
+ const S = this.size, c = S / 2;
+ const R = c - 3; // inner radius (clip mask handles the rim)
+ ctx.clearRect(0, 0, S, S);
+
+ // Ground + faint grid rings.
+ ctx.save();
+ ctx.beginPath(); ctx.arc(c, c, R, 0, TAU); ctx.clip();
+ ctx.fillStyle = 'rgba(10,10,12,0.82)';
+ ctx.fillRect(0, 0, S, S);
+ ctx.strokeStyle = 'rgba(255,255,255,0.06)';
+ ctx.lineWidth = 1;
+ for (let r = R / 3; r < R; r += R / 3) { ctx.beginPath(); ctx.arc(c, c, r, 0, TAU); ctx.stroke(); }
+ // Cross-hair grid aligned to the rotating map.
+ ctx.strokeStyle = 'rgba(255,255,255,0.05)';
+ ctx.beginPath(); ctx.moveTo(c - R, c); ctx.lineTo(c + R, c); ctx.moveTo(c, c - R); ctx.lineTo(c, c + R); ctx.stroke();
+
+ // World boundary ring (where the plaza ends).
+ if (this.boundary > 0) {
+ const ppm = (S / 2) / this.range;
+ const br = this.boundary * ppm;
+ if (br < R + 30) {
+ const p = this._project(0, 0); // world origin's screen offset
+ ctx.strokeStyle = 'rgba(255,255,255,0.22)';
+ ctx.lineWidth = 1.5;
+ ctx.beginPath();
+ ctx.arc(c + p.sx, c + p.sy, br, 0, TAU);
+ ctx.stroke();
+ }
+ }
+
+ // Blips.
+ for (const b of this.blips) {
+ const p = this._project(b.x, b.z);
+ let bx = p.sx, by = p.sy;
+ const dist = Math.hypot(bx, by);
+ const edge = R - 6;
+ const clamped = dist > edge;
+ if (clamped) { const k = edge / dist; bx *= k; by *= k; }
+ const color = b.color || (b.kind === 'party' ? '#7fd1ff' : b.kind === 'poi' ? '#ffd166' : b.kind === 'waypoint' ? '#fff' : 'rgba(255,255,255,0.85)');
+ if (b.kind === 'waypoint') {
+ // A diamond waypoint marker.
+ ctx.save();
+ ctx.translate(c + bx, c + by); ctx.rotate(Math.PI / 4);
+ ctx.fillStyle = color; ctx.fillRect(-3.5, -3.5, 7, 7);
+ ctx.restore();
+ } else {
+ ctx.beginPath();
+ ctx.arc(c + bx, c + by, clamped ? 2.5 : (b.kind === 'poi' ? 3.4 : 3), 0, TAU);
+ ctx.fillStyle = color;
+ ctx.fill();
+ if (!clamped && b.kind !== 'peer') { ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.stroke(); }
+ }
+ }
+ ctx.restore();
+
+ // Player arrow at centre (always points up — the map rotates beneath it).
+ ctx.save();
+ ctx.translate(c, c);
+ ctx.beginPath();
+ ctx.moveTo(0, -7); ctx.lineTo(5, 6); ctx.lineTo(0, 3); ctx.lineTo(-5, 6); ctx.closePath();
+ ctx.fillStyle = '#fff';
+ ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 3;
+ ctx.fill();
+ ctx.restore();
+
+ // Compass N marker: world-north (−Z) rotated into map space, parked on the rim.
+ const ny = this.viewer.yaw;
+ const ndirX = Math.sin(ny), ndirY = Math.cos(ny); // screen dir of world (0,-1)
+ const rim = R - 11;
+ this.north.style.transform = `translate(${(ndirX * rim).toFixed(1)}px, ${(ndirY * rim).toFixed(1)}px) translate(-50%, -50%)`;
+ }
+
+ dispose() { this.root?.remove(); }
+}
diff --git a/src/game/hud/radial-menu.css b/src/game/hud/radial-menu.css
new file mode 100644
index 000000000..27de409fc
--- /dev/null
+++ b/src/game/hud/radial-menu.css
@@ -0,0 +1,113 @@
+/* RadialMenu — shared chrome for the interaction menu + weapon wheel.
+ Inherits the /play monochrome tokens (--cc-*) from coincommunities.css. */
+
+.wh-radial {
+ position: fixed;
+ inset: 0;
+ z-index: 60;
+ display: grid;
+ place-items: center;
+ background: radial-gradient(circle at center, rgba(0, 0, 0, 0.42), rgba(0, 0, 0, 0.72));
+ opacity: 0;
+ transition: opacity 0.16s ease;
+ -webkit-backdrop-filter: blur(2px);
+ backdrop-filter: blur(2px);
+}
+.wh-radial.is-open { opacity: 1; }
+
+.wh-radial-stage {
+ position: relative;
+ width: min(78vw, 78vh, 460px);
+ aspect-ratio: 1;
+ transform: scale(0.86);
+ transition: transform 0.18s cubic-bezier(0.2, 0.9, 0.25, 1);
+}
+.wh-radial.is-open .wh-radial-stage { transform: scale(1); }
+
+.wh-radial-svg {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ overflow: visible;
+ filter: drop-shadow(0 18px 50px rgba(0, 0, 0, 0.65));
+}
+
+/* Wedges: glassy by default, accent-lit on focus. --wedge-accent overrides the
+ highlight per item (e.g. a danger-red destroy action). */
+.wh-radial-wedge {
+ --wedge-accent: var(--cc-accent, #fff);
+ fill: rgba(16, 16, 20, 0.82);
+ stroke: rgba(255, 255, 255, 0.1);
+ stroke-width: 1.2;
+ cursor: pointer;
+ transition: fill 0.12s ease, stroke 0.12s ease, opacity 0.12s ease;
+}
+.wh-radial-wedge:hover { fill: rgba(34, 34, 40, 0.9); }
+.wh-radial-wedge.is-focus {
+ fill: color-mix(in srgb, var(--wedge-accent) 22%, rgba(20, 20, 24, 0.92));
+ stroke: var(--wedge-accent);
+ stroke-width: 2;
+}
+.wh-radial-wedge.is-disabled { opacity: 0.4; cursor: not-allowed; pointer-events: none; }
+
+.wh-radial-glabel { pointer-events: none; transition: transform 0.12s ease; }
+.wh-radial-icon {
+ font-size: 30px;
+ text-anchor: middle;
+ dominant-baseline: middle;
+ fill: var(--cc-text, #f5f5f6);
+}
+.wh-radial-text {
+ font: 600 13px/1 ui-sans-serif, system-ui, -apple-system, sans-serif;
+ letter-spacing: 0.02em;
+ text-anchor: middle;
+ dominant-baseline: middle;
+ fill: var(--cc-dim, #9a9aa2);
+ transition: fill 0.12s ease;
+}
+.wh-radial-glabel.is-focus .wh-radial-text { fill: var(--cc-text, #fff); }
+.wh-radial-glabel.is-focus { transform: scale(1.04); transform-origin: center; transform-box: fill-box; }
+
+/* Centre hub — names the focused action, GTA-style. */
+.wh-radial-hub {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ width: 38%;
+ aspect-ratio: 1;
+ border-radius: 50%;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 2px;
+ text-align: center;
+ padding: 6px;
+ background: rgba(8, 8, 10, 0.78);
+ border: 1px solid var(--cc-edge, rgba(255, 255, 255, 0.12));
+ box-shadow: inset 0 0 24px rgba(0, 0, 0, 0.6);
+ pointer-events: none;
+}
+.wh-radial-hub-icon { font-size: clamp(22px, 5vw, 34px); line-height: 1; }
+.wh-radial-hub-label {
+ font: 700 clamp(12px, 2.6vw, 15px)/1.15 ui-sans-serif, system-ui, sans-serif;
+ color: var(--cc-text, #f5f5f6);
+ max-width: 92%;
+}
+.wh-radial-hub-hint {
+ font: 500 11px/1.2 ui-sans-serif, system-ui, sans-serif;
+ color: var(--cc-faint, #6b6b72);
+ max-width: 92%;
+}
+
+@media (max-width: 560px) {
+ .wh-radial-stage { width: min(86vw, 86vh, 380px); }
+ .wh-radial-icon { font-size: 26px; }
+ .wh-radial-text { font-size: 11px; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .wh-radial, .wh-radial-stage, .wh-radial-glabel { transition: none; }
+}
diff --git a/src/game/hud/radial-menu.js b/src/game/hud/radial-menu.js
new file mode 100644
index 000000000..fe8adeca4
--- /dev/null
+++ b/src/game/hud/radial-menu.js
@@ -0,0 +1,303 @@
+// RadialMenu — a GTA-style radial selector used for both the interaction menu
+// ("M") and the weapon/action wheel (hold-to-open). One component, two configs.
+//
+// It renders an SVG ring of wedges around a centre hub, and resolves a focused
+// item from mouse angle, arrow keys, number keys, touch drag, or a gamepad
+// stick. Two open styles:
+// - 'toggle' (interaction menu): opens, you click/Enter a wedge, it closes.
+// - 'hold' (weapon wheel): opens while a key is held; the wedge under the
+// pointer/stick is committed on release. GTA's weapon wheel feel.
+//
+// Fully keyboard- + touch- + gamepad-navigable, design-token themed, and self
+// contained — the host just calls open()/close() and gets an onSelect(item).
+
+import './radial-menu.css';
+
+const TAU = Math.PI * 2;
+
+// Annular-sector path between inner radius `ri` and outer `ro`, sweeping a0→a1.
+function wedgePath(cx, cy, ri, ro, a0, a1) {
+ const pt = (r, a) => `${(cx + r * Math.cos(a)).toFixed(2)} ${(cy + r * Math.sin(a)).toFixed(2)}`;
+ const large = (a1 - a0) % TAU > Math.PI ? 1 : 0;
+ return `M ${pt(ro, a0)} A ${ro} ${ro} 0 ${large} 1 ${pt(ro, a1)} L ${pt(ri, a1)} A ${ri} ${ri} 0 ${large} 0 ${pt(ri, a0)} Z`;
+}
+
+export class RadialMenu {
+ /**
+ * @param {object} opts
+ * @param {string} [opts.id] DOM id for the overlay (default 'wh-radial')
+ * @param {string} [opts.title] centre-hub title shown when nothing is focused
+ * @param {'toggle'|'hold'} [opts.mode] open style (default 'toggle')
+ * @param {(item:object)=>void} opts.onSelect committed selection callback
+ * @param {()=>void} [opts.onClose] fired whenever the menu closes
+ */
+ constructor({ id = 'wh-radial', title = '', mode = 'toggle', onSelect, onClose } = {}) {
+ this.id = id;
+ this.title = title;
+ this.mode = mode;
+ this.onSelect = onSelect || (() => {});
+ this.onClose = onClose || (() => {});
+ this.items = [];
+ this.focus = -1; // index of the focused wedge, -1 = hub/cancel
+ this.isOpen = false;
+ this._ns = 'http://www.w3.org/2000/svg';
+ this._size = 360; // SVG viewBox units; CSS scales it responsively
+ this._ri = 70; // inner (hub) radius
+ this._ro = 168; // outer radius
+ this._padBoot = false;
+ this._build();
+ this._bind();
+ }
+
+ _build() {
+ const root = document.createElement('div');
+ root.id = this.id;
+ root.className = 'wh-radial';
+ root.setAttribute('role', 'menu');
+ root.setAttribute('aria-hidden', 'true');
+ root.hidden = true;
+
+ const stage = document.createElement('div');
+ stage.className = 'wh-radial-stage';
+
+ const svg = document.createElementNS(this._ns, 'svg');
+ svg.setAttribute('viewBox', `0 0 ${this._size} ${this._size}`);
+ svg.setAttribute('class', 'wh-radial-svg');
+ this._wedgeLayer = document.createElementNS(this._ns, 'g');
+ this._labelLayer = document.createElementNS(this._ns, 'g');
+ svg.append(this._wedgeLayer, this._labelLayer);
+
+ // Centre hub: shows the focused item's label, or the menu title / "Close".
+ const hub = document.createElement('div');
+ hub.className = 'wh-radial-hub';
+ this._hubIcon = document.createElement('div');
+ this._hubIcon.className = 'wh-radial-hub-icon';
+ this._hubLabel = document.createElement('div');
+ this._hubLabel.className = 'wh-radial-hub-label';
+ this._hubHint = document.createElement('div');
+ this._hubHint.className = 'wh-radial-hub-hint';
+ hub.append(this._hubIcon, this._hubLabel, this._hubHint);
+
+ stage.append(svg, hub);
+ root.append(stage);
+ document.body.appendChild(root);
+ this.root = root;
+ this.stage = stage;
+ this.svg = svg;
+ this.hub = hub;
+ }
+
+ _bind() {
+ // Pointer angle → focused wedge. Listen on the whole overlay so the cursor
+ // can be anywhere; the centre deadzone reads as "cancel".
+ this.root.addEventListener('pointermove', (e) => {
+ if (!this.isOpen) return;
+ const rect = this.stage.getBoundingClientRect();
+ const cx = rect.left + rect.width / 2;
+ const cy = rect.top + rect.height / 2;
+ const dx = e.clientX - cx, dy = e.clientY - cy;
+ const dist = Math.hypot(dx, dy);
+ const dead = rect.width * (this._ri / this._size) * 0.62;
+ if (dist < dead) { this._setFocus(-1); return; }
+ this._setFocus(this._indexForAngle(Math.atan2(dy, dx)));
+ });
+ // Click a wedge (or the hub to cancel).
+ this.root.addEventListener('pointerup', (e) => {
+ if (!this.isOpen || this.mode !== 'toggle') return;
+ if (this.focus >= 0) this._commit();
+ else this.close();
+ e.stopPropagation();
+ });
+ // Background click closes without selecting.
+ this.root.addEventListener('pointerdown', (e) => {
+ if (e.target === this.root) this.close();
+ });
+ }
+
+ // Which wedge centre is nearest this pointer angle (screen space, +x right,
+ // +y down). Wedge i is centred at the top + i steps clockwise.
+ _indexForAngle(angle) {
+ const n = this.items.length;
+ if (!n) return -1;
+ // Shift so 0 maps to straight up (−90°), then quantise to the nearest slot.
+ let a = angle + Math.PI / 2;
+ a = ((a % TAU) + TAU) % TAU;
+ return Math.round(a / (TAU / n)) % n;
+ }
+
+ setTitle(title) { this.title = title || ''; }
+
+ setItems(items) {
+ this.items = (items || []).filter((it) => it && !it.hidden);
+ if (this.isOpen) this._render();
+ }
+
+ open(items) {
+ if (items) this.setItems(items);
+ if (!this.items.length) return;
+ this.isOpen = true;
+ this.focus = -1;
+ this.root.hidden = false;
+ this.root.setAttribute('aria-hidden', 'false');
+ this._render();
+ // Let the enter transition run from the next frame.
+ requestAnimationFrame(() => this.root.classList.add('is-open'));
+ this._startGamepad();
+ document.addEventListener('keydown', this._onKey, true);
+ }
+
+ close() {
+ if (!this.isOpen) return;
+ this.isOpen = false;
+ this.root.classList.remove('is-open');
+ this.root.setAttribute('aria-hidden', 'true');
+ this._stopGamepad();
+ document.removeEventListener('keydown', this._onKey, true);
+ // Hold until the exit transition finishes so it doesn't pop.
+ clearTimeout(this._hideTimer);
+ this._hideTimer = setTimeout(() => { if (!this.isOpen) this.root.hidden = true; }, 180);
+ this.onClose();
+ }
+
+ // Commit the focused wedge (hold-mode release, click, or Enter).
+ _commit() {
+ const item = this.items[this.focus];
+ this.close();
+ if (item) { try { this.onSelect(item); } catch { /* host handles */ } }
+ }
+
+ // Hold-mode: release the open key → commit whatever is focused (if anything).
+ release() {
+ if (!this.isOpen) return;
+ if (this.focus >= 0) this._commit();
+ else this.close();
+ }
+
+ _setFocus(i) {
+ if (i === this.focus) return;
+ this.focus = i;
+ this._paintFocus();
+ }
+
+ _paintFocus() {
+ const wedges = this._wedgeLayer.children;
+ for (let i = 0; i < wedges.length; i++) {
+ wedges[i].classList.toggle('is-focus', i === this.focus);
+ }
+ const labels = this._labelLayer.children;
+ for (let i = 0; i < labels.length; i++) {
+ labels[i].classList.toggle('is-focus', i === this.focus);
+ }
+ const item = this.focus >= 0 ? this.items[this.focus] : null;
+ if (item) {
+ this._hubIcon.textContent = item.icon || '';
+ this._hubLabel.textContent = item.label || '';
+ this._hubHint.textContent = item.hint || '';
+ } else {
+ this._hubIcon.textContent = '';
+ this._hubLabel.textContent = this.title || (this.mode === 'hold' ? 'Release to cancel' : 'Close');
+ this._hubHint.textContent = '';
+ }
+ }
+
+ _render() {
+ const n = this.items.length;
+ const c = this._size / 2;
+ const gap = n > 1 ? 0.045 : 0; // radians of breathing room between wedges
+ const step = TAU / n;
+ this._wedgeLayer.replaceChildren();
+ this._labelLayer.replaceChildren();
+ this.items.forEach((item, i) => {
+ // Wedge i is centred straight up (−90°) + i steps clockwise.
+ const mid = -Math.PI / 2 + i * step;
+ const a0 = mid - step / 2 + gap / 2;
+ const a1 = mid + step / 2 - gap / 2;
+ const path = document.createElementNS(this._ns, 'path');
+ path.setAttribute('d', wedgePath(c, c, this._ri, this._ro, a0, a1));
+ path.setAttribute('class', 'wh-radial-wedge');
+ if (item.color) path.style.setProperty('--wedge-accent', item.color);
+ if (item.disabled) path.classList.add('is-disabled');
+ path.setAttribute('role', 'menuitem');
+ path.setAttribute('tabindex', '-1');
+ path.setAttribute('aria-label', item.label || item.id || 'item');
+ path.addEventListener('pointerenter', () => this._setFocus(i));
+ this._wedgeLayer.appendChild(path);
+
+ // Icon + short label riding the wedge at mid radius.
+ const lr = (this._ri + this._ro) / 2;
+ const lx = c + lr * Math.cos(mid);
+ const ly = c + lr * Math.sin(mid);
+ const g = document.createElementNS(this._ns, 'g');
+ g.setAttribute('class', 'wh-radial-glabel');
+ const icon = document.createElementNS(this._ns, 'text');
+ icon.setAttribute('x', lx.toFixed(1));
+ icon.setAttribute('y', (ly - 6).toFixed(1));
+ icon.setAttribute('class', 'wh-radial-icon');
+ icon.textContent = item.icon || '';
+ const txt = document.createElementNS(this._ns, 'text');
+ txt.setAttribute('x', lx.toFixed(1));
+ txt.setAttribute('y', (ly + 20).toFixed(1));
+ txt.setAttribute('class', 'wh-radial-text');
+ txt.textContent = item.short || item.label || '';
+ g.append(icon, txt);
+ this._labelLayer.appendChild(g);
+ });
+ this._paintFocus();
+ }
+
+ // ----------------------------------------------------------------- keyboard
+ _onKey = (e) => {
+ if (!this.isOpen) return;
+ const n = this.items.length;
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.close(); return; }
+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
+ e.preventDefault(); e.stopPropagation();
+ this._setFocus(((this.focus < 0 ? -1 : this.focus) + 1 + n) % n);
+ } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
+ e.preventDefault(); e.stopPropagation();
+ this._setFocus(((this.focus < 0 ? 1 : this.focus) - 1 + n) % n);
+ } else if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault(); e.stopPropagation();
+ if (this.focus >= 0) this._commit();
+ } else if (e.key >= '1' && e.key <= '9') {
+ const i = Number(e.key) - 1;
+ if (i < n) { e.preventDefault(); e.stopPropagation(); this._setFocus(i); if (this.mode === 'toggle') this._commit(); }
+ }
+ };
+
+ // ------------------------------------------------------------------ gamepad
+ // While open, poll the first connected pad: left stick steers focus, the
+ // south/A button (0) confirms, B (1) / Start (9) cancels.
+ _startGamepad() {
+ if (typeof navigator === 'undefined' || !navigator.getGamepads) return;
+ this._padPrev = { confirm: false, cancel: false };
+ const poll = () => {
+ if (!this.isOpen) return;
+ this._gamepadId = requestAnimationFrame(poll);
+ const pads = navigator.getGamepads ? navigator.getGamepads() : [];
+ const pad = [...pads].find(Boolean);
+ if (!pad) return;
+ const ax = pad.axes[0] || 0, ay = pad.axes[1] || 0;
+ if (Math.hypot(ax, ay) > 0.5) this._setFocus(this._indexForAngle(Math.atan2(ay, ax)));
+ else if (this.mode === 'toggle') this._setFocus(-1);
+ const confirm = !!(pad.buttons[0] && pad.buttons[0].pressed);
+ const cancel = !!((pad.buttons[1] && pad.buttons[1].pressed) || (pad.buttons[9] && pad.buttons[9].pressed));
+ if (confirm && !this._padPrev.confirm) { if (this.focus >= 0) this._commit(); }
+ else if (cancel && !this._padPrev.cancel) this.close();
+ this._padPrev = { confirm, cancel };
+ };
+ this._gamepadId = requestAnimationFrame(poll);
+ }
+
+ _stopGamepad() {
+ if (this._gamepadId) cancelAnimationFrame(this._gamepadId);
+ this._gamepadId = 0;
+ }
+
+ dispose() {
+ this._stopGamepad();
+ clearTimeout(this._hideTimer);
+ document.removeEventListener('keydown', this._onKey, true);
+ this.root?.remove();
+ }
+}
diff --git a/src/game/hud/world-hud.css b/src/game/hud/world-hud.css
new file mode 100644
index 000000000..bd067cf69
--- /dev/null
+++ b/src/game/hud/world-hud.css
@@ -0,0 +1,219 @@
+/* WorldHud — unified GTA-style chrome. Inherits the /play monochrome tokens
+ (--cc-*) from coincommunities.css; falls back gracefully if loaded alone. */
+
+.wh-hud {
+ --wh-pad: 14px;
+ position: fixed;
+ inset: 0;
+ z-index: 30;
+ pointer-events: none; /* the world stays interactive; children opt back in */
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
+ color: var(--cc-text, #f5f5f6);
+}
+.wh-hud [hidden] { display: none !important; }
+
+/* ---------------------------------------------------------------- money ---- */
+.wh-money {
+ position: absolute;
+ top: calc(var(--wh-pad) + 92px); /* clears the cc status pill / voice button */
+ right: var(--wh-pad);
+ display: flex;
+ flex-direction: column;
+ align-items: flex-end;
+ gap: 6px;
+}
+.wh-cash {
+ display: flex;
+ align-items: baseline;
+ gap: 4px;
+ padding: 5px 11px;
+ border-radius: var(--cc-radius, 4px);
+ background: var(--cc-panel, rgba(12, 12, 14, 0.78));
+ border: 1px solid var(--cc-edge, rgba(255, 255, 255, 0.12));
+ -webkit-backdrop-filter: blur(8px);
+ backdrop-filter: blur(8px);
+ box-shadow: var(--cc-shadow, 0 16px 50px rgba(0, 0, 0, 0.7));
+ transition: transform 0.18s ease, color 0.18s ease;
+}
+.wh-cash-glyph { font-weight: 800; color: var(--cc-dim, #9a9aa2); font-size: 14px; }
+.wh-cash-amt {
+ font-variant-numeric: tabular-nums;
+ font-weight: 800;
+ font-size: 19px;
+ letter-spacing: 0.01em;
+}
+.wh-cash.is-gain { animation: wh-cash-gain 0.55s ease; }
+.wh-cash.is-loss { animation: wh-cash-loss 0.55s ease; }
+@keyframes wh-cash-gain {
+ 0% { transform: scale(1); color: var(--cc-text, #fff); }
+ 35% { transform: scale(1.12); color: #8effa6; }
+ 100% { transform: scale(1); }
+}
+@keyframes wh-cash-loss {
+ 0% { transform: scale(1); }
+ 35% { transform: scale(0.94); color: #ff9b9b; }
+ 100% { transform: scale(1); }
+}
+.wh-banked {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 3px 9px;
+ border-radius: var(--cc-radius-sm, 2px);
+ background: rgba(8, 8, 10, 0.6);
+ border: 1px solid var(--cc-edge-soft, rgba(255, 255, 255, 0.07));
+ font-size: 13px;
+ font-variant-numeric: tabular-nums;
+ color: var(--cc-dim, #9a9aa2);
+}
+.wh-banked-glyph { font-size: 11px; opacity: 0.85; }
+
+/* Wanted stars. */
+.wh-wanted { display: flex; gap: 2px; margin-top: 2px; }
+.wh-star {
+ font-size: 17px;
+ line-height: 1;
+ color: rgba(255, 255, 255, 0.16);
+ transition: color 0.18s ease, transform 0.18s ease;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
+}
+.wh-star.is-on { color: #fff; }
+.wh-wanted.is-hunting .wh-star.is-on { animation: wh-star-flash 0.9s steps(2) infinite; }
+@keyframes wh-star-flash { 50% { color: var(--cc-dim, #9a9aa2); } }
+
+/* ------------------------------------------------------------ objective ---- */
+.wh-objective {
+ position: absolute;
+ left: var(--wh-pad);
+ top: 50%;
+ transform: translateY(-50%);
+ display: flex;
+ max-width: min(320px, 42vw);
+ border-radius: var(--cc-radius, 4px);
+ overflow: hidden;
+ background: var(--cc-panel, rgba(12, 12, 14, 0.78));
+ border: 1px solid var(--cc-edge, rgba(255, 255, 255, 0.12));
+ -webkit-backdrop-filter: blur(8px);
+ backdrop-filter: blur(8px);
+ box-shadow: var(--cc-shadow, 0 16px 50px rgba(0, 0, 0, 0.7));
+}
+.wh-objective.is-in { animation: wh-obj-in 0.36s cubic-bezier(0.2, 0.9, 0.25, 1); }
+@keyframes wh-obj-in { from { opacity: 0; transform: translate(-12px, -50%); } to { opacity: 1; transform: translate(0, -50%); } }
+.wh-obj-bar { width: 4px; flex: none; background: var(--obj-accent, #fff); }
+.wh-obj-body { padding: 9px 13px; }
+.wh-obj-title { font-weight: 700; font-size: 14px; }
+.wh-obj-detail { font-size: 12.5px; color: var(--cc-dim, #9a9aa2); margin-top: 2px; }
+
+/* ----------------------------------------------------- vitals + minimap ---- */
+.wh-corner-bl {
+ position: absolute;
+ left: var(--wh-pad);
+ bottom: var(--wh-pad);
+ display: flex;
+ flex-direction: column;
+ gap: 7px;
+ align-items: flex-start;
+}
+.wh-vitals { display: flex; flex-direction: column; gap: 4px; width: 184px; }
+.wh-bar {
+ position: relative;
+ height: 7px;
+ border-radius: 4px;
+ overflow: hidden;
+ background: rgba(8, 8, 10, 0.7);
+ border: 1px solid var(--cc-edge-soft, rgba(255, 255, 255, 0.07));
+ /* faint segment ticks for a game-y read */
+ background-image: repeating-linear-gradient(90deg, transparent 0, transparent 11px, rgba(0, 0, 0, 0.55) 11px, rgba(0, 0, 0, 0.55) 12px);
+}
+.wh-bar-fill {
+ display: block;
+ height: 100%;
+ width: 100%;
+ transition: width 0.22s ease, background 0.22s ease;
+}
+.wh-bar--hp .wh-bar-fill { background: linear-gradient(90deg, #e7e7ea, #fff); }
+.wh-bar--hp.is-critical .wh-bar-fill { background: linear-gradient(90deg, #ff6b6b, #ff9b9b); }
+.wh-bar--hp.is-critical { animation: wh-hp-pulse 0.8s ease-in-out infinite; }
+@keyframes wh-hp-pulse { 50% { box-shadow: 0 0 10px rgba(255, 80, 80, 0.55); } }
+.wh-bar--armor .wh-bar-fill { background: linear-gradient(90deg, #7c93b8, #b9c8e0); }
+
+.wh-minimap {
+ position: relative;
+ width: 184px;
+ height: 184px;
+ border-radius: 50%;
+ overflow: visible;
+ pointer-events: auto;
+ border: 1.5px solid var(--cc-edge, rgba(255, 255, 255, 0.14));
+ box-shadow: var(--cc-shadow, 0 16px 50px rgba(0, 0, 0, 0.7)), inset 0 0 0 4px rgba(0, 0, 0, 0.35);
+ background: rgba(6, 6, 8, 0.5);
+}
+.wh-minimap-canvas { width: 184px; height: 184px; border-radius: 50%; display: block; }
+.wh-minimap-n {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ font: 800 11px/1 ui-sans-serif, system-ui, sans-serif;
+ color: var(--cc-text, #fff);
+ text-shadow: 0 1px 3px rgba(0, 0, 0, 0.9);
+ pointer-events: none;
+}
+
+/* --------------------------------------------------------------- speedo ---- */
+.wh-speedo {
+ position: absolute;
+ right: var(--wh-pad);
+ bottom: var(--wh-pad);
+ width: 124px;
+ height: 124px;
+ pointer-events: none;
+ display: grid;
+ place-items: center;
+}
+.wh-speed-dial {
+ position: absolute;
+ inset: 0;
+ border-radius: 50%;
+ background: conic-gradient(from 225deg, rgba(255, 255, 255, 0.14) 0deg, rgba(255, 255, 255, 0.14) 270deg, transparent 270deg);
+ -webkit-mask: radial-gradient(circle, transparent 46px, #000 47px, #000 56px, transparent 57px);
+ mask: radial-gradient(circle, transparent 46px, #000 47px, #000 56px, transparent 57px);
+}
+.wh-speed-fill {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ width: 3px;
+ height: 56px;
+ background: #fff;
+ transform-origin: bottom center;
+ transform: translate(-50%, -100%) rotate(-135deg);
+ border-radius: 2px;
+ box-shadow: 0 0 6px rgba(255, 255, 255, 0.6);
+ transition: transform 0.12s linear;
+}
+.wh-speed-read { text-align: center; }
+.wh-speed-num { font-weight: 800; font-size: 30px; line-height: 1; font-variant-numeric: tabular-nums; }
+.wh-speed-unit { font-size: 9px; letter-spacing: 0.14em; color: var(--cc-dim, #9a9aa2); }
+.wh-speed-gear {
+ position: absolute;
+ bottom: 18px;
+ font-weight: 700;
+ font-size: 12px;
+ color: var(--cc-dim, #9a9aa2);
+}
+
+/* ----------------------------------------------------------- responsive ---- */
+@media (max-width: 640px) {
+ .wh-hud { --wh-pad: 10px; }
+ .wh-money { top: calc(var(--wh-pad) + 96px); }
+ .wh-vitals { width: 132px; }
+ .wh-minimap, .wh-minimap-canvas { width: 132px; height: 132px; }
+ .wh-objective { max-width: 60vw; }
+ .wh-speedo { width: 96px; height: 96px; }
+ .wh-speed-num { font-size: 22px; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .wh-cash, .wh-bar-fill, .wh-speed-fill, .wh-objective.is-in { transition: none; animation: none; }
+ .wh-wanted.is-hunting .wh-star.is-on, .wh-bar--hp.is-critical { animation: none; }
+}
diff --git a/src/game/hud/world-hud.js b/src/game/hud/world-hud.js
new file mode 100644
index 000000000..16c5de5e6
--- /dev/null
+++ b/src/game/hud/world-hud.js
@@ -0,0 +1,196 @@
+// WorldHud — the one HUD system the World Online briefs push data into.
+//
+// GTA-style chrome: a rotating minimap with compass + live player blips
+// (bottom-left), cash/banked (top-right), health/armor bars (above the
+// minimap), a wanted-level star row, an active-objective card, and a vehicle
+// speedo. Each element appears ONLY when it has real data — no element is shown
+// with placeholder numbers. Sibling briefs feed it:
+// - W04 economy → setCash / setBanked
+// - W07 combat → setHealth / setArmor / setWanted
+// - W05 quests → setObjective / clearObjective
+// - W09 social → minimap.setBlips (party/POIs)
+// - W02 driving → setSpeed / hideSpeed
+//
+// The host (/play) drives the minimap viewer + blips every frame and forwards
+// the player's purse/HP, so what ships today is fully wired to live data; the
+// combat/quest/vehicle setters stay dormant until those briefs light them up.
+
+import './world-hud.css';
+import { Minimap } from './minimap.js';
+
+function el(tag, props = {}, kids = []) {
+ const n = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (k === 'class') n.className = v;
+ else if (k === 'text') n.textContent = v;
+ else if (k === 'hidden') n.hidden = !!v;
+ else if (v != null) n.setAttribute(k, v);
+ }
+ for (const c of [].concat(kids)) if (c) n.appendChild(c);
+ return n;
+}
+
+const fmtCash = (n) => '$' + Math.round(Number(n) || 0).toLocaleString();
+
+export class WorldHud {
+ constructor() {
+ this._cash = 0;
+ this._cashShown = 0;
+ this._context = 'onfoot';
+ this._build();
+ }
+
+ _build() {
+ // --- Top-right money cluster (cash + optional banked) -------------------
+ this.cashEl = el('span', { class: 'wh-cash-amt', text: '$0' });
+ this.cashRow = el('div', { class: 'wh-cash', title: 'Cash on hand' }, [
+ el('span', { class: 'wh-cash-glyph', text: '$' }), this.cashEl,
+ ]);
+ this.bankedEl = el('span', { class: 'wh-banked-amt', text: '$0' });
+ this.bankedRow = el('div', { class: 'wh-banked', hidden: true, title: 'Banked' }, [
+ el('span', { class: 'wh-banked-glyph', text: '🏦' }), this.bankedEl,
+ ]);
+ this.wantedRow = el('div', { class: 'wh-wanted', hidden: true, role: 'status', 'aria-label': 'Wanted level' });
+ this._stars = [];
+ for (let i = 0; i < 5; i++) {
+ const s = el('span', { class: 'wh-star', text: '★' });
+ this._stars.push(s);
+ this.wantedRow.appendChild(s);
+ }
+ this.moneyCol = el('div', { class: 'wh-money' }, [this.cashRow, this.bankedRow, this.wantedRow]);
+
+ // --- Active objective card (left) --------------------------------------
+ this.objTitle = el('div', { class: 'wh-obj-title' });
+ this.objDetail = el('div', { class: 'wh-obj-detail' });
+ this.objCard = el('div', { class: 'wh-objective', hidden: true, role: 'status' }, [
+ el('div', { class: 'wh-obj-bar' }),
+ el('div', { class: 'wh-obj-body' }, [this.objTitle, this.objDetail]),
+ ]);
+
+ // --- Bottom-left vitals + minimap --------------------------------------
+ this.hpFill = el('i', { class: 'wh-bar-fill' });
+ this.hpBar = el('div', { class: 'wh-bar wh-bar--hp', hidden: true, role: 'progressbar', 'aria-label': 'Health' }, [this.hpFill]);
+ this.armorFill = el('i', { class: 'wh-bar-fill' });
+ this.armorBar = el('div', { class: 'wh-bar wh-bar--armor', hidden: true, role: 'progressbar', 'aria-label': 'Armor' }, [this.armorFill]);
+ this.vitals = el('div', { class: 'wh-vitals' }, [this.hpBar, this.armorBar]);
+
+ this.minimap = new Minimap();
+ this.cornerBL = el('div', { class: 'wh-corner-bl' }, [this.vitals, this.minimap.root]);
+
+ // --- Speedo (bottom-right, vehicles only) ------------------------------
+ this.speedNum = el('div', { class: 'wh-speed-num', text: '0' });
+ this.speedGear = el('div', { class: 'wh-speed-gear', text: '' });
+ this.speedFill = el('i', { class: 'wh-speed-fill' });
+ this.speedo = el('div', { class: 'wh-speedo', hidden: true }, [
+ el('div', { class: 'wh-speed-dial' }, [this.speedFill]),
+ el('div', { class: 'wh-speed-read' }, [this.speedNum, el('div', { class: 'wh-speed-unit', text: 'KM/H' })]),
+ this.speedGear,
+ ]);
+
+ this.root = el('div', { id: 'wh-hud', class: 'wh-hud' }, [this.moneyCol, this.objCard, this.cornerBL, this.speedo]);
+ this.root.hidden = true;
+ document.body.appendChild(this.root);
+ }
+
+ // ------------------------------------------------------------- visibility
+ show() { this.root.hidden = false; }
+ hide() { this.root.hidden = true; }
+
+ // A coarse hint from the host about what the player is doing. Drives nothing
+ // destructive — elements still self-gate on having data — but lets us bias
+ // minimap scale (wider when driving) and add a body class for theming.
+ setContext(ctx) {
+ if (ctx === this._context) return;
+ this._context = ctx;
+ this.root.dataset.context = ctx;
+ this.minimap.setRange(ctx === 'driving' ? 130 : 70);
+ }
+
+ // ------------------------------------------------------------------ money
+ setCash(n, { animate = true } = {}) {
+ this._cash = Number(n) || 0;
+ if (!animate) { this._cashShown = this._cash; this.cashEl.textContent = fmtCash(this._cash); }
+ this.cashRow.hidden = false;
+ }
+ // A money delta worth celebrating (positive = gain pop, negative = spend).
+ bumpCash(delta) {
+ this.cashRow.classList.remove('is-gain', 'is-loss');
+ void this.cashRow.offsetWidth;
+ this.cashRow.classList.add(delta >= 0 ? 'is-gain' : 'is-loss');
+ }
+ setBanked(n) {
+ if (n == null) { this.bankedRow.hidden = true; return; }
+ this.bankedEl.textContent = fmtCash(n);
+ this.bankedRow.hidden = false;
+ }
+
+ // ----------------------------------------------------------------- vitals
+ setHealth(hp, maxHp) {
+ const max = Number(maxHp) || 0;
+ if (max <= 0) { this.hpBar.hidden = true; return; }
+ const pct = Math.max(0, Math.min(1, (Number(hp) || 0) / max));
+ this.hpBar.hidden = false;
+ this.hpFill.style.width = (pct * 100).toFixed(1) + '%';
+ this.hpBar.setAttribute('aria-valuenow', String(Math.round(pct * 100)));
+ this.hpBar.classList.toggle('is-critical', pct <= 0.25);
+ }
+ setArmor(armor, maxArmor) {
+ const max = Number(maxArmor) || 0;
+ if (max <= 0) { this.armorBar.hidden = true; return; }
+ const pct = Math.max(0, Math.min(1, (Number(armor) || 0) / max));
+ this.armorBar.hidden = false;
+ this.armorFill.style.width = (pct * 100).toFixed(1) + '%';
+ this.armorBar.setAttribute('aria-valuenow', String(Math.round(pct * 100)));
+ }
+
+ // ----------------------------------------------------------------- wanted
+ setWanted(stars) {
+ const s = Math.max(0, Math.min(5, Math.round(Number(stars) || 0)));
+ this.wantedRow.hidden = s <= 0;
+ this._stars.forEach((node, i) => node.classList.toggle('is-on', i < s));
+ this.wantedRow.classList.toggle('is-hunting', s >= 3);
+ }
+
+ // -------------------------------------------------------------- objective
+ setObjective({ title = '', detail = '', color = '' } = {}) {
+ this.objTitle.textContent = title;
+ this.objDetail.textContent = detail;
+ this.objDetail.hidden = !detail;
+ this.objCard.style.setProperty('--obj-accent', color || 'var(--cc-accent, #fff)');
+ this.objCard.hidden = !title;
+ this.objCard.classList.remove('is-in');
+ void this.objCard.offsetWidth;
+ this.objCard.classList.add('is-in');
+ }
+ clearObjective() { this.objCard.hidden = true; }
+
+ // ----------------------------------------------------------------- speedo
+ setSpeed({ kmh = 0, gear = '', max = 200 } = {}) {
+ this.speedo.hidden = false;
+ const v = Math.max(0, Math.round(kmh));
+ this.speedNum.textContent = String(v);
+ this.speedGear.textContent = gear ? String(gear) : '';
+ this.speedGear.hidden = !gear;
+ const pct = Math.max(0, Math.min(1, kmh / (max || 200)));
+ // Sweep the dial fill from −135° to +135° (270° arc).
+ this.speedFill.style.transform = `rotate(${(-135 + pct * 270).toFixed(1)}deg)`;
+ }
+ hideSpeed() { this.speedo.hidden = true; }
+
+ // ------------------------------------------------------------------- frame
+ tick(dt) {
+ // Ease the cash counter toward its target so earnings roll up GTA-style.
+ if (this._cashShown !== this._cash) {
+ const diff = this._cash - this._cashShown;
+ const stepTo = Math.abs(diff) < 1 ? this._cash : this._cashShown + diff * Math.min(1, dt * 9);
+ this._cashShown = Math.abs(this._cash - stepTo) < 0.5 ? this._cash : stepTo;
+ this.cashEl.textContent = fmtCash(this._cashShown);
+ }
+ this.minimap.tick(dt);
+ }
+
+ dispose() {
+ this.minimap.dispose();
+ this.root?.remove();
+ }
+}
diff --git a/src/game/npc/ambient-life.js b/src/game/npc/ambient-life.js
new file mode 100644
index 000000000..e3199e87e
--- /dev/null
+++ b/src/game/npc/ambient-life.js
@@ -0,0 +1,363 @@
+// Ambient world life — pedestrians and vehicle traffic that make the plaza
+// breathe (W08).
+//
+// Everything here is a *pure function of a shared world clock* (wall time) and
+// the world seed, so two players standing in the same town see the same crowd
+// walking the same routes and the same cars on the same stretch of road —
+// without a single ambient NPC crossing the wire. That's the brief's deal:
+// ambient life is client-side and deterministic; only consequential NPCs
+// (vendors, quests, mobs) are server-authoritative.
+//
+// Performance is built in: a small cast of detailed GLB pedestrians near the
+// action, a larger instanced "impostor" crowd in the distance (two InstancedMesh
+// for the whole background), and a handful of grouped vehicles on the ring road.
+// Counts are honest and capped, and the detailed crowd tapers as real players
+// join so a busy world is never padded with fakes.
+
+import {
+ Group, Vector3, Object3D, Color, Mesh,
+ InstancedMesh, CapsuleGeometry, SphereGeometry, MeshStandardMaterial,
+ BoxGeometry, CylinderGeometry, MeshBasicMaterial,
+} from 'three';
+import { AnimationManager } from '../../animation-manager.js';
+import { buildAvatar, CLIP_WALK } from '../avatar-rig.js';
+import { mulberry32 } from './nav-graph.js';
+
+const GALLERY_URL = '/api/avatars/public?limit=24';
+const DEFAULT_AVATAR = '/avatars/default.glb';
+
+const PED_WALK_SPEED = 1.35; // m/s along the loop — an unhurried stroll
+const DETAILED_PEDS = 6; // GLB-bodied pedestrians near the centre
+const IMPOSTOR_PEDS = 14; // cheap instanced crowd in the distance
+const VEHICLES = 5; // cars/wagons on the ring road
+const VEHICLE_SPEED = 6.5; // m/s
+const PED_AVOID_RADIUS = 2.0; // how close before a ped sidesteps the player
+const CAR_BRAKE_RADIUS = 5.5; // how close before a car yields to the player
+
+const PED_LINES = ['gm', 'wagmi', 'nice build', 'lfg', 'few understand', 'vibes', 'we so back', 'probably nothing'];
+
+// One shared wall clock, in seconds. Clients are NTP-close, so a continuous
+// function of this reads identically across machines for ambient purposes.
+const worldClock = () => Date.now() / 1000;
+
+// ---- detailed GLB pedestrian -------------------------------------------------
+
+class Pedestrian {
+ constructor(scene, nav, { loopIdx, phase, speedScale, avatarUrl, seed }) {
+ this.scene = scene;
+ this.nav = nav;
+ this.loopIdx = loopIdx;
+ this.phase = phase;
+ this.speed = PED_WALK_SPEED * speedScale;
+ this.height = 1.7;
+ this._disposed = false;
+ this._avoid = new Vector3();
+ this._rng = mulberry32(seed);
+ this._sayIn = 8 + this._rng() * 22;
+
+ this.rig = new Group();
+ scene.add(this.rig);
+ this.anim = new AnimationManager();
+ this.bubble = null;
+ this._bubbleTimer = null;
+
+ buildAvatar(this.rig, avatarUrl || DEFAULT_AVATAR, this.anim)
+ .then(({ height }) => {
+ if (this._disposed) return;
+ this.height = height;
+ // Loaded into idle by buildAvatar — set them strolling.
+ this.anim.crossfadeTo(CLIP_WALK, 0.2).catch(() => {});
+ })
+ .catch(() => {});
+ }
+
+ say(text) {
+ if (this.bubble) this.bubble.remove();
+ this.bubble = document.createElement('div');
+ this.bubble.className = 'cc-bubble npc-bubble';
+ this.bubble.textContent = text;
+ document.body.appendChild(this.bubble);
+ clearTimeout(this._bubbleTimer);
+ this._bubbleTimer = setTimeout(() => { this.bubble?.remove(); this.bubble = null; }, 4000);
+ }
+
+ update(dt, T, player) {
+ // Base position is a pure function of the shared clock — identical on every
+ // client. Arc-length advances at a steady stroll.
+ const d = this.phase + this.speed * T;
+ const p = this.nav.pedPoint(this.loopIdx, d);
+
+ // Local, cosmetic sidestep around the player. Re-converges to zero, so it
+ // never desyncs the shared baseline between clients.
+ if (player) {
+ const dx = p.x - player.x, dz = p.z - player.z;
+ const dist = Math.hypot(dx, dz);
+ if (dist < PED_AVOID_RADIUS && dist > 1e-3) {
+ const push = (PED_AVOID_RADIUS - dist);
+ this._avoid.x += (dx / dist * push - this._avoid.x) * Math.min(1, dt * 4);
+ this._avoid.z += (dz / dist * push - this._avoid.z) * Math.min(1, dt * 4);
+ }
+ }
+ this._avoid.multiplyScalar(1 - Math.min(1, dt * 2));
+
+ this.rig.position.set(p.x + this._avoid.x, 0, p.z + this._avoid.z);
+ this.rig.rotation.y = Math.atan2(p.dirX, p.dirZ);
+ this.anim.update(dt);
+
+ this._sayIn -= dt;
+ if (this._sayIn <= 0) { this._sayIn = 14 + this._rng() * 26; this.say(PED_LINES[(this._rng() * PED_LINES.length) | 0]); }
+ }
+
+ dispose() {
+ this._disposed = true;
+ this.scene.remove(this.rig);
+ this.bubble?.remove();
+ clearTimeout(this._bubbleTimer);
+ this.anim.dispose?.();
+ }
+}
+
+// ---- vehicle (grouped, biome-styled) -----------------------------------------
+
+// Build a low-poly vehicle. style 'wagon' for frontier towns, 'car' elsewhere.
+// Shared unit geometry scaled per part keeps a vehicle to a handful of meshes.
+function buildVehicle(style) {
+ const g = new Group();
+ const box = new BoxGeometry(1, 1, 1);
+ const wheelGeo = new CylinderGeometry(0.34, 0.34, 0.22, 12);
+ const wheels = [];
+ const wheelMat = new MeshStandardMaterial({ color: 0x1a1a1d, roughness: 0.9 });
+ const addWheel = (x, z) => {
+ const w = new Mesh(wheelGeo, wheelMat);
+ w.rotation.z = Math.PI / 2;
+ w.position.set(x, 0.34, z);
+ w.castShadow = true;
+ g.add(w); wheels.push(w);
+ };
+
+ let brakeLights = null;
+ if (style === 'wagon') {
+ const bodyMat = new MeshStandardMaterial({ color: 0x6e5238, roughness: 1 });
+ const coverMat = new MeshStandardMaterial({ color: 0xd8cdb0, roughness: 1 });
+ const body = new Mesh(box, bodyMat); body.scale.set(1.5, 0.7, 3.0); body.position.y = 0.75; body.castShadow = true; g.add(body);
+ const cover = new Mesh(box, coverMat); cover.scale.set(1.45, 1.0, 2.2); cover.position.set(0, 1.45, -0.1); cover.castShadow = true; g.add(cover);
+ // A simple draft animal up front so a wagon isn't gliding on its own.
+ const horse = new Mesh(box, new MeshStandardMaterial({ color: 0x3a2a1e, roughness: 1 }));
+ horse.scale.set(0.7, 0.9, 1.4); horse.position.set(0, 0.9, 2.4); horse.castShadow = true; g.add(horse);
+ addWheel(-0.85, 1.0); addWheel(0.85, 1.0); addWheel(-0.85, -1.0); addWheel(0.85, -1.0);
+ } else {
+ const bodyMat = new MeshStandardMaterial({ color: 0x2b3340, roughness: 0.5, metalness: 0.3 });
+ const cabinMat = new MeshStandardMaterial({ color: 0x10151c, roughness: 0.3, metalness: 0.2 });
+ const body = new Mesh(box, bodyMat); body.scale.set(1.7, 0.7, 3.6); body.position.y = 0.62; body.castShadow = true; g.add(body);
+ const cabin = new Mesh(box, cabinMat); cabin.scale.set(1.5, 0.7, 1.9); cabin.position.set(0, 1.15, -0.1); cabin.castShadow = true; g.add(cabin);
+ const head = new Mesh(box, new MeshBasicMaterial({ color: 0xfff3cf })); head.scale.set(1.5, 0.16, 0.1); head.position.set(0, 0.62, 1.81); g.add(head);
+ brakeLights = new Mesh(box, new MeshBasicMaterial({ color: 0x551111 })); brakeLights.scale.set(1.5, 0.18, 0.1); brakeLights.position.set(0, 0.62, -1.81); g.add(brakeLights);
+ addWheel(-0.92, 1.15); addWheel(0.92, 1.15); addWheel(-0.92, -1.2); addWheel(0.92, -1.2);
+ }
+ return { group: g, wheels, brakeLights };
+}
+
+class Vehicle {
+ constructor(scene, nav, { phase, lane, style, dir }) {
+ this.nav = nav;
+ this.phase = phase;
+ this.lane = lane;
+ this.dir = dir; // +1 / -1 travel direction around the ring
+ this.curL = phase;
+ const built = buildVehicle(style);
+ this.group = built.group;
+ this.wheels = built.wheels;
+ this.brakeLights = built.brakeLights;
+ scene.add(this.group);
+ this.scene = scene;
+ }
+
+ update(dt, T, player) {
+ // Target arc-length from the shared clock — the consistent baseline.
+ const targetL = this.phase + this.dir * VEHICLE_SPEED * T;
+
+ // Yield to the local player: if they're standing on the road just ahead,
+ // hold position rather than drive through them. This is local-only (each
+ // player sees traffic yield to them) and re-converges to the baseline once
+ // the road clears, so the shared schedule stays the source of truth.
+ let blocked = false;
+ if (player) {
+ const ahead = this.nav.roadPoint(this.curL + this.dir * 3.5, this.lane);
+ const dx = ahead.x - player.x, dz = ahead.z - player.z;
+ if (Math.hypot(dx, dz) < CAR_BRAKE_RADIUS) blocked = true;
+ }
+ const desired = blocked ? Math.min(this.curL, targetL, this.curL) : targetL;
+ const prevL = this.curL;
+ this.curL += (desired - this.curL) * Math.min(1, dt * (blocked ? 4 : 2.5));
+
+ const p = this.nav.roadPoint(this.curL, this.lane);
+ this.group.position.set(p.x, 0, p.z);
+ this.group.rotation.y = Math.atan2(p.dirX * this.dir, p.dirZ * this.dir);
+
+ // Spin the wheels with actual travel; flash brake lights when yielding.
+ const moved = Math.abs(this.curL - prevL);
+ for (const w of this.wheels) w.rotation.x += moved * 1.8;
+ if (this.brakeLights) this.brakeLights.material.color.setHex(blocked ? 0xff3b30 : 0x551111);
+ }
+
+ dispose() { this.scene.remove(this.group); }
+}
+
+// ---- the ambient-life system -------------------------------------------------
+
+export class AmbientLife {
+ constructor({ scene, nav, biome }) {
+ this.scene = scene;
+ this.nav = nav;
+ this.biome = biome;
+ this.peds = [];
+ this.vehicles = [];
+ this._avatarPool = null;
+ this._impostor = null;
+ this._dummy = new Object3D();
+ this._wantPeds = DETAILED_PEDS;
+
+ this._buildImpostors();
+ this._buildVehicles();
+ this._loadAvatarPoolThenPeds();
+ }
+
+ // A single InstancedMesh pair (bodies + heads) carries the whole background
+ // crowd on the outermost loop — one draw call each, no per-ped objects.
+ _buildImpostors() {
+ const rand = mulberry32((this.nav.seed ^ 0x9e3779b9) >>> 0);
+ const bodyGeo = new CapsuleGeometry(0.28, 0.7, 4, 8);
+ const headGeo = new SphereGeometry(0.22, 10, 8);
+ const bodyMat = new MeshStandardMaterial({ roughness: 0.95 });
+ const headMat = new MeshStandardMaterial({ roughness: 0.9, color: 0xcaa98a });
+ const bodies = new InstancedMesh(bodyGeo, bodyMat, IMPOSTOR_PEDS);
+ const heads = new InstancedMesh(headGeo, headMat, IMPOSTOR_PEDS);
+ bodies.castShadow = true;
+ this._impostorSpec = [];
+ const palette = [0x5a6472, 0x6b5a72, 0x4d6b5a, 0x72655a, 0x556070];
+ for (let i = 0; i < IMPOSTOR_PEDS; i++) {
+ bodies.setColorAt(i, new Color(palette[i % palette.length]));
+ this._impostorSpec.push({
+ loopIdx: 0, // outermost loop only — keeps impostors in the distance
+ phase: rand() * 1000,
+ speed: PED_WALK_SPEED * (0.85 + rand() * 0.4),
+ bob: rand() * Math.PI * 2,
+ });
+ }
+ if (bodies.instanceColor) bodies.instanceColor.needsUpdate = true;
+ this.scene.add(bodies, heads);
+ this._impostor = { bodies, heads };
+ }
+
+ _buildVehicles() {
+ const rand = mulberry32((this.nav.seed ^ 0x85ebca6b) >>> 0);
+ const style = this.biome?.town === 'frontier' ? 'wagon' : 'car';
+ const spacing = this.nav.roadLen / VEHICLES;
+ for (let i = 0; i < VEHICLES; i++) {
+ const dir = i % 2 === 0 ? 1 : -1;
+ const lane = dir > 0 ? -this.nav.roadWidth * 0.22 : this.nav.roadWidth * 0.22;
+ this.vehicles.push(new Vehicle(this.scene, this.nav, {
+ phase: i * spacing + rand() * spacing * 0.4,
+ lane,
+ dir,
+ style,
+ }));
+ }
+ }
+
+ async _loadAvatarPoolThenPeds() {
+ let urls = [];
+ try {
+ const r = await fetch(GALLERY_URL, { headers: { accept: 'application/json' } });
+ if (r.ok) { const { avatars } = await r.json(); urls = (avatars || []).map((a) => a.model_url || a.base_model_url).filter(Boolean); }
+ } catch { /* default-avatar fallback below */ }
+ this._avatarPool = urls;
+ this._syncPeds();
+ }
+
+ // Deterministic avatar assignment: shuffle the pool by seed so ped #k shows the
+ // same model on every client.
+ _pedAvatar(k) {
+ const pool = this._avatarPool;
+ if (!pool || !pool.length) return DEFAULT_AVATAR;
+ const rand = mulberry32((this.nav.seed ^ (k * 0x27d4eb2f)) >>> 0);
+ return pool[(rand() * pool.length) | 0];
+ }
+
+ _syncPeds() {
+ if (!this._avatarPool) return; // pool still loading
+ const want = this._wantPeds;
+ while (this.peds.length < want) {
+ const k = this.peds.length;
+ const rand = mulberry32((this.nav.seed ^ (k * 0x165667b1)) >>> 0);
+ // Detailed peds ride the inner loops; impostors hold the outer one.
+ const loopIdx = 1 + (k % (this.nav.pedLoopCount - 1));
+ this.peds.push(new Pedestrian(this.scene, this.nav, {
+ loopIdx,
+ phase: rand() * 1000,
+ speedScale: 0.85 + rand() * 0.4,
+ avatarUrl: this._pedAvatar(k),
+ seed: (this.nav.seed ^ (k * 0x9e3779b9)) >>> 0,
+ }));
+ }
+ while (this.peds.length > want) this.peds.pop().dispose();
+ }
+
+ // The crowd tapers as real peers arrive, so the world is lively when empty but
+ // never padded with fakes once it's genuinely busy. Peer count is the room's
+ // authoritative set, so this stays consistent across clients.
+ setRealPeers(n) {
+ const want = Math.max(0, DETAILED_PEDS - (n | 0));
+ if (want === this._wantPeds) return;
+ this._wantPeds = want;
+ this._syncPeds();
+ }
+
+ // Drive everything from the shared clock. `project` places detailed-ped speech
+ // bubbles; `player` is the local player position for reactivity.
+ update(dt, { player, project } = {}) {
+ const T = worldClock();
+
+ for (const p of this.peds) {
+ p.update(dt, T, player);
+ if (p.bubble && project) project(p.bubble, p.rig.position.x, p.height + 0.6, p.rig.position.z);
+ }
+ for (const v of this.vehicles) v.update(dt, T, player);
+
+ // Impostor crowd — one matrix write per instance, distance only.
+ if (this._impostor) {
+ const { bodies, heads } = this._impostor;
+ for (let i = 0; i < this._impostorSpec.length; i++) {
+ const s = this._impostorSpec[i];
+ const pt = this.nav.pedPoint(s.loopIdx, s.phase + s.speed * T);
+ const bob = Math.sin(T * 4 + s.bob) * 0.04;
+ this._dummy.position.set(pt.x, 0.71 + bob, pt.z);
+ this._dummy.rotation.set(0, Math.atan2(pt.dirX, pt.dirZ), 0);
+ this._dummy.updateMatrix();
+ bodies.setMatrixAt(i, this._dummy.matrix);
+ this._dummy.position.y = 1.5 + bob;
+ this._dummy.updateMatrix();
+ heads.setMatrixAt(i, this._dummy.matrix);
+ }
+ bodies.instanceMatrix.needsUpdate = true;
+ heads.instanceMatrix.needsUpdate = true;
+ }
+ }
+
+ // Honest live counts for the manager's HUD / debugging.
+ get counts() {
+ return { detailed: this.peds.length, impostors: IMPOSTOR_PEDS, vehicles: this.vehicles.length };
+ }
+
+ dispose() {
+ for (const p of this.peds) p.dispose();
+ for (const v of this.vehicles) v.dispose();
+ this.peds = []; this.vehicles = [];
+ if (this._impostor) {
+ this.scene.remove(this._impostor.bodies, this._impostor.heads);
+ this._impostor.bodies.geometry.dispose();
+ this._impostor.heads.geometry.dispose();
+ this._impostor = null;
+ }
+ }
+}
diff --git a/src/game/npc/mobs.js b/src/game/npc/mobs.js
new file mode 100644
index 000000000..cc3312972
--- /dev/null
+++ b/src/game/npc/mobs.js
@@ -0,0 +1,133 @@
+// Hostile mobs & enforcers (W08 × W07).
+//
+// Mobs are consequential — they deal damage and drop loot — so unlike the
+// ambient crowd they are NOT client-authoritative. Their existence, health,
+// damage, and rewards belong to the combat system (W07). This module is the
+// *visual + navigation* half: given an authoritative hostile from W07, it puts a
+// body in the world and walks it toward its target along the nav graph; contact
+// is only ever *reported* to W07, which decides the outcome. Nothing here can be
+// spoofed from the client because nothing here grants an effect.
+//
+// W07 isn't merged yet, so this system is fully gated: with no `window.twsCombat`
+// contract present it spawns nothing and fakes no combat — it simply sleeps until
+// the foundation it depends on lands. The contract it consumes:
+//
+// window.twsCombat.onHostileSpawn(cb) cb({ id, kind, pos, target, speed })
+// window.twsCombat.onHostileState(cb) cb({ id, pos?, target? }) // server moves
+// window.twsCombat.onHostileDespawn(cb) cb({ id })
+// window.twsCombat.reportContact(id) // mob reached melee range — server rules
+//
+// When W07 ships, mobs light up with zero changes here.
+
+import { Group, Mesh, Vector3, CapsuleGeometry, SphereGeometry, MeshStandardMaterial } from 'three';
+
+const MOB_TINT = { enforcer: 0x3a4656, bandit: 0x5a2a2a };
+const CONTACT_RANGE = 1.6; // metres — when we tell W07 the mob is in melee
+const REPATH_INTERVAL = 0.6; // s between navmesh queries while chasing
+
+// A single hostile body — a menacing capsule until W07 supplies a model. It walks
+// toward a target the server owns; it never decides anything.
+class Mob {
+ constructor(scene, nav, spec) {
+ this.scene = scene;
+ this.nav = nav;
+ this.id = spec.id;
+ this.speed = spec.speed || 2.4;
+ this.target = new Vector3(spec.target?.x || 0, 0, spec.target?.z || 0);
+ this._path = [];
+ this._repathIn = 0;
+ this._contacted = false;
+
+ this.rig = new Group();
+ this.rig.position.set(spec.pos?.x || 0, 0, spec.pos?.z || 0);
+ const tint = MOB_TINT[spec.kind] || MOB_TINT.enforcer;
+ const body = new Mesh(new CapsuleGeometry(0.32, 0.8, 4, 10), new MeshStandardMaterial({ color: tint, roughness: 0.85 }));
+ body.position.y = 0.95; body.castShadow = true;
+ const head = new Mesh(new SphereGeometry(0.26, 12, 10), new MeshStandardMaterial({ color: tint, roughness: 0.8 }));
+ head.position.y = 1.65; head.castShadow = true;
+ this.rig.add(body, head);
+ scene.add(this.rig);
+ }
+
+ setTarget(pos) { if (pos) { this.target.set(pos.x || 0, 0, pos.z || 0); this._repathIn = 0; } }
+ setPos(pos) { if (pos) this.rig.position.set(pos.x || 0, 0, pos.z || 0); }
+
+ async _repath() {
+ this._path = await this.nav.findPath(this.rig.position, this.target);
+ }
+
+ update(dt, onContact) {
+ this._repathIn -= dt;
+ if (this._repathIn <= 0) { this._repathIn = REPATH_INTERVAL; this._repath(); }
+
+ const wp = this._path[0];
+ if (wp) {
+ const p = this.rig.position;
+ const dx = wp.x - p.x, dz = wp.z - p.z;
+ const dist = Math.hypot(dx, dz);
+ if (dist < 0.4) { this._path.shift(); }
+ else {
+ const step = Math.min(dist, this.speed * dt);
+ p.x += dx / dist * step; p.z += dz / dist * step;
+ this.rig.rotation.y = Math.atan2(dx, dz);
+ }
+ }
+
+ // Reached melee range of its target: report once and let W07 rule on it.
+ const tx = this.target.x - this.rig.position.x, tz = this.target.z - this.rig.position.z;
+ if (!this._contacted && Math.hypot(tx, tz) < CONTACT_RANGE) {
+ this._contacted = true;
+ onContact?.(this.id);
+ } else if (this._contacted && Math.hypot(tx, tz) > CONTACT_RANGE * 1.5) {
+ this._contacted = false; // left melee — allow a future contact report
+ }
+ }
+
+ dispose() { this.scene.remove(this.rig); }
+}
+
+export class MobSystem {
+ constructor({ scene, nav }) {
+ this.scene = scene;
+ this.nav = nav;
+ this.mobs = new Map();
+ this._unsub = [];
+
+ const combat = typeof window !== 'undefined' ? window.twsCombat : null;
+ this.enabled = !!(combat && typeof combat.onHostileSpawn === 'function');
+ if (!this.enabled) return; // W07 absent — sleep, spawn nothing, fake nothing
+
+ this.combat = combat;
+ this._unsub.push(combat.onHostileSpawn((spec) => this._spawn(spec)));
+ if (combat.onHostileState) this._unsub.push(combat.onHostileState((s) => this._state(s)));
+ if (combat.onHostileDespawn) this._unsub.push(combat.onHostileDespawn(({ id }) => this._despawn(id)));
+ }
+
+ _spawn(spec) {
+ if (!spec?.id || this.mobs.has(spec.id)) return;
+ this.mobs.set(spec.id, new Mob(this.scene, this.nav, spec));
+ }
+ _state(s) {
+ const m = this.mobs.get(s?.id);
+ if (!m) return;
+ if (s.target) m.setTarget(s.target);
+ if (s.pos) m.setPos(s.pos);
+ }
+ _despawn(id) {
+ const m = this.mobs.get(id);
+ if (m) { m.dispose(); this.mobs.delete(id); }
+ }
+
+ update(dt) {
+ if (!this.enabled || !this.mobs.size) return;
+ const report = (id) => { try { this.combat.reportContact?.(id); } catch { /* contract optional */ } };
+ for (const m of this.mobs.values()) m.update(dt, report);
+ }
+
+ dispose() {
+ for (const fn of this._unsub) { try { fn?.(); } catch { /* ignore */ } }
+ this._unsub = [];
+ for (const m of this.mobs.values()) m.dispose();
+ this.mobs.clear();
+ }
+}
diff --git a/src/game/npc/nav-graph.js b/src/game/npc/nav-graph.js
new file mode 100644
index 000000000..e9b561ef2
--- /dev/null
+++ b/src/game/npc/nav-graph.js
@@ -0,0 +1,158 @@
+// Deterministic navigation substrate for the living world (W08).
+//
+// The world has no streamed road network yet (that lands with W01). Until then,
+// this module synthesizes a navigation graph from the plaza's own geometry — a
+// set of closed pedestrian loops and one ring road — entirely as a *pure
+// function of the world seed*. Same coin → identical graph on every client, so
+// the crowd and traffic that ride it (ambient-life.js) read the same everywhere
+// without syncing a single NPC over the wire.
+//
+// When W01 ships a real navmesh it registers it via `registerNavmesh()`; from
+// then on `findPath()` routes through three-pathfinding (lazy-imported only when
+// a navmesh actually exists, so the package never weighs on the bundle until the
+// foundation that needs it is merged). Everything else — pedestrians, traffic,
+// mob AI — consumes this one graph, so the day the navmesh arrives the world's
+// life upgrades in place.
+
+import { Vector3 } from 'three';
+
+// mulberry32 — a tiny, fast, seedable PRNG. Deterministic given a seed, so the
+// whole graph (and the life on it) is reproducible across clients.
+export function mulberry32(seed) {
+ let a = seed >>> 0;
+ return function () {
+ a |= 0; a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+// One closed ring of points at radius R, with optional per-point radial waviness
+// so a pedestrian loop reads as an organic stroll rather than a perfect circle.
+function ringLoop(R, segments, rand, waviness = 0) {
+ const pts = [];
+ for (let i = 0; i < segments; i++) {
+ const a = (i / segments) * Math.PI * 2;
+ const r = R * (1 + (waviness ? (rand() - 0.5) * 2 * waviness : 0));
+ pts.push({ x: Math.cos(a) * r, z: Math.sin(a) * r });
+ }
+ return pts;
+}
+
+// Arc-length of a closed polyline (last point wraps to the first).
+function loopLength(pts) {
+ let len = 0;
+ for (let i = 0; i < pts.length; i++) {
+ const a = pts[i], b = pts[(i + 1) % pts.length];
+ len += Math.hypot(b.x - a.x, b.z - a.z);
+ }
+ return len;
+}
+
+// Sample a closed polyline at arc-length `dist` (wrapping). Returns the world
+// position and the unit tangent (heading) at that point — the heading lets an
+// NPC face the way it's walking with zero extra state.
+function sampleLoop(pts, dist) {
+ const total = loopLength(pts);
+ let d = ((dist % total) + total) % total;
+ for (let i = 0; i < pts.length; i++) {
+ const a = pts[i], b = pts[(i + 1) % pts.length];
+ const seg = Math.hypot(b.x - a.x, b.z - a.z);
+ if (d <= seg || i === pts.length - 1) {
+ const t = seg > 1e-6 ? d / seg : 0;
+ return {
+ x: a.x + (b.x - a.x) * t,
+ z: a.z + (b.z - a.z) * t,
+ dirX: seg > 1e-6 ? (b.x - a.x) / seg : 0,
+ dirZ: seg > 1e-6 ? (b.z - a.z) / seg : 1,
+ };
+ }
+ d -= seg;
+ }
+ return { x: pts[0].x, z: pts[0].z, dirX: 0, dirZ: 1 };
+}
+
+export class NavGraph {
+ // radius: the inner play circle NPCs may roam (kept inside the server clamp).
+ constructor({ radius = 54, seed = 0 } = {}) {
+ this.radius = radius;
+ this.seed = seed >>> 0;
+ const rand = mulberry32(this.seed || 0x3d3d3d);
+
+ // Pedestrian loops at descending radii so foot traffic fills the plaza in
+ // depth instead of a single conga line. Jittered for organic paths.
+ this.pedLoops = [
+ ringLoop(radius * 0.82, 18, rand, 0.05),
+ ringLoop(radius * 0.58, 14, rand, 0.06),
+ ringLoop(radius * 0.34, 10, rand, 0.07),
+ ];
+ // Each loop's cached length, so samplers don't recompute every frame.
+ this._pedLens = this.pedLoops.map(loopLength);
+
+ // One clean ring road just inside the plaza edge — vehicles want a smooth,
+ // predictable path, so no waviness here. Width drives the asphalt band the
+ // world-life manager paints under it.
+ this.road = ringLoop(radius * 0.92, 48, rand);
+ this.roadRadius = radius * 0.92;
+ this.roadLen = loopLength(this.road);
+ this.roadWidth = 4.6;
+
+ // W01 navmesh, registered later. While null, every query falls back to the
+ // synthesized graph above.
+ this._navmesh = null; // { zone, geometry } once W01 registers one
+ this._pathfinding = null; // lazily-constructed three-pathfinding instance
+ this._zoneId = 'play';
+ }
+
+ // Sample pedestrian loop `i` at arc-length `dist`. Pure function of its args,
+ // hence identical on every client given the same world time.
+ pedPoint(i, dist) {
+ const loop = this.pedLoops[i % this.pedLoops.length];
+ return sampleLoop(loop, dist);
+ }
+ pedLoopLength(i) { return this._pedLens[i % this._pedLens.length]; }
+ get pedLoopCount() { return this.pedLoops.length; }
+
+ // Sample the ring road at arc-length `dist`, offset `lane` metres to the
+ // inside (negative) or outside (positive) of the centre-line.
+ roadPoint(dist, lane = 0) {
+ const p = sampleLoop(this.road, dist);
+ // Right-hand normal of the tangent, scaled by the lane offset.
+ return { x: p.x + p.dirZ * lane, z: p.z - p.dirX * lane, dirX: p.dirX, dirZ: p.dirZ };
+ }
+
+ // W01 hands us its navmesh geometry + zone here. We don't build the
+ // three-pathfinding instance yet — that happens lazily on the first findPath()
+ // so the package stays out of the bundle until a navmesh is genuinely present.
+ registerNavmesh({ geometry, zoneId = 'play' } = {}) {
+ if (!geometry) return;
+ this._navmesh = { geometry };
+ this._zoneId = zoneId;
+ this._pathfinding = null; // rebuild on next path query
+ }
+ get hasNavmesh() { return !!this._navmesh; }
+
+ // Route from `from` to `to`. With a navmesh, this is a real A* path through
+ // three-pathfinding; without one, a straight segment (the synthesized graph is
+ // open plaza, so a direct line is the honest answer). Async because the
+ // pathfinder is lazy-imported on first use.
+ async findPath(from, to) {
+ const start = from instanceof Vector3 ? from : new Vector3(from.x, from.y || 0, from.z);
+ const end = to instanceof Vector3 ? to : new Vector3(to.x, to.y || 0, to.z);
+ if (!this._navmesh) return [end.clone()];
+ try {
+ if (!this._pathfinding) {
+ const { Pathfinding } = await import('three-pathfinding');
+ this._pathfinding = new Pathfinding();
+ this._pathfinding.setZoneData(this._zoneId, Pathfinding.createZone(this._navmesh.geometry));
+ }
+ const groupId = this._pathfinding.getGroup(this._zoneId, start);
+ const path = this._pathfinding.findPath(start, end, this._zoneId, groupId);
+ return path && path.length ? path : [end.clone()];
+ } catch {
+ // A malformed navmesh shouldn't strand an NPC — fall back to direct.
+ return [end.clone()];
+ }
+ }
+}
diff --git a/src/game/npc/npc-catalog.js b/src/game/npc/npc-catalog.js
new file mode 100644
index 000000000..cc08bee49
--- /dev/null
+++ b/src/game/npc/npc-catalog.js
@@ -0,0 +1,167 @@
+// Data-driven catalog of interactive NPCs.
+//
+// One table, read by world-life.js, describes every vendor, quest-giver, and
+// flavor townsperson in a world: who they are, where they stand, what they say,
+// and what pressing E does. Adding an NPC is a table entry, never new wiring.
+//
+// Role actions reach the economy (W04) and quest (W05) systems through small
+// `window` contracts so this brief can ship before those do: if the system is
+// present the NPC drives it; if not, the NPC gives a designed, honest "opens with
+// the next update" beat instead of a dead button or a faked shop. The contracts:
+//
+// window.twsEconomy.openVendor(shop) → open a buy/sell shop (W04)
+// window.twsQuests.offerMission(mission) → present a job/mission (W05)
+//
+// The flagship $THREE town gets the full cast first (W00: land flagship features
+// in the home town). Every other coin world gets a couple of flavor locals so it
+// never feels abandoned.
+
+import { isHomeTown } from '../home-town.js';
+
+const AVATAR_A = '/avatars/default.glb';
+const AVATAR_B = '/avatars/cz.glb';
+
+// Reach the W04 vendor system, or fall back to an honest "coming soon" beat that
+// still tells the player exactly what this stall will do.
+function openVendorOrInform({ npc, ui }) {
+ const shop = npc.def.shop;
+ const econ = typeof window !== 'undefined' ? window.twsEconomy : null;
+ if (econ && typeof econ.openVendor === 'function') {
+ npc.say(shop.greeting);
+ npc.emote('av-call-me');
+ econ.openVendor(shop);
+ return;
+ }
+ npc.say(shop.soon);
+ ui?.toast?.(`${shop.title} — opens with the in-world economy.`, 'info');
+}
+
+// Reach the W05 mission system, or fall back to an honest "no work yet" beat.
+function offerMissionOrInform({ npc, ui }) {
+ const mission = npc.def.mission;
+ const quests = typeof window !== 'undefined' ? window.twsQuests : null;
+ if (quests && typeof quests.offerMission === 'function') {
+ npc.say(mission.greeting);
+ npc.emote('av-arm-flex');
+ quests.offerMission(mission);
+ return;
+ }
+ npc.say(mission.soon);
+ ui?.toast?.(`${mission.title} — jobs open with the missions update.`, 'info');
+}
+
+// Build the interactive-NPC list for a world. `world` carries { mint, biome }.
+export function npcCatalogFor(world) {
+ const list = [];
+ const home = isHomeTown(world?.mint);
+
+ if (home) {
+ // The market trader — the front of the economy. Stands plaza-west with a
+ // stall the manager paints behind him.
+ list.push({
+ id: 'vendor-market',
+ name: 'Marisol · Trader',
+ role: 'vendor',
+ avatar: AVATAR_B,
+ pos: { x: -11, z: -3 },
+ yaw: Math.PI / 2,
+ range: 5,
+ prompt: 'Browse the market',
+ onInteract: openVendorOrInform,
+ shop: {
+ id: 'general',
+ title: 'Dust Gulch Market',
+ greeting: 'Welcome, partner. Everything’s priced fair.',
+ soon: 'Stall’s nearly stocked — the market opens with the next update.',
+ // Catalog described honestly so the empty state still teaches what's coming.
+ goods: [
+ { name: 'Fishing Rod', kind: 'tool' },
+ { name: 'Pickaxe', kind: 'tool' },
+ { name: 'Lantern', kind: 'gear' },
+ ],
+ },
+ });
+
+ // The sheriff — quest-giver. Posts work on the board by the jail.
+ list.push({
+ id: 'quest-sheriff',
+ name: 'Sheriff Boone',
+ role: 'quest',
+ avatar: AVATAR_A,
+ pos: { x: -13, z: 9 },
+ yaw: 0,
+ range: 5,
+ prompt: 'See available work',
+ onInteract: offerMissionOrInform,
+ mission: {
+ id: 'first-bounty',
+ title: 'Sheriff’s Board',
+ greeting: 'Town could use a hand. Pick up a job off the board.',
+ soon: 'No bounties posted yet — work opens with the missions update.',
+ },
+ });
+
+ // Flavor locals — pure life, cycle through chatter.
+ list.push({
+ id: 'flavor-prospector',
+ name: 'Old Pete',
+ role: 'flavor',
+ avatar: AVATAR_B,
+ pos: { x: 15, z: 11 },
+ yaw: -Math.PI * 0.7,
+ prompt: 'Talk',
+ dialogue: [
+ 'Struck color up the mesa once. Spent it all by sundown.',
+ 'You watch them two robots by the plaza? Tradin’ real coin.',
+ 'Storm’s comin’. Always is, out here.',
+ ],
+ });
+ list.push({
+ id: 'flavor-piano',
+ name: 'Saloon Kid',
+ role: 'flavor',
+ avatar: AVATAR_A,
+ pos: { x: -6, z: 17 },
+ yaw: -Math.PI / 2,
+ prompt: 'Talk',
+ dialogue: [
+ 'Drinks are on the house — once we get a bartender.',
+ 'Heard the bank’s holdin’ real $THREE in the vault.',
+ 'You build somethin’ nice, I’ll play you a tune.',
+ ],
+ });
+ return list;
+ }
+
+ // Any other coin world: a couple of locals so the plaza has a pulse, placed
+ // off the spawn line.
+ list.push({
+ id: 'flavor-local-1',
+ name: 'Local',
+ role: 'flavor',
+ avatar: AVATAR_A,
+ pos: { x: -12, z: 6 },
+ yaw: Math.PI / 3,
+ prompt: 'Talk',
+ dialogue: [
+ 'New here? Walk around — you can build on this world.',
+ 'Whole place runs on $THREE. Few understand.',
+ 'More folks show up every day. We so back.',
+ ],
+ });
+ list.push({
+ id: 'flavor-local-2',
+ name: 'Local',
+ role: 'flavor',
+ avatar: AVATAR_B,
+ pos: { x: 13, z: -8 },
+ yaw: -Math.PI * 0.8,
+ prompt: 'Talk',
+ dialogue: [
+ 'gm. Vibes are immaculate today.',
+ 'Press B to build with everyone here.',
+ 'This is the way.',
+ ],
+ });
+ return list;
+}
diff --git a/src/game/npc/npc.js b/src/game/npc/npc.js
new file mode 100644
index 000000000..da405fb26
--- /dev/null
+++ b/src/game/npc/npc.js
@@ -0,0 +1,137 @@
+// A generalized interactive NPC — the reusable engine behind the Agent Exchange.
+//
+// agent-commerce.js proved the pattern: a GLB-bodied character standing in the
+// world, a proximity prompt, a dialogue beat, and a real role action on E/tap.
+// This class is that pattern with the x402-specific bits lifted out, so vendors
+// (W04), quest-givers (W05), and flavor townsfolk are all the same object with a
+// different `def`. The Agent Exchange remains its own special module; everything
+// else in the world is an Npc.
+//
+// The NPC owns only its body, nameplate, and speech bubble. The single shared
+// "press E" prompt and interaction dispatch live on the world-life manager, so a
+// plaza full of NPCs shows one prompt for whichever you're closest to, never a
+// thicket of them.
+
+import { Group, Vector3 } from 'three';
+import { AnimationManager } from '../../animation-manager.js';
+import { resolveAvatarUrl, buildAvatar, CLIP_IDLE, CLIP_WALK } from '../avatar-rig.js';
+import { playEmoteClip } from '../avatar-rig.js';
+
+const BUBBLE_MS = 4600;
+
+// Role → nameplate accent. Monochrome-first to match the site tokens; the marker
+// ring under the NPC carries the only colour, so the world stays calm.
+const ROLE_TINT = {
+ vendor: 'rgba(120, 220, 160, 0.95)',
+ quest: 'rgba(255, 210, 120, 0.95)',
+ flavor: 'rgba(255, 255, 255, 0.92)',
+};
+
+export class Npc {
+ // def: { id, name, role, avatar, pos:{x,z}, yaw, prompt, dialogue:[], onInteract }
+ constructor(scene, def) {
+ this.scene = scene;
+ this.def = def;
+ this.id = def.id;
+ this.name = def.name;
+ this.role = def.role || 'flavor';
+ this.height = 1.7;
+ this._disposed = false;
+ this._dialogueIdx = 0;
+ this._faceUntil = 0;
+
+ this.pos = new Vector3(def.pos.x, 0, def.pos.z);
+ this.baseYaw = def.yaw ?? 0;
+
+ this.rig = new Group();
+ this.rig.position.copy(this.pos);
+ this.rig.rotation.y = this.baseYaw;
+ scene.add(this.rig);
+
+ this.anim = new AnimationManager();
+
+ this.label = document.createElement('div');
+ this.label.className = 'cc-label npc-name';
+ this.label.style.setProperty('--npc-tint', ROLE_TINT[this.role] || ROLE_TINT.flavor);
+ this.label.textContent = def.name;
+ document.body.appendChild(this.label);
+
+ this.bubble = null;
+ this._bubbleTimer = null;
+
+ resolveAvatarUrl(def.avatar)
+ .then((u) => buildAvatar(this.rig, u, this.anim))
+ .then(({ height }) => { if (!this._disposed) this.height = height; })
+ .catch(() => {});
+ }
+
+ // How close a player must be to interact, in metres.
+ get range() { return this.def.range || 4.5; }
+
+ // Distance² from a player position to this NPC (cheap proximity test).
+ distanceTo(p) {
+ const dx = p.x - this.pos.x, dz = p.z - this.pos.z;
+ return Math.hypot(dx, dz);
+ }
+
+ say(text) {
+ if (!text) return;
+ if (this.bubble) this.bubble.remove();
+ this.bubble = document.createElement('div');
+ this.bubble.className = 'cc-bubble npc-bubble';
+ this.bubble.textContent = text;
+ document.body.appendChild(this.bubble);
+ clearTimeout(this._bubbleTimer);
+ this._bubbleTimer = setTimeout(() => { this.bubble?.remove(); this.bubble = null; }, BUBBLE_MS);
+ }
+
+ // Turn to face a point for a couple of seconds (called when the player walks
+ // up). Returns to the post heading afterwards in tick().
+ faceTowards(p) {
+ const dx = p.x - this.pos.x, dz = p.z - this.pos.z;
+ if (dx === 0 && dz === 0) return;
+ this._targetYaw = Math.atan2(dx, dz);
+ this._faceUntil = (typeof performance !== 'undefined' ? performance.now() : 0) + 2600;
+ }
+
+ async emote(name) {
+ try { await playEmoteClip(this.anim, name, 'idle'); } catch { /* clip missing */ }
+ }
+
+ // Run the NPC's role action. Custom `onInteract` (vendor/quest) takes over;
+ // otherwise cycle the flavor dialogue line by line so repeated taps feel like
+ // a conversation, not a stuck record.
+ interact(ctx) {
+ this.faceTowards(ctx.player);
+ if (typeof this.def.onInteract === 'function') {
+ try { this.def.onInteract({ npc: this, ...ctx }); } catch { /* role action failed — stay silent rather than crash the loop */ }
+ return;
+ }
+ const lines = this.def.dialogue || [];
+ if (!lines.length) return;
+ this.say(lines[this._dialogueIdx % lines.length]);
+ this._dialogueIdx++;
+ }
+
+ tick(dt) {
+ // Smoothly settle toward either the look-at-player yaw or the post heading.
+ const now = (typeof performance !== 'undefined' ? performance.now() : 0);
+ const want = (this._faceUntil > now && this._targetYaw != null) ? this._targetYaw : this.baseYaw;
+ let d = want - this.rig.rotation.y;
+ while (d > Math.PI) d -= Math.PI * 2;
+ while (d < -Math.PI) d += Math.PI * 2;
+ this.rig.rotation.y += d * Math.min(1, dt * 6);
+ this.anim.update(dt);
+ }
+
+ dispose() {
+ this._disposed = true;
+ this.scene.remove(this.rig);
+ this.label.remove();
+ this.bubble?.remove();
+ clearTimeout(this._bubbleTimer);
+ this.anim.dispose?.();
+ }
+}
+
+export { CLIP_IDLE, CLIP_WALK };
diff --git a/src/game/npc/world-life.js b/src/game/npc/world-life.js
new file mode 100644
index 000000000..724ee2c75
--- /dev/null
+++ b/src/game/npc/world-life.js
@@ -0,0 +1,211 @@
+// World life — the W08 manager that makes a coin world feel inhabited.
+//
+// It owns one deterministic nav graph and hangs everything off it: the ambient
+// crowd and traffic (ambient-life.js), the interactive NPCs from the catalog
+// (npc.js + npc-catalog.js), the W07-gated mobs (mobs.js), and the bit of road
+// geometry that makes the traffic legible. coincommunities.js builds one of these
+// per world on enter, ticks it in the render loop, routes E / tap to it, and
+// disposes it on leave — the same lifecycle the Agent Exchange already uses. The
+// Agent Exchange stays its own special module; this manages everyone else.
+
+import {
+ Group, Mesh, RingGeometry, MeshBasicMaterial, MeshStandardMaterial,
+ DoubleSide, Vector3, Raycaster, Vector2,
+} from 'three';
+import { NavGraph } from './nav-graph.js';
+import { AmbientLife } from './ambient-life.js';
+import { Npc } from './npc.js';
+import { npcCatalogFor } from './npc-catalog.js';
+import { MobSystem } from './mobs.js';
+import { log } from '../../shared/log.js';
+
+const ROLE_RING = { vendor: 0x46d49a, quest: 0xffce6e, flavor: 0xffffff };
+
+export class WorldLife {
+ // world: { mint, seed, biome } — biome is the resolved env biome object.
+ constructor({ scene, camera, renderer, getPlayer, ui, net, world, radius = 54 }) {
+ this.scene = scene;
+ this.camera = camera;
+ this.renderer = renderer;
+ this.getPlayer = getPlayer;
+ this.ui = ui;
+ this.net = net;
+ this.world = world || {};
+
+ this._injectStyles();
+
+ this.nav = new NavGraph({ radius, seed: world?.seed >>> 0 });
+ this._paintRoad();
+
+ this.ambient = new AmbientLife({ scene, nav: this.nav, biome: world?.biome });
+ this.mobs = new MobSystem({ scene, nav: this.nav });
+
+ // Interactive NPCs from the data-driven catalog.
+ this.npcs = npcCatalogFor(world).map((def) => {
+ const npc = new Npc(scene, def);
+ npc.marker = this._npcMarker(def);
+ return npc;
+ });
+
+ // One shared "press E" prompt for whichever NPC you're nearest.
+ this.prompt = document.createElement('div');
+ this.prompt.className = 'npc-prompt';
+ document.body.appendChild(this.prompt);
+ this._promptNpc = null;
+
+ this._ray = new Raycaster();
+ this._ndc = new Vector2();
+ this._ringT = 0;
+ }
+
+ // A subtle road band + inner kerb so the traffic reads as driving on something,
+ // not gliding over grass. Dirt for the frontier town, dark asphalt elsewhere.
+ _paintRoad() {
+ const r = this.nav.roadRadius, w = this.nav.roadWidth;
+ const frontier = this.world?.biome?.town === 'frontier';
+ this.roadGroup = new Group();
+ const road = new Mesh(
+ new RingGeometry(r - w / 2, r + w / 2, 96),
+ new MeshStandardMaterial({ color: frontier ? 0x6b5536 : 0x24272c, roughness: 1, metalness: 0 }),
+ );
+ road.rotation.x = -Math.PI / 2; road.position.y = 0.012; road.receiveShadow = true;
+ this.roadGroup.add(road);
+ // A pale kerb just inside, hinting a sidewalk for the foot traffic.
+ const kerb = new Mesh(
+ new RingGeometry(r - w / 2 - 0.5, r - w / 2 - 0.18, 96),
+ new MeshBasicMaterial({ color: frontier ? 0x9a8458 : 0x3a3f47, transparent: true, opacity: 0.6, side: DoubleSide }),
+ );
+ kerb.rotation.x = -Math.PI / 2; kerb.position.y = 0.014;
+ this.roadGroup.add(kerb);
+ this.scene.add(this.roadGroup);
+ }
+
+ // A faint role-tinted ground ring under an interactive NPC so the spot reads as
+ // a place (a market, a board) rather than a person standing in a field.
+ _npcMarker(def) {
+ const ring = new Mesh(
+ new RingGeometry(1.0, 1.3, 40),
+ new MeshBasicMaterial({ color: ROLE_RING[def.role] || ROLE_RING.flavor, transparent: true, opacity: 0.28, side: DoubleSide }),
+ );
+ ring.rotation.x = -Math.PI / 2;
+ ring.position.set(def.pos.x, 0.02, def.pos.z);
+ this.scene.add(ring);
+ return ring;
+ }
+
+ _injectStyles() {
+ if (document.getElementById('npc-styles')) return;
+ const s = document.createElement('style');
+ s.id = 'npc-styles';
+ s.textContent = `
+ .npc-name { color: var(--npc-tint, #fff); text-shadow: 0 1px 3px rgba(0,0,0,0.7); }
+ .npc-bubble { /* inherits .cc-bubble; ambient chatter + NPC dialogue */ }
+ .npc-prompt {
+ position: fixed; left: 0; top: 0; z-index: 16; pointer-events: none;
+ transform: translate(-50%, -100%); white-space: nowrap;
+ background: var(--cc-panel-solid, #0c0c0e); border: 1px solid var(--cc-edge, rgba(255,255,255,0.12));
+ color: var(--cc-text, #f5f5f6); font-size: 12px; font-weight: 700; letter-spacing: 0.04em;
+ padding: 6px 11px; border-radius: var(--cc-radius, 4px); box-shadow: var(--cc-glow, 0 0 14px rgba(255,255,255,0.25));
+ text-transform: uppercase; transition: opacity 0.18s ease; opacity: 0;
+ }
+ .npc-prompt.npc-show { opacity: 1; }
+ .npc-prompt .npc-key {
+ display: inline-block; min-width: 16px; text-align: center; margin-right: 5px;
+ background: #fff; color: var(--cc-ink, #060607); border-radius: 3px; padding: 0 4px;
+ }`;
+ document.head.appendChild(s);
+ }
+
+ // Project a world point to a screen-space DOM transform (same math the rest of
+ // the scene uses). Hidden when behind the camera.
+ _place(node, x, y, z) {
+ const w = this.renderer.domElement.clientWidth, h = this.renderer.domElement.clientHeight;
+ const v = new Vector3(x, y, z).project(this.camera);
+ if (v.z > 1 || v.z < -1) { node.style.display = 'none'; return; }
+ node.style.display = '';
+ node.style.transform = `translate(-50%, -100%) translate(${(v.x * 0.5 + 0.5) * w}px, ${(-v.y * 0.5 + 0.5) * h}px)`;
+ }
+
+ // Nearest interactive NPC within its own interaction range, else null.
+ _nearestNpc(p) {
+ let best = null, bestD = Infinity;
+ for (const npc of this.npcs) {
+ const d = npc.distanceTo(p);
+ if (d <= npc.range && d < bestD) { best = npc; bestD = d; }
+ }
+ return best;
+ }
+
+ // Tell the ambient crowd how many real players are present so it tapers.
+ setRealPeers(n) { this.ambient?.setRealPeers(n); }
+
+ tick(dt) {
+ const player = this.getPlayer?.();
+ const project = (node, x, y, z) => this._place(node, x, y, z);
+
+ this.ambient?.update(dt, { player, project });
+ this.mobs?.update(dt);
+
+ for (const npc of this.npcs) {
+ npc.tick(dt);
+ this._place(npc.label, npc.pos.x, npc.height + 0.2, npc.pos.z);
+ if (npc.bubble) this._place(npc.bubble, npc.pos.x, npc.height + 0.7, npc.pos.z);
+ }
+
+ // Breathe the NPC markers.
+ this._ringT += dt;
+ const pulse = 0.22 + 0.1 * (0.5 + 0.5 * Math.sin(this._ringT * 2));
+ for (const npc of this.npcs) if (npc.marker) npc.marker.material.opacity = pulse;
+
+ // Single proximity prompt for the nearest interactive NPC.
+ const near = player ? this._nearestNpc(player) : null;
+ if (near !== this._promptNpc) {
+ this._promptNpc = near;
+ if (near) this.prompt.innerHTML = `<span class="npc-key">E</span> ${near.def.prompt || 'Talk'}`;
+ }
+ if (near) {
+ this.prompt.classList.add('npc-show');
+ this._place(this.prompt, near.pos.x, near.height + 0.9, near.pos.z);
+ near.faceTowards(player); // turn to greet whoever walks up
+ } else {
+ this.prompt.classList.remove('npc-show');
+ }
+ }
+
+ // Player pressed E: talk to / open the nearest interactive NPC. Returns true if
+ // one consumed the press, so the caller can stop here.
+ interact() {
+ const player = this.getPlayer?.();
+ if (!player) return false;
+ const npc = this._nearestNpc(player);
+ if (!npc) return false;
+ try { npc.interact({ player, ui: this.ui, net: this.net, world: this.world }); }
+ catch (e) { log.warn('[world-life] npc interact failed:', e?.message); }
+ return true;
+ }
+
+ // Tap/click an NPC (or its marker ring) while in range — the touch equivalent
+ // of E. Returns true if it consumed the tap.
+ tryActivateAt(clientX, clientY) {
+ const player = this.getPlayer?.();
+ if (!player) return false;
+ const near = this._nearestNpc(player);
+ if (!near) return false;
+ const el = this.renderer.domElement;
+ const rect = el.getBoundingClientRect();
+ this._ndc.set(((clientX - rect.left) / rect.width) * 2 - 1, -((clientY - rect.top) / rect.height) * 2 + 1);
+ this._ray.setFromCamera(this._ndc, this.camera);
+ const targets = this.npcs.flatMap((n) => (n.marker ? [n.rig, n.marker] : [n.rig]));
+ if (this._ray.intersectObjects(targets, true).length > 0) { this.interact(); return true; }
+ return false;
+ }
+
+ dispose() {
+ this.ambient?.dispose();
+ this.mobs?.dispose();
+ for (const npc of this.npcs) { npc.dispose(); if (npc.marker) { this.scene.remove(npc.marker); npc.marker.geometry.dispose(); } }
+ this.npcs = [];
+ if (this.roadGroup) { this.scene.remove(this.roadGroup); this.roadGroup = null; }
+ this.prompt?.remove();
+ }
+}
diff --git a/src/game/play-systems.js b/src/game/play-systems.js
index 73f88ff7e..c15589254 100644
--- a/src/game/play-systems.js
+++ b/src/game/play-systems.js
@@ -17,15 +17,31 @@
import {
Group, Mesh, Color, Vector3,
- CircleGeometry, RingGeometry, CylinderGeometry, SphereGeometry,
+ CircleGeometry, RingGeometry, CylinderGeometry, SphereGeometry, ConeGeometry, BoxGeometry, IcosahedronGeometry,
MeshStandardMaterial, MeshBasicMaterial,
BufferGeometry, Line, LineBasicMaterial, Float32BufferAttribute, DoubleSide,
} from 'three';
-import { FISHING_SPOTS, nearestFishingSpot } from '../../multiplayer/src/world-features.js';
+import {
+ FISHING_SPOTS, nearestFishingSpot,
+ TREES, nearestTree, ROCKS, nearestRock,
+ FIREPITS, nearestFirepit, MOB_SPAWNS, nearestMobSpawn,
+} from '../../multiplayer/src/world-features.js';
import { itemDisplay } from './items.js';
import './play-systems.css';
+// Contextual activities the world offers, beyond fishing. Each entry knows the
+// tool the player must hold (null = none), the nearest-node finder (shared with the
+// server so the range rule never drifts), and the verb shown on the action button.
+// Ordered by how close the player must be — when several are reachable, tick() picks
+// the nearest. Fishing keeps its bespoke cast path; these four share one dispatch.
+const ACTIVITIES = [
+ { type: 'chop', tool: 'axe', near: nearestTree, label: 'Chop', glyph: '🪓', noTool: 'Need an axe' },
+ { type: 'mine', tool: 'pickaxe', near: nearestRock, label: 'Mine', glyph: '⛏️', noTool: 'Need a pickaxe' },
+ { type: 'attack', tool: 'sword', near: nearestMobSpawn, label: 'Attack', glyph: '⚔️', noTool: 'Need a sword' },
+ { type: 'cook', tool: null, near: nearestFirepit, label: 'Cook fish', glyph: '🍳', noTool: '' },
+];
+
const SKILL_META = {
fishing: { label: 'Fishing', glyph: '🎣' },
cooking: { label: 'Cooking', glyph: '🍳' },
@@ -217,6 +233,31 @@ export class PlaySystems {
if (this._invOpen) this._renderInventory();
}
+ // ---------------------------------------------------------------- accessors
+ // The unified WorldHud owns the canonical cash/health readout, so the legacy
+ // gold purse is hidden when that HUD is active — one money readout, not two.
+ setGoldVisible(v) { if (this.gold) this.gold.hidden = !v; }
+
+ getGold() { return this.profile?.gold ?? 0; }
+ getHp() { return this.profile?.hp ?? 0; }
+ getMaxHp() { return this.profile?.maxHp ?? 0; }
+
+ // Hotbar projected for the weapon/action wheel: glyph + name + qty per slot.
+ getHotbarItems() {
+ const hb = this.profile?.hotbar || [];
+ const active = this.profile?.activeSlot ?? -1;
+ const out = [];
+ for (let i = 0; i < Math.max(6, hb.length); i++) {
+ const slot = hb[i] || { item: '', qty: 0 };
+ const disp = slot.item ? itemDisplay(slot.item) : null;
+ out.push({
+ slot: i, empty: !slot.item, active: i === active,
+ glyph: disp ? disp.glyph : '', name: disp ? disp.name : '', qty: slot.qty || 0,
+ });
+ }
+ return out;
+ }
+
onXpGain(g) {
if (!g || !g.skill) return;
this.skills[g.skill] = { level: g.level, xp: g.xp, levelXp: g.levelXp, nextXp: g.nextXp };
diff --git a/src/game/world-env.js b/src/game/world-env.js
index 9621c6f43..5248bc31d 100644
--- a/src/game/world-env.js
+++ b/src/game/world-env.js
@@ -504,14 +504,25 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58, opts =
const animators = [];
// --- Sky + atmosphere --------------------------------------------------
- scene.background = gradientSky(biome.sky[0], biome.sky[1], biome.sky[2]);
scene.fog = new Fog(new Color(biome.fog), biome.fogNear, biome.fogFar);
+ // Swap the graded sky backdrop and retint the fog. Exposed via setSky() so the
+ // day/night cycle can move the whole atmosphere across the day; the previous
+ // texture is disposed so a long session doesn't leak canvases.
+ function applySky(top, mid, horizon, fogColor) {
+ const tex = gradientSky(top, mid, horizon);
+ scene.background?.dispose?.();
+ scene.background = tex;
+ if (fogColor && scene.fog) scene.fog.color.set(fogColor);
+ }
+ applySky(biome.sky[0], biome.sky[1], biome.sky[2]);
// --- Lighting ----------------------------------------------------------
// One key sun (casts the long shadows), a sky/ground hemisphere fill, and a
// touch of ambient so shadowed geometry never goes muddy. All biome-tuned.
- root.add(new HemisphereLight(biome.hemi[0], biome.hemi[1], biome.hemi[2]));
- root.add(new AmbientLight(0xffffff, biome.ambient));
+ const hemi = new HemisphereLight(biome.hemi[0], biome.hemi[1], biome.hemi[2]);
+ const ambient = new AmbientLight(0xffffff, biome.ambient);
+ root.add(hemi);
+ root.add(ambient);
const sun = new Vector3();
sun.setFromSphericalCoords(1, MathUtils.degToRad(90 - biome.sun.elevation), MathUtils.degToRad(biome.sun.azimuth));
@@ -656,20 +667,31 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58, opts =
// storm (fog closes in, the key dims) and euphoria (fog opens out, the sun
// flares). We lerp toward the target so a jumpy feed reads as a tide, not a
// strobe. Baselines are captured so every community settles back to its own.
- const baseFogNear = biome.fogNear, baseFogFar = biome.fogFar;
- const baseSun = biome.sun.intensity;
+ // Daytime baselines the market mood multiplies. The day/night cycle drives
+ // these through setBaseSun/setBaseFog so the time of day sets the base and the
+ // trade tape's mood still flexes it on top — the two compose instead of fighting.
+ const base = { sun: biome.sun.intensity, fogNear: biome.fogNear, fogFar: biome.fogFar };
let mood = 0, moodTarget = 0; // -1 storm … +1 euphoric
animators.push((t, dt) => {
mood += (moodTarget - mood) * Math.min(1, dt * 0.6);
- scene.fog.near = baseFogNear * (1 + mood * 0.18);
- scene.fog.far = baseFogFar * (1 + mood * 0.28);
- sunLight.intensity = baseSun * (1 + mood * 0.22);
+ scene.fog.near = base.fogNear * (1 + mood * 0.18);
+ scene.fog.far = base.fogFar * (1 + mood * 0.28);
+ sunLight.intensity = base.sun * (1 + mood * 0.22);
});
let t = 0;
return {
biome,
seed,
+ // Handles the day/night cycle writes through (createDayNightCycle reads
+ // these). `sun` is the unit direction vector the sunLight position derives
+ // from; the cycle re-aims and re-colours it across the day.
+ lights: { sunLight, sun, hemi, ambient },
+ // Replace the graded sky + fog tint (used by the day/night cycle).
+ setSky(top, mid, horizon, fogColor) { applySky(top, mid, horizon, fogColor); },
+ // Set the daytime base the market mood multiplies (see `base` above).
+ setBaseSun(v) { base.sun = v; },
+ setBaseFog(near, far) { base.fogNear = near; base.fogFar = far; },
// Kick the boundary ring to a colour. strength 0..1 sets the flash
// intensity; it decays back to the coin's accent within ~0.6s.
flashRing(color, strength = 0.6) {
diff --git a/src/game/world-zones.js b/src/game/world-zones.js
new file mode 100644
index 000000000..b4044abe0
--- /dev/null
+++ b/src/game/world-zones.js
@@ -0,0 +1,150 @@
+// World zones & spawn-point registry for the /play open-world district.
+//
+// W01 lays the ground every other world feature stands on, and this module is
+// the DATA spine of it: the named zones (downtown, docks, wilds…) other briefs
+// flag for safe/danger PvP, NPC traffic, and quests, plus the spawn-point table
+// they consume (where players drop in, where vehicles and vendors live, where a
+// race grid lines up). It is pure data + cheap geometry helpers — no Three.js,
+// no DOM — so the server, the client renderer, and any later system can all
+// reason about the same map without drifting apart.
+//
+// Coordinates are world metres in the XZ plane; the ground sits at y = 0. The
+// district is a square centred on the origin; the original circular plaza lives
+// on as `Downtown`, the central spawn hub, so the totem/market screens/ponds the
+// other systems anchor there keep working unchanged.
+
+// District dimensions. The server mirrors `half` as WORLD_HALF_M in
+// multiplayer/src/rooms/WalkRoom.js — keep the two in sync (the authoritative
+// bounds clamp and the rendered world must agree).
+export const DISTRICT = {
+ half: 200, // half-extent: the world spans [-200, 200] on X and Z (400 m square)
+ plazaRadius: 58, // central Downtown plaza — the spawn hub, kept clear of buildings
+ blockSize: 46, // city-block footprint (sidewalk slab edge)
+ roadWidth: 12, // street width between blocks
+};
+
+// Movement clamp limit. A small margin inside the hard edge so an avatar pressed
+// against the bound never visually clips the world's rim. The server applies the
+// same square clamp authoritatively (anti-teleport stays independent).
+export const WORLD_BOUND = DISTRICT.half - 2;
+
+// --- Zones -----------------------------------------------------------------
+// Each zone carries a `kind` (drives the HUD tint + music later), gameplay
+// `flags` other briefs read (pvp, traffic, water, …), and a `shape` for the
+// point test. Listed in resolution priority: the FIRST shape that contains a
+// point wins, so put specific places (Downtown) before broad ones (Wilds).
+export const ZONES = [
+ {
+ id: 'downtown', label: 'Downtown', kind: 'safe',
+ flags: { pvp: false, traffic: true, vendors: true, spawnSafe: true },
+ shape: { type: 'circle', x: 0, z: 0, r: DISTRICT.plazaRadius + 8 },
+ },
+ {
+ id: 'docks', label: 'The Docks', kind: 'neutral',
+ flags: { pvp: false, traffic: true, water: true, cargo: true },
+ shape: { type: 'rect', minX: 96, maxX: DISTRICT.half, minZ: -78, maxZ: 78 },
+ },
+ {
+ id: 'wilds', label: 'The Wilds', kind: 'danger',
+ flags: { pvp: true, traffic: false, loot: true },
+ // The lawless outskirts: everything past this radius from the centre that
+ // no more specific zone has already claimed.
+ shape: { type: 'ring', x: 0, z: 0, r: 138 },
+ },
+];
+
+// Anything not inside a listed zone is the ordinary street grid: neutral, with
+// background traffic, no PvP.
+export const DEFAULT_ZONE = Object.freeze({
+ id: 'streets', label: 'The Streets', kind: 'neutral',
+ flags: { pvp: false, traffic: true },
+});
+
+function inShape(shape, x, z) {
+ switch (shape.type) {
+ case 'circle':
+ return Math.hypot(x - shape.x, z - shape.z) <= shape.r;
+ case 'ring':
+ return Math.hypot(x - shape.x, z - shape.z) >= shape.r;
+ case 'rect':
+ return x >= shape.minX && x <= shape.maxX && z >= shape.minZ && z <= shape.maxZ;
+ default:
+ return false;
+ }
+}
+
+// Which zone is the point (x,z) in? Returns the first matching zone by priority,
+// or DEFAULT_ZONE. Cheap enough to call per-frame for the local player.
+export function zoneAt(x, z) {
+ for (const zone of ZONES) {
+ if (inShape(zone.shape, x, z)) return zone;
+ }
+ return DEFAULT_ZONE;
+}
+
+// --- Spawn-point registry --------------------------------------------------
+// One table other briefs import. `type` partitions it: 'player' drop-ins (kept
+// at the Downtown origin so the server's first-move anti-teleport check passes),
+// 'vehicle' bays along the avenues (W02), 'vendor' stalls (economy briefs), and
+// a 'race-grid' start line down the dock front (race briefs). yaw is the facing
+// in radians. Adding a point here is how a later brief places a thing in the
+// world without hand-coding coordinates twice.
+export const SPAWN_POINTS = [
+ // Player drop-ins — a tight ring on the Downtown plaza. Near the origin by
+ // design: the server seeds every joiner at (0,0,0) and rejects a first move
+ // farther than its max-step, so player spawns must sit within that radius.
+ { id: 'spawn-n', type: 'player', x: 0, z: -0.7, yaw: 0, zone: 'downtown' },
+ { id: 'spawn-e', type: 'player', x: 0.7, z: 0, yaw: -Math.PI / 2, zone: 'downtown' },
+ { id: 'spawn-s', type: 'player', x: 0, z: 0.7, yaw: Math.PI, zone: 'downtown' },
+ { id: 'spawn-w', type: 'player', x: -0.7, z: 0, yaw: Math.PI / 2, zone: 'downtown' },
+
+ // Vehicle bays along the main cross avenues (consumed by W02 — vehicles).
+ { id: 'veh-north-ave', type: 'vehicle', x: 6, z: -90, yaw: 0, zone: 'streets' },
+ { id: 'veh-south-ave', type: 'vehicle', x: -6, z: 90, yaw: Math.PI, zone: 'streets' },
+ { id: 'veh-east-ave', type: 'vehicle', x: 90, z: 6, yaw: -Math.PI / 2, zone: 'docks' },
+ { id: 'veh-west-ave', type: 'vehicle', x: -90, z: -6, yaw: Math.PI / 2, zone: 'streets' },
+
+ // Vendor stalls ringing Downtown (economy / shop briefs).
+ { id: 'vendor-ne', type: 'vendor', x: 44, z: -44, yaw: -Math.PI * 0.75, zone: 'streets' },
+ { id: 'vendor-sw', type: 'vendor', x: -44, z: 44, yaw: Math.PI * 0.25, zone: 'streets' },
+
+ // Race start grid down the dock front (race / mission briefs).
+ { id: 'race-dock-1', type: 'race-grid', x: 150, z: -10, yaw: Math.PI, zone: 'docks' },
+ { id: 'race-dock-2', type: 'race-grid', x: 150, z: 0, yaw: Math.PI, zone: 'docks' },
+ { id: 'race-dock-3', type: 'race-grid', x: 150, z: 10, yaw: Math.PI, zone: 'docks' },
+];
+
+// All spawn points of one type, in registry order.
+export function spawnsOfType(type) {
+ return SPAWN_POINTS.filter((s) => s.type === type);
+}
+
+// Pick a spawn point of a type. `rand` is an optional 0..1 source (seeded RNG or
+// Math.random); omit it for the first/canonical point. Falls back to the origin
+// so a caller asking for a type with no points still gets a usable spawn.
+export function pickSpawn(type, rand) {
+ const list = spawnsOfType(type);
+ if (!list.length) return { id: `${type}-origin`, type, x: 0, z: 0, yaw: 0, zone: 'downtown' };
+ const i = typeof rand === 'function' ? Math.floor(rand() * list.length) % list.length : 0;
+ return list[i];
+}
+
+// The canonical drop-in: a player spawn jittered onto its micro-ring so two
+// joiners never stack exactly on each other, while staying inside the server's
+// first-move radius. Returns { x, z, yaw } in world metres.
+export function playerSpawn(rand = Math.random) {
+ const ring = spawnsOfType('player');
+ const base = ring[Math.floor(rand() * ring.length) % ring.length] || { x: 0, z: 0, yaw: 0 };
+ const a = rand() * Math.PI * 2;
+ const r = 0.15 + rand() * 0.35;
+ return { x: base.x + Math.cos(a) * r, z: base.z + Math.sin(a) * r, yaw: base.yaw };
+}
+
+// Square clamp to the playable bounds. Mirrors the server's authoritative clamp
+// so client prediction and the server agree on the world's edge.
+export function clampToBounds(x, z) {
+ return {
+ x: Math.max(-WORLD_BOUND, Math.min(WORLD_BOUND, x)),
+ z: Math.max(-WORLD_BOUND, Math.min(WORLD_BOUND, z)),
+ };
+}
diff --git a/src/nich-agent.js b/src/nich-agent.js
index ef1ffc5f1..898b35ee6 100644
--- a/src/nich-agent.js
+++ b/src/nich-agent.js
@@ -898,12 +898,19 @@ function _escapeHTML(s) {
.replace(/'/g, '&#39;');
}
-// Model choices surfaced in the header dropdown. `auto` lets the server pick
-// based on which keys are configured (Anthropic → OpenRouter → Groq → OpenAI).
+// Model choices surfaced in the header dropdown. `auto` lets the server pick —
+// which now resolves to GPT-OSS 120B on OpenRouter (the platform default, free),
+// then Groq, then any configured paid keys. See api/_lib/chat-models.js.
// Free OpenRouter entries are tool-call capable; Gemma/Qwen omitted because
// their tool-calling is unreliable.
const MODEL_OPTIONS = [
- { id: 'auto', label: 'Auto', provider: null, model: null },
+ { id: 'auto', label: 'Auto (GPT-OSS 120B)', provider: null, model: null },
+ {
+ id: 'openrouter:gpt-oss',
+ label: 'GPT-OSS 120B (free)',
+ provider: 'openrouter',
+ model: 'openai/gpt-oss-120b:free',
+ },
{ id: 'anthropic:sonnet', label: 'Claude Sonnet 4.6', provider: 'anthropic', model: 'claude-sonnet-4-6' },
{
id: 'openrouter:llama-70b',
@@ -911,12 +918,6 @@ const MODEL_OPTIONS = [
provider: 'openrouter',
model: 'meta-llama/llama-3.3-70b-instruct:free',
},
- {
- id: 'openrouter:gpt-oss',
- label: 'GPT-OSS 120B (free)',
- provider: 'openrouter',
- model: 'openai/gpt-oss-120b:free',
- },
{
id: 'openrouter:hermes',
label: 'Hermes 3 405B (free)',
diff --git a/src/physics/physics-world.js b/src/physics/physics-world.js
index 9551b8b82..25914b329 100644
--- a/src/physics/physics-world.js
+++ b/src/physics/physics-world.js
@@ -45,6 +45,7 @@ export class PhysicsWorld {
this._obstacles = []; // [{ body }] — cleared/rebuilt per environment
this._dynamics = []; // [{ body, mesh, spawn }] — props synced to meshes
this._character = null;
+ this._vehicles = []; // [vehicle façade] — raycast vehicles, pre-stepped each substep
}
/** Create a world with the WASM runtime guaranteed ready. */
@@ -258,6 +259,164 @@ export class PhysicsWorld {
return this._character;
}
+ // ── Raycast vehicle ──────────────────────────────────────────────────────
+
+ /**
+ * A Rapier raycast vehicle (Rapier's built-in DynamicRayCastVehicleController):
+ * a dynamic cuboid chassis with four ray-cast wheels providing suspension,
+ * steering, engine force and braking. We don't hand-roll suspension — the
+ * controller does it. The returned façade is fed driver intent via setInput()
+ * and is integrated automatically inside step() (call setInput before step).
+ *
+ * @param {{position:{x,y,z}, yaw?:number, spec:object}} opts spec = a
+ * VEHICLE_TYPES entry (mass, topSpeed, engineForce, dims, wheel, …).
+ */
+ createVehicle({ position = { x: 0, y: 1, z: 0 }, yaw = 0, spec }) {
+ const R = this.RAPIER;
+ const { l, w, h } = spec.dims;
+ const hx = w / 2, hy = h / 2, hz = l / 2;
+
+ const half = yaw / 2;
+ const rot = { x: 0, y: Math.sin(half), z: 0, w: Math.cos(half) };
+ const body = this.world.createRigidBody(
+ R.RigidBodyDesc.dynamic()
+ .setTranslation(position.x, position.y, position.z)
+ .setRotation(rot)
+ .setLinearDamping(0.12)
+ .setAngularDamping(0.55)
+ .setCanSleep(false),
+ );
+ // Mass via density so the cuboid weighs the type's target mass. A lowered
+ // centre of mass keeps the car from flipping in hard turns.
+ const density = spec.mass / Math.max(0.001, l * w * h);
+ const collider = this.world.createCollider(
+ R.ColliderDesc.cuboid(hx, hy, hz)
+ .setDensity(density)
+ .setFriction(0.7)
+ .setRestitution(0.05)
+ .setTranslation(0, -hy * 0.3, 0),
+ body,
+ );
+
+ const controller = this.world.createVehicleController(body);
+ controller.indexUpAxis = 1; // +y is up
+ controller.setIndexForwardAxis = 2; // +z is forward (matches the mesh)
+
+ const dir = { x: 0, y: -1, z: 0 }; // suspension casts straight down
+ const axle = { x: -1, y: 0, z: 0 }; // wheels spin about the x axle
+ const wb = w / 2 - spec.wheel.inset; // half track width
+ // Connection points sit in the lower body; rays start here and reach the
+ // ground through the suspension rest length + wheel radius.
+ const cy = -hy * 0.2;
+ const conns = [
+ { x: wb, y: cy, z: spec.wheel.frontZ }, // 0 front-left (steered)
+ { x: -wb, y: cy, z: spec.wheel.frontZ }, // 1 front-right (steered)
+ { x: wb, y: cy, z: spec.wheel.rearZ }, // 2 rear-left
+ { x: -wb, y: cy, z: spec.wheel.rearZ }, // 3 rear-right
+ ];
+ for (const c of conns) {
+ controller.addWheel(c, dir, axle, spec.suspension.rest, spec.wheel.radius);
+ }
+ for (let i = 0; i < 4; i++) {
+ controller.setWheelSuspensionStiffness(i, spec.suspension.stiffness);
+ controller.setWheelMaxSuspensionTravel(i, spec.suspension.travel);
+ controller.setWheelSuspensionCompression(i, spec.suspension.compression);
+ controller.setWheelSuspensionRelaxation(i, spec.suspension.relax);
+ controller.setWheelFrictionSlip(i, spec.grip);
+ controller.setWheelSideFrictionStiffness(i, 1.0);
+ }
+
+ // Exclude the chassis from its own wheel ray-casts so a wheel never reports
+ // the car's own underside as the ground.
+ const chassisHandle = collider.handle;
+ const wheelFilter = (col) => col.handle !== chassisHandle;
+
+ const vehicle = {
+ body,
+ controller,
+ spec,
+ steer: 0,
+ _throttle: 0,
+ _brake: 0,
+ _steerTarget: 0,
+ _handbrake: false,
+ /** Feed one frame of driver intent. throttle/brake in [0,1], steer in [-1,1]. */
+ setInput({ throttle = 0, brake = 0, steer = 0, handbrake = false } = {}) {
+ this._throttle = Math.max(0, Math.min(1, throttle));
+ this._brake = Math.max(0, Math.min(1, brake));
+ this._steerTarget = Math.max(-1, Math.min(1, steer));
+ this._handbrake = !!handbrake;
+ },
+ /** Integrate the controller one substep — called from PhysicsWorld.step. */
+ _preStep(dt) {
+ // Ease the steering angle toward the target so turns aren't instant.
+ const target = this._steerTarget * spec.steerMax;
+ const rate = spec.steerSpeed * dt;
+ this.steer += Math.max(-rate, Math.min(rate, target - this.steer));
+ controller.setWheelSteering(0, this.steer);
+ controller.setWheelSteering(1, this.steer);
+
+ const speed = controller.currentVehicleSpeed();
+ let force = 0;
+ let brakeImpulse = 0;
+ if (this._throttle > 0) {
+ // Cut the throttle at top speed so the car can't accelerate forever.
+ force = speed < spec.topSpeed ? spec.engineForce * this._throttle : 0;
+ }
+ if (this._brake > 0) {
+ if (speed > 0.6) {
+ brakeImpulse = spec.brakeForce * this._brake; // slowing down
+ } else {
+ force = -spec.reverseForce * this._brake; // reversing from a stop
+ }
+ }
+ if (this._handbrake) brakeImpulse = Math.max(brakeImpulse, spec.brakeForce * 2.2);
+ // Light engine braking when coasting so the car rolls to rest.
+ if (this._throttle === 0 && this._brake === 0 && !this._handbrake) {
+ brakeImpulse = spec.brakeForce * 0.12;
+ }
+ const perWheelForce = force / 4; // all-wheel drive for arcade stability
+ for (let i = 0; i < 4; i++) {
+ controller.setWheelEngineForce(i, perWheelForce);
+ controller.setWheelBrake(i, brakeImpulse);
+ }
+ controller.updateVehicle(dt, undefined, undefined, wheelFilter);
+ },
+ /** Current world transform + forward speed, for rendering + netcode. */
+ transform() {
+ const t = body.translation();
+ const r = body.rotation();
+ return { x: t.x, y: t.y, z: t.z, qx: r.x, qy: r.y, qz: r.z, qw: r.w, speed: controller.currentVehicleSpeed() };
+ },
+ /** Hard-place the chassis (initial seat, flip recovery) and kill momentum. */
+ teleport(p, q) {
+ body.setTranslation({ x: p.x, y: p.y, z: p.z }, true);
+ if (q) body.setRotation({ x: q.qx, y: q.qy, z: q.qz, w: q.qw }, true);
+ body.setLinvel({ x: 0, y: 0, z: 0 }, true);
+ body.setAngvel({ x: 0, y: 0, z: 0 }, true);
+ this.steer = 0;
+ },
+ /** True when the car has rolled past ~110° — the driver can request a reset. */
+ flipped() {
+ const r = body.rotation();
+ // World up (0,1,0) rotated by the body; its y component is the chassis'
+ // up·worldUp. Below ~-0.35 means it's substantially upside-down.
+ const uy = 1 - 2 * (r.x * r.x + r.z * r.z);
+ return uy < -0.35;
+ },
+ };
+ this._vehicles.push(vehicle);
+ return vehicle;
+ }
+
+ /** Remove a vehicle created with createVehicle(). */
+ removeVehicle(vehicle) {
+ const i = this._vehicles.indexOf(vehicle);
+ if (i >= 0) this._vehicles.splice(i, 1);
+ try { this.world.removeVehicleController(vehicle.controller); } catch { /* already gone */ }
+ try { this.world.removeRigidBody(vehicle.body); } catch { /* already gone */ }
+ }
+
// ── Per-frame integration ────────────────────────────────────────────────
/**
@@ -270,6 +429,9 @@ export class PhysicsWorld {
let steps = 0;
this.world.timestep = this._fixedDt;
while (this._accumulator >= this._fixedDt && steps < 5) {
+ // Vehicles must integrate their suspension/engine BEFORE the world solves,
+ // each substep, or their chassis velocity lags the simulation.
+ for (const v of this._vehicles) v._preStep(this._fixedDt);
this.world.step();
this._accumulator -= this._fixedDt;
steps++;
@@ -297,6 +459,7 @@ export class PhysicsWorld {
this._ground = null;
this._obstacles.length = 0;
this._dynamics.length = 0;
+ this._vehicles.length = 0;
this._character = null;
}
}