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.

wip: commit all pending changes before merge with remote

nirholas76767679f4dd
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/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 34040f7a2..9aff896ad 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 }
// mission-complete → { mission, gold, coop, coin } — /play job or heist finished
@@ -40,6 +41,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..955bc1544 100644
--- a/api/_lib/presence-store.js
+++ b/api/_lib/presence-store.js
@@ -72,16 +72,33 @@ 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 {
+ // Dynamic import (not top-level) so this module stays importable by endpoints
+ // that never mint tickets, and resilient if the dependency is unavailable.
+ const { crewTagFor } = await import('./crews-store.js');
+ 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 +108,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/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/pump-fun-mcp.js b/api/pump-fun-mcp.js
index 958940f08..6cfe642fd 100644
--- a/api/pump-fun-mcp.js
+++ b/api/pump-fun-mcp.js
@@ -546,6 +546,144 @@ async function handleWatchWhales({ mint, minUsd = 5000, durationMs = 5000 }) {
return { mint, minUsd: minUsdNum, durationMs: windowMs, count: trades.length, trades };
}
+// ── getTokenTrades (real on-chain history, indexer-optional) ────────────────
+
+// Recent trade history for a mint, read directly from chain so it works without
+// the optional pump.fun indexer. Pre-graduation tokens trade against the pump
+// bonding-curve program (`TradeEvent`); graduated tokens trade on the pump AMM
+// pool (`BuyEvent`/`SellEvent`). We pull recent signatures for whichever account
+// is live, fetch those transactions, and decode the on-chain events.
+async function readTradesFromChain({ mint, limit, network }) {
+ const pk = solanaPubkey(mint);
+ if (!pk) throw rpcError(-32602, 'invalid mint');
+ const want = Math.min(50, Math.max(1, Number(limit) || 20));
+ // Fetch a few extra signatures since some touching the account aren't trades
+ // (fee claims, migrations) and get filtered out during decode.
+ const sigLimit = Math.min(60, want * 2);
+ const connection = getConnection({ network });
+
+ // Resolve whether the token has graduated to the AMM. A live pool means we
+ // read AMM Buy/Sell events; otherwise we read bonding-curve TradeEvents.
+ let pool = null;
+ try {
+ const ammState = await getAmmPoolState({ network, mint });
+ pool = ammState?.poolKey ?? null;
+ } catch (e) {
+ // No pool yet (pool_not_found) or a transient AMM read failure — fall
+ // through to the bonding-curve path rather than failing the request.
+ void e;
+ }
+
+ const [anchor, pumpSdk, ammSdk, solPrice] = await Promise.all([
+ import('@coral-xyz/anchor'),
+ import('@pump-fun/pump-sdk'),
+ import('@pump-fun/pump-swap-sdk'),
+ getSolPriceUsd(),
+ ]);
+ const { BorshCoder, EventParser } = anchor;
+
+ const isAmm = !!pool;
+ let address;
+ let parser;
+ if (isAmm) {
+ address = pool;
+ const coder = new BorshCoder(ammSdk.pumpAmmJson);
+ parser = new EventParser(ammSdk.PUMP_AMM_PROGRAM_ID, coder);
+ } else {
+ const { getPumpSdkV2 } = await import('./_lib/pump.js');
+ const v2 = await getPumpSdkV2({ network });
+ address = v2.bondingCurvePda(pk);
+ const coder = new BorshCoder(pumpSdk.pumpIdl);
+ parser = new EventParser(pumpSdk.PUMP_PROGRAM_ID, coder);
+ }
+
+ const sigInfos = await connection.getSignaturesForAddress(address, { limit: sigLimit });
+ if (!sigInfos.length) return { mint, network, graduated: isAmm, count: 0, trades: [] };
+
+ const signatures = sigInfos.map((s) => s.signature);
+ const mintStr = pk.toString();
+ const poolStr = pool?.toString();
+ const trades = [];
+
+ function decodeTx(tx, signature) {
+ const logs = tx?.meta?.logMessages;
+ if (!logs || tx.meta.err) return null;
+ const blockTime = tx.blockTime ? tx.blockTime * 1000 : Date.now();
+ let parsed;
+ try {
+ parsed = parser.parseLogs(logs);
+ } catch {
+ return null;
+ }
+ for (const event of parsed) {
+ if (isAmm && (event.name === 'BuyEvent' || event.name === 'SellEvent')) {
+ const d = event.data;
+ if (poolStr && d.pool?.toString() !== poolStr) continue;
+ const isBuy = event.name === 'BuyEvent';
+ const lamports = isBuy ? d.quoteAmountIn : d.quoteAmountOut;
+ const tokens = isBuy ? d.baseAmountOut : d.baseAmountIn;
+ const sol = Number(lamports?.toString() ?? '0') / 1e9;
+ return {
+ signature,
+ isBuy,
+ solAmount: sol,
+ tokenAmount: tokens?.toString() ?? '0',
+ usdValue: sol * solPrice,
+ wallet: d.user?.toString() ?? null,
+ timestamp: d.timestamp
+ ? Number(d.timestamp.toString())
+ : Math.floor(blockTime / 1000),
+ };
+ }
+ if (!isAmm && event.name === 'TradeEvent') {
+ const d = event.data;
+ if (d.mint?.toString() !== mintStr) continue;
+ const sol = Number(d.solAmount?.toString() ?? '0') / 1e9;
+ return {
+ signature,
+ isBuy: !!d.isBuy,
+ solAmount: sol,
+ tokenAmount: d.tokenAmount?.toString() ?? '0',
+ usdValue: sol * solPrice,
+ wallet: d.user?.toString() ?? null,
+ timestamp: d.timestamp
+ ? Number(d.timestamp.toString())
+ : Math.floor(blockTime / 1000),
+ };
+ }
+ }
+ return null;
+ }
+
+ // Fetch in small chunks and stop as soon as we have enough trades. Most
+ // signatures touching the curve/pool account ARE trades, so we rarely need
+ // the full window — chunking also keeps batch sizes friendly to public RPCs.
+ const CHUNK = 8;
+ for (let off = 0; off < signatures.length && trades.length < want; off += CHUNK) {
+ const slice = signatures.slice(off, off + CHUNK);
+ const txs = await connection.getTransactions(slice, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ for (let i = 0; i < txs.length && trades.length < want; i++) {
+ const trade = decodeTx(txs[i], slice[i]);
+ if (trade) trades.push(trade);
+ }
+ }
+
+ return { mint, network, graduated: isAmm, count: trades.length, trades };
+}
+
+async function handleGetTokenTrades({ mint, limit = 20, network = 'mainnet' }) {
+ // Fast path: if the indexer is configured it serves richer historical data.
+ if (pumpfunBotEnabled()) {
+ const r = await pumpfunMcpCall('getTokenTrades', { mint, limit });
+ if (r.ok) return r.data;
+ // Indexer configured but errored — fall back to on-chain reads.
+ }
+ return readTradesFromChain({ mint, limit, network });
+}
+
// ── Dispatch ───────────────────────────────────────────────────────────────
const HANDLERS = {
@@ -555,7 +693,7 @@ const HANDLERS = {
kol_radar: handleKolRadar,
kol_leaderboard: handleKolLeaderboard,
searchTokens: indexerOrUnavailable('searchTokens'),
- getTokenTrades: indexerOrUnavailable('getTokenTrades'),
+ getTokenTrades: handleGetTokenTrades,
getTrendingTokens: indexerOrUnavailable('getTrendingTokens'),
getNewTokens: indexerOrUnavailable('getNewTokens'),
getGraduatedTokens: indexerOrUnavailable('getGraduatedTokens'),
diff --git a/multiplayer/src/activities.js.tmp.4033808.adac1fce2562 b/multiplayer/src/activities.js.tmp.4033808.adac1fce2562
new file mode 100644
index 000000000..1e459c1f1
--- /dev/null
+++ b/multiplayer/src/activities.js.tmp.4033808.adac1fce2562
@@ -0,0 +1,162 @@
+// Gather & craft activities for the /play coin worlds (W06) — woodcutting, mining
+// and cooking, the chop/mine/cook counterpart to WalkRoom's fishing.
+//
+// The logic lives HERE, not inline in WalkRoom, for two reasons: it keeps the room a
+// thin validator-and-replicator (the same split combat.js/vehicles.js use), and it
+// is independently unit-testable. Each handler takes the live `room` so it can reach
+// the room's authoritative helpers (`_actionOk`, `_grantXp`, `_sendInv`,
+// `_questEvent`, `_persistEcon`) and off-schema economy (`econ`) without duplicating
+// them — the WalkRoom only has to register the three message handlers.
+//
+// Authority model is byte-identical to _handleFish: client sends an intent → we
+// validate tool + range + cooldown + pack space → roll the yield against the skill
+// and the node's difficulty → grant item + XP → reply with `inv`/`notice`. The
+// client is pure UI; nothing here trusts a client-sent position or reward.
+
+import { addItem, hasRoomFor, countItem, removeItem } from './economy.js';
+import {
+ itemLabel, gatherChance, gatherDoubleChance, coalBonusChance, cookBurnChance,
+} from './items.js';
+import { treeInRange, rockInRange, firepitInRange } from './world-features.js';
+
+// Per-swing cadence on the real clock (ms). The handlers tolerate a profile whose
+// `cd` map predates these keys — `now < undefined` is false, so a missing key just
+// means "ready now", and the first action arms it.
+export const ACTIVITY_COOLDOWN_MS = { chop: 1300, mine: 1500, cook: 900 };
+
+// The two gather activities differ only in tool, node, resource and the mining-only
+// coal bonus — so one config table drives both through the shared core below.
+const GATHER = {
+ chop: {
+ tool: 'axe', skill: 'woodcutting', item: 'wood', inRange: treeInRange,
+ toolHint: 'Equip an axe to chop.', rangeHint: 'Move up to a tree to chop.',
+ holdText: 'The trunk holds firm.',
+ },
+ mine: {
+ tool: 'pickaxe', skill: 'mining', item: 'stone', inRange: rockInRange, coal: true,
+ toolHint: 'Equip a pickaxe to mine.', rangeHint: 'Move up to a rock to mine.',
+ holdText: 'The rock holds firm.',
+ },
+};
+
+// Chop a tree / mine a rock. `type` is 'chop' or 'mine'. Mirrors _handleFish.
+export function handleGather(room, client, type) {
+ const cfg = GATHER[type];
+ if (!cfg) return;
+ const player = room.state.players.get(client.sessionId);
+ const profile = room.econ.get(client.sessionId);
+ if (!player || !profile) return;
+ if (!room._actionOk(client.sessionId, type)) return;
+
+ const now = Date.now();
+ if (profile.cd && now < profile.cd[type]) return; // mid-swing
+
+ const active = profile.hotbar[profile.activeSlot];
+ if (!active || active.item !== cfg.tool) {
+ client.send('notice', { kind: 'tool', text: cfg.toolHint });
+ return;
+ }
+ const node = cfg.inRange(player.x, player.z);
+ if (!node) {
+ client.send('notice', { kind: type, text: cfg.rangeHint });
+ return;
+ }
+ if (!hasRoomFor(profile, cfg.item)) {
+ client.send('notice', { kind: 'full', text: 'Your inventory is full.' });
+ return;
+ }
+
+ if (profile.cd) profile.cd[type] = now + ACTIVITY_COOLDOWN_MS[type];
+ const lvl = profile.levels[cfg.skill] || 1;
+ const difficulty = node.difficulty || 1;
+
+ if (Math.random() >= gatherChance(lvl, difficulty)) {
+ // A swing that bites but yields nothing — a little XP keeps the grind honest.
+ room._grantXp(client, profile, cfg.skill, 2);
+ client.send('notice', { kind: type, got: 0, node: node.id, text: cfg.holdText });
+ return;
+ }
+
+ const want = 1 + (Math.random() < gatherDoubleChance(lvl, difficulty) ? 1 : 0);
+ const leftover = addItem(profile, cfg.item, want);
+ const got = want - leftover;
+ if (got <= 0) {
+ client.send('notice', { kind: 'full', text: 'Your inventory is full.' });
+ return;
+ }
+ const parts = [`${got > 1 ? got + ' ' : ''}${itemLabel(cfg.item).toLowerCase()}`];
+ let xp = Math.round((9 + Math.floor(Math.random() * 5) + lvl * 0.3) * difficulty) * got;
+ room._questEvent?.(client, profile, { type: 'collect', item: cfg.item, qty: got });
+
+ // Mining bonus: a chance to also surface coal (subject to pack space).
+ if (cfg.coal && hasRoomFor(profile, 'coal') && Math.random() < coalBonusChance(lvl, node.coal || 1)) {
+ if (addItem(profile, 'coal', 1) === 0) {
+ parts.push(itemLabel('coal').toLowerCase());
+ xp += 6;
+ room._questEvent?.(client, profile, { type: 'collect', item: 'coal', qty: 1 });
+ }
+ }
+
+ room._grantXp(client, profile, cfg.skill, xp);
+ room._sendInv(client, profile);
+ client.send('notice', { kind: type, got, node: node.id, text: `Got ${parts.join(' + ')}.` });
+ room._persistEcon(client.sessionId);
+}
+
+// Cook a raw fish at a roast pit: consume one raw fish, roll the burn chance against
+// cooking skill, and on success add an edible cooked fish (with XP). A burn loses the
+// fish — a low-level cook's tax that fades with training. No tool needed; the fire is
+// the station.
+export function handleCook(room, client) {
+ const player = room.state.players.get(client.sessionId);
+ const profile = room.econ.get(client.sessionId);
+ if (!player || !profile) return;
+ if (!room._actionOk(client.sessionId, 'cook')) return;
+
+ const now = Date.now();
+ if (profile.cd && now < profile.cd.cook) return;
+
+ if (!firepitInRange(player.x, player.z)) {
+ client.send('notice', { kind: 'cook', text: 'Stand by a roast pit to cook.' });
+ return;
+ }
+ if (countItem(profile, 'fish') <= 0) {
+ client.send('notice', { kind: 'cook', text: 'You have no raw fish to cook.' });
+ return;
+ }
+
+ if (profile.cd) profile.cd.cook = now + ACTIVITY_COOLDOWN_MS.cook;
+ const lvl = profile.levels.cooking || 1;
+ removeItem(profile, 'fish', 1);
+
+ if (Math.random() < cookBurnChance(lvl)) {
+ room._grantXp(client, profile, 'cooking', 3); // you learn from a burn, a little
+ room._sendInv(client, profile);
+ client.send('notice', { kind: 'cook', cooked: 0, text: 'You burned the fish.' });
+ room._persistEcon(client.sessionId);
+ return;
+ }
+ if (!hasRoomFor(profile, 'cookedFish')) {
+ // The raw fish is already gone; refund it so a full pack can't eat the catch.
+ addItem(profile, 'fish', 1);
+ if (profile.cd) profile.cd.cook = now; // didn't actually cook — don't burn the cadence
+ room._sendInv(client, profile);
+ client.send('notice', { kind: 'full', text: 'Your inventory is full.' });
+ return;
+ }
+ addItem(profile, 'cookedFish', 1);
+ const xp = 14 + Math.floor(Math.random() * 5) + Math.floor(lvl * 0.3);
+ room._grantXp(client, profile, 'cooking', xp);
+ room._questEvent?.(client, profile, { type: 'collect', item: 'cookedFish', qty: 1 });
+ room._sendInv(client, profile);
+ client.send('notice', { kind: 'cook', cooked: 1, text: `Cooked a ${itemLabel('cookedFish').toLowerCase()}.` });
+ room._persistEcon(client.sessionId);
+}
+
+// Wire the three intents onto a room. Called once from WalkRoom.onCreate — the room's
+// only obligation, keeping the gather/craft logic out of the room file entirely.
+export function registerActivityHandlers(room) {
+ room.onMessage('chop', (client) => handleGather(room, client, 'chop'));
+ room.onMessage('mine', (client) => handleGather(room, client, 'mine'));
+ room.onMessage('cook', (client) => handleCook(room, client));
+}
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/game-token.js b/multiplayer/src/game-token.js
index 3eda58e3a..fb0bef3f7 100644
--- a/multiplayer/src/game-token.js
+++ b/multiplayer/src/game-token.js
@@ -403,3 +403,123 @@ export async function verifySpinPayment({ quoteToken, txSig, buyerWallet }) {
if (delta(treasuryATA) < BigInt(q.treasuryRaw)) return { ok: false, reason: 'treasury_underpaid' };
return { ok: true, nonce: q.nonce, quote: q };
}
+
+// --- generic fixed-amount purchases (W04 $THREE boutique) -------------------
+//
+// The boutique — and any future fixed-price $THREE sink — settles through this pair,
+// the spin flow's sibling generalised over an arbitrary token amount and `purpose`.
+// The player signs ONE transaction that splits a FIXED $THREE amount between the burn
+// sink and the treasury, carrying a memo nonce that binds the on-chain tx to this
+// exact quote. The server prices the charge (never the client), then re-fetches the
+// confirmed tx from RPC and checks both legs landed before releasing the unlock.
+// Replay protection is the caller's responsibility (track consumed nonces) AND, for
+// idempotent grants like a cosmetic unlock, a double-settle can never double-deliver.
+
+/**
+ * Build the unsigned $THREE purchase the buyer signs. `amountRaw` is the total in
+ * base units (string|bigint), split burn/treasury by `burnBps` (default 50/50).
+ * `extra` is sealed into the quote verbatim (e.g. the boutique listing id) so settle
+ * can act on it without trusting the client. Returns null when no treasury is
+ * configured, the buyer isn't a real wallet, or the amount is non-positive.
+ * @param {{ buyerWallet: string, amountRaw: string|bigint, purpose: string, burnBps?: number, extra?: object }} params
+ * @returns {Promise<null | { quoteToken: string, txBase64: string, quote: object }>}
+ */
+export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, burnBps = 5000, extra = {} }) {
+ if (!tokenConfigured()) return null;
+ if (!isWalletAddress(buyerWallet)) return null;
+ let total;
+ try { total = BigInt(amountRaw); } catch { return null; }
+ if (!(total > 0n)) return null;
+
+ const { burn: burnRaw, treasury: treasuryRaw } = splitBurnTreasury(total, burnBps);
+ const treasuryAddr = treasuryWallet();
+ const nonce = crypto.randomBytes(16).toString('hex');
+
+ const conn = new Connection(SOLANA_RPC, 'confirmed');
+ const mint = new PublicKey(TOKEN_MINT);
+ const buyer = new PublicKey(buyerWallet);
+ const burn = new PublicKey(BURN_ADDRESS);
+ const treasury = new PublicKey(treasuryAddr);
+
+ const buyerATA = await getAssociatedTokenAddress(mint, buyer);
+ const burnATA = await getAssociatedTokenAddress(mint, burn);
+ const treasuryATA = await getAssociatedTokenAddress(mint, treasury);
+
+ const tx = new Transaction();
+ const [burnAcct, treasuryAcct] = await Promise.all([
+ conn.getAccountInfo(burnATA),
+ conn.getAccountInfo(treasuryATA),
+ ]);
+ if (!burnAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, burnATA, burn, mint));
+ if (!treasuryAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, treasuryATA, treasury, mint));
+ tx.add(createTransferInstruction(buyerATA, burnATA, buyer, burnRaw));
+ tx.add(createTransferInstruction(buyerATA, treasuryATA, buyer, treasuryRaw));
+ tx.add(memoInstruction(nonce));
+
+ const { blockhash } = await conn.getLatestBlockhash('confirmed');
+ tx.feePayer = buyer;
+ tx.recentBlockhash = blockhash;
+ const txBase64 = tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64');
+
+ const quotePayload = {
+ purpose,
+ mint: TOKEN_MINT,
+ decimals: TOKEN_DECIMALS,
+ symbol: TOKEN_SYMBOL,
+ buyer: buyerWallet,
+ total: total.toString(),
+ tokens: Number(total) / 10 ** TOKEN_DECIMALS,
+ burnAddr: BURN_ADDRESS,
+ burnRaw: burnRaw.toString(),
+ treasuryAddr,
+ treasuryRaw: treasuryRaw.toString(),
+ nonce,
+ ...extra,
+ };
+ const quoteToken = signQuote(quotePayload);
+ return { quoteToken, txBase64, quote: { ...quotePayload, ttlSeconds: QUOTE_TTL_SECONDS } };
+}
+
+/**
+ * Verify a settled $THREE purchase on-chain: the quote is untampered, unexpired, and
+ * matches the expected purpose + buyer; the tx carries the quote's memo nonce; and the
+ * burn + treasury legs each received at least their share. Pre/post token-balance
+ * deltas make this robust to however the wallet assembled the transfers.
+ * @param {{ quoteToken: string, txSig: string, buyerWallet?: string, purpose?: string }} params
+ * @returns {Promise<{ ok: boolean, reason?: string, nonce?: string, quote?: object }>}
+ */
+export async function verifyTokenPurchase({ quoteToken, txSig, buyerWallet, purpose }) {
+ const q = verifyQuote(quoteToken);
+ if (!q || (purpose && q.purpose !== purpose)) return { ok: false, reason: 'bad_quote' };
+ if (buyerWallet && q.buyer && q.buyer !== buyerWallet) return { ok: false, reason: 'buyer_mismatch' };
+ if (typeof txSig !== 'string' || txSig.length < 32 || txSig.length > 128) return { ok: false, reason: 'bad_signature' };
+
+ const conn = new Connection(SOLANA_RPC, 'confirmed');
+ let tx;
+ try {
+ tx = await conn.getParsedTransaction(txSig, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 });
+ } catch {
+ return { ok: false, reason: 'rpc_error' };
+ }
+ if (!tx) return { ok: false, reason: 'not_found' };
+ if (tx.meta?.err) return { ok: false, reason: 'tx_failed' };
+
+ // Memo must equal the quote nonce — binds this tx to this exact quote.
+ const memoIx = (tx.transaction?.message?.instructions || []).find(
+ (ix) => ix.programId?.toString() === MEMO_PROGRAM_ID.toBase58(),
+ );
+ const memo = typeof memoIx?.parsed === 'string' ? memoIx.parsed : null;
+ if (!memo || memo !== q.nonce) return { ok: false, reason: 'memo_mismatch' };
+
+ const mint = TOKEN_MINT;
+ const burnATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.burnAddr))).toBase58();
+ const treasuryATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.treasuryAddr))).toBase58();
+ const delta = (ownerATA) => {
+ const pre = (tx.meta?.preTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);
+ const post = (tx.meta?.postTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);
+ return BigInt(post?.uiTokenAmount?.amount || '0') - BigInt(pre?.uiTokenAmount?.amount || '0');
+ };
+ if (delta(burnATA) < BigInt(q.burnRaw)) return { ok: false, reason: 'burn_underpaid' };
+ if (delta(treasuryATA) < BigInt(q.treasuryRaw)) return { ok: false, reason: 'treasury_underpaid' };
+ return { ok: true, nonce: q.nonce, quote: q };
+}
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/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/shop.js b/multiplayer/src/shop.js
new file mode 100644
index 000000000..5e00c3f63
--- /dev/null
+++ b/multiplayer/src/shop.js
@@ -0,0 +1,105 @@
+// Commerce price tables (W04) — the single source of truth for the /play general
+// store (cash sell/buy) and the $THREE boutique (premium cosmetic unlocks). Shared
+// verbatim by the authoritative server (WalkRoom validates every transaction against
+// these) and the client (PlayCommerce renders the catalogs from the same numbers),
+// so a price the player sees is exactly the price the server charges — no drift.
+// Dependency-free beyond the item/cosmetic registries so both the Node server and the
+// Vite client import the identical table.
+//
+// Two currencies, kept strictly separate:
+// • CASH — the in-game purse ("gold"): a game resource earned by gathering, fishing
+// and combat and spent at the general store. Never on-chain, never a token.
+// • $THREE — the platform's only coin (CA in CLAUDE.md). Spent on-chain at the
+// boutique to unlock premium cosmetics. The on-chain settlement + verification
+// live in game-token.js; this module only holds the catalog the boutique reads.
+
+import { itemLabel } from './items.js';
+import { COSMETICS, getCosmetic } from './cosmetics-catalog.js';
+
+// --- General store: cash economy -------------------------------------------
+
+// Cash a vendor pays for one unit of a gathered/looted item. ONLY items listed here
+// are sellable — tools, weapons, ammo, the armor vest, mounts and the rest of the
+// starter kit are deliberately excluded so a player can neither dump their kit for
+// cash nor farm a buy→sell arbitrage. Values are tuned so honest gathering funds a
+// few catalog upgrades without trivialising progression.
+export const SELL_PRICES = {
+ wood: 2,
+ stone: 2,
+ coal: 6,
+ fish: 3,
+ cookedFish: 9,
+ bones: 4,
+ hide: 8,
+};
+
+// The general store's buy catalog: tools and consumables a player can replace or
+// stock up on with cash. Each entry buys `qty` of `item` for `price` cash. Every item
+// here has a real in-game use today (gather/fish tools, a melee weapon, heal potions,
+// the armor vest, and the ammo the W07 weapons burn) — nothing dead is sold.
+export const BUY_CATALOG = [
+ { item: 'rod', qty: 1, price: 45 },
+ { item: 'axe', qty: 1, price: 40 },
+ { item: 'pickaxe', qty: 1, price: 50 },
+ { item: 'hammer', qty: 1, price: 40 },
+ { item: 'sword', qty: 1, price: 120 },
+ { item: 'healthPotion', qty: 1, price: 30 },
+ { item: 'vest', qty: 1, price: 60 },
+ { item: 'ammo', qty: 12, price: 24 },
+ { item: 'arrow', qty: 12, price: 18 },
+];
+
+const BUY_BY_ITEM = new Map(BUY_CATALOG.map((e) => [e.item, e]));
+
+// Cash one unit of `item` sells for (0 = the store won't buy it).
+export function sellPrice(item) {
+ return SELL_PRICES[item] || 0;
+}
+
+export function isSellable(item) {
+ return sellPrice(item) > 0;
+}
+
+// The catalog entry for a buyable item, or null when it isn't for sale.
+export function buyEntry(item) {
+ return BUY_BY_ITEM.get(item) || null;
+}
+
+// Serializable catalog for the client store UI — labels resolved here so the client
+// renders names from the same vocabulary the server uses.
+export function clientStoreCatalog() {
+ return {
+ sell: Object.entries(SELL_PRICES).map(([item, price]) => ({ item, label: itemLabel(item), price })),
+ buy: BUY_CATALOG.map((e) => ({ item: e.item, qty: e.qty, price: e.price, label: itemLabel(e.item) })),
+ };
+}
+
+// --- $THREE boutique: premium cosmetic unlocks -----------------------------
+//
+// The boutique sells the premium cosmetics from cosmetics-catalog.js. Each cosmetic's
+// `price` is its cost in WHOLE $THREE tokens; the boutique charges exactly that
+// on-chain (built, settled and verified in game-token.js) and, on success, grants the
+// unlock into the account's owned set — the W04 unlock ledger that W03's wardrobe
+// reads. Only premium cosmetics appear here; free ones are already owned by everyone.
+
+export function boutiqueListings() {
+ return COSMETICS
+ .filter((c) => c.tier === 'premium' && Number(c.price) > 0)
+ .map((c) => ({
+ id: c.id,
+ name: c.name,
+ slot: c.slot,
+ rarity: c.rarity,
+ price: Number(c.price),
+ swatch: c.swatch || null,
+ thumb: c.thumb || null,
+ }));
+}
+
+// The $THREE price (whole tokens) to unlock `id`, or 0 when it isn't a sellable
+// premium cosmetic. The server prices the on-chain charge from THIS, never from a
+// client-supplied number.
+export function boutiquePrice(id) {
+ const c = getCosmetic(id);
+ return c && c.tier === 'premium' && Number(c.price) > 0 ? Number(c.price) : 0;
+}
diff --git a/multiplayer/src/vehicles.js b/multiplayer/src/vehicles.js
new file mode 100644
index 000000000..315dede4d
--- /dev/null
+++ b/multiplayer/src/vehicles.js
@@ -0,0 +1,144 @@
+// 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. The avenue bays mirror W01's vehicle
+// spawn-points (src/game/world-zones.js SPAWN_POINTS, type:'vehicle') so cars
+// park on the open cross-avenues the district keeps clear of buildings; two
+// plaza-edge cars sit near the Downtown spawn so a freshly-dropped player finds a
+// ride within a few seconds' walk (clear of the totem (0,0,-12), the jumbotron
+// (0,0,-30) and the Agent Exchange (8,0,-6)). yaw is the resting heading (0 = +z).
+export const VEHICLE_SPAWNS = [
+ // Avenue bays — keep in sync with world-zones.js type:'vehicle' points.
+ { id: 'veh-north-ave', type: 'coupe', x: 6, z: -90, yaw: 0 },
+ { id: 'veh-south-ave', type: 'sedan', x: -6, z: 90, yaw: Math.PI },
+ { id: 'veh-east-ave', type: 'pickup', x: 90, z: 6, yaw: -Math.PI / 2 },
+ { id: 'veh-west-ave', type: 'buggy', x: -90, z: -6, yaw: Math.PI / 2 },
+ // Plaza-edge starters for discoverability.
+ { id: 'veh-plaza-1', type: 'sedan', x: -16, z: 14, yaw: Math.PI },
+ { id: 'veh-plaza-2', type: 'buggy', x: 18, z: 14, yaw: Math.PI },
+];
+
+// --- Anti-cheat limits (server-enforced) ----------------------------------
+
+// World bounds must match WalkRoom's authoritative player clamp (the W01 square
+// district WORLD_BOUND = DISTRICT.half - 2) so a car is held to the same playable
+// area as a pedestrian — applied per-axis, not as a disc.
+export const VEHICLE_WORLD_BOUND_M = 198;
+
+// 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/pages/agent-detail.html b/pages/agent-detail.html
index 9b096b55e..b684c2efd 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -86,6 +86,7 @@
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/footer.css" />
<script defer src="/footer-newsletter.js"></script>
+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
</head>
<body>
<header><div id="nav-container"></div></header>
@@ -136,6 +137,14 @@
<span class="ad-dot">·</span>
<span id="ad-asset-kind">Core Asset</span>
</div>
+ <div class="ad-market-meta" id="ad-market-meta" hidden>
+ <button type="button" id="d-author" class="ad-author-btn" aria-label="View creator profile">—</button>
+ <span class="ad-dot">·</span>
+ <span id="ad-published"></span>
+ <span id="ad-category" class="ad-cat-pill"></span>
+ <span id="ad-views" class="ad-stat-pill"></span>
+ <span id="ad-forks-pill" class="ad-stat-pill" hidden></span>
+ </div>
<div id="ad-meta-skeleton" class="skeleton" style="width: 150px; height: 16px; margin-top: 8px; display: none;"></div>
<p class="ad-hero-desc" id="ad-desc"></p>
<div id="ad-desc-skeleton" class="skeleton" style="width: 80%; height: 48px; margin-top: 8px; display: none;"></div>
@@ -151,10 +160,54 @@
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="margin-right:6px"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>
Share
</button>
+ <span class="ad-market-actions" id="ad-market-actions" hidden>
+ <button type="button" id="ad-fork" class="ad-btn ad-btn-primary">⑂ Fork &amp; Chat</button>
+ <button type="button" id="ad-bookmark" class="ad-btn" aria-pressed="false">☆ Save</button>
+ <button type="button" id="ad-export-json" class="ad-btn">↓ Export JSON</button>
+ </span>
</div>
</div>
</section>
+ <section class="ad-card ad-sale-card" id="ad-sale-card" hidden>
+ <div class="ad-card-head">
+ <span class="ad-bullet ad-bullet-green"></span>
+ <h2>OWNERSHIP</h2>
+ </div>
+ <div id="ad-sale-panel"></div>
+ </section>
+
+ <section class="ad-card ad-preview-card" id="ad-preview-card" hidden>
+ <div class="ad-card-head">
+ <span class="ad-bullet ad-bullet-green"></span>
+ <h2>TRY IT NOW</h2>
+ <span class="ad-preview-hint">Send a message — no fork required</span>
+ </div>
+ <div class="ad-preview-thread" id="d-preview-thread" aria-live="polite"></div>
+ <form class="ad-preview-form" id="d-preview-form" autocomplete="off">
+ <input
+ type="text"
+ id="d-preview-input"
+ class="ad-preview-input"
+ placeholder="Ask this agent anything…"
+ maxlength="2000"
+ required
+ />
+ <button type="submit" class="ad-btn ad-btn-primary" id="d-preview-send">Send</button>
+ </form>
+ <div class="ad-preview-footer" id="d-preview-footer"></div>
+ </section>
+
+ <section class="ad-card ad-pricing-card" id="ad-pricing-card" hidden>
+ <div class="ad-card-head">
+ <span class="ad-bullet ad-bullet-amber"></span>
+ <h2>SKILLS &amp; PRICING</h2>
+ </div>
+ <div class="ad-pricing-summary" id="ad-pricing-summary" hidden></div>
+ <div id="ad-pricing-body"></div>
+ <div id="ad-pricing-library" hidden></div>
+ </section>
+
<section class="ad-card">
<div class="ad-card-head">
<span class="ad-bullet"></span>
@@ -323,6 +376,42 @@
</div>
</section>
+ <section class="ad-card ad-embed-card" id="ad-embed-card" hidden>
+ <div class="ad-card-head">
+ <span class="ad-bullet ad-bullet-muted"></span>
+ <h2>EMBED THIS AGENT</h2>
+ </div>
+ <p class="ad-embed-lede">Drop the agent anywhere — as a web component, iframe, or direct link.</p>
+ <div class="ad-embed-section">
+ <div class="ad-embed-label"><span>Web component</span><button class="ad-embed-copy" type="button" data-embed="wc">Copy</button></div>
+ <pre class="ad-embed-code" id="ad-embed-wc"></pre>
+ </div>
+ <div class="ad-embed-section">
+ <div class="ad-embed-label"><span>Iframe</span><button class="ad-embed-copy" type="button" data-embed="iframe">Copy</button></div>
+ <pre class="ad-embed-code" id="ad-embed-iframe"></pre>
+ </div>
+ <div class="ad-embed-section">
+ <div class="ad-embed-label"><span>Direct link</span><button class="ad-embed-copy" type="button" data-embed="link">Copy</button></div>
+ <pre class="ad-embed-code" id="ad-embed-link"></pre>
+ </div>
+ </section>
+
+ <section class="ad-card ad-versions-card" id="ad-versions-card" hidden>
+ <div class="ad-card-head">
+ <span class="ad-bullet ad-bullet-dim"></span>
+ <h2>VERSION HISTORY</h2>
+ </div>
+ <ul class="ad-versions" id="ad-versions-list"></ul>
+ </section>
+
+ <section class="ad-card ad-similar-card" id="ad-similar-card" hidden>
+ <div class="ad-card-head">
+ <span class="ad-bullet"></span>
+ <h2>SIMILAR AGENTS</h2>
+ </div>
+ <div class="ad-similar-grid" id="ad-similar-grid"></div>
+ </section>
+
<details class="ad-card ad-collapse">
<summary>
<span class="ad-bullet ad-bullet-muted"></span>
@@ -356,6 +445,31 @@
</main>
</div>
+ <div class="creator-modal-overlay" id="creator-modal-overlay" hidden aria-modal="true" role="dialog" aria-labelledby="creator-modal-title">
+ <div class="creator-modal" role="document">
+ <button class="creator-modal-close" id="creator-modal-close" aria-label="Close">×</button>
+ <header class="creator-modal-head">
+ <div class="creator-modal-avatar" id="creator-modal-avatar"></div>
+ <div class="creator-modal-meta">
+ <div class="creator-modal-eyebrow">Creator profile</div>
+ <h2 class="creator-modal-title" id="creator-modal-title">—</h2>
+ <div class="creator-modal-handle" id="creator-modal-handle"></div>
+ <div class="creator-modal-stats" id="creator-modal-stats"></div>
+ </div>
+ </header>
+ <div class="creator-modal-body">
+ <section>
+ <h3 class="creator-modal-sectiontitle">Published agents <span id="creator-agents-count" class="muted"></span></h3>
+ <div class="creator-modal-grid" id="creator-agents-grid"><div class="market-empty">Loading…</div></div>
+ </section>
+ <section>
+ <h3 class="creator-modal-sectiontitle">Public avatars <span id="creator-avatars-count" class="muted"></span></h3>
+ <div class="creator-modal-grid" id="creator-avatars-grid"><div class="market-empty">Loading…</div></div>
+ </section>
+ </div>
+ </div>
+ </div>
+
<script type="module" src="/src/agent-detail.js"></script>
<script src="/brand.js" defer></script>
<div id="footer-container"></div>
diff --git a/pages/brain.html b/pages/brain.html
index ba8b42daf..47bad02f7 100644
--- a/pages/brain.html
+++ b/pages/brain.html
@@ -274,7 +274,5 @@
<script src="/nav.js" defer></script>
<script type="module" src="/src/brain.js"></script>
<script src="/brand.js" defer></script>
- <div id="footer-container"></div>
- <script src="/footer.js"></script>
</body>
</html>
diff --git a/pages/create-character.html b/pages/create-character.html
new file mode 100644
index 000000000..900a5f789
--- /dev/null
+++ b/pages/create-character.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, maximum-scale=1, viewport-fit=cover" />
+ <title>Character creator · three.ws</title>
+ <link rel="icon" href="/favicon.ico" />
+ <meta name="description" content="Build your 3D character — generate it from a photo, a Ready Player Me avatar, or your own model, then dress it in the wardrobe and step into the world." />
+ <meta name="robots" content="index, follow" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/create/character" />
+ <meta property="og:title" content="Character creator · three.ws" />
+ <meta property="og:description" content="Build your 3D character and step into the world." />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <link rel="canonical" href="https://three.ws/create/character" />
+
+ <link rel="stylesheet" href="/src/character-creator.css" />
+</head>
+<body>
+ <header class="cc-topbar">
+ <a class="back" href="/play" aria-label="Back to play">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" />
+ </svg>
+ </a>
+ <div class="brand"><strong>three.ws</strong> · Character creator</div>
+ </header>
+
+ <main class="cc-layout">
+ <!-- Live 3D turntable -->
+ <section class="cc-stage" id="cc-stage" data-state="loading" aria-label="Avatar preview">
+ <canvas id="cc-canvas"></canvas>
+ <div class="cc-veil cc-veil--spin" id="cc-stage-veil">Loading avatar…</div>
+ <div class="cc-stage__label" id="cc-avatar-label">Starter avatar</div>
+ <div class="cc-stage__hint" aria-hidden="true">drag to rotate</div>
+ </section>
+
+ <!-- Controls -->
+ <section class="cc-panel" aria-label="Customize">
+ <h1>Create your character</h1>
+ <p class="cc-sub">Pick a body, dress it, and step into the world. Everything previews live, and your look follows you to every coin world.</p>
+
+ <p class="cc-section-label">Choose your avatar</p>
+ <div class="cc-sources">
+ <button type="button" class="cc-source" id="cc-src-rpm">
+ <span class="ic" aria-hidden="true">🧍</span>
+ <span class="t">Ready Player Me</span>
+ <span class="d">Full-body creator</span>
+ </button>
+ <button type="button" class="cc-source" id="cc-src-selfie">
+ <span class="ic" aria-hidden="true">📸</span>
+ <span class="t">From a selfie</span>
+ <span class="d">Photo → 3D</span>
+ </button>
+ <button type="button" class="cc-source" id="cc-src-import">
+ <span class="ic" aria-hidden="true">📦</span>
+ <span class="t">Import</span>
+ <span class="d">.glb / .vrm</span>
+ </button>
+ </div>
+ <div class="cc-import-url">
+ <input type="url" id="cc-import-url" placeholder="…or paste a GLB/VRM URL" autocomplete="off" inputmode="url" />
+ <button type="button" id="cc-import-url-btn">Load</button>
+ </div>
+ <input type="file" id="cc-import-file" accept=".glb,.vrm,model/gltf-binary" hidden />
+
+ <p class="cc-section-label">Wardrobe</p>
+ <div id="cc-wardrobe"></div>
+
+ <div class="cc-finish">
+ <input type="text" id="cc-name-input" class="cc-name-input" placeholder="Name your character" maxlength="24" autocomplete="off" aria-label="Character name" />
+ <div class="cc-actions">
+ <button type="button" class="cc-btn cc-btn--ghost" id="cc-save-only">Save</button>
+ <button type="button" class="cc-btn cc-btn--primary" id="cc-save">Enter the world →</button>
+ </div>
+ </div>
+ </section>
+ </main>
+
+ <!-- Ready Player Me modal -->
+ <div class="cc-modal" id="cc-rpm-modal" role="dialog" aria-modal="true" aria-label="Ready Player Me avatar creator" hidden>
+ <div class="cc-modal__inner">
+ <button type="button" class="cc-modal__close" id="cc-rpm-close">Close</button>
+ <iframe id="cc-rpm-frame" title="Ready Player Me" allow="camera *; microphone *; clipboard-write" src="about:blank"></iframe>
+ </div>
+ </div>
+
+ <div class="cc-toast" id="cc-toast" role="status" aria-live="polite"></div>
+
+ <script type="module" src="/src/character-creator.js"></script>
+ <script src="/brand.js" defer></script>
+</body>
+</html>
diff --git a/pages/create.html b/pages/create.html
index 37d819735..8cb37d55c 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -889,16 +889,16 @@
<h2 class="card-title">Start with a template</h2>
</div>
<p class="card-subtitle">
- Pick a ready-made character and customize it in our web editor —
- faces, outfits, colors. No download, nothing to install.
+ Pick a ready-made avatar and make it yours. Preview it in the
+ browser, then save and customize. The fastest way to start.
</p>
<div class="card-meta" aria-hidden="true">
<span class="chip">Free</span>
- <span class="chip">~30 sec</span>
+ <span class="chip">~15 sec</span>
<span class="chip chip-ok">No sign-in to try</span>
</div>
<span class="card-cta">
- Open editor
+ Browse templates
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="5" y1="12" x2="19" y2="12" />
<polyline points="12 5 19 12 12 19" />
@@ -928,6 +928,33 @@
</div>
<div class="secondary-grid" role="group" aria-label="More ways to create">
+ <div class="create-card tile" id="card-customize" role="button" tabindex="0" aria-label="Customize a base avatar in the editor">
+ <div class="card-icon-row">
+ <div class="card-icon" aria-hidden="true">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="12" cy="8" r="3.5" />
+ <path d="M5 20c0-3.87 3.13-7 7-7s7 3.13 7 7" />
+ <path d="M18 3l3 3-9 9-4 1 1-4 9-9z" />
+ </svg>
+ </div>
+ <h2 class="card-title">Customize a base avatar</h2>
+ </div>
+ <p class="card-subtitle">
+ Sculpt the face, pick outfits and colors in our in-browser
+ editor. Start from a base and make it unmistakably yours.
+ </p>
+ <div class="card-meta" aria-hidden="true">
+ <span class="chip">Faces & outfits</span>
+ <span class="chip chip-ok">No sign-in</span>
+ </div>
+ <span class="card-cta card-cta--ghost">
+ Open editor
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="5" y1="12" x2="19" y2="12" />
+ <polyline points="12 5 19 12 12 19" />
+ </svg>
+ </span>
+ </div>
<div class="create-card tile" id="card-selfie" role="button" tabindex="0" aria-label="Scan yourself into a 3D avatar">
<div class="card-icon-row">
<div class="card-icon" aria-hidden="true">
diff --git a/public/gallery/index.html.tmp.37604.12034d52bd27 b/public/gallery/index.html.tmp.37604.12034d52bd27
new file mode 100644
index 000000000..b7fdecab7
--- /dev/null
+++ b/public/gallery/index.html.tmp.37604.12034d52bd27
@@ -0,0 +1,155 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>Avatar Gallery · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+ <meta
+ name="description"
+ content="Every public 3D avatar made on three.ws. Browse, preview, embed, or remix — all from one gallery."
+ />
+ <meta name="theme-color" content="#000000" />
+ <link rel="canonical" href="https://three.ws/gallery" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:title" content="Avatar Gallery · three.ws" />
+ <meta
+ property="og:description"
+ content="Every public 3D avatar made on three.ws. Preview, embed, or remix from one place."
+ />
+ <meta property="og:url" content="https://three.ws/gallery" />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Avatar Gallery · three.ws" />
+ <meta
+ name="twitter:description"
+ content="Every public 3D avatar made on three.ws."
+ />
+ <meta name="twitter:image" content="https://three.ws/og-image.png" />
+
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/gallery/gallery.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+
+ <meta property="og:site_name" content="three.ws">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Avatar Gallery","description":"Every public 3D avatar in the system, browsable as a grid.","url":"https://three.ws/gallery","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+</head>
+ <body class="gallery-page">
+ <header>
+ <div id="nav-container"></div>
+ </header>
+ <script src="/nav.js"></script>
+
+ <main class="gallery-main">
+ <section class="gallery-hero">
+ <div class="gallery-hero-inner">
+ <div class="gallery-hero-chips">
+ <div class="gallery-hero-chip">
+ <span class="gallery-hero-dot"></span>
+ <span>Public avatar gallery</span>
+ </div>
+ <a
+ href="/dashboard/avatars"
+ class="gallery-hero-chip gallery-hero-chip--link"
+ data-role="my-avatars-chip"
+ hidden
+ >
+ <span>My avatars →</span>
+ </a>
+ </div>
+ <h1 class="gallery-title">Every avatar, ever made.</h1>
+ <p class="gallery-sub">
+ The community-made 3D avatars on three.ws. Click any card to preview in
+ the viewer, then embed it anywhere or remix into a new agent.
+ </p>
+
+ <div class="gallery-stats">
+ <div class="gallery-stat">
+ <div class="gallery-stat-value" data-role="stat-count">—</div>
+ <div class="gallery-stat-label">Avatars</div>
+ </div>
+ <div class="gallery-stat">
+ <div class="gallery-stat-value" data-role="stat-views">—</div>
+ <div class="gallery-stat-label">Total views</div>
+ </div>
+ </div>
+
+ <div class="gallery-hero-ctas">
+ <button type="button" class="gallery-hero-btn gallery-hero-btn--primary" data-create-from-template>Create from template</button>
+ <a class="gallery-hero-btn" href="/create/selfie">Create from selfie</a>
+ <a class="gallery-hero-btn" href="/dashboard/avatars">Upload avatar</a>
+ </div>
+
+ </div>
+ </section>
+
+ <section class="gallery-controls">
+ <div class="gallery-controls-top">
+ <div class="gallery-search">
+ <svg
+ class="gallery-search-icon"
+ viewBox="0 0 20 20"
+ fill="none"
+ aria-hidden="true"
+ >
+ <circle cx="9" cy="9" r="6" stroke="currentColor" stroke-width="1.6" />
+ <path d="m14 14 4 4" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" />
+ </svg>
+ <input
+ type="search"
+ placeholder="Search by name or description…"
+ data-role="search"
+ aria-label="Search avatars"
+ autocomplete="off"
+ spellcheck="false"
+ />
+ <button
+ type="button"
+ class="gallery-search-clear"
+ data-role="search-clear"
+ aria-label="Clear search"
+ hidden
+ >
+ ×
+ </button>
+ </div>
+ <div class="gallery-sort-select">
+ <label for="gallery-sort">Sort:</label>
+ <select id="gallery-sort" data-role="sort">
+ <option value="newest">Newest</option>
+ <option value="popular">Most viewed</option>
+ <option value="alpha">A → Z</option>
+ </select>
+ </div>
+ </div>
+ <div class="gallery-tag-wrap" data-role="tag-wrap" hidden>
+ <div class="gallery-tag-label">Tags</div>
+ <div class="gallery-tags" data-role="tags"></div>
+ </div>
+ </section>
+
+ <section class="gallery-grid-wrap">
+ <div class="gallery-grid" data-role="grid"></div>
+ <div class="gallery-status" data-role="status"></div>
+ <div class="gallery-sentinel" data-role="sentinel" aria-hidden="true"></div>
+ <div class="gallery-load-more-wrap">
+ <button class="gallery-load-more" data-role="load-more" hidden>
+ Load more
+ </button>
+ </div>
+ </section>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+
+ <!-- Sets window.twsOnchainBadge for the static gallery.js (bundled by Vite). -->
+ <script type="module">import '/src/shared/onchain-badge.js';</script>
+ <script type="module" src="/gallery/gallery.js"></script>
+ <script src="/brand.js" defer></script>
+</body>
+</html>
diff --git a/public/nav.css b/public/nav.css
index 43394f01d..e6f67a660 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 6acf9aab4..fc48ced8a 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/w10-fixture.html b/scripts/w10-fixture.html
new file mode 100644
index 000000000..0bab21e9d
--- /dev/null
+++ b/scripts/w10-fixture.html
@@ -0,0 +1,31 @@
+<!doctype html>
+<!-- Verification fixture for the W10 HUD layer. Loads coincommunities.css for the
+ design tokens, then mounts the WorldHudSystem with a real three camera so the
+ layer can be exercised in a browser without the rest of /play. Temporary. -->
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>W10 HUD fixture</title>
+ <link rel="stylesheet" href="/src/game/coincommunities.css" />
+ <style>html,body{margin:0;height:100%;background:#060607}</style>
+</head>
+<body>
+ <script type="module">
+ import { PerspectiveCamera } from 'three';
+ import { WorldHudSystem } from '/src/game/hud/index.js';
+ const camera = new PerspectiveCamera(50, 16 / 9, 0.1, 9000);
+ let hotbar = [
+ { slot: 0, empty: false, glyph: '🎣', name: 'Fishing rod', qty: 1, active: true },
+ { slot: 1, empty: false, glyph: '🐟', name: 'Fish', qty: 3, active: false },
+ { slot: 2, empty: true, glyph: '', name: '', qty: 0, active: false },
+ ];
+ const sys = new WorldHudSystem(camera, {
+ actions: { leave: () => {}, emote: () => {}, equipSlot: () => {} },
+ getEmotes: () => [{ name: 'wave', icon: '👋', label: 'Wave' }, { name: 'dance', icon: '🕺', label: 'Dance' }],
+ getHotbar: () => hotbar,
+ });
+ window.__WH__ = { sys, camera };
+ </script>
+</body>
+</html>
diff --git a/src/agent-detail.css b/src/agent-detail.css
index 3d7a9b3d4..17c944795 100644
--- a/src/agent-detail.css
+++ b/src/agent-detail.css
@@ -648,3 +648,468 @@ a { color: inherit; text-decoration: none; }
.ad-review-skel-line.med { width: 70%; }
.ad-review-skel-line.long { width: 90%; }
+
+/* ───────────────────────────────────────────────────────────────────────────
+ Marketplace-feature enrichment (agent-detail-market.js)
+ 3D avatar · hero meta/actions · live preview · skills/pricing · sale panel ·
+ embed · similar · versions · creator modal · payment modal.
+ Tokens mirror :root above; monochrome surface, no chroma accents.
+─────────────────────────────────────────────────────────────────────────── */
+
+/* 3D avatar in the hero — match the static avatar footprint. */
+.ad-hero-avatar-3d {
+ width: 120px;
+ height: 120px;
+ border-radius: 16px;
+ background: var(--ad-bg-2);
+ border: 1px solid var(--ad-line);
+ --poster-color: transparent;
+ overflow: hidden;
+}
+
+/* Hero metadata row */
+.ad-market-meta {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: 8px;
+ font-size: 13px;
+ color: var(--ad-muted);
+}
+.ad-author-btn {
+ background: none;
+ border: 0;
+ padding: 0;
+ color: var(--ad-text);
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+ border-bottom: 1px dashed var(--ad-line-2);
+}
+.ad-author-btn:hover:not(:disabled) { color: #fff; border-bottom-color: var(--ad-text); }
+.ad-author-btn:disabled { cursor: default; border-bottom: 0; color: var(--ad-muted); }
+.ad-cat-pill,
+.ad-stat-pill {
+ display: inline-flex;
+ align-items: center;
+ padding: 2px 9px;
+ border-radius: 999px;
+ border: 1px solid var(--ad-line);
+ background: var(--ad-bg-2);
+ font-size: 12px;
+ color: var(--ad-muted);
+}
+
+/* Hero actions */
+.ad-market-actions { display: inline-flex; gap: 8px; flex-wrap: wrap; }
+#ad-bookmark.on { color: var(--ad-amber); border-color: rgba(245,165,36,0.4); }
+
+/* ── Live preview ──────────────────────────────────────────────────────── */
+.ad-preview-hint { margin-left: auto; font-size: 12px; color: var(--ad-dim); }
+.ad-preview-thread {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ max-height: 320px;
+ overflow-y: auto;
+ padding: 4px 2px;
+ margin-bottom: 12px;
+}
+.market-preview-msg { display: flex; }
+.market-preview-msg.user { justify-content: flex-end; }
+.market-preview-msg.assistant { justify-content: flex-start; }
+.market-preview-bubble {
+ max-width: 80%;
+ padding: 9px 13px;
+ border-radius: 14px;
+ font-size: 14px;
+ line-height: 1.5;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+.market-preview-msg.user .market-preview-bubble {
+ background: var(--ad-text);
+ color: var(--ad-bg);
+ border-bottom-right-radius: 4px;
+}
+.market-preview-msg.assistant .market-preview-bubble {
+ background: var(--ad-bg-2);
+ border: 1px solid var(--ad-line);
+ color: var(--ad-text);
+ border-bottom-left-radius: 4px;
+}
+.market-preview-bubble.streaming::after {
+ content: '▋';
+ animation: ad-blink 1s steps(2) infinite;
+ margin-left: 1px;
+}
+@keyframes ad-blink { 0%,50% { opacity: 1; } 50.01%,100% { opacity: 0; } }
+.ad-preview-form { display: flex; gap: 8px; }
+.ad-preview-input {
+ flex: 1;
+ min-width: 0;
+ padding: 10px 13px;
+ border-radius: 10px;
+ border: 1px solid var(--ad-line-2);
+ background: var(--ad-bg-2);
+ color: var(--ad-text);
+ font: inherit;
+ font-size: 14px;
+}
+.ad-preview-input:focus { outline: none; border-color: var(--ad-text); }
+.ad-preview-footer { margin-top: 8px; font-size: 12px; color: var(--ad-dim); min-height: 14px; }
+.ad-preview-footer.err { color: #ff6b6b; }
+
+/* ── Skills & pricing ──────────────────────────────────────────────────── */
+.ad-pricing-summary {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 12px;
+ margin-bottom: 12px;
+ border-radius: 10px;
+ background: rgba(245,165,36,0.08);
+ border: 1px solid rgba(245,165,36,0.2);
+ font-size: 13px;
+ color: var(--ad-text);
+}
+.ad-pricing-icon {
+ display: inline-flex;
+ width: 18px; height: 18px;
+ align-items: center; justify-content: center;
+ border-radius: 50%;
+ background: var(--ad-amber);
+ color: #000;
+ font-weight: 700;
+ font-size: 12px;
+}
+.ad-skill-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-wrap: wrap;
+ padding: 10px 0;
+ border-bottom: 1px solid var(--ad-line);
+}
+.ad-skill-row:last-child { border-bottom: 0; }
+.ad-skill-name { font-size: 14px; color: var(--ad-text); font-weight: 500; }
+.ad-skill-actions { display: inline-flex; align-items: center; gap: 6px; margin-left: auto; flex-wrap: wrap; }
+.ad-price-badge {
+ display: inline-flex;
+ padding: 3px 10px;
+ border-radius: 999px;
+ font-size: 12px;
+ font-weight: 600;
+ border: 1px solid var(--ad-line-2);
+}
+.ad-price-badge.free { color: var(--ad-green); border-color: rgba(74,222,128,0.3); }
+.ad-price-badge.paid { color: var(--ad-amber); border-color: rgba(245,165,36,0.35); }
+.ad-price-badge.owned { color: var(--ad-green); border-color: rgba(74,222,128,0.3); background: rgba(74,222,128,0.08); }
+.ad-skill-btn {
+ padding: 5px 12px;
+ border-radius: 8px;
+ border: 1px solid var(--ad-line-2);
+ background: var(--ad-bg-2);
+ color: var(--ad-text);
+ font: inherit;
+ font-size: 12px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s;
+}
+.ad-skill-btn:hover { background: rgba(255,255,255,0.06); border-color: var(--ad-text); }
+.ad-skill-btn.purchase-btn { background: var(--ad-text); color: var(--ad-bg); border-color: var(--ad-text); }
+.ad-skill-btn.purchase-btn:hover { background: #fff; }
+#ad-pricing-library { margin-top: 14px; }
+
+/* ── Sale / ownership panel ────────────────────────────────────────────── */
+.ad-sale-eyebrow { font-size: 12px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ad-muted); }
+.ad-sale-price { font-size: 24px; font-weight: 700; margin: 4px 0 14px; color: var(--ad-text); }
+.ad-sale-price.free { color: var(--ad-green); }
+.ad-sale-field { display: block; font-size: 12px; color: var(--ad-muted); margin-bottom: 12px; }
+.ad-sale-field input {
+ display: block;
+ width: 100%;
+ box-sizing: border-box;
+ margin-top: 5px;
+ padding: 9px 12px;
+ border-radius: 9px;
+ border: 1px solid var(--ad-line-2);
+ background: var(--ad-bg-2);
+ color: var(--ad-text);
+ font: inherit;
+ font-size: 14px;
+}
+.ad-sale-field input:focus { outline: none; border-color: var(--ad-text); }
+.ad-sale-input-wrap { position: relative; display: block; }
+.ad-sale-currency {
+ position: absolute;
+ right: 12px; top: 50%;
+ transform: translateY(-50%);
+ font-size: 12px;
+ color: var(--ad-dim);
+ margin-top: 2px;
+}
+.ad-sale-actions { display: flex; gap: 8px; margin-top: 4px; }
+.ad-sale-status { font-size: 13px; margin: 10px 0 0; min-height: 16px; }
+.ad-sale-status.err { color: #ff6b6b; }
+.ad-sale-status.ok { color: var(--ad-green); }
+.ad-sale-hint { font-size: 12px; color: var(--ad-dim); margin: 8px 0 0; line-height: 1.5; }
+
+/* ── Embed ─────────────────────────────────────────────────────────────── */
+.ad-embed-lede { font-size: 13px; color: var(--ad-muted); margin: 0 0 16px; }
+.ad-embed-section { margin-bottom: 14px; }
+.ad-embed-label { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; font-size: 12px; color: var(--ad-muted); }
+.ad-embed-copy {
+ padding: 3px 11px;
+ border-radius: 7px;
+ border: 1px solid var(--ad-line-2);
+ background: var(--ad-bg-2);
+ color: var(--ad-text);
+ font: inherit;
+ font-size: 11px;
+ font-weight: 600;
+ cursor: pointer;
+}
+.ad-embed-copy:hover { background: rgba(255,255,255,0.06); }
+.ad-embed-copy.copied { color: var(--ad-green); border-color: rgba(74,222,128,0.3); }
+.ad-embed-code {
+ margin: 0;
+ padding: 12px 14px;
+ border-radius: 10px;
+ background: var(--ad-bg);
+ border: 1px solid var(--ad-line);
+ font-family: 'SF Mono', ui-monospace, monospace;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--ad-text);
+ overflow-x: auto;
+ white-space: pre;
+}
+
+/* ── Version history ───────────────────────────────────────────────────── */
+.ad-versions { list-style: none; margin: 0; padding: 0; }
+.ad-version-row {
+ display: grid;
+ grid-template-columns: auto 1fr auto;
+ gap: 12px;
+ align-items: center;
+ padding: 10px 0;
+ border-bottom: 1px solid var(--ad-line);
+}
+.ad-version-row:last-child { border-bottom: 0; }
+.ad-version-tag { font-family: 'SF Mono', ui-monospace, monospace; font-size: 12px; color: var(--ad-amber); }
+.ad-version-log { font-size: 13px; color: var(--ad-text); }
+.ad-version-when { font-size: 12px; color: var(--ad-dim); white-space: nowrap; }
+
+/* ── Similar agents ────────────────────────────────────────────────────── */
+.ad-similar-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
+ gap: 12px;
+}
+.ad-similar-item {
+ display: block;
+ text-decoration: none;
+ color: inherit;
+ padding: 12px;
+ border-radius: 12px;
+ background: var(--ad-bg-2);
+ border: 1px solid var(--ad-line);
+ transition: border-color 0.15s, transform 0.15s;
+}
+.ad-similar-item:hover { border-color: var(--ad-line-2); transform: translateY(-2px); }
+.ad-similar-thumb {
+ width: 100%;
+ aspect-ratio: 1;
+ border-radius: 9px;
+ background: var(--ad-bg) center/cover no-repeat;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 28px;
+ font-weight: 700;
+ color: var(--ad-muted);
+ margin-bottom: 9px;
+}
+.ad-similar-name { font-size: 13px; font-weight: 600; color: var(--ad-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.ad-similar-meta { font-size: 11px; color: var(--ad-dim); margin-top: 3px; }
+
+/* ── Creator modal ─────────────────────────────────────────────────────── */
+.creator-modal-overlay {
+ position: fixed; inset: 0; z-index: 1000;
+ display: flex; align-items: center; justify-content: center;
+ padding: 20px;
+ background: rgba(0,0,0,0.7);
+ opacity: 0;
+ transition: opacity 0.2s;
+ -webkit-backdrop-filter: blur(4px);
+ backdrop-filter: blur(4px);
+}
+.creator-modal-overlay.show { opacity: 1; }
+.creator-modal {
+ position: relative;
+ width: min(720px, 100%);
+ max-height: 86vh;
+ overflow-y: auto;
+ background: var(--ad-card);
+ border: 1px solid var(--ad-line-2);
+ border-radius: 16px;
+ padding: 24px;
+ box-shadow: var(--shadow-2);
+}
+.creator-modal-close {
+ position: absolute; top: 14px; right: 14px;
+ width: 30px; height: 30px;
+ border-radius: 8px;
+ border: 1px solid var(--ad-line);
+ background: var(--ad-bg-2);
+ color: var(--ad-text);
+ font-size: 18px;
+ cursor: pointer;
+}
+.creator-modal-close:hover { background: rgba(255,255,255,0.06); }
+.creator-modal-head { display: flex; gap: 16px; align-items: center; margin-bottom: 22px; }
+.creator-modal-avatar {
+ width: 64px; height: 64px;
+ border-radius: 50%;
+ background: var(--ad-bg-2) center/cover no-repeat;
+ display: flex; align-items: center; justify-content: center;
+ font-size: 26px; font-weight: 700; color: var(--ad-muted);
+ flex-shrink: 0;
+}
+.creator-modal-eyebrow { font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ad-dim); }
+.creator-modal-title { margin: 2px 0 0; font-size: 22px; color: var(--ad-text); }
+.creator-modal-handle { font-size: 13px; color: var(--ad-muted); margin-top: 2px; }
+.creator-modal-stats { display: flex; gap: 16px; margin-top: 8px; font-size: 12px; color: var(--ad-muted); }
+.creator-modal-stats strong { color: var(--ad-text); margin-right: 4px; }
+.creator-modal-body { display: grid; gap: 22px; }
+.creator-modal-sectiontitle { font-size: 13px; color: var(--ad-text); margin: 0 0 12px; }
+.creator-modal-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 12px; }
+.creator-mini-card {
+ padding: 10px;
+ border-radius: 11px;
+ background: var(--ad-bg-2);
+ border: 1px solid var(--ad-line);
+ cursor: pointer;
+ transition: border-color 0.15s, transform 0.15s;
+}
+.creator-mini-card:hover { border-color: var(--ad-line-2); transform: translateY(-2px); }
+.creator-mini-card .thumb {
+ width: 100%; aspect-ratio: 1; border-radius: 8px;
+ background: var(--ad-bg) center/cover no-repeat;
+ display: flex; align-items: center; justify-content: center;
+ font-size: 22px; font-weight: 700; color: var(--ad-muted);
+ margin-bottom: 8px;
+}
+.creator-mini-card .name { font-size: 12px; font-weight: 600; color: var(--ad-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.creator-mini-card .meta { font-size: 10px; color: var(--ad-dim); margin-top: 3px; display: flex; gap: 5px; flex-wrap: wrap; }
+.market-empty { font-size: 13px; color: var(--ad-dim); padding: 8px 0; }
+
+/* ── Payment modal (shared engine) ─────────────────────────────────────── */
+.market-modal-overlay {
+ position: fixed; inset: 0; z-index: 1100;
+ display: flex; align-items: center; justify-content: center;
+ padding: 20px;
+ background: rgba(0,0,0,0.72);
+ -webkit-backdrop-filter: blur(4px);
+ backdrop-filter: blur(4px);
+}
+.market-modal {
+ position: relative;
+ width: min(440px, 100%);
+ background: var(--ad-card);
+ border: 1px solid var(--ad-line-2);
+ border-radius: 16px;
+ box-shadow: var(--shadow-2);
+ overflow: hidden;
+}
+.market-modal-head { display: flex; align-items: center; justify-content: space-between; padding: 18px 20px; border-bottom: 1px solid var(--ad-line); }
+.market-modal-head h2 { margin: 0; font-size: 17px; color: var(--ad-text); }
+.market-modal-close {
+ width: 30px; height: 30px; border-radius: 8px;
+ border: 1px solid var(--ad-line); background: var(--ad-bg-2);
+ color: var(--ad-text); font-size: 18px; cursor: pointer;
+}
+.market-modal-close:hover { background: rgba(255,255,255,0.06); }
+.payment-modal-body { padding: 20px; }
+.payment-modal-badge {
+ display: flex; gap: 8px; align-items: flex-start;
+ padding: 9px 12px; border-radius: 9px; margin-bottom: 14px;
+ font-size: 12px; line-height: 1.5;
+ background: var(--ad-bg-2); border: 1px solid var(--ad-line);
+ color: var(--ad-muted);
+}
+.payment-modal-badge.warn { background: rgba(245,165,36,0.08); border-color: rgba(245,165,36,0.25); color: var(--ad-text); }
+#payment-modal-lede { font-size: 13px; color: var(--ad-muted); margin: 0 0 12px; }
+.payment-item {
+ display: flex; flex-direction: column; gap: 2px;
+ padding: 12px 14px; border-radius: 10px;
+ background: var(--ad-bg-2); border: 1px solid var(--ad-line);
+ margin-bottom: 12px;
+}
+.payment-item strong { font-size: 15px; color: var(--ad-text); }
+.payment-item span { font-size: 11px; color: var(--ad-dim); }
+.payment-item em { font-size: 13px; color: var(--ad-muted); font-style: normal; }
+.payment-price {
+ display: flex; align-items: center; justify-content: space-between;
+ padding: 12px 0; margin-bottom: 14px;
+ border-top: 1px solid var(--ad-line); border-bottom: 1px solid var(--ad-line);
+}
+.payment-price span { font-size: 13px; color: var(--ad-muted); }
+.payment-price strong { font-size: 18px; color: var(--ad-text); }
+.payment-wallet-area { display: flex; flex-direction: column; gap: 8px; margin-bottom: 14px; }
+.payment-wallet-area p { margin: 0; font-size: 13px; color: var(--ad-muted); }
+.payment-wallet-area p.small { font-size: 11px; color: var(--ad-dim); }
+.payment-wallet-area a { color: var(--ad-text); }
+.btn-primary, .payment-confirm-btn {
+ width: 100%; padding: 11px 16px; border-radius: 10px;
+ border: 1px solid var(--ad-text); background: var(--ad-text); color: var(--ad-bg);
+ font: inherit; font-size: 14px; font-weight: 600; cursor: pointer; text-align: center; text-decoration: none;
+ box-sizing: border-box;
+}
+.btn-primary:hover, .payment-confirm-btn:hover { background: #fff; }
+.btn-primary:disabled, .payment-confirm-btn:disabled { opacity: 0.5; cursor: not-allowed; }
+.btn-secondary {
+ width: 100%; padding: 11px 16px; border-radius: 10px;
+ border: 1px solid var(--ad-line-2); background: var(--ad-bg-2); color: var(--ad-text);
+ font: inherit; font-size: 14px; font-weight: 600; cursor: pointer; text-align: center; text-decoration: none;
+ box-sizing: border-box;
+}
+.btn-secondary:hover { background: rgba(255,255,255,0.06); }
+.wallet-pick { margin-bottom: 6px; }
+.payment-qr { display: flex; flex-direction: column; align-items: center; gap: 8px; margin: 12px 0; }
+.payment-qr .muted { font-size: 11px; color: var(--ad-dim); text-align: center; }
+.payment-status { font-size: 13px; margin-top: 12px; min-height: 16px; color: var(--ad-muted); }
+.payment-status.err { color: #ff6b6b; }
+.payment-status.ok { color: var(--ad-green); }
+.payment-modal-retry p { margin: 0 0 8px; font-size: 13px; color: var(--ad-text); }
+.retry-tx { font-size: 12px; color: var(--ad-dim); margin-bottom: 10px; }
+.retry-tx a { color: var(--ad-text); }
+.retry-actions { display: flex; gap: 8px; }
+.retry-primary {
+ flex: 1; padding: 9px; border-radius: 9px; border: 1px solid var(--ad-text);
+ background: var(--ad-text); color: var(--ad-bg); font: inherit; font-weight: 600; cursor: pointer;
+}
+.retry-secondary {
+ flex: 1; padding: 9px; border-radius: 9px; border: 1px solid var(--ad-line-2);
+ background: var(--ad-bg-2); color: var(--ad-text); font: inherit; font-weight: 600; cursor: pointer;
+}
+.payment-modal-success { padding: 30px 24px; text-align: center; }
+.ps-check {
+ width: 52px; height: 52px; margin: 0 auto 14px;
+ border-radius: 50%; background: rgba(74,222,128,0.12);
+ display: flex; align-items: center; justify-content: center;
+ font-size: 26px; color: var(--ad-green);
+}
+.ps-title { margin: 0 0 6px; font-size: 19px; color: var(--ad-text); }
+.ps-sub { margin: 0 0 18px; font-size: 13px; color: var(--ad-muted); line-height: 1.5; }
+.ps-actions { display: flex; flex-direction: column; gap: 8px; }
+.muted { color: var(--ad-muted); }
+.muted.small { font-size: 11px; }
+
+@media (max-width: 640px) {
+ .ad-version-row { grid-template-columns: auto 1fr; }
+ .ad-version-when { grid-column: 2; }
+}
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 4c736dc74..cae7d4d5f 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -30,6 +30,7 @@ import { renderError as renderAsyncError } from './shared/async-state.js';
import { openCoinLaunch } from './shared/agent-coin.js';
import { Modal } from './shared/modal.js';
import { showSharePanel } from './shared/share.js';
+import { enrichAgentDetail } from './agent-detail-market.js';
import { log } from './shared/log.js';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -314,6 +315,12 @@ function render(agent) {
wireShareButton(agent);
loadExtraSections(agent.id, agent.rawMetadata);
+
+ // Layer the marketplace discovery + commerce features (3D avatar, live chat
+ // preview, creator profile, skill pricing, sale panel, embed, similar,
+ // versions) onto the canonical page. No-ops if the agent isn't published to
+ // the marketplace, so the base page is never blocked.
+ enrichAgentDetail(agent).catch((e) => log.warn('[agent-detail] enrich failed:', e?.message));
}
async function loadExtraSections(agentId, rec) {
@@ -1258,7 +1265,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/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/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/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-activities.js b/src/game/play-activities.js
new file mode 100644
index 000000000..1aa81ddff
--- /dev/null
+++ b/src/game/play-activities.js
@@ -0,0 +1,355 @@
+// Play activities — the gather→craft layer for the /play coin worlds (W06).
+//
+// The chop/mine/cook counterpart to PlaySystems' fishing: it renders the world's
+// gather/craft stations (a grove of trees, a quarry of rocks, two roast pits), gates
+// a single contextual action prompt as the player walks up to one, plays the local
+// 3D feedback (chips, shards, embers, a flaring fire), and sends the intent. Every
+// yield, XP gain and level-up is rolled SERVER-side (WalkRoom → activities.js) and
+// streamed back over the same profile/inv/xpgain/levelup/notice events PlaySystems
+// already renders into the HUD — so this module never simulates a result locally.
+//
+// It is deliberately self-contained and instantiated as a SIBLING of PlaySystems
+// from coincommunities.js (not nested inside it): it owns only its own scene group,
+// one prompt button, and a lightweight mirror of the parts of the profile it needs
+// (hotbar/activeSlot/inv) which it keeps current straight from the net events. That
+// keeps it decoupled — fishing and gathering never fight over one file or one button
+// (their stations sit in different corners of the map, so at most one is ever in
+// range), and either can evolve without touching the other.
+
+import {
+ Group, Mesh, Vector3,
+ RingGeometry, CylinderGeometry, ConeGeometry, BoxGeometry, IcosahedronGeometry,
+ MeshStandardMaterial, MeshBasicMaterial, DoubleSide,
+} from 'three';
+
+import {
+ TREES, nearestTree, ROCKS, nearestRock, FIREPITS, nearestFirepit,
+} from '../../multiplayer/src/world-features.js';
+import { itemDisplay } from './items.js';
+
+// The three gather/craft activities. Each knows the tool the player must hold (null
+// for cooking — the fire is the station), the nearest-node finder (shared with the
+// server so the range rule never drifts), and how the prompt + 3D feedback read.
+const ACTIVITIES = [
+ { type: 'chop', tool: 'axe', skill: 'woodcutting', near: nearestTree, label: 'Chop', glyph: '🪓', noTool: 'Equip an axe', fx: 0x8a5a32 },
+ { type: 'mine', tool: 'pickaxe', skill: 'mining', near: nearestRock, label: 'Mine', glyph: '⛏️', noTool: 'Equip a pickaxe', fx: 0xb8c0cc },
+ { type: 'cook', tool: null, skill: 'cooking', near: nearestFirepit, label: 'Cook fish', glyph: '🍳', noTool: '', fx: 0xffa53a },
+];
+
+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 (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);
+ else if (v != null) n.setAttribute(k, v);
+ }
+ for (const c of [].concat(kids)) if (c) n.appendChild(c);
+ return n;
+}
+
+export class PlayActivities {
+ /**
+ * @param {object} opts
+ * @param {import('three').Scene} opts.scene
+ * @param {() => ({x,y,z,yaw,height})} opts.getPlayer local avatar pose
+ * @param {object} opts.net CommunityNet (chop/mine/cook/equip + profile/inv/notice events)
+ * @param {object} opts.ui CommunityUI (toast)
+ */
+ constructor({ scene, getPlayer, net, ui }) {
+ this.scene = scene;
+ this.getPlayer = getPlayer;
+ this.net = net;
+ this.ui = ui;
+
+ // Lightweight mirror of the parts of the server profile this module needs,
+ // kept current from the same net events PlaySystems renders into the HUD.
+ this._hotbar = [];
+ this._activeSlot = -1;
+ this._inv = [];
+
+ this._t = 0;
+ this._near = null; // nearest in-range activity { def, node, gap } or null
+ this._fx = []; // live one-shot particle bursts
+ this._stations = []; // { type, id, group, marker, anchor, hitNode?, baseY?, flame? }
+
+ this._buildScene();
+ this._buildPrompt();
+
+ // Subscribe to the economy stream. net.on returns an unsubscribe; collect them
+ // so dispose() leaves no dangling handlers when the player switches coins.
+ this._offs = [];
+ if (net?.on) {
+ this._offs.push(net.on('profile', (snap) => this._onProfile(snap)));
+ this._offs.push(net.on('inv', (delta) => this._onInv(delta)));
+ this._offs.push(net.on('notice', (n) => this._onNotice(n)));
+ }
+ }
+
+ // ---------------------------------------------------------------- profile mirror
+ _onProfile(snap) {
+ if (!snap || typeof snap !== 'object') return;
+ this._hotbar = Array.isArray(snap.hotbar) ? snap.hotbar : [];
+ this._activeSlot = Number.isFinite(snap.activeSlot) ? snap.activeSlot : -1;
+ this._inv = Array.isArray(snap.inv) ? snap.inv : [];
+ }
+ _onInv(delta) {
+ if (!delta) return;
+ if (Array.isArray(delta.hotbar)) this._hotbar = delta.hotbar;
+ if (Number.isFinite(delta.activeSlot)) this._activeSlot = delta.activeSlot;
+ if (Array.isArray(delta.inv)) this._inv = delta.inv;
+ }
+ // A gather/cook success rolls back as a notice carrying the activity kind — spawn
+ // the authoritative yield burst (failures already showed a small swing burst).
+ _onNotice(n) {
+ if (!n) return;
+ const def = ACTIVITIES.find((a) => a.type === n.kind);
+ if (!def) return;
+ const got = n.got != null ? n.got : n.cooked;
+ if (!got) return; // miss/burn — the swing feedback already played
+ const node = n.node ? this._nodeById(n.node) : null;
+ const anchor = node || this._near?.node;
+ if (anchor) this._spawnFx(anchor, def.fx, 7, 1.1);
+ if (def.type === 'cook') { const st = this._stationById(n.node) || this._stations.find((s) => s.type === 'cook'); if (st) st._flare = 0.7; }
+ }
+
+ _activeItem() {
+ const i = this._activeSlot;
+ return i >= 0 && this._hotbar[i] ? this._hotbar[i].item : '';
+ }
+
+ // ---------------------------------------------------------------- scene
+ _buildScene() {
+ const group = new Group();
+ group.name = 'play-activities';
+ for (const t of TREES) group.add(this._buildTree(t));
+ for (const r of ROCKS) group.add(this._buildRock(r));
+ for (const f of FIREPITS) group.add(this._buildFirepit(f));
+ this.scene.add(group);
+ this._group = group;
+ }
+
+ _marker(radius, color) {
+ const m = new Mesh(
+ new RingGeometry(radius, radius + 0.18, 32),
+ new MeshBasicMaterial({ color, transparent: true, opacity: 0.0, side: DoubleSide }),
+ );
+ m.rotation.x = -Math.PI / 2;
+ m.position.y = 0.05;
+ return m;
+ }
+
+ _buildTree(node) {
+ const g = new Group();
+ g.position.set(node.x, 0, node.z);
+ const h = 2.6 + (node.difficulty - 1) * 0.8;
+ const trunk = new Mesh(new CylinderGeometry(0.18, 0.28, h * 0.55, 7), new MeshStandardMaterial({ color: 0x6b4a2e, roughness: 0.95 }));
+ trunk.position.y = h * 0.275; trunk.castShadow = true; g.add(trunk);
+ const leafMat = new MeshStandardMaterial({ color: 0x2f6d3a, roughness: 0.9 });
+ const lower = new Mesh(new ConeGeometry(1.15, h * 0.55, 8), leafMat); lower.position.y = h * 0.62; lower.castShadow = true; g.add(lower);
+ const upper = new Mesh(new ConeGeometry(0.8, h * 0.42, 8), leafMat); upper.position.y = h * 0.92; upper.castShadow = true; g.add(upper);
+ const marker = this._marker(node.r + 0.5, 0x9be8a6); g.add(marker);
+ this._stations.push({ type: 'chop', id: node.id, marker, anchor: { x: node.x, z: node.z }, hitNode: trunk, baseY: trunk.position.y });
+ return g;
+ }
+
+ _buildRock(node) {
+ const g = new Group();
+ g.position.set(node.x, 0, node.z);
+ const stoneMat = new MeshStandardMaterial({ color: 0x7c8492, roughness: 1, flatShading: true });
+ const coalMat = new MeshStandardMaterial({ color: 0x2b2f38, roughness: 1, flatShading: true });
+ const main = new Mesh(new IcosahedronGeometry(node.r * 0.9, 0), stoneMat); main.position.y = node.r * 0.6; main.scale.y = 0.8; main.castShadow = true; g.add(main);
+ const lump = new Mesh(new IcosahedronGeometry(node.r * 0.5, 0), stoneMat); lump.position.set(node.r * 0.7, node.r * 0.35, -node.r * 0.4); lump.castShadow = true; g.add(lump);
+ const vein = new Mesh(new IcosahedronGeometry(node.r * 0.34, 0), coalMat); vein.position.set(-node.r * 0.4, node.r * 0.5, node.r * 0.45); g.add(vein);
+ const marker = this._marker(node.r + 0.6, 0xc8d0dc); g.add(marker);
+ this._stations.push({ type: 'mine', id: node.id, marker, anchor: { x: node.x, z: node.z }, hitNode: main, baseY: main.position.y });
+ return g;
+ }
+
+ _buildFirepit(node) {
+ const g = new Group();
+ g.position.set(node.x, 0, node.z);
+ const stoneMat = new MeshStandardMaterial({ color: 0x6a6f78, roughness: 1, flatShading: true });
+ for (let i = 0; i < 8; i++) {
+ const a = (i / 8) * Math.PI * 2;
+ const s = new Mesh(new IcosahedronGeometry(0.16, 0), stoneMat);
+ s.position.set(Math.cos(a) * node.r * 0.7, 0.12, Math.sin(a) * node.r * 0.7); g.add(s);
+ }
+ const logMat = new MeshStandardMaterial({ color: 0x5a3d22, roughness: 0.95 });
+ for (let i = 0; i < 3; i++) {
+ const log = new Mesh(new CylinderGeometry(0.08, 0.08, node.r * 1.1, 6), logMat);
+ log.rotation.z = Math.PI / 2; log.rotation.y = (i / 3) * Math.PI; log.position.y = 0.12; g.add(log);
+ }
+ const flame = new Mesh(new ConeGeometry(0.28, 0.8, 8), new MeshBasicMaterial({ color: 0xff8a2a, transparent: true, opacity: 0.85 }));
+ flame.position.y = 0.55; g.add(flame);
+ const marker = this._marker(node.r + 0.5, 0xffc890); g.add(marker);
+ this._stations.push({ type: 'cook', id: node.id, marker, anchor: { x: node.x, z: node.z }, flame });
+ return g;
+ }
+
+ _stationById(id) { return this._stations.find((s) => s.id === id) || null; }
+ _nodeById(id) {
+ return TREES.find((n) => n.id === id) || ROCKS.find((n) => n.id === id) || FIREPITS.find((n) => n.id === id) || null;
+ }
+
+ // ---------------------------------------------------------------- prompt DOM
+ _buildPrompt() {
+ // Reuse PlaySystems' .ps-action styling so the gather prompt is visually
+ // identical to the Cast button (they're never on screen at the same time).
+ this.btn = el('button', { class: 'ps-action pa-action', hidden: true, onclick: () => this.doAction() });
+ document.body.appendChild(this.btn);
+ }
+
+ // ---------------------------------------------------------------- per-frame
+ tick(dt) {
+ this._t += dt;
+ const p = this.getPlayer?.();
+ if (!p) return;
+
+ // Nearest in-range activity (mirrors each server *InRange check).
+ let near = null;
+ for (const def of ACTIVITIES) {
+ const n = def.near(p.x, p.z);
+ if (n && n.gap <= 0 && (!near || n.gap < near.gap)) near = { def, node: n.node, gap: n.gap };
+ }
+ this._near = near;
+ this._updatePrompt();
+
+ // Pulse markers (the in-range one brightest), flicker flames, decay hit shakes.
+ const activeId = near?.node.id;
+ const glow = 0.16 + Math.sin(this._t * 2) * 0.10;
+ for (const st of this._stations) {
+ if (st.marker) st.marker.material.opacity = st.id === activeId ? glow + 0.28 : glow;
+ if (st.flame) {
+ const flicker = 1 + Math.sin(this._t * 9 + st.anchor.x) * 0.12 + (st._flare || 0);
+ st.flame.scale.set(1, flicker, 1);
+ if (st._flare) st._flare = Math.max(0, st._flare - dt * 1.6);
+ }
+ if (st._shake && st.hitNode) {
+ if (st.type === 'mine') st.hitNode.position.y = st.baseY - 0.12 * st._shake * Math.abs(Math.sin(this._t * 28));
+ else st.hitNode.rotation.z = Math.sin(this._t * 40) * 0.08 * st._shake;
+ st._shake = Math.max(0, st._shake - dt * 3.5);
+ if (st._shake === 0) { st.hitNode.rotation.z = 0; if (st.type === 'mine') st.hitNode.position.y = st.baseY; }
+ }
+ }
+
+ this._tickFx(dt);
+ }
+
+ _updatePrompt() {
+ const near = this._near;
+ if (!near) { if (!this.btn.hidden) this.btn.hidden = true; return; }
+ const def = near.def;
+ const holding = this._activeItem();
+ let label, disabled = false;
+ if (def.tool) {
+ const hasTool = this._hotbar.some((s) => s.item === def.tool);
+ label = holding === def.tool ? `${def.glyph} ${def.label}` : hasTool ? `${def.glyph} Equip ${itemDisplay(def.tool).name.toLowerCase()}` : `${def.glyph} ${def.noTool}`;
+ disabled = !hasTool;
+ } else {
+ const hasFish = this._inv.some((s) => s.item === 'fish');
+ label = `${def.glyph} ${def.label}`;
+ disabled = !hasFish;
+ }
+ this.btn.textContent = label;
+ this.btn.classList.toggle('is-disabled', disabled);
+ this.btn.hidden = false;
+ }
+
+ // Public: act on the nearest station. Returns true if a station was in range (so
+ // the F-key handler knows whether to fall through to fishing). Mirrors the server's
+ // preconditions for instant, honest feedback: auto-equip the tool the player owns
+ // but isn't holding, surface a missing tool/fish, else play feedback + send.
+ doAction() {
+ const near = this._near;
+ if (!near) return false;
+ const def = near.def;
+ if (def.tool) {
+ const holding = this._activeItem();
+ if (holding !== def.tool) {
+ const slot = this._hotbar.findIndex((s) => s.item === def.tool);
+ if (slot >= 0) {
+ this.net?.equip(slot);
+ this._activeSlot = slot; // optimistic; server echoes inv
+ this.ui?.toast?.(`${itemDisplay(def.tool).name} equipped — ${def.label.toLowerCase()} again.`, 'info');
+ return true;
+ }
+ this.ui?.toast?.(`${def.noTool} to ${def.label.toLowerCase()}.`, 'warn');
+ return true;
+ }
+ } else if (def.type === 'cook') {
+ if (!this._inv.some((s) => s.item === 'fish')) { this.ui?.toast?.('You have no raw fish to cook.', 'warn'); return true; }
+ }
+ this._hit(def, near.node);
+ this.net?.[def.type]?.();
+ return true;
+ }
+
+ // ---------------------------------------------------------------- 3D feedback
+ _hit(def, node) {
+ const st = this._stationById(node.id);
+ if (st) { if (def.type === 'cook') st._flare = 0.6; else st._shake = 1; }
+ this._spawnFx(node, def.fx, def.type === 'cook' ? 3 : 4, 0.7);
+ }
+
+ _spawnFx(node, color, count = 6, speed = 1) {
+ const g = new Group();
+ g.position.set(node.x, 0.9, node.z);
+ const mat = new MeshBasicMaterial({ color, transparent: true, opacity: 0.95 });
+ const bits = [];
+ for (let i = 0; i < count; i++) {
+ const b = new Mesh(new BoxGeometry(0.09, 0.09, 0.09), mat);
+ const a = Math.random() * Math.PI * 2;
+ const sp = (0.9 + Math.random() * 1.1) * speed;
+ b.userData.v = { x: Math.cos(a) * sp, y: 1.8 + Math.random() * 1.4, z: Math.sin(a) * sp };
+ b.rotation.set(Math.random() * 3, Math.random() * 3, Math.random() * 3);
+ g.add(b); bits.push(b);
+ }
+ this.scene.add(g);
+ this._fx.push({ group: g, mat, bits, age: 0, ttl: 0.7 });
+ }
+
+ _tickFx(dt) {
+ if (!this._fx.length) return;
+ for (let i = this._fx.length - 1; i >= 0; i--) {
+ const fx = this._fx[i];
+ fx.age += dt;
+ for (const b of fx.bits) {
+ const v = b.userData.v;
+ v.y -= 9.8 * dt;
+ b.position.x += v.x * dt;
+ b.position.y = Math.max(0, b.position.y + v.y * dt);
+ b.position.z += v.z * dt;
+ b.rotation.x += dt * 6; b.rotation.y += dt * 5;
+ }
+ fx.mat.opacity = Math.max(0, 0.95 * (1 - fx.age / fx.ttl));
+ if (fx.age >= fx.ttl) {
+ this.scene.remove(fx.group);
+ fx.group.traverse((n) => { if (n.isMesh) n.geometry?.dispose?.(); });
+ fx.mat.dispose();
+ this._fx.splice(i, 1);
+ }
+ }
+ }
+
+ // ---------------------------------------------------------------- teardown
+ dispose() {
+ for (const off of this._offs || []) { try { off(); } catch {} }
+ this._offs = [];
+ for (const fx of this._fx) {
+ this.scene.remove(fx.group);
+ fx.group.traverse((n) => { if (n.isMesh) n.geometry?.dispose?.(); });
+ fx.mat.dispose();
+ }
+ this._fx = [];
+ if (this._group) {
+ this.scene.remove(this._group);
+ this._group.traverse((n) => {
+ if (n.isMesh) { n.geometry?.dispose?.(); const ms = Array.isArray(n.material) ? n.material : [n.material]; ms.forEach((m) => m?.dispose?.()); }
+ });
+ this._group = null;
+ }
+ this.btn?.remove();
+ }
+}
diff --git a/src/game/play-combat.js.tmp.4039013.89318219aab0 b/src/game/play-combat.js.tmp.4039013.89318219aab0
new file mode 100644
index 000000000..3288ca868
--- /dev/null
+++ b/src/game/play-combat.js.tmp.4039013.89318219aab0
@@ -0,0 +1,587 @@
+// Play combat (W07) — the client layer for the /play coin-world combat system.
+//
+// Authority lives entirely on the server (WalkRoom): this module is pure
+// presentation + intent. It renders the danger-zone signposting, the roaming mobs
+// and death-drop tombstones the server replicates, the player's vitals (HP + armor
+// + wanted stars + bank), floating damage numbers, weapon swing/fire FX, and the
+// death/respawn screen — and it sends attack/loot/bank/respawn INTENTS. It never
+// decides a hit, an HP value, or a kill; it draws what the server says happened.
+//
+// It owns its own DOM (a HUD layer) and scene objects (zone rings, mob + tombstone
+// meshes, transient FX) and tears both down cleanly on dispose() so switching coins
+// never leaks meshes or panels. Vitals are fed from the same private profile/inv
+// stream the rest of the economy uses; world entities arrive over the synced mob/
+// tombstone state callbacks.
+
+import {
+ Group, Mesh, Color, Vector3,
+ CircleGeometry, RingGeometry, BoxGeometry, SphereGeometry, ConeGeometry, PlaneGeometry,
+ MeshStandardMaterial, MeshBasicMaterial, DoubleSide,
+} from 'three';
+
+import { DANGER_ZONES, dangerZoneAt } from '../../multiplayer/src/world-features.js';
+import { itemDisplay } from './items.js';
+import './play-combat.css';
+
+// Per-mob render hints, mirroring the server's MOB_STATS color/scale so a goblin
+// looks like a goblin on every client without syncing cosmetic data.
+const MOB_LOOK = {
+ dummy: { color: 0x9aa3b2, scale: 1.0, label: 'Training dummy' },
+ goblin: { color: 0x5f8a3a, scale: 0.9, label: 'Goblin' },
+ ogre: { color: 0x8a6a3a, scale: 1.35, label: 'Ogre' },
+ troll: { color: 0x4a6a6a, scale: 1.7, label: 'Cave troll' },
+};
+const LOOT_REACH_M = 2.6; // mirror of the server's loot range (for the button gate)
+
+function el(tag, props = {}, kids = []) {
+ const n = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (k === 'class') n.className = v;
+ else if (k === 'text') n.textContent = v;
+ else if (k === 'html') n.innerHTML = v;
+ else if (k === 'hidden') n.hidden = !!v;
+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);
+ else if (v != null) n.setAttribute(k, v);
+ }
+ for (const c of [].concat(kids)) if (c) n.appendChild(c);
+ return n;
+}
+
+export class PlayCombat {
+ /**
+ * @param {object} opts
+ * @param {import('three').Scene} opts.scene
+ * @param {import('three').Camera} opts.camera
+ * @param {import('three').WebGLRenderer} opts.renderer
+ * @param {() => ({x,y,z,yaw,height})} opts.getPlayer local avatar pose
+ * @param {object} opts.net CommunityNet (attack/loot/bank/respawn + combat events)
+ * @param {object} opts.ui CommunityUI (toast)
+ * @param {(x:number,z:number)=>void} [opts.onTeleport] move the local avatar (respawn)
+ */
+ constructor({ scene, camera, renderer, getPlayer, net, ui, onTeleport }) {
+ this.scene = scene;
+ this.camera = camera;
+ this.renderer = renderer;
+ this.getPlayer = getPlayer;
+ this.net = net;
+ this.ui = ui;
+ this.onTeleport = onTeleport;
+
+ this.vitals = { hp: 100, maxHp: 100, armor: 0, maxArmor: 100, heat: 0, gold: 0, bank: 0 };
+ this.dead = false;
+ this._respawnReadyAt = 0;
+ this._t = 0;
+ this._zone = null; // current danger zone (or null = safe)
+ this._mobs = new Map(); // id -> { group, target, hpFill, hpWrap, hp, maxHp, kind, hitFlash }
+ this._tombs = new Map(); // id -> { group }
+ this._fx = []; // transient scene FX { group, ttl, age, kind, ... }
+ this._floats = []; // DOM damage numbers { node, ttl, age }
+ this._unsubs = [];
+
+ this._buildZoneRings();
+ this._buildHud();
+ this._subscribe();
+ this._bindKeys();
+ }
+
+ // ---------------------------------------------------------------- scene
+ // A translucent red disc + pulsing rim at each danger zone, so the wilderness
+ // reads as dangerous from across the map (GTA-style red-zone signposting).
+ _buildZoneRings() {
+ const group = new Group();
+ group.name = 'pc-danger-zones';
+ this._zoneMarkers = [];
+ for (const z of DANGER_ZONES) {
+ const g = new Group();
+ g.position.set(z.x, 0, z.z);
+ const disc = new Mesh(
+ new CircleGeometry(z.r, 48),
+ new MeshBasicMaterial({ color: 0xff3b30, transparent: true, opacity: 0.06, side: DoubleSide, depthWrite: false }),
+ );
+ disc.rotation.x = -Math.PI / 2;
+ disc.position.y = 0.03;
+ g.add(disc);
+ const rim = new Mesh(
+ new RingGeometry(z.r - 0.5, z.r, 64),
+ new MeshBasicMaterial({ color: 0xff5a4d, transparent: true, opacity: 0.5, side: DoubleSide, depthWrite: false }),
+ );
+ rim.rotation.x = -Math.PI / 2;
+ rim.position.y = 0.05;
+ g.add(rim);
+ group.add(g);
+ this._zoneMarkers.push({ rim });
+ }
+ this.scene.add(group);
+ this._zoneGroup = group;
+ }
+
+ // A blocky little foe: body + head + eyes, tinted per kind, with a billboarded
+ // HP bar above it. Readable at a glance without an art pipeline.
+ _buildMobMesh(kind) {
+ const look = MOB_LOOK[kind] || MOB_LOOK.goblin;
+ const g = new Group();
+ const s = look.scale;
+ const bodyMat = new MeshStandardMaterial({ color: look.color, roughness: 0.85, metalness: 0.05 });
+ const body = new Mesh(new BoxGeometry(0.7 * s, 0.9 * s, 0.5 * s), bodyMat);
+ body.position.y = 0.75 * s;
+ body.castShadow = true;
+ g.add(body);
+ const head = new Mesh(new BoxGeometry(0.5 * s, 0.45 * s, 0.45 * s), bodyMat);
+ head.position.y = 1.4 * s;
+ head.castShadow = true;
+ g.add(head);
+ const eyeMat = new MeshBasicMaterial({ color: 0xffd166 });
+ for (const dx of [-0.12 * s, 0.12 * s]) {
+ const eye = new Mesh(new BoxGeometry(0.08 * s, 0.08 * s, 0.05 * s), eyeMat);
+ eye.position.set(dx, 1.45 * s, 0.24 * s);
+ g.add(eye);
+ }
+ // Floating HP bar.
+ const hpWrap = new Group();
+ hpWrap.position.y = 1.95 * s;
+ const bg = new Mesh(new PlaneGeometry(1.0, 0.13), new MeshBasicMaterial({ color: 0x14181f, transparent: true, opacity: 0.85, depthTest: false }));
+ bg.renderOrder = 999;
+ const fill = new Mesh(new PlaneGeometry(1.0, 0.13), new MeshBasicMaterial({ color: 0x4cd964, depthTest: false }));
+ fill.renderOrder = 1000;
+ fill.position.z = 0.001;
+ hpWrap.add(bg); hpWrap.add(fill);
+ g.add(hpWrap);
+ g.userData = { bodyMat, baseColor: new Color(look.color) };
+ return { group: g, hpFill: fill, hpWrap };
+ }
+
+ _buildTombMesh() {
+ const g = new Group();
+ const stoneMat = new MeshStandardMaterial({ color: 0x6b7280, roughness: 0.95 });
+ const base = new Mesh(new BoxGeometry(0.7, 0.12, 0.5), stoneMat);
+ base.position.y = 0.06;
+ g.add(base);
+ const slab = new Mesh(new BoxGeometry(0.55, 0.7, 0.16), stoneMat);
+ slab.position.y = 0.42;
+ slab.castShadow = true;
+ g.add(slab);
+ // Soft loot glow on top so it reads as lootable.
+ const glow = new Mesh(
+ new RingGeometry(0.5, 0.8, 28),
+ new MeshBasicMaterial({ color: 0xffd166, transparent: true, opacity: 0.0, side: DoubleSide, depthWrite: false }),
+ );
+ glow.rotation.x = -Math.PI / 2;
+ glow.position.y = 0.02;
+ g.add(glow);
+ g.userData = { glow };
+ return { group: g };
+ }
+
+ // ---------------------------------------------------------------- HUD
+ _buildHud() {
+ // Vitals: HP + armor bars, wanted stars, purse + bank.
+ this.hpFill = el('span', { class: 'pc-bar-fill pc-hp-fill' });
+ this.hpText = el('span', { class: 'pc-bar-text' });
+ this.armorFill = el('span', { class: 'pc-bar-fill pc-armor-fill' });
+ this.armorText = el('span', { class: 'pc-bar-text' });
+ this.armorRow = el('div', { class: 'pc-bar pc-armor', title: 'Armor (absorbs damage before HP)' }, [this.armorFill, this.armorText]);
+ this.wantedEl = el('div', { class: 'pc-wanted', title: 'Wanted level', hidden: true });
+ this.bankEl = el('div', { class: 'pc-bank', title: 'Banked gold (safe on death)' });
+
+ this.vitalsPanel = el('div', { class: 'pc-vitals' }, [
+ el('div', { class: 'pc-bar pc-hp', title: 'Health' }, [this.hpFill, this.hpText]),
+ this.armorRow,
+ this.wantedEl,
+ this.bankEl,
+ ]);
+
+ // Contextual action stack (bottom-right): Attack, Loot, Bank.
+ this.attackBtn = el('button', { class: 'pc-btn pc-attack', title: 'Attack (F)', onclick: () => this.attack() }, [el('span', { text: '⚔️ Attack' })]);
+ this.lootBtn = el('button', { class: 'pc-btn pc-loot', title: 'Loot (G)', hidden: true, onclick: () => this.net?.loot() }, [el('span', { text: '🪦 Loot' })]);
+ this.bankDepositBtn = el('button', { class: 'pc-btn pc-bank-btn', title: 'Deposit all carried gold', hidden: true, onclick: () => this.net?.bank({ all: 'deposit' }) }, [el('span', { text: '🏦 Deposit' })]);
+ this.bankWithdrawBtn = el('button', { class: 'pc-btn pc-bank-btn', title: 'Withdraw all banked gold', hidden: true, onclick: () => this.net?.bank({ all: 'withdraw' }) }, [el('span', { text: '💸 Withdraw' })]);
+ this.actionStack = el('div', { class: 'pc-actions' }, [this.bankWithdrawBtn, this.bankDepositBtn, this.lootBtn, this.attackBtn]);
+
+ // Zone banner (top-center), shown briefly when crossing a boundary.
+ this.zoneBanner = el('div', { class: 'pc-zone-banner', hidden: true });
+
+ // Death screen overlay.
+ this.deathTitle = el('div', { class: 'pc-death-title', text: 'You were taken down' });
+ this.deathSub = el('div', { class: 'pc-death-sub' });
+ this.respawnBtn = el('button', { class: 'pc-respawn', onclick: () => this.net?.respawn() });
+ this.deathScreen = el('div', { class: 'pc-death', hidden: true }, [
+ el('div', { class: 'pc-death-card' }, [this.deathTitle, this.deathSub, this.respawnBtn]),
+ ]);
+
+ this.root = el('div', { id: 'pc-hud' }, [this.vitalsPanel, this.actionStack, this.zoneBanner, this.deathScreen]);
+ document.body.appendChild(this.root);
+ this._renderVitals();
+ }
+
+ _renderVitals() {
+ const v = this.vitals;
+ const hpPct = v.maxHp > 0 ? Math.max(0, Math.min(100, (v.hp / v.maxHp) * 100)) : 0;
+ this.hpFill.style.width = `${hpPct}%`;
+ this.hpFill.classList.toggle('is-low', hpPct <= 30);
+ this.hpText.textContent = `${Math.ceil(v.hp)}/${v.maxHp}`;
+
+ const hasArmor = v.armor > 0;
+ this.armorRow.classList.toggle('is-empty', !hasArmor);
+ const armPct = v.maxArmor > 0 ? Math.max(0, Math.min(100, (v.armor / v.maxArmor) * 100)) : 0;
+ this.armorFill.style.width = `${armPct}%`;
+ this.armorText.textContent = hasArmor ? `${Math.ceil(v.armor)}` : '';
+
+ const stars = Math.max(0, Math.min(5, Math.ceil(v.heat)));
+ this.wantedEl.hidden = stars <= 0;
+ if (stars > 0) this.wantedEl.textContent = '★'.repeat(stars) + '☆'.repeat(5 - stars);
+
+ this.bankEl.textContent = v.bank > 0 ? `🏦 ${v.bank.toLocaleString()}` : '';
+ this.bankEl.hidden = v.bank <= 0;
+ }
+
+ // ---------------------------------------------------------------- net
+ setVitals(snap) {
+ if (!snap || typeof snap !== 'object') return;
+ const v = this.vitals;
+ if (Number.isFinite(snap.hp)) v.hp = snap.hp;
+ if (Number.isFinite(snap.maxHp)) v.maxHp = snap.maxHp;
+ if (Number.isFinite(snap.armor)) v.armor = snap.armor;
+ if (Number.isFinite(snap.maxArmor)) v.maxArmor = snap.maxArmor;
+ if (Number.isFinite(snap.heat)) v.heat = snap.heat;
+ if (Number.isFinite(snap.gold)) v.gold = snap.gold;
+ if (Number.isFinite(snap.bank)) v.bank = snap.bank;
+ this._renderVitals();
+ }
+
+ _subscribe() {
+ const on = (ev, fn) => { const off = this.net?.on?.(ev, fn); if (off) this._unsubs.push(off); };
+ on('profile', (s) => this.setVitals(s));
+ on('inv', (s) => this.setVitals(s));
+ on('combatHit', (d) => this._onHit(d));
+ on('combatSwing', (d) => this._onSwing(d));
+ on('mobDown', (d) => this._onMobDown(d));
+ on('death', (d) => this._onDeath(d));
+ on('respawn', (d) => this._onRespawn(d));
+ on('mobAdd', (mob, id) => this._mobAdd(mob, id));
+ on('mobChange', (mob, id) => this._mobChange(mob, id));
+ on('mobRemove', (id) => this._mobRemove(id));
+ on('tombAdd', (t, id) => this._tombAdd(t, id));
+ on('tombChange', (t, id) => this._tombChange(t, id));
+ on('tombRemove', (id) => this._tombRemove(id));
+ }
+
+ _bindKeys() {
+ this._onKey = (e) => {
+ if (e.repeat) return;
+ const tag = (e.target?.tagName || '').toLowerCase();
+ if (tag === 'input' || tag === 'textarea') return;
+ const k = e.key.toLowerCase();
+ if (k === 'f') { e.preventDefault(); this.attack(); }
+ else if (k === 'g') { e.preventDefault(); if (!this.lootBtn.hidden) this.net?.loot(); }
+ };
+ window.addEventListener('keydown', this._onKey);
+ }
+
+ // ---------------------------------------------------------------- mobs
+ _mobAdd(mob, id) {
+ if (this._mobs.has(id)) return;
+ const { group, hpFill, hpWrap } = this._buildMobMesh(mob.kind);
+ group.position.set(mob.x, mob.y || 0, mob.z);
+ group.rotation.y = mob.yaw || 0;
+ this.scene.add(group);
+ this._mobs.set(id, {
+ group, hpFill, hpWrap, kind: mob.kind,
+ hp: mob.hp, maxHp: mob.maxHp,
+ target: { x: mob.x, z: mob.z, yaw: mob.yaw || 0 },
+ hitFlash: 0,
+ });
+ this._setMobHp(this._mobs.get(id), mob.hp, mob.maxHp);
+ }
+
+ _mobChange(mob, id) {
+ const m = this._mobs.get(id);
+ if (!m) { this._mobAdd(mob, id); return; }
+ m.target.x = mob.x; m.target.z = mob.z; m.target.yaw = mob.yaw || 0;
+ if (mob.hp < m.hp) m.hitFlash = 0.18; // took damage → flash
+ this._setMobHp(m, mob.hp, mob.maxHp);
+ }
+
+ _setMobHp(m, hp, maxHp) {
+ m.hp = hp; m.maxHp = maxHp;
+ const pct = maxHp > 0 ? Math.max(0, Math.min(1, hp / maxHp)) : 0;
+ m.hpFill.scale.x = Math.max(0.001, pct);
+ m.hpFill.position.x = -(1 - pct) * 0.5; // left-anchor the shrinking bar
+ m.hpFill.material.color.setHex(pct > 0.5 ? 0x4cd964 : pct > 0.25 ? 0xffd166 : 0xff5a4d);
+ }
+
+ _mobRemove(id) {
+ const m = this._mobs.get(id);
+ if (!m) return;
+ this._disposeGroup(m.group);
+ this._mobs.delete(id);
+ }
+
+ _onMobDown(d) {
+ // A slain mob: a quick dust poof where it fell (the mesh itself is removed via
+ // mobRemove, which the server fires alongside this).
+ this._spawnPoof(d.x, 0.8, d.z, 0xffe7a8);
+ }
+
+ // ---------------------------------------------------------------- tombs
+ _tombAdd(t, id) {
+ if (this._tombs.has(id)) return;
+ const { group } = this._buildTombMesh();
+ group.position.set(t.x, 0, t.z);
+ this.scene.add(group);
+ this._tombs.set(id, { group });
+ }
+
+ _tombChange() { /* contents change is server-side; the marker stays put */ }
+
+ _tombRemove(id) {
+ const t = this._tombs.get(id);
+ if (!t) return;
+ this._disposeGroup(t.group);
+ this._tombs.delete(id);
+ }
+
+ // ---------------------------------------------------------------- combat FX
+ attack() {
+ if (this.dead) return;
+ this.net?.attack();
+ const p = this.getPlayer();
+ this._spawnSwing(p);
+ }
+
+ _onSwing(d) {
+ if (!d || d.id === this.net?.sessionId) return; // our own swing is local
+ const peer = this.net?.state?.players?.get?.(d.id);
+ if (!peer) return;
+ this._spawnSwing({ x: peer.x, y: peer.y, z: peer.z, yaw: peer.yaw, height: 1.7 }, d.kind);
+ }
+
+ // Melee → a quick slash arc in front; ranged → a muzzle flash + forward tracer.
+ _spawnSwing(p, kind) {
+ const isRanged = kind === 'ranged' || (kind == null && false);
+ const fx = new Group();
+ const fwd = new Vector3(Math.sin(p.yaw || 0), 0, Math.cos(p.yaw || 0));
+ const chest = new Vector3(p.x, (p.height || 1.6) * 0.6, p.z);
+ if (kind === 'ranged') {
+ const muzzle = chest.clone().add(fwd.clone().multiplyScalar(0.6));
+ const flash = new Mesh(new SphereGeometry(0.12, 8, 8), new MeshBasicMaterial({ color: 0xfff1a8, transparent: true, opacity: 0.9 }));
+ flash.position.copy(muzzle);
+ fx.add(flash);
+ const tracer = new Mesh(
+ new BoxGeometry(0.04, 0.04, 6),
+ new MeshBasicMaterial({ color: 0xfff1a8, transparent: true, opacity: 0.7 }),
+ );
+ tracer.position.copy(chest).add(fwd.clone().multiplyScalar(3.2));
+ tracer.rotation.y = p.yaw || 0;
+ fx.add(tracer);
+ this._fx.push({ group: fx, age: 0, ttl: 0.18, kind: 'ranged' });
+ } else {
+ const arc = new Mesh(
+ new RingGeometry(0.9, 1.25, 16, 1, -0.8, 1.6),
+ new MeshBasicMaterial({ color: 0xe6f0ff, transparent: true, opacity: 0.8, side: DoubleSide, depthWrite: false }),
+ );
+ arc.rotation.x = -Math.PI / 2.2;
+ arc.rotation.z = -(p.yaw || 0);
+ arc.position.copy(chest).add(fwd.clone().multiplyScalar(0.5));
+ fx.add(arc);
+ this._fx.push({ group: fx, age: 0, ttl: 0.22, kind: 'melee' });
+ }
+ this.scene.add(fx);
+ }
+
+ _spawnPoof(x, y, z, color) {
+ const g = new Group();
+ const m = new Mesh(
+ new SphereGeometry(0.4, 10, 8),
+ new MeshBasicMaterial({ color, transparent: true, opacity: 0.7, depthWrite: false }),
+ );
+ m.position.set(x, y, z);
+ g.add(m);
+ this.scene.add(g);
+ this._fx.push({ group: g, age: 0, ttl: 0.5, kind: 'poof', mesh: m });
+ }
+
+ _onHit(d) {
+ if (!d) return;
+ // Flash a hit mob.
+ if (d.vKind === 'mob') {
+ const m = this._mobs.get(d.vId);
+ if (m) m.hitFlash = 0.18;
+ }
+ // Floating damage number at the hit point.
+ if (Number.isFinite(d.dmg) && d.dmg > 0) {
+ this._spawnFloat(d.x, (d.y || 0) + 1.6, d.z, d.dmg, d.killed, d.vId === this.net?.sessionId);
+ }
+ }
+
+ // A DOM damage number projected to where the hit landed, drifting up as it fades.
+ _spawnFloat(x, y, z, dmg, killed, onSelf) {
+ const sp = this._toScreen(x, y, z);
+ if (!sp.visible) return;
+ const node = el('div', {
+ class: 'pc-float' + (killed ? ' is-kill' : '') + (onSelf ? ' is-self' : ''),
+ text: killed ? `-${dmg} ☠` : `-${dmg}`,
+ });
+ node.style.left = `${sp.x}px`;
+ node.style.top = `${sp.y}px`;
+ document.body.appendChild(node);
+ requestAnimationFrame(() => node.classList.add('is-rise'));
+ this._floats.push({ node, age: 0, ttl: 0.95 });
+ }
+
+ _toScreen(x, y, z) {
+ const v = new Vector3(x, y, z).project(this.camera);
+ const dom = this.renderer?.domElement;
+ const w = dom ? dom.clientWidth : window.innerWidth;
+ const h = dom ? dom.clientHeight : window.innerHeight;
+ return { x: (v.x * 0.5 + 0.5) * w, y: (-v.y * 0.5 + 0.5) * h, visible: v.z < 1 };
+ }
+
+ // ---------------------------------------------------------------- death
+ _onDeath(d) {
+ this.dead = true;
+ this._respawnReadyAt = this._t + (Number.isFinite(d?.respawnInMs) ? d.respawnInMs / 1000 : 5);
+ this.deathSub.textContent = d?.by ? `Taken down by ${d.by}.` : 'You went down in the wilds.';
+ this.deathScreen.hidden = false;
+ this._updateRespawnBtn();
+ }
+
+ _onRespawn(d) {
+ this.dead = false;
+ this.deathScreen.hidden = true;
+ if (d && Number.isFinite(d.x) && Number.isFinite(d.z)) this.onTeleport?.(d.x, d.z);
+ }
+
+ _updateRespawnBtn() {
+ const remain = Math.max(0, this._respawnReadyAt - this._t);
+ if (remain > 0.05) {
+ this.respawnBtn.disabled = true;
+ this.respawnBtn.textContent = `Respawn in ${Math.ceil(remain)}…`;
+ } else {
+ this.respawnBtn.disabled = false;
+ this.respawnBtn.textContent = 'Respawn at spawn';
+ }
+ }
+
+ // ---------------------------------------------------------------- per-frame
+ tick(dt) {
+ this._t += dt;
+ const p = this.getPlayer();
+
+ // Zone signposting — banner on crossing, button + danger-ring pulse.
+ const zone = dangerZoneAt(p.x, p.z);
+ const zoneId = zone?.id || null;
+ if (zoneId !== (this._zone?.id || null)) {
+ this._zone = zone;
+ this._showZoneBanner(zone);
+ }
+ const pulse = 0.4 + Math.sin(this._t * 3) * 0.18;
+ for (const zm of this._zoneMarkers) zm.rim.material.opacity = pulse;
+
+ // Mobs: smooth toward the authoritative transform; flash on hit; billboard HP.
+ const camPos = this.camera.position;
+ for (const m of this._mobs.values()) {
+ const g = m.group;
+ g.position.x += (m.target.x - g.position.x) * Math.min(1, dt * 10);
+ g.position.z += (m.target.z - g.position.z) * Math.min(1, dt * 10);
+ let dy = m.target.yaw - g.rotation.y;
+ while (dy > Math.PI) dy -= Math.PI * 2;
+ while (dy < -Math.PI) dy += Math.PI * 2;
+ g.rotation.y += dy * Math.min(1, dt * 8);
+ m.hpWrap.lookAt(camPos.x, m.hpWrap.getWorldPosition(new Vector3()).y, camPos.z);
+ if (m.hitFlash > 0) {
+ m.hitFlash = Math.max(0, m.hitFlash - dt);
+ const k = m.hitFlash / 0.18;
+ g.userData.bodyMat.color.copy(g.userData.baseColor).lerp(new Color(0xffffff), k);
+ }
+ }
+
+ // Tombstones: gentle loot-glow pulse.
+ const glow = 0.25 + Math.sin(this._t * 2.5) * 0.15;
+ for (const t of this._tombs.values()) {
+ const gl = t.group.userData.glow;
+ if (gl) gl.material.opacity = glow;
+ }
+
+ // Transient FX.
+ for (let i = this._fx.length - 1; i >= 0; i--) {
+ const f = this._fx[i];
+ f.age += dt;
+ const k = f.age / f.ttl;
+ if (f.kind === 'poof' && f.mesh) { f.mesh.scale.setScalar(1 + k * 1.6); f.mesh.material.opacity = Math.max(0, 0.7 * (1 - k)); }
+ else f.group.children.forEach((c) => { if (c.material) c.material.opacity = Math.max(0, (c.material.opacity ?? 1) * (1 - dt * 6)); });
+ if (f.age >= f.ttl) { this._disposeGroup(f.group); this._fx.splice(i, 1); }
+ }
+
+ // DOM damage floats time out (CSS drives the motion).
+ for (let i = this._floats.length - 1; i >= 0; i--) {
+ const fl = this._floats[i];
+ fl.age += dt;
+ if (fl.age >= fl.ttl) { fl.node.remove(); this._floats.splice(i, 1); }
+ }
+
+ this._updateActions(p, zone);
+ if (this.dead) this._updateRespawnBtn();
+ }
+
+ _showZoneBanner(zone) {
+ clearTimeout(this._bannerTimer);
+ if (zone) {
+ this.zoneBanner.className = 'pc-zone-banner is-danger';
+ this.zoneBanner.innerHTML = `⚠ Entering <strong>${zone.name}</strong><span>PvP is live · monsters roam · richer loot</span>`;
+ } else {
+ this.zoneBanner.className = 'pc-zone-banner is-safe';
+ this.zoneBanner.innerHTML = `✓ <strong>Safe zone</strong><span>No PvP · bank your gold here</span>`;
+ }
+ this.zoneBanner.hidden = false;
+ requestAnimationFrame(() => this.zoneBanner.classList.add('is-show'));
+ this._bannerTimer = setTimeout(() => {
+ this.zoneBanner.classList.remove('is-show');
+ setTimeout(() => { this.zoneBanner.hidden = true; }, 400);
+ }, 2600);
+ }
+
+ // Show/hide the contextual buttons: Loot near a tombstone, Bank in a safe zone.
+ _updateActions(p, zone) {
+ this.actionStack.classList.toggle('is-hidden', this.dead);
+
+ let nearTomb = false;
+ for (const t of this._tombs.values()) {
+ if (Math.hypot(t.group.position.x - p.x, t.group.position.z - p.z) <= LOOT_REACH_M) { nearTomb = true; break; }
+ }
+ this.lootBtn.hidden = !nearTomb;
+
+ const safe = !zone;
+ this.bankDepositBtn.hidden = !(safe && this.vitals.gold > 0);
+ this.bankWithdrawBtn.hidden = !(safe && this.vitals.bank > 0);
+ }
+
+ // ---------------------------------------------------------------- teardown
+ _disposeGroup(group) {
+ this.scene.remove(group);
+ group.traverse((n) => {
+ if (n.isMesh) {
+ n.geometry?.dispose?.();
+ const ms = Array.isArray(n.material) ? n.material : [n.material];
+ ms.forEach((mm) => mm?.dispose?.());
+ }
+ });
+ }
+
+ dispose() {
+ this._unsubs.forEach((off) => { try { off(); } catch {} });
+ this._unsubs = [];
+ window.removeEventListener('keydown', this._onKey);
+ clearTimeout(this._bannerTimer);
+ for (const m of this._mobs.values()) this._disposeGroup(m.group);
+ this._mobs.clear();
+ for (const t of this._tombs.values()) this._disposeGroup(t.group);
+ this._tombs.clear();
+ for (const f of this._fx) this._disposeGroup(f.group);
+ this._fx = [];
+ this._floats.forEach((fl) => fl.node.remove());
+ this._floats = [];
+ if (this._zoneGroup) this._disposeGroup(this._zoneGroup);
+ this._zoneGroup = null;
+ this.root?.remove();
+ }
+}
diff --git a/src/game/play-systems.js b/src/game/play-systems.js
index 73f88ff7e..546de3f48 100644
--- a/src/game/play-systems.js
+++ b/src/game/play-systems.js
@@ -17,7 +17,7 @@
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';
@@ -26,6 +26,7 @@ import { FISHING_SPOTS, nearestFishingSpot } from '../../multiplayer/src/world-f
import { itemDisplay } from './items.js';
import './play-systems.css';
+
const SKILL_META = {
fishing: { label: 'Fishing', glyph: '🎣' },
cooking: { label: 'Cooking', glyph: '🍳' },
@@ -217,6 +218,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/quest-systems.js.tmp.4027623.503fe5f6b249 b/src/game/quest-systems.js.tmp.4027623.503fe5f6b249
new file mode 100644
index 000000000..35814bb47
--- /dev/null
+++ b/src/game/quest-systems.js.tmp.4027623.503fe5f6b249
@@ -0,0 +1,440 @@
+// Quest systems — the jobs/missions/heists layer grafted onto the /play coin worlds
+// (W05). The companion to play-systems.js (economy/fishing): this owns the jobs
+// board, the active-objective HUD tracker, the in-world quest objects + waypoint
+// beacons, and the contextual interact prompt.
+//
+// Authority is the server (WalkRoom + multiplayer/src/quests.js): this client browses
+// the board, renders objective progress streamed back over CommunityNet's `quests` /
+// `questComplete` events, draws waypoints to the current objective, and sends
+// accept/abandon/interact intents. It never decides a mission is complete — it shows
+// what the server says. Nothing here is simulated locally.
+//
+// It owns its own DOM (a HUD appended to <body>, styled to the /play monochrome
+// tokens) and its own scene objects (the dock crate, market stall, vault terminals,
+// the vault, survey beacons + waypoint shafts), and tears both down on leave() so
+// switching coins never leaks meshes or panels.
+
+import {
+ Group, Mesh,
+ BoxGeometry, CylinderGeometry, ConeGeometry, RingGeometry,
+ MeshStandardMaterial, MeshBasicMaterial, DoubleSide,
+} from 'three';
+
+import { QUEST_ZONES, zoneAt } from '../../multiplayer/src/quest-zones.js';
+import './quest-systems.css';
+
+// Verb + glyph per interact action, used on the contextual prompt and the object
+// labels. Mirrors the server's action vocabulary (quest-zones.js).
+const ACTION_UI = {
+ pickup: { verb: 'Pick up the crate', glyph: '📦' },
+ dropoff: { verb: 'Deliver the crate', glyph: '🏷️' },
+ terminal: { verb: 'Disable the alarm', glyph: '🖥️' },
+ crack: { verb: 'Crack the vault', glyph: '🏦' },
+};
+
+// Reward icon by mission kind, for the board + completion banner.
+const KIND_GLYPH = { job: '📋', heist: '💰' };
+
+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 (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);
+ else if (v != null) n.setAttribute(k, v);
+ }
+ for (const c of [].concat(kids)) if (c) n.appendChild(c);
+ return n;
+}
+
+export class QuestSystems {
+ /**
+ * @param {object} opts
+ * @param {import('three').Scene} opts.scene
+ * @param {() => ({x,y,z,yaw,height})} opts.getPlayer local avatar pose
+ * @param {object} opts.net CommunityNet (questAccept/Abandon/Interact intents)
+ * @param {object} opts.ui CommunityUI (toast)
+ */
+ constructor({ scene, getPlayer, net, ui }) {
+ this.scene = scene;
+ this.getPlayer = getPlayer;
+ this.net = net;
+ this.ui = ui;
+
+ this.snap = { offers: [], active: [], day: '' };
+ this._targetZones = new Set(); // zone ids that are a current objective target
+ this._nearZone = null; // interact zone the player is standing in
+ this._boardOpen = false;
+ this._t = 0;
+ this._zoneObjs = new Map(); // zoneId -> { group, beacon, ring } scene handles
+
+ this._buildScene();
+ this._buildHud();
+
+ // Ask the server for the board immediately (also re-sent on join server-side).
+ this.net?.requestQuests?.();
+ }
+
+ // ---------------------------------------------------------------- scene
+ _buildScene() {
+ const group = new Group();
+ group.name = 'quest-zones';
+ for (const zone of QUEST_ZONES) {
+ const obj = this._buildZoneObject(zone);
+ group.add(obj.group);
+ this._zoneObjs.set(zone.id, obj);
+ }
+ this.scene.add(group);
+ this._zoneGroup = group;
+ }
+
+ // A quest zone's in-world presence: a footprint ring, a kind-specific prop, and a
+ // vertical waypoint beacon that brightens when this zone is the active target.
+ _buildZoneObject(zone) {
+ const g = new Group();
+ g.position.set(zone.x, 0, zone.z);
+
+ // Footprint ring on the ground (reads as an interactable from a distance).
+ const ring = new Mesh(
+ new RingGeometry(Math.max(0.1, zone.r - 0.12), zone.r, 40),
+ new MeshBasicMaterial({ color: 0xbfeaff, transparent: true, opacity: 0.32, side: DoubleSide }),
+ );
+ ring.rotation.x = -Math.PI / 2;
+ ring.position.y = 0.05;
+ g.add(ring);
+
+ // Kind-specific prop.
+ const prop = this._buildProp(zone);
+ if (prop) g.add(prop);
+
+ // Waypoint beacon — a tall, soft light shaft. Dim by default; the tick()
+ // brightens + pulses it when the zone is the current objective target.
+ const beacon = new Mesh(
+ new CylinderGeometry(0.14, 0.14, 7, 8, 1, true),
+ new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.0, side: DoubleSide }),
+ );
+ beacon.position.y = 3.5;
+ g.add(beacon);
+
+ return { group: g, beacon, ring };
+ }
+
+ _buildProp(zone) {
+ const accent = new MeshStandardMaterial({ color: 0x2b3340, roughness: 0.7, metalness: 0.2, emissive: 0x0a1622, emissiveIntensity: 0.4 });
+ if (zone.action === 'pickup') {
+ const crate = new Mesh(new BoxGeometry(1.1, 1.0, 1.1), new MeshStandardMaterial({ color: 0x6b5836, roughness: 0.85 }));
+ crate.position.y = 0.5;
+ crate.castShadow = true;
+ return crate;
+ }
+ if (zone.action === 'dropoff') {
+ const grp = new Group();
+ const table = new Mesh(new BoxGeometry(1.6, 0.2, 1.0), new MeshStandardMaterial({ color: 0x4a4030, roughness: 0.9 }));
+ table.position.y = 0.7; table.castShadow = true; grp.add(table);
+ const post = new Mesh(new CylinderGeometry(0.07, 0.07, 1.6, 6), accent);
+ post.position.set(0.7, 0.8, 0); grp.add(post);
+ return grp;
+ }
+ if (zone.action === 'terminal') {
+ const grp = new Group();
+ const cab = new Mesh(new BoxGeometry(0.7, 1.2, 0.45), accent);
+ cab.position.y = 0.6; cab.castShadow = true; grp.add(cab);
+ const screen = new Mesh(new BoxGeometry(0.52, 0.4, 0.04), new MeshStandardMaterial({ color: 0x0a1a14, emissive: 0x3fd28a, emissiveIntensity: 0.9, roughness: 0.3 }));
+ screen.position.set(0, 0.95, 0.24); grp.add(screen);
+ return grp;
+ }
+ if (zone.action === 'crack') {
+ const grp = new Group();
+ const body = new Mesh(new BoxGeometry(2.4, 2.4, 1.4), new MeshStandardMaterial({ color: 0x3a414c, roughness: 0.5, metalness: 0.5 }));
+ body.position.y = 1.2; body.castShadow = true; grp.add(body);
+ const door = new Mesh(new CylinderGeometry(0.85, 0.85, 0.2, 24), new MeshStandardMaterial({ color: 0x9aa3af, roughness: 0.35, metalness: 0.7 }));
+ door.rotation.x = Math.PI / 2;
+ door.position.set(0, 1.2, 0.72); grp.add(door);
+ return grp;
+ }
+ // goto lookouts: a simple guidepost cone so the spot reads as a destination.
+ const post = new Mesh(new ConeGeometry(0.5, 1.4, 6), accent);
+ post.position.y = 0.7; post.castShadow = true;
+ return post;
+ }
+
+ // ---------------------------------------------------------------- HUD DOM
+ _buildHud() {
+ this.boardBadge = el('span', { class: 'qs-jobs-badge', hidden: true });
+ this.boardBtn = el('button', { class: 'qs-jobs-btn', title: 'Jobs board (J)', 'aria-label': 'Open jobs board', onclick: () => this.toggleBoard() }, [
+ el('span', { class: 'qs-jobs-glyph', text: '📋' }),
+ el('span', { text: 'Jobs' }),
+ this.boardBadge,
+ ]);
+
+ this.trackerList = el('div', { class: 'qs-track-list' });
+ this.tracker = el('div', { class: 'qs-tracker', hidden: true, role: 'status', 'aria-live': 'polite' }, [this.trackerList]);
+
+ this.promptBtn = el('button', { class: 'qs-prompt', hidden: true, onclick: () => this.interact() });
+
+ this.boardBody = el('div', { class: 'qs-board-body' });
+ this.boardPanel = el('div', { class: 'qs-panel qs-board', hidden: true, role: 'dialog', 'aria-label': 'Jobs board' }, [
+ el('div', { class: 'qs-panel-head' }, [
+ el('span', { class: 'qs-panel-title', text: 'Jobs & Heists' }),
+ el('button', { class: 'qs-x', 'aria-label': 'Close', text: '✕', onclick: () => this.toggleBoard(false) }),
+ ]),
+ this.boardBody,
+ ]);
+
+ this.root = el('div', { id: 'qs-hud' }, [this.boardBtn, this.tracker, this.promptBtn, this.boardPanel]);
+ document.body.appendChild(this.root);
+ }
+
+ // ---------------------------------------------------------------- data in
+ setQuests(snap) {
+ if (!snap || typeof snap !== 'object') return;
+ this.snap = {
+ offers: Array.isArray(snap.offers) ? snap.offers : [],
+ active: Array.isArray(snap.active) ? snap.active : [],
+ day: snap.day || '',
+ };
+ this._recomputeTargets();
+ this._renderTracker();
+ this._renderBadge();
+ if (this._boardOpen) this._renderBoard();
+ }
+
+ // A mission/heist finished — celebrate. The purse/XP already updated via the
+ // economy events; this is the moment of delight.
+ onComplete(c) {
+ if (!c) return;
+ const glyph = c.coop ? '💰' : KIND_GLYPH[c.kind] || '✓';
+ const gold = c.reward?.gold ? `+${Number(c.reward.gold).toLocaleString()} gold` : 'Reward claimed';
+ this._celebrate(`${glyph} ${c.title || 'Mission complete'}`, gold);
+ }
+
+ // Which zone ids are a CURRENT objective target across all active runs (drives
+ // waypoint beacons + whether the interact prompt should show at a given zone).
+ _recomputeTargets() {
+ const set = new Set();
+ for (const run of this.snap.active) {
+ const obj = (run.objectives || []).find((o) => o.current);
+ if (!obj) continue;
+ if (Array.isArray(obj.zones)) obj.zones.forEach((z) => set.add(z));
+ else if (obj.zone) set.add(obj.zone);
+ }
+ this._targetZones = set;
+ }
+
+ // ---------------------------------------------------------------- render
+ _renderBadge() {
+ const n = this.snap.offers.length;
+ this.boardBadge.textContent = String(n);
+ this.boardBadge.hidden = n === 0;
+ }
+
+ _renderTracker() {
+ this.trackerList.replaceChildren();
+ const active = this.snap.active;
+ if (!active.length) { this.tracker.hidden = true; return; }
+ this.tracker.hidden = false;
+ const p = this.getPlayer();
+ for (const run of active) {
+ const obj = (run.objectives || []).find((o) => o.current) || run.objectives?.[run.objectives.length - 1];
+ const card = el('div', { class: 'qs-track' + (run.coop ? ' is-coop' : '') });
+ const head = el('div', { class: 'qs-track-head' }, [
+ el('span', { class: 'qs-track-title', text: run.title }),
+ run.coop ? el('span', { class: 'qs-track-crew', text: `Crew ${run.crew || 1}/${run.party || 2}` }) : null,
+ ]);
+ card.appendChild(head);
+
+ const list = el('div', { class: 'qs-track-objs' });
+ (run.objectives || []).forEach((o) => {
+ const cls = o.done ? 'is-done' : o.current ? 'is-current' : 'is-pending';
+ const tick = o.done ? '✓' : o.current ? '▸' : '○';
+ const count = o.count > 1 ? ` (${o.progress}/${o.count})` : '';
+ list.appendChild(el('div', { class: `qs-obj ${cls}` }, [
+ el('span', { class: 'qs-obj-tick', text: tick }),
+ el('span', { class: 'qs-obj-label', text: o.label + count }),
+ ]));
+ });
+ card.appendChild(list);
+
+ if (obj && (obj.zone || (obj.zones && obj.zones.length))) {
+ const target = this._nearestTargetZone(obj, p);
+ if (target) {
+ const d = Math.round(Math.hypot(p.x - target.x, p.z - target.z));
+ card.appendChild(el('div', { class: 'qs-track-way', text: `${target.label} · ${d}m` }));
+ }
+ }
+ this.trackerList.appendChild(card);
+ }
+ }
+
+ _nearestTargetZone(obj, p) {
+ const ids = Array.isArray(obj.zones) ? obj.zones : (obj.zone ? [obj.zone] : []);
+ let best = null, bestD = Infinity;
+ for (const id of ids) {
+ const z = QUEST_ZONES.find((q) => q.id === id);
+ if (!z) continue;
+ const d = Math.hypot(p.x - z.x, p.z - z.z);
+ if (d < bestD) { best = z; bestD = d; }
+ }
+ return best;
+ }
+
+ _renderBoard() {
+ this.boardBody.replaceChildren();
+ const activeIds = new Set(this.snap.active.map((r) => r.id));
+
+ if (this.snap.active.length) {
+ this.boardBody.appendChild(el('div', { class: 'qs-board-section', text: 'In progress' }));
+ for (const run of this.snap.active) this.boardBody.appendChild(this._activeCard(run));
+ }
+
+ const offers = this.snap.offers.filter((o) => !activeIds.has(o.id));
+ const daily = offers.filter((o) => o.repeat === 'daily');
+ const heists = offers.filter((o) => o.kind === 'heist');
+ const jobs = offers.filter((o) => o.kind !== 'heist' && o.repeat !== 'daily');
+
+ if (daily.length) {
+ this.boardBody.appendChild(el('div', { class: 'qs-board-section', text: "Today's jobs · resets daily" }));
+ for (const o of daily) this.boardBody.appendChild(this._offerCard(o));
+ }
+ if (jobs.length) {
+ this.boardBody.appendChild(el('div', { class: 'qs-board-section', text: 'Jobs' }));
+ for (const o of jobs) this.boardBody.appendChild(this._offerCard(o));
+ }
+ if (heists.length) {
+ this.boardBody.appendChild(el('div', { class: 'qs-board-section', text: 'Heists · co-op' }));
+ for (const o of heists) this.boardBody.appendChild(this._offerCard(o));
+ }
+
+ if (!this.snap.active.length && !offers.length) {
+ this.boardBody.appendChild(el('div', { class: 'qs-board-empty', text: 'No jobs available right now. Daily jobs refresh at midnight UTC — check back then.' }));
+ }
+ }
+
+ _rewardText(reward) {
+ const parts = [];
+ if (reward?.gold) parts.push(`${Number(reward.gold).toLocaleString()} gold`);
+ if (reward?.xp?.amount) parts.push(`${reward.xp.amount} ${reward.xp.skill} XP`);
+ return parts.join(' · ') || 'Reward';
+ }
+
+ _offerCard(o) {
+ const glyph = o.kind === 'heist' ? '💰' : KIND_GLYPH.job;
+ const objs = el('ul', { class: 'qs-card-objs' },
+ (o.objectives || []).map((ob) => el('li', { text: ob.label + (ob.count > 1 ? ` ×${ob.count}` : '') })),
+ );
+ const accept = el('button', {
+ class: 'qs-accept', text: o.kind === 'heist' ? 'Join crew' : 'Accept',
+ onclick: () => { this.net?.questAccept?.(o.id); },
+ });
+ return el('div', { class: 'qs-card' + (o.kind === 'heist' ? ' is-heist' : '') }, [
+ el('div', { class: 'qs-card-top' }, [
+ el('span', { class: 'qs-card-glyph', text: glyph }),
+ el('div', { class: 'qs-card-meta' }, [
+ el('span', { class: 'qs-card-title', text: o.title }),
+ el('span', { class: 'qs-card-giver', text: `${o.giver}${o.repeat === 'daily' ? ' · daily' : o.repeat === 'once' ? ' · one-time' : ''}` }),
+ ]),
+ o.kind === 'heist' ? el('span', { class: 'qs-card-party', text: `${o.party}-crew` }) : null,
+ ]),
+ el('div', { class: 'qs-card-summary', text: o.summary }),
+ objs,
+ el('div', { class: 'qs-card-foot' }, [
+ el('span', { class: 'qs-card-reward', text: '🪙 ' + this._rewardText(o.reward) }),
+ accept,
+ ]),
+ ]);
+ }
+
+ _activeCard(run) {
+ const cur = (run.objectives || []).find((o) => o.current);
+ return el('div', { class: 'qs-card is-active' }, [
+ el('div', { class: 'qs-card-top' }, [
+ el('span', { class: 'qs-card-glyph', text: run.coop ? '💰' : KIND_GLYPH.job }),
+ el('div', { class: 'qs-card-meta' }, [
+ el('span', { class: 'qs-card-title', text: run.title }),
+ el('span', { class: 'qs-card-giver', text: cur ? cur.label : 'In progress' }),
+ ]),
+ run.coop ? el('span', { class: 'qs-card-party', text: `Crew ${run.crew || 1}/${run.party || 2}` }) : null,
+ ]),
+ el('div', { class: 'qs-card-foot' }, [
+ el('span', { class: 'qs-card-reward', text: '🪙 ' + this._rewardText(run.reward) }),
+ el('button', { class: 'qs-abandon', text: run.coop ? 'Leave crew' : 'Abandon', onclick: () => this.net?.questAbandon?.(run.id) }),
+ ]),
+ ]);
+ }
+
+ // ---------------------------------------------------------------- actions
+ toggleBoard(force) {
+ this._boardOpen = force == null ? !this._boardOpen : !!force;
+ this.boardPanel.hidden = !this._boardOpen;
+ this.boardBtn.classList.toggle('is-on', this._boardOpen);
+ if (this._boardOpen) { this.net?.requestQuests?.(); this._renderBoard(); }
+ }
+
+ // Act at the quest object the player is standing in. Server resolves the zone +
+ // action from its authoritative position, so we just fire the intent.
+ interact() {
+ if (!this._nearZone) return;
+ this.net?.questInteract?.();
+ }
+
+ // ---------------------------------------------------------------- per-frame
+ tick(dt) {
+ this._t += dt;
+ const p = this.getPlayer();
+
+ const z = zoneAt(p.x, p.z);
+ this._nearZone = z && z.kind === 'interact' ? z : null;
+ this._updatePrompt();
+
+ for (const [id, obj] of this._zoneObjs) {
+ const isTarget = this._targetZones.has(id);
+ const pulse = 0.35 + Math.sin(this._t * 2.4) * 0.18;
+ obj.beacon.material.opacity = isTarget ? pulse : 0.0;
+ obj.ring.material.opacity = isTarget ? 0.5 : 0.18;
+ }
+
+ // Cheap periodic tracker refresh so the distance chip stays live.
+ if (this.snap.active.length && (this._t - (this._lastTrackAt || 0)) > 0.5) {
+ this._lastTrackAt = this._t;
+ this._renderTracker();
+ }
+ }
+
+ _updatePrompt() {
+ const z = this._nearZone;
+ if (!z || !this._targetZones.has(z.id)) {
+ if (!this.promptBtn.hidden) this.promptBtn.hidden = true;
+ return;
+ }
+ const ui = ACTION_UI[z.action] || { verb: 'Interact', glyph: '✋' };
+ this.promptBtn.textContent = `${ui.glyph} ${ui.verb}`;
+ this.promptBtn.hidden = false;
+ }
+
+ // ---------------------------------------------------------------- fx
+ _celebrate(title, sub) {
+ const card = el('div', { class: 'qs-complete' }, [
+ el('div', { class: 'qs-complete-mark', text: 'MISSION COMPLETE' }),
+ el('div', { class: 'qs-complete-title', text: title }),
+ el('div', { class: 'qs-complete-sub', text: sub }),
+ ]);
+ document.body.appendChild(card);
+ requestAnimationFrame(() => card.classList.add('is-show'));
+ setTimeout(() => { card.classList.remove('is-show'); setTimeout(() => card.remove(), 400); }, 2600);
+ }
+
+ // ---------------------------------------------------------------- teardown
+ dispose() {
+ if (this._zoneGroup) {
+ this.scene.remove(this._zoneGroup);
+ this._zoneGroup.traverse((n) => {
+ if (n.isMesh) { n.geometry?.dispose?.(); const ms = Array.isArray(n.material) ? n.material : [n.material]; ms.forEach((m) => m?.dispose?.()); }
+ });
+ this._zoneGroup = null;
+ }
+ this._zoneObjs.clear();
+ this.root?.remove();
+ document.querySelectorAll('.qs-complete').forEach((n) => n.remove());
+ }
+}
diff --git a/src/game/vehicle-mesh.js b/src/game/vehicle-mesh.js
new file mode 100644
index 000000000..c2bee42fa
--- /dev/null
+++ b/src/game/vehicle-mesh.js
@@ -0,0 +1,221 @@
+// Procedural vehicle meshes — original, honest geometry (no third-party model
+// assets), built from primitives so they load instantly and theme to each
+// vehicle's colour. One builder per silhouette (coupe / sedan / pickup / buggy)
+// keeps the four types visually distinct, matching their distinct handling.
+//
+// The returned group's origin is the chassis CENTRE, aligned with the Rapier
+// rigid body's origin, with +z forward and +y up — so the physics transform maps
+// straight onto group.position / group.quaternion. Wheels are returned separately:
+// each is a steer pivot (set rotation.y to steer, position to follow suspension)
+// holding a spinner mesh (set rotation.x to roll). The manager drives both from
+// the vehicle controller each frame.
+
+import {
+ Group, Mesh, BoxGeometry, CylinderGeometry, SphereGeometry,
+ MeshStandardMaterial, MeshBasicMaterial, Color,
+} from 'three';
+
+function lighten(hex, amt) {
+ const c = new Color(hex);
+ c.lerp(new Color(0xffffff), amt);
+ return c.getHex();
+}
+function darken(hex, amt) {
+ const c = new Color(hex);
+ c.lerp(new Color(0x000000), amt);
+ return c.getHex();
+}
+
+// A reusable wheel: a black tyre cylinder (axle along x) plus a metallic hub, so
+// the spin reads. Built once per wheel; the geometry is pre-oriented so the
+// spinner only ever rotates about x to roll.
+function buildWheel(radius, halfWidth) {
+ const pivot = new Group(); // steering + suspension follow
+ const spinner = new Group(); // rolling
+ pivot.add(spinner);
+
+ const tyreGeo = new CylinderGeometry(radius, radius, halfWidth * 2, 22);
+ tyreGeo.rotateZ(Math.PI / 2); // axis Y → axis X (the axle)
+ const tyre = new Mesh(tyreGeo, new MeshStandardMaterial({ color: 0x141417, roughness: 0.85, metalness: 0.1 }));
+ tyre.castShadow = true;
+ spinner.add(tyre);
+
+ const hubGeo = new CylinderGeometry(radius * 0.42, radius * 0.42, halfWidth * 2.05, 12);
+ hubGeo.rotateZ(Math.PI / 2);
+ const hub = new Mesh(hubGeo, new MeshStandardMaterial({ color: 0xb8bcc4, roughness: 0.35, metalness: 0.8 }));
+ spinner.add(hub);
+ // A spoke bar so the roll is legible at speed.
+ const spokeGeo = new BoxGeometry(halfWidth * 2.1, radius * 1.5, radius * 0.16);
+ const spoke = new Mesh(spokeGeo, new MeshStandardMaterial({ color: 0x33363d, roughness: 0.5, metalness: 0.6 }));
+ spinner.add(spoke);
+
+ return { pivot, spinner };
+}
+
+function bodyMat(color) {
+ return new MeshStandardMaterial({ color, roughness: 0.42, metalness: 0.55 });
+}
+function glassMat() {
+ return new MeshStandardMaterial({ color: 0x0a0d14, roughness: 0.15, metalness: 0.4, emissive: 0x05070b, emissiveIntensity: 0.4 });
+}
+
+// Two red tail-light strips at the rear; the manager brightens them on braking.
+function buildTailLights(width, z, y) {
+ const lights = [];
+ const geo = new BoxGeometry(0.32, 0.16, 0.06);
+ for (const sx of [-1, 1]) {
+ const mat = new MeshBasicMaterial({ color: 0x6e1411 });
+ const m = new Mesh(geo, mat);
+ m.position.set(sx * (width / 2 - 0.3), y, z);
+ lights.push(m);
+ }
+ return lights;
+}
+// Headlights — static emissive pucks so the car reads as facing forward.
+function buildHeadLights(width, z, y) {
+ const geo = new SphereGeometry(0.13, 12, 10);
+ const mat = new MeshBasicMaterial({ color: 0xf4f1d8 });
+ const out = [];
+ for (const sx of [-1, 1]) {
+ const m = new Mesh(geo, mat);
+ m.position.set(sx * (width / 2 - 0.32), y, z);
+ out.push(m);
+ }
+ return out;
+}
+
+function buildCoupe(spec, color) {
+ const body = new Group();
+ const { l, w } = spec.dims;
+ const main = bodyMat(color);
+ const lower = new Mesh(new BoxGeometry(w, 0.55, l), main);
+ lower.position.y = 0.05; lower.castShadow = true; lower.receiveShadow = true;
+ body.add(lower);
+ // Sleek raked cabin, set back.
+ const cabin = new Mesh(new BoxGeometry(w * 0.82, 0.46, l * 0.42), bodyMat(lighten(color, 0.05)));
+ cabin.position.set(0, 0.5, -0.15); cabin.castShadow = true;
+ body.add(cabin);
+ const glass = new Mesh(new BoxGeometry(w * 0.78, 0.34, l * 0.4), glassMat());
+ glass.position.set(0, 0.52, -0.12);
+ body.add(glass);
+ // A low front splitter for a sporty nose.
+ const splitter = new Mesh(new BoxGeometry(w * 0.96, 0.12, 0.5), bodyMat(darken(color, 0.5)));
+ splitter.position.set(0, -0.18, l / 2 - 0.2);
+ body.add(splitter);
+ return body;
+}
+
+function buildSedan(spec, color) {
+ const body = new Group();
+ const { l, w } = spec.dims;
+ const lower = new Mesh(new BoxGeometry(w, 0.62, l), bodyMat(color));
+ lower.position.y = 0.08; lower.castShadow = true; lower.receiveShadow = true;
+ body.add(lower);
+ const cabin = new Mesh(new BoxGeometry(w * 0.9, 0.6, l * 0.5), bodyMat(lighten(color, 0.04)));
+ cabin.position.set(0, 0.62, -0.05); cabin.castShadow = true;
+ body.add(cabin);
+ const glass = new Mesh(new BoxGeometry(w * 0.86, 0.46, l * 0.48), glassMat());
+ glass.position.set(0, 0.64, -0.03);
+ body.add(glass);
+ return body;
+}
+
+function buildPickup(spec, color) {
+ const body = new Group();
+ const { l, w } = spec.dims;
+ const chassis = new Mesh(new BoxGeometry(w, 0.66, l), bodyMat(color));
+ chassis.position.y = 0.1; chassis.castShadow = true; chassis.receiveShadow = true;
+ body.add(chassis);
+ // Forward cab.
+ const cab = new Mesh(new BoxGeometry(w * 0.94, 0.82, l * 0.4), bodyMat(lighten(color, 0.03)));
+ cab.position.set(0, 0.78, l * 0.18); cab.castShadow = true;
+ body.add(cab);
+ const glass = new Mesh(new BoxGeometry(w * 0.9, 0.5, l * 0.36), glassMat());
+ glass.position.set(0, 0.86, l * 0.19);
+ body.add(glass);
+ // Open rear bed: floor + three low walls.
+ const bedMat = bodyMat(darken(color, 0.18));
+ const bedW = w * 0.96, bedL = l * 0.4, wall = 0.32;
+ const floor = new Mesh(new BoxGeometry(bedW, 0.16, bedL), bedMat);
+ floor.position.set(0, 0.5, -l * 0.22); body.add(floor);
+ const back = new Mesh(new BoxGeometry(bedW, wall, 0.12), bedMat);
+ back.position.set(0, 0.64, -l * 0.42); body.add(back);
+ for (const sx of [-1, 1]) {
+ const side = new Mesh(new BoxGeometry(0.12, wall, bedL), bedMat);
+ side.position.set(sx * (bedW / 2 - 0.06), 0.64, -l * 0.22); body.add(side);
+ }
+ return body;
+}
+
+function buildBuggy(spec, color) {
+ const body = new Group();
+ const { l, w } = spec.dims;
+ const tub = new Mesh(new BoxGeometry(w * 0.78, 0.5, l * 0.8), bodyMat(color));
+ tub.position.y = 0.08; tub.castShadow = true; tub.receiveShadow = true;
+ body.add(tub);
+ // Exposed roll cage from thin bars.
+ const cageMat = new MeshStandardMaterial({ color: darken(color, 0.45), roughness: 0.4, metalness: 0.7 });
+ const bar = (sx, z) => {
+ const m = new Mesh(new BoxGeometry(0.1, 0.78, 0.1), cageMat);
+ m.position.set(sx * w * 0.32, 0.5, z); body.add(m);
+ };
+ bar(-1, 0.2); bar(1, 0.2); bar(-1, -0.5); bar(1, -0.5);
+ const roof = new Mesh(new BoxGeometry(w * 0.7, 0.1, 0.84), cageMat);
+ roof.position.set(0, 0.88, -0.15); body.add(roof);
+ const seatback = new Mesh(new BoxGeometry(w * 0.6, 0.42, 0.12), glassMat());
+ seatback.position.set(0, 0.42, -0.42); body.add(seatback);
+ return body;
+}
+
+const BUILDERS = { coupe: buildCoupe, sedan: buildSedan, pickup: buildPickup, buggy: buildBuggy };
+
+/**
+ * Build a complete vehicle mesh for a spec + colour.
+ * @returns {{ group, wheels:Array<{pivot,spinner}>, brakeLights:Mesh[], dispose:Function }}
+ */
+export function buildVehicleMesh(spec, color) {
+ const group = new Group();
+ const tint = Number.isFinite(color) ? color : spec.color;
+
+ const builder = BUILDERS[spec.id] || buildSedan;
+ const body = builder(spec, tint);
+ group.add(body);
+
+ // Lights, placed off the body's front/rear faces.
+ const { l, w } = spec.dims;
+ const tail = buildTailLights(w, -l / 2 + 0.05, 0.18);
+ const head = buildHeadLights(w, l / 2 - 0.05, 0.12);
+ for (const m of tail) group.add(m);
+ for (const m of head) group.add(m);
+
+ // Four wheels at the chassis corners (matching the physics connection points).
+ const wb = w / 2 - spec.wheel.inset;
+ const cy = -spec.dims.h * 0.2; // resting connection height in chassis space
+ const positions = [
+ { x: wb, z: spec.wheel.frontZ },
+ { x: -wb, z: spec.wheel.frontZ },
+ { x: wb, z: spec.wheel.rearZ },
+ { x: -wb, z: spec.wheel.rearZ },
+ ];
+ const wheels = positions.map((p) => {
+ const wheel = buildWheel(spec.wheel.radius, spec.wheel.halfWidth);
+ wheel.pivot.position.set(p.x, cy - spec.suspension.rest, p.z);
+ group.add(wheel.pivot);
+ return wheel;
+ });
+
+ return {
+ group,
+ wheels,
+ brakeLights: tail,
+ dispose() {
+ group.traverse((o) => {
+ if (o.geometry) o.geometry.dispose?.();
+ if (o.material) {
+ if (Array.isArray(o.material)) o.material.forEach((m) => m.dispose?.());
+ else o.material.dispose?.();
+ }
+ });
+ },
+ };
+}
diff --git a/src/game/vehicles.js b/src/game/vehicles.js
new file mode 100644
index 000000000..401c1bf5c
--- /dev/null
+++ b/src/game/vehicles.js
@@ -0,0 +1,591 @@
+// VehicleManager — drivable, networked vehicles for /play.
+//
+// Networking follows the same authoritative-relay pattern the movement netcode
+// already uses (and the model Notblox uses for its Rapier cars): the DRIVER
+// simulates the vehicle locally with Rapier's built-in raycast vehicle controller
+// and streams the resulting transform; the server validates per-type speed/bounds
+// and relays it, staying the gate on who may drive what. Everyone else is a pure
+// spectator of the replicated transform, interpolated smoothly.
+//
+// Only the vehicle the local player is driving is ever simulated here — a single
+// Rapier world holds the ground, the central totem, and (as kinematic ghosts) the
+// other players' cars so the local car can bump them. Parked and remote-driven
+// vehicles are interpolated meshes, cheap and ghost-light.
+//
+// This subsystem is intentionally tightly coupled to the scene (camera handoff,
+// avatar seating, shared input), so it takes the CoinCommunities `host` and reads
+// its live fields (localPos, localYaw, localRig, keys, camera) — exactly the
+// coupling PlaySystems and AgentCommerce already have.
+
+import { Vector3, Quaternion, Raycaster, Vector2 } from 'three';
+import { PhysicsWorld } from '../physics/physics-world.js';
+import { buildVehicleMesh } from './vehicle-mesh.js';
+import { CLIP_IDLE } from './avatar-rig.js';
+import {
+ vehicleSpec, vehicleRestHeight,
+ VEHICLE_ENTER_RANGE_M, VEHICLE_WORLD_BOUND_M,
+} from '../../multiplayer/src/vehicles.js';
+import { log } from '../shared/log.js';
+
+const REMOTE_LERP = 0.2; // per-frame position/rotation interpolation
+const ENTER_TIMEOUT_MS = 2600; // give up waiting for an enter grant
+const KNOCK_SPEED = 4.5; // m/s a car must exceed to shove a pedestrian
+const FLIP_RESET_MS = 2200; // auto-right a car left upside-down this long
+
+const _q = new Quaternion();
+const _v = new Vector3();
+const _v2 = new Vector3();
+
+function yawFromQuat(qx, qy, qz, qw) {
+ return Math.atan2(2 * (qw * qy + qx * qz), 1 - 2 * (qy * qy + qx * qx));
+}
+function shortestAngle(a, b) {
+ let d = b - a;
+ while (d > Math.PI) d -= Math.PI * 2;
+ while (d < -Math.PI) d += Math.PI * 2;
+ return d;
+}
+
+export class VehicleManager {
+ constructor({ host }) {
+ this.host = host;
+ this.scene = host.scene;
+ this.camera = host.camera;
+ this.renderer = host.renderer;
+ this.net = host.net;
+ this.ui = host.ui;
+
+ this.vehicles = new Map(); // id → { id, state, spec, mesh, collider, wheelRoll }
+ this._drivingId = null;
+ this._pendingEnter = null;
+ this._pendingTimer = null;
+ this.vehicle = null; // the Rapier vehicle façade while driving
+ this._touch = { throttle: 0, brake: 0, steer: 0, handbrake: false };
+ this._kbHandbrake = false;
+ this._flipSince = 0;
+ this._prevCamDist = host.camDist;
+
+ // One physics world for the local driver: flat ground + the central totem as
+ // an obstacle. Created up-front so Rapier's WASM is warm by the time the
+ // player reaches a car. Failure (no WebGL/WASM) leaves driving disabled, not
+ // the whole scene broken.
+ this.phys = null;
+ this._physReady = PhysicsWorld.create({ gravity: { x: 0, y: -18, z: 0 } })
+ .then((p) => {
+ p.addGround(0, 400);
+ // The coin totem sits at (0,0,-12); make it solid so cars can't drive
+ // through the landmark.
+ p.addStaticCylinder({ position: { x: 0, y: 3, z: -12 }, radius: 1.6, halfHeight: 3.2 });
+ this.phys = p;
+ })
+ .catch((err) => { log.warn('[vehicles] physics init failed:', err?.message); });
+
+ this._injectStyles();
+ this._buildPrompt();
+ this._buildControls();
+
+ this._raycaster = new Raycaster();
+ this._ndc = new Vector2();
+ }
+
+ // ---------------------------------------------------------------- net state
+
+ addVehicle(state, id) {
+ if (this.vehicles.has(id)) { this.changeVehicle(state, id); return; }
+ const spec = vehicleSpec(state.type);
+ const mesh = buildVehicleMesh(spec, state.color >>> 0);
+ mesh.group.position.set(state.x, state.y, state.z);
+ mesh.group.quaternion.set(state.qx, state.qy, state.qz, state.qw);
+ this.scene.add(mesh.group);
+ this.vehicles.set(id, { id, state, spec, mesh, collider: null, wheelRoll: 0 });
+ }
+
+ changeVehicle(state, id) {
+ const entry = this.vehicles.get(id);
+ if (!entry) { this.addVehicle(state, id); return; }
+ entry.state = state; // live schema proxy — read latest each frame
+ // The server kicked us out of the seat (disconnect sweep, eviction): bail out
+ // of the driving state cleanly so we don't keep streaming a car we don't own.
+ if (entry.id === this._drivingId && state.driver !== this.net?.sessionId) {
+ this._endDriving(this.vehicle ? this.vehicle.transform() : null, /* serverForced */ true);
+ }
+ }
+
+ removeVehicle(id) {
+ const entry = this.vehicles.get(id);
+ if (!entry) return;
+ if (entry.id === this._drivingId) this._endDriving(null, true);
+ entry.collider?.remove();
+ this.scene.remove(entry.mesh.group);
+ entry.mesh.dispose();
+ this.vehicles.delete(id);
+ }
+
+ // Server's targeted reply to our enter/exit request.
+ onAck(msg) {
+ if (!msg || typeof msg !== 'object') return;
+ if (msg.event === 'enter') {
+ if (this._pendingEnter && msg.id === this._pendingEnter) this._beginDriving(msg.id);
+ } else if (msg.event === 'deny') {
+ this._clearPending();
+ const why = msg.reason === 'occupied' ? 'Someone’s already driving that.'
+ : msg.reason === 'range' ? 'Get closer to the vehicle.'
+ : 'That vehicle’s gone.';
+ this.ui?.toast?.(why, 'warn');
+ } else if (msg.event === 'exit') {
+ // We already exited optimistically; reconcile the avatar to the server's
+ // authored drop point so on-foot movement resumes from the agreed spot.
+ if (typeof msg.x === 'number' && typeof msg.z === 'number') {
+ this.host.localPos.x = msg.x;
+ this.host.localPos.z = msg.z;
+ }
+ }
+ }
+
+ // ---------------------------------------------------------------- frame tick
+
+ isDriving() { return !!this._drivingId; }
+
+ tick(dt) {
+ // Interpolate every vehicle we're not actively simulating, and keep their
+ // kinematic ghosts (for the local car to collide with) in step.
+ for (const [, entry] of this.vehicles) {
+ if (entry.id === this._drivingId) continue;
+ this._interpolate(entry, dt);
+ }
+
+ if (this._drivingId) {
+ this._drive(dt);
+ } else {
+ this._updatePrompt();
+ this._pedestrianKnock(dt);
+ }
+ }
+
+ _interpolate(entry, dt) {
+ const s = entry.state;
+ const g = entry.mesh.group;
+ _v.set(s.x, s.y, s.z);
+ g.position.lerp(_v, REMOTE_LERP);
+ _q.set(s.qx, s.qy, s.qz, s.qw);
+ g.quaternion.slerp(_q, REMOTE_LERP);
+
+ // Spin the wheels from the replicated speed so a moving car doesn't glide on
+ // frozen tyres; steer is left centred (we don't replicate wheel angle).
+ entry.wheelRoll += (s.speed / entry.spec.wheel.radius) * dt;
+ for (const w of entry.mesh.wheels) w.spinner.rotation.x = entry.wheelRoll;
+
+ // Maintain a kinematic ghost so the locally-driven car can bump this one.
+ if (this.phys) {
+ if (!entry.collider) {
+ const { l, w, h } = entry.spec.dims;
+ entry.collider = this.phys.addKinematicBox({
+ halfExtents: { x: w / 2, y: h / 2, z: l / 2 },
+ position: { x: g.position.x, y: g.position.y, z: g.position.z },
+ });
+ }
+ entry.collider.setTransform(g.position, { qx: s.qx, qy: s.qy, qz: s.qz, qw: s.qw });
+ }
+ }
+
+ // Push the on-foot local player out of the path of any fast-moving car so a
+ // vehicle can't drive straight through them. Server-safe: the nudge is small
+ // per frame, well under the move-step clamp, so ordinary sendMove relays it.
+ _pedestrianKnock(dt) {
+ const p = this.host.localPos;
+ for (const [, entry] of this.vehicles) {
+ const s = entry.state;
+ if (!s.driver || Math.abs(s.speed) < KNOCK_SPEED) continue;
+ const reach = entry.spec.dims.l / 2 + 0.7;
+ const dx = p.x - s.x, dz = p.z - s.z;
+ const d = Math.hypot(dx, dz);
+ if (d > reach || d < 1e-3) continue;
+ const push = (1 - d / reach) * Math.min(Math.abs(s.speed), 14) * dt;
+ p.x += (dx / d) * push;
+ p.z += (dz / d) * push;
+ this._damageHook?.({ id: entry.id, speed: s.speed, victim: 'self' });
+ }
+ }
+
+ // ---------------------------------------------------------------- driving sim
+
+ _drive(dt) {
+ const entry = this.vehicles.get(this._drivingId);
+ if (!entry || !this.vehicle || !this.phys) return;
+
+ // Gather intent: keyboard (WASD / arrows / space) + on-screen touch controls.
+ const keys = this.host.keys;
+ let throttle = (keys.has('w') || keys.has('arrowup')) ? 1 : 0;
+ let brake = (keys.has('s') || keys.has('arrowdown')) ? 1 : 0;
+ let steer = 0;
+ if (keys.has('a') || keys.has('arrowleft')) steer -= 1;
+ if (keys.has('d') || keys.has('arrowright')) steer += 1;
+ throttle = Math.max(throttle, this._touch.throttle);
+ brake = Math.max(brake, this._touch.brake);
+ steer = Math.max(-1, Math.min(1, steer + this._touch.steer));
+ const handbrake = this._kbHandbrake || this._touch.handbrake;
+ this.vehicle.setInput({ throttle, brake, steer, handbrake });
+
+ // Step the simulation, then read the authoritative-for-us transform.
+ this.phys.step(dt);
+ let t = this.vehicle.transform();
+
+ // World bounds — clamp the car inside the square district (the server clamps
+ // per-axis too). Only correct when actually past an edge, to avoid jitter.
+ if (Math.abs(t.x) > VEHICLE_WORLD_BOUND_M || Math.abs(t.z) > VEHICLE_WORLD_BOUND_M) {
+ const cx = Math.max(-VEHICLE_WORLD_BOUND_M, Math.min(VEHICLE_WORLD_BOUND_M, t.x));
+ const cz = Math.max(-VEHICLE_WORLD_BOUND_M, Math.min(VEHICLE_WORLD_BOUND_M, t.z));
+ this.vehicle.teleport({ x: cx, y: t.y, z: cz }, t);
+ t = this.vehicle.transform();
+ }
+
+ // Auto-right a car that's been flipped on its roof for a while.
+ if (this.vehicle.flipped()) {
+ if (!this._flipSince) this._flipSince = performance.now();
+ else if (performance.now() - this._flipSince > FLIP_RESET_MS) this._rightVehicle(t);
+ } else {
+ this._flipSince = 0;
+ }
+
+ // Drive the mesh + wheels from the simulation.
+ const g = entry.mesh.group;
+ g.position.set(t.x, t.y, t.z);
+ g.quaternion.set(t.qx, t.qy, t.qz, t.qw);
+ this._updateDrivenWheels(entry);
+ // Brake-light glow when slowing or reversing.
+ const braking = brake > 0 || handbrake;
+ for (const bl of entry.mesh.brakeLights) bl.material.color.setHex(braking ? 0xff3b30 : 0x6e1411);
+
+ // Seat the avatar, hand the camera to a chase view, and carry the player's
+ // networked position with the car (so peers see them at the wheel and exiting
+ // is continuous). localPos drives the existing follow camera + nameplates.
+ const yaw = yawFromQuat(t.qx, t.qy, t.qz, t.qw);
+ this.host.localPos.set(t.x, t.y, t.z);
+ this.host.localYaw = yaw;
+ this.host.motion = 'idle';
+ this._seatAvatar(entry, t, yaw);
+ this.host.camYaw += shortestAngle(this.host.camYaw, yaw) * Math.min(1, dt * 6);
+
+ this._updateSpeedo(t.speed);
+
+ // Stream the authoritative transform (throttled to the send rate in the net).
+ this.net?.sendVSync({
+ id: this._drivingId,
+ x: t.x, y: t.y, z: t.z,
+ qx: t.qx, qy: t.qy, qz: t.qz, qw: t.qw,
+ speed: t.speed,
+ });
+ }
+
+ _seatAvatar(entry, t, yaw) {
+ const rig = this.host.localRig;
+ if (!rig) return;
+ const seat = entry.spec.seat;
+ _v2.set(seat.x, seat.y, seat.z).applyQuaternion(_q.set(t.qx, t.qy, t.qz, t.qw));
+ rig.position.set(t.x + _v2.x, t.y + _v2.y - entry.spec.dims.h * 0.2, t.z + _v2.z);
+ rig.rotation.set(0, yaw, 0);
+ if (this.host.localAnim?.currentName !== CLIP_IDLE) this.host.localAnim?.crossfadeTo(CLIP_IDLE, 0.2);
+ }
+
+ _updateDrivenWheels(entry) {
+ const ctrl = this.vehicle.controller;
+ const rest = entry.spec.suspension.rest;
+ for (let i = 0; i < entry.mesh.wheels.length; i++) {
+ const w = entry.mesh.wheels[i];
+ const conn = ctrl.wheelChassisConnectionPointCs(i);
+ const susp = ctrl.wheelSuspensionLength(i);
+ const steerAng = ctrl.wheelSteering(i) || 0;
+ const roll = ctrl.wheelRotation(i) || 0;
+ if (conn) w.pivot.position.set(conn.x, conn.y - (typeof susp === 'number' ? susp : rest), conn.z);
+ w.pivot.rotation.y = steerAng;
+ w.spinner.rotation.x = roll;
+ }
+ }
+
+ _rightVehicle(t) {
+ const yaw = yawFromQuat(t.qx, t.qy, t.qz, t.qw);
+ const half = yaw / 2;
+ this.vehicle.teleport(
+ { x: t.x, y: t.y + 1.0, z: t.z },
+ { qx: 0, qy: Math.sin(half), qz: 0, qw: Math.cos(half) },
+ );
+ this._flipSince = 0;
+ this.ui?.toast?.('Vehicle flipped — set you back upright.', 'info');
+ }
+
+ // ---------------------------------------------------------------- enter/exit
+
+ // Contextual interact: leave the car if driving, otherwise take the nearest one.
+ interact() {
+ if (this._drivingId) { this.requestExit(); return true; }
+ return this._enterNearest();
+ }
+
+ // Touch: tapping a parked vehicle takes the wheel (the touch-native equivalent
+ // of the F prompt). Returns true if a vehicle was tapped + entered.
+ tryActivateAt(raycaster) {
+ if (this._drivingId || this._pendingEnter) return false;
+ const near = this._nearestParked();
+ if (!near) return false;
+ const hit = raycaster.intersectObject(near.entry.mesh.group, true);
+ if (hit.length) { this._requestEnter(near.entry.id); return true; }
+ return false;
+ }
+
+ _enterNearest() {
+ if (this._drivingId || this._pendingEnter) return false;
+ const near = this._nearestParked();
+ if (!near) return false;
+ this._requestEnter(near.entry.id);
+ return true;
+ }
+
+ _nearestParked() {
+ const p = this.host.localPos;
+ let best = null;
+ for (const [, entry] of this.vehicles) {
+ if (entry.state.driver) continue; // occupied
+ const g = entry.mesh.group;
+ const d = Math.hypot(p.x - g.position.x, p.z - g.position.z);
+ if (d <= VEHICLE_ENTER_RANGE_M && (!best || d < best.d)) best = { entry, d };
+ }
+ return best;
+ }
+
+ _requestEnter(id) {
+ this._pendingEnter = id;
+ this.net?.sendVEnter(id);
+ clearTimeout(this._pendingTimer);
+ this._pendingTimer = setTimeout(() => this._clearPending(), ENTER_TIMEOUT_MS);
+ this.prompt.classList.remove('veh-show');
+ }
+
+ _clearPending() {
+ this._pendingEnter = null;
+ clearTimeout(this._pendingTimer);
+ }
+
+ async _beginDriving(id) {
+ this._clearPending();
+ await this._physReady;
+ const entry = this.vehicles.get(id);
+ if (!entry || !this.phys) return;
+ // Another change may have arrived; re-confirm the server seated us.
+ if (entry.state.driver && entry.state.driver !== this.net?.sessionId) return;
+
+ const s = entry.state;
+ const yaw = yawFromQuat(s.qx, s.qy, s.qz, s.qw);
+ this.vehicle = this.phys.createVehicle({
+ position: { x: s.x, y: vehicleRestHeight(s.type) + 0.1, z: s.z },
+ yaw,
+ spec: entry.spec,
+ });
+ this.vehicle.teleport({ x: s.x, y: s.y + 0.1, z: s.z }, { qx: s.qx, qy: s.qy, qz: s.qz, qw: s.qw });
+ // The driven car is the dynamic body now — drop its kinematic ghost so the two
+ // don't fight.
+ entry.collider?.remove();
+ entry.collider = null;
+ this._drivingId = id;
+ this._flipSince = 0;
+
+ this._prevCamDist = this.host.camDist;
+ this.host.camDist = Math.max(this.host.camDist, 11);
+ this._showControls(true);
+ this.ui?.toast?.(`Driving the ${entry.spec.label} — ${this._isTouch() ? 'use the on-screen pedals' : 'WASD to drive, Space to handbrake'}, ${this._isTouch() ? 'tap Exit' : 'F'} to get out.`, 'info');
+ }
+
+ requestExit() {
+ if (!this._drivingId || !this.vehicle) return;
+ const t = this.vehicle.transform();
+ this.net?.sendVExit({
+ id: this._drivingId,
+ x: t.x, y: t.y, z: t.z,
+ qx: t.qx, qy: t.qy, qz: t.qz, qw: t.qw,
+ speed: 0,
+ });
+ this._endDriving(t, false);
+ }
+
+ _endDriving(t, serverForced) {
+ const id = this._drivingId;
+ this._drivingId = null;
+ this._flipSince = 0;
+ if (this.vehicle) { this.phys?.removeVehicle(this.vehicle); this.vehicle = null; }
+ this._showControls(false);
+ this.host.camDist = this._prevCamDist;
+
+ // Drop the avatar beside the driver's door (mirrors the server's drop math) so
+ // our optimistic position matches the authoritative one within the move clamp.
+ if (t) {
+ const yaw = yawFromQuat(t.qx, t.qy, t.qz, t.qw);
+ const entry = id ? this.vehicles.get(id) : null;
+ const off = (entry ? entry.spec.dims.w / 2 : 1) + 0.6;
+ const dx = Math.max(-VEHICLE_WORLD_BOUND_M, Math.min(VEHICLE_WORLD_BOUND_M, t.x + Math.cos(yaw) * off));
+ const dz = Math.max(-VEHICLE_WORLD_BOUND_M, Math.min(VEHICLE_WORLD_BOUND_M, t.z - Math.sin(yaw) * off));
+ this.host.localPos.set(dx, 0, dz);
+ this.host.localYaw = yaw;
+ } else {
+ this.host.localPos.y = 0;
+ }
+ this.host.motion = 'idle';
+ if (this.host.localRig) {
+ this.host.localRig.position.copy(this.host.localPos);
+ this.host.localRig.rotation.set(0, this.host.localYaw, 0);
+ }
+ if (serverForced && t === null) this.ui?.toast?.('You were removed from the vehicle.', 'warn');
+ }
+
+ // ---------------------------------------------------------------- input glue
+
+ // The scene routes Space here while driving (it otherwise jumps).
+ setHandbrake(on) { this._kbHandbrake = !!on; }
+
+ // ---------------------------------------------------------------- prompt + HUD
+
+ _updatePrompt() {
+ const near = this._nearestParked();
+ if (!near || this._pendingEnter) { this.prompt.classList.remove('veh-show'); return; }
+ const g = near.entry.mesh.group;
+ const w = this.renderer.domElement.clientWidth, h = this.renderer.domElement.clientHeight;
+ _v.set(g.position.x, g.position.y + 1.6, g.position.z).project(this.camera);
+ if (_v.z > 1 || _v.z < -1) { this.prompt.classList.remove('veh-show'); return; }
+ this.prompt.querySelector('.veh-label').textContent = `Drive the ${near.entry.spec.label}`;
+ this.prompt.style.transform = `translate(-50%, -100%) translate(${(_v.x * 0.5 + 0.5) * w}px, ${(-_v.y * 0.5 + 0.5) * h}px)`;
+ this.prompt.classList.add('veh-show');
+ }
+
+ _updateSpeedo(speed) {
+ if (!this._speedoVal) return;
+ this._speedoVal.textContent = String(Math.round(Math.abs(speed) * 3.6));
+ }
+
+ _isTouch() {
+ return typeof matchMedia === 'function' && matchMedia('(hover: none), (pointer: coarse)').matches;
+ }
+
+ _buildPrompt() {
+ this.prompt = document.createElement('div');
+ this.prompt.className = 'veh-prompt';
+ this.prompt.innerHTML = '<span class="veh-key">F</span><span class="veh-label">Drive</span>';
+ document.body.appendChild(this.prompt);
+ }
+
+ // Driving HUD: a speedometer plus an exit button always, and an on-screen pedal
+ // + steering cluster on touch devices. Pointer events (not click) so holding a
+ // pedal accelerates and releasing lets off — works for touch and mouse alike.
+ _buildControls() {
+ const wrap = document.createElement('div');
+ wrap.className = 'veh-hud';
+ wrap.innerHTML = `
+ <div class="veh-speedo"><b class="veh-speed-val">0</b><span>km/h</span></div>
+ <button class="veh-exit" type="button" aria-label="Exit vehicle">Exit <span class="veh-key">F</span></button>
+ <div class="veh-pads">
+ <div class="veh-steer">
+ <button class="veh-btn veh-left" type="button" aria-label="Steer left">◀</button>
+ <button class="veh-btn veh-right" type="button" aria-label="Steer right">▶</button>
+ </div>
+ <div class="veh-pedals">
+ <button class="veh-btn veh-brake" type="button" aria-label="Brake / reverse">⊘</button>
+ <button class="veh-btn veh-hand" type="button" aria-label="Handbrake">P</button>
+ <button class="veh-btn veh-gas" type="button" aria-label="Accelerate">▲</button>
+ </div>
+ </div>`;
+ document.body.appendChild(wrap);
+ this._hud = wrap;
+ this._speedoVal = wrap.querySelector('.veh-speed-val');
+
+ wrap.querySelector('.veh-exit').addEventListener('click', () => this.requestExit());
+
+ const hold = (sel, on, off) => {
+ const el = wrap.querySelector(sel);
+ const down = (e) => { e.preventDefault(); on(); };
+ const up = (e) => { e.preventDefault(); off(); };
+ el.addEventListener('pointerdown', down);
+ el.addEventListener('pointerup', up);
+ el.addEventListener('pointercancel', up);
+ el.addEventListener('pointerleave', up);
+ };
+ hold('.veh-gas', () => { this._touch.throttle = 1; }, () => { this._touch.throttle = 0; });
+ hold('.veh-brake', () => { this._touch.brake = 1; }, () => { this._touch.brake = 0; });
+ hold('.veh-left', () => { this._touch.steer = -1; }, () => { this._touch.steer = 0; });
+ hold('.veh-right', () => { this._touch.steer = 1; }, () => { this._touch.steer = 0; });
+ hold('.veh-hand', () => { this._touch.handbrake = true; }, () => { this._touch.handbrake = false; });
+ }
+
+ _showControls(on) {
+ this._hud?.classList.toggle('veh-driving', on);
+ this._hud?.classList.toggle('veh-touch', on && this._isTouch());
+ if (!on) this._touch = { throttle: 0, brake: 0, steer: 0, handbrake: false };
+ }
+
+ _injectStyles() {
+ if (document.getElementById('veh-styles')) return;
+ const s = document.createElement('style');
+ s.id = 'veh-styles';
+ s.textContent = `
+ .veh-prompt {
+ position: fixed; left: 0; top: 0; z-index: 16; pointer-events: none;
+ transform: translate(-50%, -100%); white-space: nowrap; display: none;
+ background: var(--cc-panel-solid, #0c0c0e); border: 1px solid var(--cc-edge, rgba(255,255,255,0.14));
+ color: var(--cc-text, #f5f5f6); font: 700 12px Inter, system-ui, sans-serif; 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;
+ }
+ .veh-prompt.veh-show { display: block; }
+ .veh-key {
+ display: inline-block; min-width: 16px; text-align: center; margin: 0 0 0 6px;
+ background: #fff; color: #060607; border-radius: 3px; padding: 0 4px; font-weight: 800;
+ }
+ .veh-prompt .veh-key { margin: 0 6px 0 0; }
+ .veh-hud { position: fixed; inset: 0; z-index: 22; pointer-events: none; display: none; }
+ .veh-hud.veh-driving { display: block; }
+ .veh-speedo {
+ position: fixed; right: 18px; bottom: 22px; text-align: center; pointer-events: none;
+ background: var(--cc-panel, rgba(12,12,14,0.82)); -webkit-backdrop-filter: blur(12px); backdrop-filter: blur(12px);
+ border: 1px solid var(--cc-edge, rgba(255,255,255,0.12)); border-radius: 12px; padding: 8px 14px;
+ color: var(--cc-text, #f5f5f6); font-family: Inter, system-ui, sans-serif;
+ }
+ .veh-speedo b { display: block; font-size: 30px; font-weight: 800; line-height: 1; font-variant-numeric: tabular-nums; }
+ .veh-speedo span { font-size: 10px; letter-spacing: 0.18em; color: var(--cc-dim, #8c8c92); text-transform: uppercase; }
+ .veh-exit {
+ position: fixed; top: 76px; right: 18px; pointer-events: auto; cursor: pointer;
+ background: var(--cc-panel-solid, #0c0c0e); color: var(--cc-text, #f5f5f6);
+ border: 1px solid var(--cc-edge, rgba(255,255,255,0.16)); border-radius: 8px; padding: 8px 12px;
+ font: 700 12px Inter, system-ui, sans-serif; text-transform: uppercase; letter-spacing: 0.05em;
+ transition: background 0.15s ease, border-color 0.15s ease;
+ }
+ .veh-exit:hover { background: #17171b; border-color: rgba(255,255,255,0.32); }
+ .veh-exit:active { transform: translateY(1px); }
+ .veh-pads { display: none; }
+ .veh-hud.veh-touch .veh-pads { display: block; }
+ .veh-steer { position: fixed; left: 18px; bottom: 24px; display: flex; gap: 14px; }
+ .veh-pedals { position: fixed; right: 18px; bottom: 92px; display: flex; flex-direction: column; gap: 12px; align-items: center; }
+ .veh-btn {
+ pointer-events: auto; cursor: pointer; width: 64px; height: 64px; border-radius: 50%;
+ background: var(--cc-panel, rgba(12,12,14,0.8)); -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);
+ border: 1px solid var(--cc-edge, rgba(255,255,255,0.16)); color: var(--cc-text, #f5f5f6);
+ font-size: 22px; font-weight: 800; display: flex; align-items: center; justify-content: center;
+ touch-action: none; user-select: none; -webkit-user-select: none; transition: background 0.1s ease, transform 0.1s ease;
+ }
+ .veh-btn:active { background: rgba(255,255,255,0.22); transform: scale(0.94); }
+ .veh-gas { width: 78px; height: 78px; }
+ @media (max-width: 560px) { .veh-exit { top: 64px; } }
+ `;
+ document.head.appendChild(s);
+ }
+
+ dispose() {
+ if (this._drivingId) this._endDriving(this.vehicle ? this.vehicle.transform() : null, true);
+ clearTimeout(this._pendingTimer);
+ for (const [, entry] of this.vehicles) {
+ entry.collider?.remove();
+ this.scene.remove(entry.mesh.group);
+ entry.mesh.dispose();
+ }
+ this.vehicles.clear();
+ this.prompt?.remove();
+ this._hud?.remove();
+ this._physReady?.then?.(() => this.phys?.dispose());
+ if (this.phys) { this.phys.dispose(); this.phys = null; }
+ }
+}
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/marketplace.js b/src/marketplace.js
index 8273728f4..c783f4d06 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -1855,9 +1855,9 @@ function renderSkillCard(s) {
${toolsDisplay}
${ratingDisplay}
</div>
- <div class="skill-meta" style="justify-content:space-between">
+ <div class="skill-meta skill-foot">
${installedTag || '<span></span>'}
- <span class="open-cta" style="color:#fafafa;opacity:0.6;font-weight:500">Details →</span>
+ <span class="open-cta">Details <span class="open-cta-arrow" aria-hidden="true">→</span></span>
</div>
</div>`;
}
diff --git a/vite.config.js b/vite.config.js
index cb2b5d498..fe2cd708c 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -252,6 +252,7 @@ const appConfig = {
'create-agent': resolve(__dirname, 'pages/create-agent.html'),
forge: resolve(__dirname, 'pages/forge.html'),
'create-selfie': resolve(__dirname, 'pages/create-selfie.html'),
+ 'create-character': resolve(__dirname, 'pages/create-character.html'),
scan: resolve(__dirname, 'pages/scan.html'),
worlds: resolve(__dirname, 'pages/worlds.html'),
'avatar-studio': resolve(__dirname, 'pages/avatar-studio.html'),
@@ -497,6 +498,8 @@ const appConfig = {
'/create-agent': resolve(root, 'pages/create-agent.html'),
'/create/selfie': resolve(root, 'pages/create-selfie.html'),
'/create/selfie/': resolve(root, 'pages/create-selfie.html'),
+ '/create/character': resolve(root, 'pages/create-character.html'),
+ '/create/character/': resolve(root, 'pages/create-character.html'),
'/create/video': resolve(root, 'pages/create/video.html'),
'/create/video/': resolve(root, 'pages/create/video.html'),
'/extension/privacy': resolve(root, 'pages/extension-privacy.html'),