Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add fishing system and HUD for /play coin worlds
overstepping721c7899463b
diff --git a/api/openapi-json.js b/api/openapi-json.jsindex 72c0585ba..4cfe4d659 100644--- a/api/openapi-json.js+++ b/api/openapi-json.js@@ -209,7 +209,8 @@ export default wrap(async (req, res) => {get: {operationId: 'healthz',summary: 'Service liveness',- description: 'Lightweight liveness probe with uptime + service version. No auth.',+ description:+ 'Lightweight liveness probe with uptime + service version. No auth.',security: [],responses: {200: { description: 'Health summary JSON' },@@ -224,8 +225,18 @@ export default wrap(async (req, res) => {'Returns raw bonding-curve state, current spot price + market cap, and graduation progress for a Pump.fun token. Public, edge-cached for 10s.',security: [],parameters: [- { name: 'mint', in: 'query', required: true, schema: { type: 'string' }, description: 'Base58 SPL mint address' },- { name: 'network', in: 'query', schema: { type: 'string', enum: ['mainnet', 'devnet'] } },+ {+ name: 'mint',+ in: 'query',+ required: true,+ schema: { type: 'string' },+ description: 'Base58 SPL mint address',+ },+ {+ name: 'network',+ in: 'query',+ schema: { type: 'string', enum: ['mainnet', 'devnet'] },+ },],responses: {200: { description: 'Bonding curve snapshot' },@@ -242,13 +253,36 @@ export default wrap(async (req, res) => {'Deterministic buy or sell quote computed via @nirholas/pump-sdk on the live bonding curve. Returns output amount, price impact %, and a market context block.',security: [],parameters: [- { name: 'mint', in: 'query', required: true, schema: { type: 'string' } },- { name: 'side', in: 'query', required: true, schema: { type: 'string', enum: ['buy', 'sell'] } },- { name: 'amount', in: 'query', required: true, schema: { type: 'number', minimum: 0 }, description: 'For buy: SOL. For sell: tokens (UI units, 6 decimals).' },- { name: 'network', in: 'query', schema: { type: 'string', enum: ['mainnet', 'devnet'] } },+ {+ name: 'mint',+ in: 'query',+ required: true,+ schema: { type: 'string' },+ },+ {+ name: 'side',+ in: 'query',+ required: true,+ schema: { type: 'string', enum: ['buy', 'sell'] },+ },+ {+ name: 'amount',+ in: 'query',+ required: true,+ schema: { type: 'number', minimum: 0 },+ description:+ 'For buy: SOL. For sell: tokens (UI units, 6 decimals).',+ },+ {+ name: 'network',+ in: 'query',+ schema: { type: 'string', enum: ['mainnet', 'devnet'] },+ },],responses: {- 200: { description: 'Quote payload with input/output and priceImpactPct' },+ 200: {+ description: 'Quote payload with input/output and priceImpactPct',+ },400: { description: 'Validation error' },404: { description: 'No bonding curve for that mint' },},@@ -259,9 +293,14 @@ export default wrap(async (req, res) => {operationId: 'x402_agent_reputation',summary: 'Paid: Agent Reputation snapshot',description:- 'Pay $0.01 USDC to retrieve a three.ws agent\'s reputation snapshot synthesized from pump_agent_payments, distribute/buyback success history, and signed Solana memo attestations.',+ "Pay $0.01 USDC to retrieve a three.ws agent's reputation snapshot synthesized from pump_agent_payments, distribute/buyback success history, and signed Solana memo attestations.",parameters: [- { name: 'agent_id', in: 'query', required: true, schema: { type: 'string', format: 'uuid' } },+ {+ name: 'agent_id',+ in: 'query',+ required: true,+ schema: { type: 'string', format: 'uuid' },+ },],responses: {200: { description: 'Reputation snapshot JSON' },@@ -269,7 +308,10 @@ export default wrap(async (req, res) => {402: { description: 'Payment Required (x402)' },404: { description: 'agent_id not found' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '0.01' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.01' },+ protocols: X402_PROTOCOLS,+ },},},'/api/x402/onchain-identity-verify': {@@ -279,16 +321,34 @@ export default wrap(async (req, res) => {description:'Pay $0.005 USDC to verify whether a three.ws agent_id actually owns/deployed a given contract or mint on a given CAIP-2 chain, using the canonical meta.onchain unified index.',parameters: [- { name: 'agent_id', in: 'query', required: true, schema: { type: 'string', format: 'uuid' } },- { name: 'chain', in: 'query', required: true, schema: { type: 'string' } },- { name: 'contract_or_mint', in: 'query', required: true, schema: { type: 'string' } },+ {+ name: 'agent_id',+ in: 'query',+ required: true,+ schema: { type: 'string', format: 'uuid' },+ },+ {+ name: 'chain',+ in: 'query',+ required: true,+ schema: { type: 'string' },+ },+ {+ name: 'contract_or_mint',+ in: 'query',+ required: true,+ schema: { type: 'string' },+ },],responses: {200: { description: 'Verification result JSON' },400: { description: 'Missing or invalid parameters' },402: { description: 'Payment Required (x402)' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '0.005' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.005' },+ protocols: X402_PROTOCOLS,+ },},},'/api/x402/pump-agent-audit': {@@ -298,7 +358,12 @@ export default wrap(async (req, res) => {description:'Pay $0.02 USDC to retrieve a full operational audit of a pump.fun mint: USDC paid in, distinct payers, distribute/buyback success history, latest error reasons, and derived risk flags.',parameters: [- { name: 'mint', in: 'query', required: true, schema: { type: 'string', minLength: 32, maxLength: 44 } },+ {+ name: 'mint',+ in: 'query',+ required: true,+ schema: { type: 'string', minLength: 32, maxLength: 44 },+ },],responses: {200: { description: 'Audit JSON' },@@ -306,7 +371,10 @@ export default wrap(async (req, res) => {402: { description: 'Payment Required (x402)' },404: { description: 'Mint not indexed' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '0.02' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.02' },+ protocols: X402_PROTOCOLS,+ },},},'/api/x402/skill-marketplace': {@@ -317,13 +385,20 @@ export default wrap(async (req, res) => {'Pay $0.001 USDC to list active skill listings with prices across all three.ws agents. Optional skill filter returns the cheapest provider for that capability.',parameters: [{ name: 'skill', in: 'query', schema: { type: 'string' } },- { name: 'limit', in: 'query', schema: { type: 'integer', minimum: 1, maximum: 200 } },+ {+ name: 'limit',+ in: 'query',+ schema: { type: 'integer', minimum: 1, maximum: 200 },+ },],responses: {200: { description: 'Marketplace listings JSON' },402: { description: 'Payment Required (x402)' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '0.001' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.001' },+ protocols: X402_PROTOCOLS,+ },},},'/api/x402/symbol-availability': {@@ -333,15 +408,27 @@ export default wrap(async (req, res) => {description:'Pay $0.001 USDC to check whether a candidate ticker collides with any three.ws-indexed pump.fun mint. Returns exact matches plus trigram-similar tickers and a recommendation.',parameters: [- { name: 'ticker', in: 'query', required: true, schema: { type: 'string', minLength: 1, maxLength: 32 } },- { name: 'network', in: 'query', schema: { type: 'string', enum: ['mainnet', 'devnet'] } },+ {+ name: 'ticker',+ in: 'query',+ required: true,+ schema: { type: 'string', minLength: 1, maxLength: 32 },+ },+ {+ name: 'network',+ in: 'query',+ schema: { type: 'string', enum: ['mainnet', 'devnet'] },+ },],responses: {200: { description: 'Symbol availability JSON' },400: { description: 'Missing or invalid ticker' },402: { description: 'Payment Required (x402)' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '0.001' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.001' },+ protocols: X402_PROTOCOLS,+ },},},'/api/x402/mint-to-mesh-batch': {@@ -362,7 +449,11 @@ export default wrap(async (req, res) => {type: 'array',minItems: 1,maxItems: 10,- items: { type: 'string', minLength: 32, maxLength: 44 },+ items: {+ type: 'string',+ minLength: 32,+ maxLength: 44,+ },},},},@@ -374,7 +465,10 @@ export default wrap(async (req, res) => {400: { description: 'Missing or invalid body' },402: { description: 'Payment Required (x402)' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '0.05' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.05' },+ protocols: X402_PROTOCOLS,+ },},},'/api/x402/model-check': {@@ -397,7 +491,10 @@ export default wrap(async (req, res) => {400: { description: 'Missing or invalid url' },402: { description: 'Payment Required (x402)' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '0.001' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.001' },+ protocols: X402_PROTOCOLS,+ },},},'/api/x402/mint-to-mesh': {@@ -420,7 +517,10 @@ export default wrap(async (req, res) => {400: { description: 'Missing or invalid mint' },402: { description: 'Payment Required (x402)' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '0.001' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.001' },+ protocols: X402_PROTOCOLS,+ },},},'/api/insights/revenue-vision': {@@ -430,7 +530,12 @@ export default wrap(async (req, res) => {description:'Pay $0.001 USDC to receive a single prioritized next-best move, a data-grounded insight, and an honestly-calibrated confidence rating for the supplied mission brief.',parameters: [- { name: 'agent_codename', in: 'query', required: true, schema: { type: 'string' } },+ {+ name: 'agent_codename',+ in: 'query',+ required: true,+ schema: { type: 'string' },+ },{name: 'power_request',in: 'query',@@ -451,7 +556,10 @@ export default wrap(async (req, res) => {400: { description: 'Missing or invalid parameters' },402: { description: 'Payment Required (x402)' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '0.001' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.001' },+ protocols: X402_PROTOCOLS,+ },},},'/api/x402/permit2-paid-demo': {@@ -459,12 +567,15 @@ export default wrap(async (req, res) => {operationId: 'x402_permit2_paid_demo',summary: 'Paid: Gasless Permit2 + EIP-2612 settlement demo',description:- 'Pay $0.001 USDC via the Permit2-only path so a wallet holding USDC but zero ETH can complete the flow. CDP\'s x402ExactPermit2Proxy submits the EIP-2612 permit + Permit2 transfer atomically; the response surfaces the on-chain tx hash and a Basescan link.',+ "Pay $0.001 USDC via the Permit2-only path so a wallet holding USDC but zero ETH can complete the flow. CDP's x402ExactPermit2Proxy submits the EIP-2612 permit + Permit2 transfer atomically; the response surfaces the on-chain tx hash and a Basescan link.",responses: {200: { description: 'Settlement summary with tx hash' },402: { description: 'Payment Required (x402)' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '0.001' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.001' },+ protocols: X402_PROTOCOLS,+ },},},'/api/x402/dance-tip': {@@ -510,7 +621,10 @@ export default wrap(async (req, res) => {400: { description: 'Missing or invalid parameters' },402: { description: 'Payment Required (x402)' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '0.001' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.001' },+ protocols: X402_PROTOCOLS,+ },},},'/api/x402/asset-download': {@@ -561,10 +675,26 @@ export default wrap(async (req, res) => {properties: {name: { type: 'string', maxLength: 32 },symbol: { type: 'string', maxLength: 10 },- metadataUri: { type: 'string', maxLength: 2048, description: 'Pre-pinned metadata URI. Provide this or imageUrl.' },- imageUrl: { type: 'string', maxLength: 2048, description: 'Image URL to pin to pump.fun IPFS. Provide this or metadataUri.' },+ metadataUri: {+ type: 'string',+ maxLength: 2048,+ description:+ 'Pre-pinned metadata URI. Provide this or imageUrl.',+ },+ imageUrl: {+ type: 'string',+ maxLength: 2048,+ description:+ 'Image URL to pin to pump.fun IPFS. Provide this or metadataUri.',+ },description: { type: 'string', maxLength: 2000 },- creator: { type: 'string', minLength: 32, maxLength: 44, description: 'Solana wallet that receives creator rewards.' },+ creator: {+ type: 'string',+ minLength: 32,+ maxLength: 44,+ description:+ 'Solana wallet that receives creator rewards.',+ },vanityPrefix: { type: 'string', maxLength: 5 },vanitySuffix: { type: 'string', maxLength: 5 },},@@ -578,7 +708,10 @@ export default wrap(async (req, res) => {402: { description: 'Payment Required (x402)' },503: { description: 'Launcher not configured' },},- 'x-payment-info': { price: { mode: 'fixed', currency: 'USD', amount: '5.00' }, protocols: X402_PROTOCOLS },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '5.00' },+ protocols: X402_PROTOCOLS,+ },},},'/api/x402/vanity': {@@ -592,19 +725,22 @@ export default wrap(async (req, res) => {name: 'prefix',in: 'query',schema: { type: 'string', maxLength: 3 },- description: 'Base58 characters the address must start with (excludes 0, O, I, l). Combined with suffix, max 3. Provide prefix and/or suffix.',+ description:+ 'Base58 characters the address must start with (excludes 0, O, I, l). Combined with suffix, max 3. Provide prefix and/or suffix.',},{name: 'suffix',in: 'query',schema: { type: 'string', maxLength: 3 },- description: 'Base58 characters the address must end with. Combined with prefix, max 3.',+ description:+ 'Base58 characters the address must end with. Combined with prefix, max 3.',},{name: 'ignoreCase',in: 'query',schema: { type: 'string', enum: ['0', '1', 'true', 'false'] },- description: 'When 1/true, match case-insensitively (faster, less specific).',+ description:+ 'When 1/true, match case-insensitively (faster, less specific).',},],responses: {@@ -620,19 +756,121 @@ export default wrap(async (req, res) => {},},},+ '/api/x402/fact-check': {+ post: {+ operationId: 'x402_fact_check',+ summary: 'Paid: Real-time fact check with sourced verdict',+ description:+ 'Pay $0.10 USDC to verify a factual claim. The server generates search queries, runs multi-source web search, extracts per-source stance with an LLM, computes a weighted verdict + confidence, and returns the supporting sources plus a SHA-256 attestation of the result.',+ requestBody: {+ required: true,+ content: {+ 'application/json': {+ schema: {+ type: 'object',+ required: ['claim'],+ properties: {+ claim: {+ type: 'string',+ minLength: 5,+ maxLength: 1000,+ description: 'The factual claim to verify.',+ },+ strictness: {+ type: 'string',+ enum: ['high', 'medium', 'low'],+ default: 'medium',+ description:+ 'high: penalizes low-authority sources. medium: default. low: accepts all sources equally.',+ },+ },+ },+ },+ },+ },+ responses: {+ 200: {+ description:+ 'Verdict JSON: verdict, confidence, claim, strictness, sources, costBreakdown, attestation',+ },+ 400: { description: 'Missing or invalid claim' },+ 402: { description: 'Payment Required (x402)' },+ },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.10' },+ protocols: X402_PROTOCOLS,+ },+ },+ },+ '/api/x402/tutor': {+ post: {+ operationId: 'x402_tutor',+ summary: 'Paid: Pay-as-you-learn tutor (one charge per answer)',+ description:+ 'Pay $0.01 USDC per answered question. Returns a leveled explanation, key points, a worked example, and a follow-up, plus a running session tab so the UI can render a live itemized invoice. Pass a sessionId to accumulate a tab across questions.',+ requestBody: {+ required: true,+ content: {+ 'application/json': {+ schema: {+ type: 'object',+ required: ['question'],+ properties: {+ sessionId: {+ type: 'string',+ maxLength: 100,+ description:+ 'Stable session identifier to accumulate a running tab. Omit to start a new session.',+ },+ question: {+ type: 'string',+ minLength: 5,+ maxLength: 2000,+ description: 'The question to be explained.',+ },+ context: {+ type: 'string',+ maxLength: 6000,+ description:+ 'Optional code or context to ground the explanation.',+ },+ level: {+ type: 'string',+ enum: ['beginner', 'intermediate', 'expert'],+ default: 'intermediate',+ description:+ 'Target expertise level — controls depth and assumed background.',+ },+ },+ },+ },+ },+ },+ responses: {+ 200: { description: 'Answer JSON with running session tab' },+ 400: { description: 'Missing or invalid question' },+ 402: { description: 'Payment Required (x402)' },+ },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.01' },+ protocols: X402_PROTOCOLS,+ },+ },+ },'/api/x402/skill-call': {get: {operationId: 'x402_skill_call',summary: 'Paid: Invoke a marketplace skill (pay-per-call)',description:- 'Pay the per-call price of a marketplace skill in USDC (Base or Solana) and receive its executable payload: the tool schema and content the calling agent runs. Payment settles straight to the skill author\'s wallet. Per-call pricing — every invocation is a fresh payment.',+ "Pay the per-call price of a marketplace skill in USDC (Base or Solana) and receive its executable payload: the tool schema and content the calling agent runs. Payment settles straight to the skill author's wallet. Per-call pricing — every invocation is a fresh payment.",parameters: [{name: 'skill',in: 'query',required: true,schema: { type: 'string', minLength: 1, maxLength: 128 },- description: 'Unique skill slug from the marketplace_skills catalog.',+ description:+ 'Unique skill slug from the marketplace_skills catalog.',},],responses: {@@ -645,7 +883,9 @@ export default wrap(async (req, res) => {'x-payment-info': {// Per-skill pricing from marketplace_skills; the live 402// challenge reflects the exact price of the requested skill.- price: { mode: 'dynamic', currency: 'USD' },+ // Bounds mirror the catalog's enforced range (price_per_call_usd+ // is validated 0–10 in api/skills/index.js; free skills 409).+ price: { mode: 'dynamic', currency: 'USD', min: '0.001', max: '10.00' },protocols: X402_PROTOCOLS,note: 'Per-call price is set per skill; the live 402 challenge reflects the exact skill price.',},diff --git a/api/wk.js b/api/wk.jsindex ccc996690..bbbb155a8 100644--- a/api/wk.js+++ b/api/wk.js@@ -508,6 +508,14 @@ function handleX402Discovery(req, res) {serviceName: 'three.ws Asset Bazaar',tags: ['3d', 'asset', 'glb', 'avatar', 'download'],}),+ factCheck: withService({+ serviceName: 'three.ws Fact Checker',+ tags: ['fact-check', 'search', 'verification', 'llm', 'attestation'],+ }),+ tutor: withService({+ serviceName: 'three.ws Pay-As-You-Learn Tutor',+ tags: ['tutor', 'education', 'llm', 'explain', 'pay-per-call'],+ }),};// USE-13: per-tool MCP catalog entries. Each priced tool is its own@@ -631,8 +639,7 @@ function handleX402Discovery(req, res) {input: {agent_codename: 'ledger-bot',power_request: 'revenue-vision',- mission_brief:- 'Find the highest-converting buyer segment this week.',+ mission_brief: 'Find the highest-converting buyer segment this week.',},inputSchema: {type: 'object',@@ -676,7 +683,7 @@ function handleX402Discovery(req, res) {url,method: 'GET',description:- 'Agent Reputation — return a reputation snapshot for a three.ws agent (USDC paid in to its pump-agent tokens, distinct payers, deployed mints, distribution success rate, Solana attestation counts). Built from three.ws\'s proprietary index of pump_agent_payments, pump_distribute_runs, and solana_attestations.',+ "Agent Reputation — return a reputation snapshot for a three.ws agent (USDC paid in to its pump-agent tokens, distinct payers, deployed mints, distribution success rate, Solana attestation counts). Built from three.ws's proprietary index of pump_agent_payments, pump_distribute_runs, and solana_attestations.",mimeType: 'application/json',serviceName: routeMeta.agentReputation.serviceName,tags: routeMeta.agentReputation.tags,@@ -736,7 +743,7 @@ function handleX402Discovery(req, res) {url,method: 'GET',description:- 'Pump-Agent Audit — full operational audit of a pump.fun agent-payments token: total USDC in, unique payers, distribute/buyback success history, latest error reasons, and risk flags (never_distributed, high_distribute_failure_rate, no_buybacks_run). Backed by three.ws\'s indexed pump_distribute_runs and pump_buyback_runs tables.',+ "Pump-Agent Audit — full operational audit of a pump.fun agent-payments token: total USDC in, unique payers, distribute/buyback success history, latest error reasons, and risk flags (never_distributed, high_distribute_failure_rate, no_buybacks_run). Backed by three.ws's indexed pump_distribute_runs and pump_buyback_runs tables.",mimeType: 'application/json',serviceName: routeMeta.pumpAudit.serviceName,tags: routeMeta.pumpAudit.tags,@@ -749,7 +756,9 @@ function handleX402Discovery(req, res) {inputSchema: {type: 'object',required: ['mint'],- properties: { mint: { type: 'string', minLength: 32, maxLength: 44 } },+ properties: {+ mint: { type: 'string', minLength: 32, maxLength: 44 },+ },},}),};@@ -830,7 +839,7 @@ function handleX402Discovery(req, res) {url,method: 'GET',description:- 'Symbol Availability — pre-launch ticker collision check against three.ws\'s pump.fun mint index. Returns exact-symbol collisions plus trigram-similar tickers so launch agents can avoid name confusion and aggregator-search dilution.',+ "Symbol Availability — pre-launch ticker collision check against three.ws's pump.fun mint index. Returns exact-symbol collisions plus trigram-similar tickers so launch agents can avoid name confusion and aggregator-search dilution.",mimeType: 'application/json',serviceName: routeMeta.symbolCheck.serviceName,tags: routeMeta.symbolCheck.tags,@@ -891,7 +900,8 @@ function handleX402Discovery(req, res) {ignoreCase: {type: 'string',enum: ['0', '1', 'true', 'false'],- description: 'When 1/true, match case-insensitively (faster, less specific).',+ description:+ 'When 1/true, match case-insensitively (faster, less specific).',},},},@@ -929,7 +939,7 @@ function handleX402Discovery(req, res) {url,method: 'GET',description:- 'Permit2 + EIP-2612 Gas Sponsoring Demo — forces the gasless Permit2 path so a fresh wallet holding USDC but ZERO ETH can complete the flow. CDP\'s x402ExactPermit2Proxy submits the EIP-2612 permit + Permit2 transfer atomically via settleWithPermit. Response surfaces the on-chain tx hash and a Basescan link.',+ "Permit2 + EIP-2612 Gas Sponsoring Demo — forces the gasless Permit2 path so a fresh wallet holding USDC but ZERO ETH can complete the flow. CDP's x402ExactPermit2Proxy submits the EIP-2612 permit + Permit2 transfer atomically via settleWithPermit. Response surfaces the on-chain tx hash and a Basescan link.",mimeType: 'application/json',serviceName: routeMeta.permit2Demo.serviceName,tags: routeMeta.permit2Demo.tags,@@ -1010,12 +1020,14 @@ function handleX402Discovery(req, res) {dancer: {type: 'string',enum: ['1', '2', '3', '4'],- description: 'Stage slot 1-4 — which dancer should take the pole.',+ description:+ 'Stage slot 1-4 — which dancer should take the pole.',},dance: {type: 'string',enum: ['rumba', 'silly', 'thriller', 'capoeira', 'hiphop'],- description: 'Performance style — a clip in /animations/manifest.json.',+ description:+ 'Performance style — a clip in /animations/manifest.json.',},},},@@ -1055,7 +1067,8 @@ function handleX402Discovery(req, res) {type: 'string',minLength: 1,maxLength: 128,- description: 'Unique asset slug from the paid_assets catalog.',+ description:+ 'Unique asset slug from the paid_assets catalog.',},},},@@ -1090,7 +1103,98 @@ function handleX402Discovery(req, res) {type: 'string',minLength: 1,maxLength: 128,- description: 'Unique skill slug from the marketplace_skills catalog.',+ description:+ 'Unique skill slug from the marketplace_skills catalog.',+ },+ },+ },+ }),+ };+ })(),+ (() => {+ const url = `${origin}/api/x402/fact-check`;+ const accepts = acceptsForPrice('100000', url);+ return {+ path: '/api/x402/fact-check',+ url,+ method: 'POST',+ description:+ 'three.ws Fact Checker — pay $0.10 USDC to verify a factual claim. Generates search queries, runs multi-source web search, extracts per-source stance with an LLM, computes a weighted verdict + confidence, and returns supporting sources plus a SHA-256 attestation of the result.',+ mimeType: 'application/json',+ serviceName: routeMeta.factCheck.serviceName,+ tags: routeMeta.factCheck.tags,+ iconUrl: routeMeta.factCheck.iconUrl,+ accepts,+ extensions: extensionsForAccepts(accepts, {+ method: 'POST',+ discoverable: true,+ input: { claim: 'The Eiffel Tower is in Paris.', strictness: 'medium' },+ inputSchema: {+ type: 'object',+ required: ['claim'],+ properties: {+ claim: {+ type: 'string',+ minLength: 5,+ maxLength: 1000,+ description: 'The factual claim to verify.',+ },+ strictness: {+ type: 'string',+ enum: ['high', 'medium', 'low'],+ description:+ 'high: penalizes low-authority sources. medium: default. low: accepts all sources equally.',+ },+ },+ },+ }),+ };+ })(),+ (() => {+ const url = `${origin}/api/x402/tutor`;+ const accepts = acceptsForPrice('10000', url);+ return {+ path: '/api/x402/tutor',+ url,+ method: 'POST',+ description:+ 'three.ws Pay-As-You-Learn Tutor — pay $0.01 USDC per answered question. Returns a leveled explanation, key points, a worked example, and a follow-up, plus a running session tab for a live itemized invoice. Pass a sessionId to accumulate a tab across questions.',+ mimeType: 'application/json',+ serviceName: routeMeta.tutor.serviceName,+ tags: routeMeta.tutor.tags,+ iconUrl: routeMeta.tutor.iconUrl,+ accepts,+ extensions: extensionsForAccepts(accepts, {+ method: 'POST',+ discoverable: true,+ input: { question: 'Why is the sky blue?', level: 'intermediate' },+ inputSchema: {+ type: 'object',+ required: ['question'],+ properties: {+ sessionId: {+ type: 'string',+ maxLength: 100,+ description:+ 'Stable session identifier to accumulate a running tab. Omit to start a new session.',+ },+ question: {+ type: 'string',+ minLength: 5,+ maxLength: 2000,+ description: 'The question to be explained.',+ },+ context: {+ type: 'string',+ maxLength: 6000,+ description:+ 'Optional code or context to ground the explanation.',+ },+ level: {+ type: 'string',+ enum: ['beginner', 'intermediate', 'expert'],+ description:+ 'Target expertise level — controls depth and assumed background.',},},},diff --git a/multiplayer/scripts/fish-smoke.mjs b/multiplayer/scripts/fish-smoke.mjsnew file mode 100644index 000000000..dff3ce065--- /dev/null+++ b/multiplayer/scripts/fish-smoke.mjs@@ -0,0 +1,65 @@+// Headless end-to-end smoke test for the /play fishing slice.+// Joins walk_world, walks to the east pond, casts, and asserts the server+// returns the profile (with a starter rod), a catch/miss notice, and fishing XP.+import { Client } from 'colyseus.js';+import { WalkState } from '../src/schemas.js';+import { FISHING_SPOTS } from '../src/world-features.js';++const SPOT = FISHING_SPOTS[0]; // east pond+const log = (...a) => console.log('[fish-smoke]', ...a);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++const got = { profile: null, notices: [], xp: [], inv: [], levelups: [] };++const client = new Client('ws://localhost:2567');+const room = await client.joinOrCreate('walk_world', { name: 'angler', pid: 'smoke-angler', coin: '' }, WalkState);+log('joined', room.sessionId);++room.onMessage('profile', (m) => { got.profile = m; log('profile: gold', m.gold, 'activeSlot', m.activeSlot, 'hotbar[0]', JSON.stringify(m.hotbar?.[0]), 'fishing', m.skills?.fishing?.level); });+room.onMessage('inv', (m) => { got.inv.push(m); });+room.onMessage('xpgain', (m) => { got.xp.push(m); log('xpgain', m.skill, '+' + m.amount, '-> lvl', m.level, 'xp', m.xp); });+room.onMessage('levelup', (m) => { got.levelups.push(m); log('LEVELUP', m.skill, m.level); });+room.onMessage('notice', (m) => { got.notices.push(m); log('notice', JSON.stringify(m)); });++await sleep(400);++// Walk to the pond in <=1.1m steps (server rejects >1.2m teleports).+let x = 0, z = 0;+const tx = SPOT.x, tz = SPOT.z;+for (let i = 0; i < 80; i++) {+ const dx = tx - x, dz = tz - z;+ const d = Math.hypot(dx, dz);+ if (d <= SPOT.r + 3.0) break; // within cast range+ const step = Math.min(1.1, d);+ x += (dx / d) * step; z += (dz / d) * step;+ room.send('move', { x, y: 0, z, yaw: Math.atan2(dx, dz), motion: 'walk' });+ await sleep(40);+}+room.send('move', { x, y: 0, z, motion: 'idle', yaw: 0 });+log('arrived near pond at', x.toFixed(1), z.toFixed(1), 'spot', SPOT.x, SPOT.z);+await sleep(200);++// Cast several times, respecting the ~1.5s per-cast cooldown.+for (let i = 0; i < 8; i++) {+ room.send('fish');+ await sleep(1700);+}+await sleep(400);++// Assertions.+let ok = true;+const assert = (cond, msg) => { if (!cond) { ok = false; log('FAIL:', msg); } else log('PASS:', msg); };+assert(got.profile, 'received profile snapshot on join');+assert(got.profile?.hotbar?.[0]?.item === 'rod', 'starter rod on hotbar slot 0');+assert(got.profile?.activeSlot === 0, 'rod pre-equipped (activeSlot 0)');+assert(got.notices.some((n) => n.kind === 'fish'), 'received at least one fishing notice');+assert(got.xp.some((g) => g.skill === 'fishing'), 'gained fishing XP');+const caught = got.notices.filter((n) => n.kind === 'fish' && n.caught > 0).length;+const fishInInv = (got.inv.at(-1)?.inv || got.profile?.inv || []).reduce((sum, s) => sum + (s.item === 'fish' ? s.qty : 0), 0);+log(`summary: ${caught} successful casts, ${fishInInv} fish in pack, ${got.xp.length} xp events, ${got.levelups.length} level-ups`);+assert(caught === 0 || fishInInv > 0, 'caught fish landed in the inventory');++room.leave();+await sleep(300);+log(ok ? 'RESULT: ALL PASS' : 'RESULT: FAILURES ABOVE');+process.exit(ok ? 0 : 1);diff --git a/multiplayer/src/economy.js b/multiplayer/src/economy.jsnew file mode 100644index 000000000..11e3c1421--- /dev/null+++ b/multiplayer/src/economy.js@@ -0,0 +1,225 @@+// Economy & progression for the /play coin worlds.+//+// The /game isometric MMO (GameRoom) keeps inventory, hotbar, gold and skills on+// the synced Colyseus schema because peers render each other's equipped tools and+// mounts on a tile grid. /play is a free-roam, per-coin social world where a+// player's pack and purse are PRIVATE — no peer needs to see them — so we keep all+// of it OFF the shared WalkState schema and stream each owner only their own state+// via targeted messages (the same pattern GameRoom already uses for skills/xpgain).+//+// That keeps the /walk experience (which shares the same schema) untouched, costs+// peers zero extra wire bytes, and lets the economy grow (cooking, gathering,+// commerce) without ever repricing the movement-critical position deltas.+//+// A "profile" here is a plain JS object — not a Schema — so these helpers operate+// on ordinary arrays. The shapes mirror items.js/playerStore.js so a fish caught on+// /play means the same thing it does in /game, and a profile persists through the+// same account-keyed playerStore.++import {+ STACKABLE_ITEMS, isEdible, scaledHeal,+} from './items.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'];++// 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'];++// XP curve — identical to GameRoom's so progression is consistent across the+// platform: level n needs 50 * n^1.8 cumulative XP, capped at LEVEL_CAP.+export function levelForXp(xp) {+ let lvl = 1;+ while (lvl < LEVEL_CAP && xp >= Math.floor(50 * Math.pow(lvl, 1.8))) lvl++;+ return lvl;+}++// Inverse of levelForXp: cumulative XP required to BE at a given level. Lets the+// client draw an exact progress bar without re-deriving the curve.+export function xpForLevel(level) {+ const lvl = Math.max(1, Math.min(LEVEL_CAP, level | 0));+ return lvl <= 1 ? 0 : Math.floor(50 * Math.pow(lvl - 1, 1.8));+}++function emptySlots(n) {+ return Array.from({ length: n }, () => ({ item: '', qty: 0 }));+}++// A fresh profile with the starter kit. `playerId` is the stable persistence key+// (wallet account or guest id) carried on the profile so save paths never need it+// threaded separately.+export function newProfile(playerId = '') {+ const hotbar = emptySlots(HOTBAR_SIZE);+ STARTER_HOTBAR.forEach((item, i) => { hotbar[i] = { item, qty: 1 }; });+ return {+ playerId,+ gold: 0,+ hp: 100,+ maxHp: 100,+ inv: emptySlots(INV_SIZE),+ hotbar,+ activeSlot: 0, // the rod, ready to cast+ xp: Object.fromEntries(SKILLS.map((s) => [s, 0])),+ levels: Object.fromEntries(SKILLS.map((s) => [s, 1])),+ };+}++// 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.+export function restoreProfile(saved, playerId = '') {+ if (!saved || typeof saved !== 'object') return newProfile(playerId);+ const base = newProfile(playerId);+ const fill = (target, src) => {+ for (let i = 0; i < target.length; i++) {+ const s = src && src[i];+ const item = s && typeof s.item === 'string' ? s.item : '';+ target[i] = { item, qty: item && Number.isFinite(s.qty) ? Math.max(0, Math.min(MAX_STACK, s.qty | 0)) : 0 };+ }+ };+ if (Array.isArray(saved.inv)) fill(base.inv, saved.inv);+ 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.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 (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;+ base.xp[skill] = v;+ base.levels[skill] = levelForXp(v);+ }+ }+ return base;+}++// The persisted slice (mirrors GameRoom._serializeProfile so the two stores stay+// interchangeable for an account that plays both surfaces).+export function serializeProfile(profile) {+ const slots = (arr) => arr.map((s) => ({ item: s.item, qty: s.qty }));+ return {+ inv: slots(profile.inv),+ hotbar: slots(profile.hotbar),+ activeSlot: profile.activeSlot,+ gold: profile.gold,+ hp: profile.hp,+ maxHp: profile.maxHp,+ xp: { ...profile.xp },+ };+}++// Is there room in the backpack for at least one of `item`? Stackables fit in any+// empty slot OR a non-full existing stack; non-stackables need an empty slot.+export function hasRoomFor(profile, item) {+ if (STACKABLE_ITEMS.has(item)) {+ for (const s of profile.inv) {+ if (!s.item) return true;+ if (s.item === item && s.qty < MAX_STACK) return true;+ }+ return false;+ }+ return profile.inv.some((s) => !s.item);+}++// Add `qty` of `item` to the backpack, filling existing stacks first. Returns the+// quantity that did NOT fit (0 = everything landed). Mirrors GameRoom._addItem.+export function addItem(profile, item, qty) {+ let left = qty;+ const inv = profile.inv;+ if (STACKABLE_ITEMS.has(item)) {+ for (const s of inv) {+ if (left <= 0) break;+ if (s.item === item && s.qty < MAX_STACK) {+ const room = MAX_STACK - s.qty;+ const m = Math.min(room, left);+ s.qty += m; left -= m;+ }+ }+ while (left > 0) {+ const empty = inv.find((s) => !s.item);+ if (!empty) break;+ const m = Math.min(MAX_STACK, left);+ empty.item = item; empty.qty = m; left -= m;+ }+ } else {+ while (left > 0) {+ const empty = inv.find((s) => !s.item);+ if (!empty) break;+ empty.item = item; empty.qty = 1; left -= 1;+ }+ }+ return left;+}++// Resolve a client slot reference { zone:'inv'|'hotbar', i } to the live slot+// object, or null when out of range. Validated like GameRoom._resolveSlot so a+// crafted index can never read outside the arrays.+export function resolveSlot(profile, ref) {+ if (!ref || typeof ref !== 'object') return null;+ const i = ref.i | 0;+ if (ref.zone === 'inv' && i >= 0 && i < INV_SIZE) return profile.inv[i];+ if (ref.zone === 'hotbar' && i >= 0 && i < HOTBAR_SIZE) return profile.hotbar[i];+ return null;+}++// Grant XP in a skill. Mutates the profile and returns the detail the owner's+// client needs to animate the gain and (when crossed) the level-up — including the+// current level's XP boundaries so the bar is exact without a round-trip.+export function grantXp(profile, skill, amount) {+ if (!SKILLS.includes(skill)) return null;+ profile.xp[skill] = (profile.xp[skill] || 0) + amount;+ const xp = profile.xp[skill];+ const level = levelForXp(xp);+ const leveledUp = level > (profile.levels[skill] || 1);+ profile.levels[skill] = level;+ const maxed = level >= LEVEL_CAP;+ return {+ skill, amount, xp, level, leveledUp,+ levelXp: xpForLevel(level),+ nextXp: maxed ? null : xpForLevel(level + 1),+ };+}++// The full snapshot the owner's client renders on join (and after any change it+// can't infer): purse, vitals, pack, hotbar, and per-skill level + bar boundaries.+export function profileSnapshot(profile) {+ const skills = {};+ for (const skill of SKILLS) {+ const level = profile.levels[skill] || 1;+ const maxed = level >= LEVEL_CAP;+ skills[skill] = {+ level,+ xp: profile.xp[skill] || 0,+ levelXp: xpForLevel(level),+ nextXp: maxed ? null : xpForLevel(level + 1),+ };+ }+ return {+ gold: profile.gold,+ hp: profile.hp,+ maxHp: profile.maxHp,+ 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,+ };+}++// 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.+export function consumeSlot(profile, slot) {+ if (!slot || !slot.item || !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 };+}diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex 233722c4f..23fecd4d6 100644--- a/multiplayer/src/rooms/WalkRoom.js+++ b/multiplayer/src/rooms/WalkRoom.js@@ -15,6 +15,14 @@ import { verifyHolderPass } from '../holder-pass.js';import { socialHub } from '../social-hub.js';import { verifyPresenceTicket } from '../presence-token.js';import { verifyPlayPass } from '../play-pass.js';+import {+ restoreProfile, serializeProfile, profileSnapshot,+ addItem, hasRoomFor, resolveSlot, grantXp, consumeSlot,+ HOTBAR_SIZE,+} from '../economy.js';+import { itemLabel, fishCatchChance, fishDoubleChance } from '../items.js';+import { fishingSpotInRange } from '../world-features.js';+import { hydratePlayer, loadPlayer, savePlayer, flushPlayer } from '../playerStore.js';// Platform entry gate (wallet-first sign-in + game-token balance). When a game// token is pinned (PLAY_GATE_MINT, falling back to THREE_MINT) every join must@@ -69,6 +77,16 @@ const MOVE_WINDOW_MS = 1000;const MOTION_VALUES = new Set(['idle', 'walk', 'run']);+// --- Economy & activities (off-schema) ------------------------------------+// A player's pack, purse and skills are PRIVATE to them — peers never render+// them in this free-roam world — so they live off the synced WalkState schema+// (kept in this.econ) and stream to the owning client via targeted messages.+// This keeps the shared /walk schema untouched and peers' wire cost at zero.+const FISH_COOLDOWN_MS = 1500; // per-cast reel time (cadence on the real clock)+const CONSUME_COOLDOWN_MS = 1100; // pace between bites — no instant heal-spam+// Per-action rate ceilings (messages/sec/client) — a flooding client is dropped.+const ACTION_RATES = { fish: 6, consume: 6, equip: 30 };+// Spatial voice signaling. The room only relays SDP/ICE between two peers (the// audio itself flows peer-to-peer over WebRTC), so the cap just has to clear a// connection handshake's burst of candidates without letting a client flood the@@ -182,6 +200,10 @@ export class WalkRoom extends Room {this.maxClients = MAX_CLIENTS_PER_ROOM;this._moveCounters = new Map(); // sessionId → { windowStart, count }this._chatCooldowns = new Map();+ // Off-schema economy: sessionId → runtime profile (pack/purse/skills + the+ // stable persistence id + per-action cooldowns). Never synced to peers.+ this.econ = new Map();+ this._actionCounters = new Map(); // sessionId → { [action]: { windowStart, count } }}async onCreate(options) {@@ -225,6 +247,12 @@ export class WalkRoom extends Room {this.onMessage('remove', (client, payload) => this._handleRemove(client, payload));this.onMessage('voice-state', (client, payload) => this._handleVoiceState(client, payload));this.onMessage('voice-signal', (client, payload) => this._handleVoiceSignal(client, payload));+ // Economy & activities (off-schema). The owning client drives these and+ // receives the authoritative result via profile/inv/xpgain/levelup/notice.+ this.onMessage('fish', (client) => this._handleFish(client));+ this.onMessage('equip', (client, payload) => this._handleEquip(client, payload));+ this.onMessage('consume', (client, payload) => this._handleConsume(client, payload));+ this.onMessage('profileReq', (client) => this._sendProfile(client));this._emoteCooldowns = new Map();this._editCounters = new Map(); // sessionId → { windowStart, count }this._voiceCounters = new Map(); // sessionId → { windowStart, count }@@ -271,7 +299,7 @@ export class WalkRoom extends Room {}}- onJoin(client, options) {+ async onJoin(client, options) {const name = clean(options?.name, 24) || `guest-${client.sessionId.slice(0, 4)}`;const player = new Player();player.id = client.sessionId;@@ -301,6 +329,21 @@ export class WalkRoom extends Room {socialHub.register(accountUid, client, this.state.coinName || 'Mainland');}+ // Economy profile (off-schema). Keyed to a stable account: the wallet verified+ // in onAuth when the platform gate is on, else a client-persisted guest id, so+ // a player's pack/purse/skills survive a disconnect and follow them between+ // coin worlds. Hydrate the durable record before the synchronous load so a+ // returning player on a fresh process isn't reset to the starter kit.+ const playerId = clean(client.userData?.account, 80) || clean(options?.pid, 80) || client.sessionId;+ try { await hydratePlayer(playerId); } catch { /* memory-only fallback */ }+ // A slower-arriving leave could fire while we awaited; bail if so.+ if (!this.state.players.has(client.sessionId)) return;+ const saved = loadPlayer(playerId);+ const profile = restoreProfile(saved?.profile, playerId);+ profile.cd = { fish: 0, consume: 0 }; // per-action cooldown clocks (runtime only)+ this.econ.set(client.sessionId, profile);+ this._sendProfile(client);+const tierTag = this.state.tier === 'holders' ? ' tier=holders' : '';console.log(`[walk_world ${this.roomId} coin=${this.state.coin || 'mainland'}${tierTag}] +join ${client.sessionId} ${name} (n=${this.state.players.size})`,@@ -309,12 +352,21 @@ export class WalkRoom extends Room {onLeave(client) {if (client.userData?.accountUid) socialHub.unregister(client.userData.accountUid, client);+ // Persist the final economy state and arm a durable flush so progress survives+ // the disconnect and the room being torn down when the last player leaves.+ const profile = this.econ.get(client.sessionId);+ if (profile) {+ this._persistEcon(client.sessionId);+ if (profile.playerId) { try { flushPlayer(profile.playerId); } catch { /* best-effort */ } }+ this.econ.delete(client.sessionId);+ }this.state.players.delete(client.sessionId);this._moveCounters.delete(client.sessionId);this._chatCooldowns.delete(client.sessionId);this._editCounters?.delete(client.sessionId);this._emoteCooldowns?.delete(client.sessionId);this._voiceCounters?.delete(client.sessionId);+ this._actionCounters.delete(client.sessionId);console.log(`[walk_world ${this.roomId}] -leave ${client.sessionId} (n=${this.state.players.size})`,);@@ -330,6 +382,13 @@ export class WalkRoom extends Room {} catch (err) {console.warn(`[walk_world ${this.roomId}] final flush failed:`, err?.message);}+ // Flush any economy profiles still resident (a redeploy can dispose a room+ // with players mid-session) so no progression is lost between the last+ // change and the room going away.+ try {+ await Promise.allSettled([...this.econ.values()]+ .map((p) => p.playerId && flushPlayer(p.playerId)).filter(Boolean));+ } catch { /* best-effort */ }console.log(`[walk_world ${this.roomId}] disposed`);}@@ -466,6 +525,153 @@ export class WalkRoom extends Room {return bucket.count <= VOICE_SIGNALS_PER_SEC_LIMIT;}+ // --- Economy & activities ------------------------------------------------++ // Send the owning client its full economy snapshot (purse, vitals, pack,+ // hotbar, per-skill level + bar boundaries). Sent on join and on demand.+ _sendProfile(client) {+ const profile = this.econ.get(client.sessionId);+ if (!profile) return;+ client.send('profile', profileSnapshot(profile));+ }++ // Send just the mutable economy slice after a change the client can't infer+ // (a catch, an eat, a purse change) — lighter than a full profile resend.+ _sendInv(client, profile) {+ client.send('inv', {+ 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,+ gold: profile.gold,+ hp: profile.hp,+ maxHp: profile.maxHp,+ });+ }++ // Grant XP and tell the earner: the gain (for the float), their new cumulative+ // XP + level boundaries (for an exact bar), and a level-up when one is crossed.+ _grantXp(client, profile, skill, amount) {+ const res = grantXp(profile, skill, amount);+ if (!res) return;+ client.send('xpgain', {+ skill: res.skill, amount: res.amount, xp: res.xp,+ level: res.level, levelXp: res.levelXp, nextXp: res.nextXp,+ });+ if (res.leveledUp) client.send('levelup', { skill: res.skill, level: res.level });+ }++ // Cast a line. Validates (rod on the active slot, beside a pond, off cooldown,+ // room in the pack) then rolls a catch against fishing skill + pond quality.+ // Every cast arms the per-cast cooldown so casting has cadence on the real+ // clock; the client renders the line/bobber while the result rides back here.+ _handleFish(client) {+ const player = this.state.players.get(client.sessionId);+ const profile = this.econ.get(client.sessionId);+ if (!player || !profile) return;+ if (!this._actionOk(client.sessionId, 'fish')) return;++ const now = Date.now();+ if (now < profile.cd.fish) return; // still reeling in the previous cast++ const active = profile.hotbar[profile.activeSlot];+ if (!active || active.item !== 'rod') {+ client.send('notice', { kind: 'tool', text: 'Equip a fishing rod to cast.' });+ return;+ }+ const spot = fishingSpotInRange(player.x, player.z);+ if (!spot) {+ client.send('notice', { kind: 'fish', text: 'Move next to the water to cast.' });+ return;+ }+ if (!hasRoomFor(profile, 'fish')) {+ client.send('notice', { kind: 'full', text: 'Your inventory is full.' });+ return;+ }++ profile.cd.fish = now + FISH_COOLDOWN_MS;+ const lvl = profile.levels.fishing || 1;+ const quality = spot.quality || 1;++ if (Math.random() < fishCatchChance(lvl, quality)) {+ const want = 1 + (Math.random() < fishDoubleChance(lvl, quality) ? 1 : 0);+ const leftover = addItem(profile, 'fish', want);+ const caught = want - leftover;+ if (caught <= 0) {+ client.send('notice', { kind: 'full', text: 'Your inventory is full.' });+ return;+ }+ const xp = Math.round((10 + Math.floor(Math.random() * 6) + lvl * 0.3) * quality) * caught;+ this._grantXp(client, profile, 'fishing', xp);+ this._sendInv(client, profile);+ client.send('notice', { kind: 'fish', caught, text: caught > 1 ? `Caught ${caught} ${itemLabel('fish').toLowerCase()}!` : `Caught a ${itemLabel('fish').toLowerCase()}.` });+ } else {+ this._grantXp(client, profile, 'fishing', 2);+ client.send('notice', { kind: 'fish', caught: 0, text: 'The fish got away.' });+ }+ this._persistEcon(client.sessionId);+ }++ // Select a hotbar slot (what the player is "holding"). -1 clears the hand.+ _handleEquip(client, payload) {+ const profile = this.econ.get(client.sessionId);+ if (!profile) return;+ if (!this._actionOk(client.sessionId, 'equip')) return;+ const i = payload?.slot | 0;+ if (i < -1 || i >= HOTBAR_SIZE) return;+ profile.activeSlot = i;+ this._sendInv(client, profile);+ }++ // Eat an edible from a referenced slot, healing scaled by cooking level.+ _handleConsume(client, payload) {+ const profile = this.econ.get(client.sessionId);+ if (!profile) return;+ if (!this._actionOk(client.sessionId, 'consume')) return;+ const now = Date.now();+ if (now < profile.cd.consume) return;+ const slot = resolveSlot(profile, payload?.slot);+ if (!slot) return;+ const res = consumeSlot(profile, slot);+ if (!res.ok) {+ const text = res.reason === 'full' ? 'You’re already at full health.' : 'That can’t be eaten.';+ client.send('notice', { kind: 'eat', text });+ return;+ }+ profile.cd.consume = now + CONSUME_COOLDOWN_MS;+ this._sendInv(client, profile);+ client.send('notice', { kind: 'eat', text: `+${res.gained} HP.` });+ this._persistEcon(client.sessionId);+ }++ // Write this session's economy profile through to the account-keyed store,+ // merging onto any existing record so non-economy fields (e.g. a /game profile+ // for the same account) are preserved. Synchronous + debounced like GameRoom.+ _persistEcon(sessionId) {+ const profile = this.econ.get(sessionId);+ if (!profile || !profile.playerId) return;+ const player = this.state.players.get(sessionId);+ const prev = loadPlayer(profile.playerId) || {};+ savePlayer(profile.playerId, {+ ...prev,+ name: player?.name || prev.name,+ gold: profile.gold,+ profile: serializeProfile(profile),+ });+ }++ // Per-action sliding-window rate limit (messages/sec/client). A flooding client+ // is silently dropped for the offending action; legitimate cadence passes.+ _actionOk(sessionId, action) {+ const limit = ACTION_RATES[action] || 10;+ const now = Date.now();+ let buckets = this._actionCounters.get(sessionId);+ if (!buckets) { buckets = {}; this._actionCounters.set(sessionId, buckets); }+ let b = buckets[action];+ if (!b || now - b.windowStart > 1000) { b = { windowStart: now, count: 0 }; buckets[action] = b; }+ b.count++;+ return b.count <= limit;+ }+// Validate a {x,y,z} grid cell from a place/remove message. Returns the packed// key string when the cell is a legal, in-bounds integer coordinate, else null._cellKey(payload) {diff --git a/multiplayer/src/world-features.js b/multiplayer/src/world-features.jsnew file mode 100644index 000000000..adafbe7f8--- /dev/null+++ b/multiplayer/src/world-features.js@@ -0,0 +1,49 @@+// Shared world features for the /play coin worlds.+//+// /play is a free-roam disc (radius ~60m), not the tile grid /game uses, so the+// spatial activities that /game anchors to map tiles (fishing spots, cooking pits,+// gather nodes) are re-anchored here to fixed positions in continuous world space.+//+// This module is the ONE source of truth for those positions, imported by BOTH the+// server (WalkRoom — validates "are you actually beside the water?") and the client+// (coincommunities/play-systems — renders the pond and gates the Cast button), so+// the playable world and the authoritative world can never drift apart. Coordinates+// are world metres in the XZ plane; the ground sits at y = 0.+//+// Every coin world shares this layout, so a player who learns where the ponds are+// in one community knows where they are in all of them. Spots avoid the spawn ring,+// the totem (0,0,-12) and the trading screen (0,0,-30) so they never overlap the+// landmarks already in the scene.++// Fishing ponds. `r` is the water radius; `quality` scales catch rate + double-haul+// odds (richer water fishes better), matching /game's per-spot quality multiplier.+export const FISHING_SPOTS = [+ { id: 'pond-east', x: 30, z: 8, r: 5.5, quality: 1 },+ { id: 'pond-west', x: -28, z: 16, r: 4.6, quality: 1.4 },+];++// How far BEYOND a pond's water edge a player may stand and still cast — you fish+// from the bank, not from the middle of the water. Generous enough that the Cast+// button feels reliable as you walk up, tight enough that it's clearly "at" the pond.+export const FISH_REACH = 3.4;++// Distance from (x,z) to the nearest castable shore of a pond. Returns the spot and+// the gap (0 when already in range) so callers can both gate the action and show a+// "walk a little closer" hint. Null when no pond is within reach.+export function nearestFishingSpot(x, z) {+ let best = null;+ for (const spot of FISHING_SPOTS) {+ const d = Math.hypot(x - spot.x, z - spot.z);+ const gap = d - (spot.r + FISH_REACH);+ if (!best || gap < best.gap) best = { spot, gap, dist: d };+ }+ return best;+}++// Server-side gate: is the player standing close enough to a pond to cast? Returns+// the spot (with its quality) or null. The single check both the server trusts and+// the client mirrors for the button — same function, no drift.+export function fishingSpotInRange(x, z) {+ const near = nearestFishingSpot(x, z);+ return near && near.gap <= 0 ? near.spot : null;+}diff --git a/scripts/_baseline.mjs b/scripts/_baseline.mjsdeleted file mode 100644index 3fa36a32e..000000000--- a/scripts/_baseline.mjs+++ /dev/null@@ -1,15 +0,0 @@-import puppeteer from 'puppeteer';-const BASE='http://localhost:3000';-const isDevNoise=(t)=>/\[vite\]/i.test(t)||/websocket/i.test(t)||/app\.github\.dev/i.test(t)||/Failed to load resource/i.test(t);-const b=await puppeteer.launch({headless:'new',args:['--enable-unsafe-swiftshader','--ignore-gpu-blocklist','--no-sandbox']});-const p=await b.newPage();-const errs=[];-p.on('console',m=>{if(m.type()==='error'&&!isDevNoise(m.text()))errs.push(m.text());});-p.on('pageerror',e=>{if(!isDevNoise(e.message))errs.push('pageerror: '+e.message);});-await p.goto(BASE+'/features',{waitUntil:'networkidle2',timeout:60000}).catch(()=>{});-await new Promise(r=>setTimeout(r,6000));-console.log('companion present with OFF:', !!(await p.$('.walk-companion-canvas')));-console.log('meshopt errors on BASELINE /features (companion OFF):', errs.filter(e=>/setMeshoptDecoder/i.test(e)).length);-console.log('total non-noise errors:', errs.length);-errs.slice(0,6).forEach(e=>console.log(' -',e.slice(0,90)));-await b.close();diff --git a/scripts/_verify-walk-companion.mjs b/scripts/_verify-walk-companion.mjsdeleted file mode 100644index d1227d407..000000000--- a/scripts/_verify-walk-companion.mjs+++ /dev/null@@ -1,141 +0,0 @@-// Self-contained verification harness for the Walk Companion-// (src/walk-companion.js). Spawns its own Vite dev server on an isolated port,-// waits for it to answer, drives it with headless Chromium (puppeteer), then-// tears the server down. Bounded server lifetime avoids fighting other work in-// this shared workspace. Asserts the companion mounts on a standard nav page-// with ?walk=1, the nav toggle reflects state, the avatar canvas renders, state-// persists across a navigation, and the disable button removes it — with zero-// real console/page errors.-import { spawn } from 'node:child_process';-import puppeteer from 'puppeteer';--const PORT = Number(process.env.PORT || 3123);-const BASE = `http://localhost:${PORT}`;-const sleep = (ms) => new Promise((r) => setTimeout(r, ms));-const fails = [];-const ok = (cond, msg) => {- console.log(`${cond ? '✓' : '✗'} ${msg}`);- if (!cond) fails.push(msg);-};--// Dev-only noise absent in production, plus a pre-existing page error (a-// meshopt-compressed avatar element on the marketing pages is loaded by another-// part of the app without a decoder — verified present with the companion OFF,-// so out of scope here; the companion's own loader sets the decoder).-const isDevNoise = (t) =>- /\[vite\]/i.test(t) ||- /websocket/i.test(t) ||- /app\.github\.dev/i.test(t) ||- /Failed to load resource/i.test(t) ||- /setMeshoptDecoder must be called/i.test(t);--// ── Boot an isolated dev server ─────────────────────────────────────────────-const server = spawn('npx', ['vite', '--port', String(PORT), '--strictPort'], {- cwd: process.cwd(),- stdio: ['ignore', 'pipe', 'pipe'],- env: process.env,-});-let serverLog = '';-server.stdout.on('data', (d) => (serverLog += d));-server.stderr.on('data', (d) => (serverLog += d));--async function waitForServer(timeoutMs) {- const start = Date.now();- while (Date.now() - start < timeoutMs) {- try {- const r = await fetch(`${BASE}/nav.js`);- if (r.ok) return true;- } catch {- /* not up yet */- }- await sleep(1000);- }- return false;-}--function shutdown(code) {- try {- server.kill('SIGTERM');- } catch {- /* ignore */- }- process.exit(code);-}--const up = await waitForServer(90000);-if (!up) {- console.log('✗ dev server did not become ready in 90s');- console.log(serverLog.split('\n').slice(-12).join('\n'));- shutdown(1);-}--const browser = await puppeteer.launch({- headless: 'new',- args: ['--enable-unsafe-swiftshader', '--ignore-gpu-blocklist', '--no-sandbox'],-});-const page = await browser.newPage();-const consoleErrors = [];-page.on('console', (m) => {- if (m.type() === 'error' && !isDevNoise(m.text())) consoleErrors.push(m.text());-});-page.on('pageerror', (e) => {- if (!isDevNoise(e.message)) consoleErrors.push(`pageerror: ${e.message}`);-});-const attr = (sel, name) =>- page.$eval(sel, (el, n) => el.getAttribute(n), name).catch(() => null);--try {- // Pre-warm: first load streams three.js unbundled in dev (optimizeDeps is- // disabled by a pre-existing dep issue), so give the first mount room.- await page.goto(`${BASE}/features?walk=1`, { waitUntil: 'domcontentloaded' });- const canvas = await page.waitForSelector('.walk-companion-canvas', { timeout: 60000 }).catch(() => null);- ok(!!canvas, 'companion canvas mounts with ?walk=1 on /features');-- ok(!!(await page.$('#home-nav-walk')), 'nav Walk toggle button present');- ok((await attr('#home-nav-walk', 'aria-pressed')) === 'true', 'toggle aria-pressed=true when enabled');-- const dims = canvas ? await canvas.evaluate((c) => ({ w: c.width, h: c.height })) : { w: 0, h: 0 };- ok(dims.w > 0 && dims.h > 0, `canvas has render dimensions (${dims.w}x${dims.h})`);-- await sleep(2500);- const bubble = await page.$eval('.walk-companion-bubble', (b) => b.textContent?.trim() || '').catch(() => '');- ok(bubble.length > 0, `context greeting shown ("${bubble.slice(0, 42)}")`);-- ok(- await page.evaluate(() => !!(window.__walkCompanion && typeof window.__walkCompanion.toggle === 'function')),- 'window.__walkCompanion API exposed',- );- ok(- (await page.evaluate(() => localStorage.getItem('walk:companion:enabled'))) === '1',- 'enabled flag persisted to localStorage',- );-- // Persistence across a navigation (three is now cached → fast).- await page.goto(`${BASE}/pricing`, { waitUntil: 'domcontentloaded' });- ok(- !!(await page.waitForSelector('.walk-companion-canvas', { timeout: 30000 }).catch(() => null)),- 'companion re-mounts on /pricing without ?walk param — persistence works',- );-- // Disable button removes it and flips the flag.- const closeBtn = await page.$('.walk-companion-close');- ok(!!closeBtn, 'disable (×) button present');- if (closeBtn) {- await closeBtn.click();- await sleep(500);- ok((await page.$('.walk-companion-canvas')) === null, 'disable button removes the companion');- ok(- (await page.evaluate(() => localStorage.getItem('walk:companion:enabled'))) === '0',- 'disable sets enabled flag to 0',- );- ok((await attr('#home-nav-walk', 'aria-pressed')) === 'false', 'nav toggle reflects disabled state');- }-- ok(consoleErrors.length === 0, `no real console errors (${consoleErrors.length})`);- consoleErrors.slice(0, 10).forEach((e) => console.log(' →', e));-} finally {- await browser.close();-}--console.log(fails.length ? `\nFAILED (${fails.length})` : '\nALL PASS');-shutdown(fails.length ? 1 : 0);diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex c48ba2341..3d5054d83 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -37,6 +37,7 @@ import { VoiceChat, voiceSupported } from './voice-chat.js';import { requestHolderPass, signInWithX, ensureSolanaWallet, relinkSolanaWallet, getSession } from '../community/town-auth.js';import { ensurePlayAccess } from './play-gate.js';import { clearStoredPass, fetchPlayConfig, signInToPlay, loadStoredPass, storePass } from './play-auth.js';+import { PlaySystems } from './play-systems.js';const WORLD_RADIUS = 58; // a touch inside the server's 60m clampconst MOVE_SPEED = 4.2;@@ -746,6 +747,23 @@ export class CoinCommunities {this.net.on('editReject', ({ reason }) => this._onEditReject(reason));// Durability flag for this world's build — drives the HUD "Saved" badge.this.net.on('persistent', (durable) => { if (this.net?.status === 'online') this.buildHud.setPersistent(durable); });++ // Game systems (economy + activities). The server streams this player's own+ // pack/purse/skills here; PlaySystems renders the HUD, ponds, and cast visual,+ // and re-anchors fishing to fixed world features. Built per-world, torn down on+ // leave() so coins never share a pond or an inventory panel.+ this.playSystems = new PlaySystems({+ scene: this.scene,+ getPlayer: () => ({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z, yaw: this.localYaw, height: this.localHeight || 1.6 }),+ net: this.net,+ ui: this.ui,+ });+ this.net.on('profile', (snap) => this.playSystems?.setProfile(snap));+ this.net.on('inv', (delta) => this.playSystems?.applyInv(delta));+ this.net.on('xpgain', (g) => this.playSystems?.onXpGain(g));+ this.net.on('levelup', (l) => this.playSystems?.onLevelup(l));+ this.net.on('notice', (n) => this.playSystems?.onNotice(n));+this.buildHud.root.hidden = false;await this.net.connect();// Player backed out mid-connect: leave() already tore everything down and@@ -960,6 +978,7 @@ export class CoinCommunities {this._passRefreshTimer = null;if (this.voice) { this.voice.dispose(); this.voice = null; }if (this.net) { this.net.destroy(); this.net = null; }+ if (this.playSystems) { this.playSystems.dispose(); this.playSystems = null; }for (const [, r] of this.remotes) r.dispose();this.remotes.clear();if (this._totem) { this.world.remove(this._totem); this._totem = null; this._coinSpin = null; }@@ -1091,6 +1110,19 @@ export class CoinCommunities {this.buildHud.select(k === '0' ? 9 : Number(k) - 1);return;}+ // F casts a line when standing by a pond (no-op elsewhere). Not while+ // building, where keys drive the block palette.+ if (k === 'f' && !this.buildHud.active) {+ e.preventDefault();+ this.playSystems?.castFish();+ return;+ }+ // 1–6 select a hotbar slot when not building.+ if (!this.buildHud.active && k.length === 1 && k >= '1' && k <= '6') {+ e.preventDefault();+ this.playSystems?.equipSlot(Number(k) - 1);+ return;+ }}this.keys.add(k);});@@ -1398,6 +1430,7 @@ export class CoinCommunities {for (const [, r] of this.remotes) r.tick(dt);this._updateLabels();this._updateVoice();+ this.playSystems?.tick(dt);if (this.net) this.net.sendMove({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z, yaw: this.localYaw, motion: this.motion });}this._tickEnv(dt);diff --git a/src/game/community-net.js b/src/game/community-net.jsindex 7a96be056..e13c9dbfe 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -14,6 +14,19 @@ import { WalkState } from '../../multiplayer/src/schemas.js';const ROOM_NAME = 'walk_world';const RECONNECT_BASE_MS = 3000;++// Stable persistence id for the off-schema economy (pack/purse/skills). When the+// player is signed in we key on their wallet; otherwise we mint and persist a guest+// id so progress survives a refresh on the same device. The server prefers the+// wallet it verified itself, so this only takes effect on un-gated/dev deploys.+function persistedPid(account) {+ if (account) return account;+ try {+ let id = localStorage.getItem('cc-pid');+ if (!id) { id = 'guest-' + Math.random().toString(36).slice(2, 12); localStorage.setItem('cc-pid', id); }+ return id;+ } catch { return ''; }+}const RECONNECT_MAX_MS = 60_000;const MAX_RECONNECT_ATTEMPTS = 6;const SEND_HZ = 15;@@ -69,6 +82,8 @@ export class CommunityNet {// refuses with a play_pass_* error. Sent for all tiers, not just holders.this.playPass = opts.playPass || '';this.account = opts.account || '';+ // Stable economy persistence key (wallet when signed in, else a guest id).+ this.pid = persistedPid(this.account);this.url = opts.url || defaultServerUrl();this.client = null;@@ -94,6 +109,12 @@ export class CommunityNet {blockRemove: new Set(), // (key) — a voxel was brokeneditReject: new Set(), // ({reason}) — the server refused one of our editspersistent: new Set(), // (bool) — whether this world's build is durably saved+ // Off-schema economy (private to this player; delivered as targeted messages).+ profile: new Set(), // (snapshot) — full purse/pack/skills on join + on demand+ inv: new Set(), // ({inv, hotbar, activeSlot, gold, hp, maxHp}) — economy delta+ xpgain: new Set(), // ({skill, amount, xp, level, levelXp, nextXp})+ levelup: new Set(), // ({skill, level})+ notice: new Set(), // ({kind, text, ...}) — activity result toast (fish/eat/tool/full)};this.ping = null; // smoothed RTT in ms, null until the first echothis._pingSentAt = 0; // perf-clock stamp of the last move awaiting an echo@@ -165,6 +186,9 @@ export class CommunityNet {// when it is. The verified wallet rides inside the signed pass; the server// binds it as the account id, so we never trust a raw `account` option.playPass: this.playPass,+ // Stable persistence key for the off-schema economy (used only when the+ // server hasn't verified a wallet account of its own — i.e. un-gated/dev).+ pid: this.pid,};// Holder worlds require a signed pass the server verifies in onAuth; carry// it (and the floor it gated on, for the seed room's HUD) only for holders.@@ -186,6 +210,13 @@ export class CommunityNet {// The server replies here when it refuses one of our place/break edits// (budget full, rate limited, …) so the HUD can explain the no-op.this.room.onMessage('edit-reject', (msg) => this._emit('editReject', msg || {}));+ // Off-schema economy: the server streams this player's own pack/purse/skills+ // here (peers never see it). Drives the HUD, inventory, hotbar and toasts.+ this.room.onMessage('profile', (msg) => this._emit('profile', msg || {}));+ this.room.onMessage('inv', (msg) => this._emit('inv', msg || {}));+ this.room.onMessage('xpgain', (msg) => this._emit('xpgain', msg || {}));+ this.room.onMessage('levelup', (msg) => this._emit('levelup', msg || {}));+ this.room.onMessage('notice', (msg) => this._emit('notice', msg || {}));const $ = getStateCallbacks(this.room);const $state = $(this.room.state);@@ -322,6 +353,12 @@ export class CommunityNet {setVoiceActive(on) { this.room?.send('voice-state', { on: !!on }); }rename(name) { this.name = name; this.room?.send('rename', { name }); }setAvatar(avatar, agent) { this.avatar = avatar; this.room?.send('avatar', { avatar, agent }); }+ // Activities & economy. Server-authoritative: these only request the action; the+ // result arrives via the profile/inv/xpgain/levelup/notice events above.+ fish() { this.room?.send('fish'); }+ equip(slot) { this.room?.send('equip', { slot }); }+ consume(ref) { this.room?.send('consume', { slot: ref }); }+ requestProfile() { this.room?.send('profileReq'); }// Update the stored play pass so the next reconnect (after a drop) uses the// refreshed credential. Does not affect the live session — the server already// authenticated this connection; the new pass is only needed for re-joins.diff --git a/src/game/game-net.js b/src/game/game-net.jsindex 217133646..614fbedfe 100644--- a/src/game/game-net.js+++ b/src/game/game-net.js@@ -216,6 +216,7 @@ export class GameNet {room.onMessage('xpgain', (g) => this._emit('xpgain', g));room.onMessage('levelup', (l) => this._emit('levelup', l));room.onMessage('died', (d) => this._emit('died', d));+ room.onMessage('hit', (h) => this._emit('hit', h));room.onMessage('cooked', (c) => this._emit('cooked', c));room.onMessage('quests', (q) => this._emit('quests', q));room.onMessage('cosmetics', (c) => this._emit('cosmetics', c));diff --git a/src/game/iso-game.js b/src/game/iso-game.jsindex c63604ba6..8c08926c2 100644--- a/src/game/iso-game.js+++ b/src/game/iso-game.js@@ -1177,6 +1177,7 @@ export class IsoGame {this.net.on('structChange', (s, id) => this._structChange(s, id));this.net.on('structRemove', (id) => this._structRemove(id));this.net.on('died', (d) => this._onDied(d));+ this.net.on('hit', (d) => this._onHit(d));this.net.on('quests', (q) => this._onQuests(q));this.net.on('cosmetics', (c) => this._onCosmetics(c));this.net.on('shop', (s) => this._onShop(s));@@ -1674,21 +1675,53 @@ export class IsoGame {group.visible = !mob.dead;group.traverse((o) => { o.userData.mobId = id; }); // resolve raycast hits → attack targetthis.objectGroup.add(group);- this.mobViews.set(id, { group, mob });+ // `body` (the material we tint for the aggro glow) is the first mesh in the+ // stand-in group; `target` drives the per-frame position lerp (Task 03 — mobs+ // chase smoothly, no teleporting between tiles).+ const body = group.children.find((o) => o.isMesh && o.material) || null;+ const v = { group, body, mob, target: new Vector3(w.x, 0, w.z), aggro: false };+ this.mobViews.set(id, v);+ this._setMobAggro(v, !!mob.aggroId);}_mobChange(mob, id) {const v = this.mobViews.get(id);if (!v) return;+ const wasDead = v.mob.dead;v.mob = mob;v.group.visible = !mob.dead;const w = this._tileToWorld(mob.tx, mob.ty);- v.group.position.set(w.x, 0, w.z);+ // Snap on (re)spawn so a mob reappearing at its home tile doesn't glide across+ // the map; otherwise tween toward the new tile each frame.+ if (wasDead && !mob.dead) v.group.position.set(w.x, 0, w.z);+ v.target.set(w.x, 0, w.z);+ this._setMobAggro(v, !!mob.aggroId);}_mobRemove(id) {const v = this.mobViews.get(id);if (v) { this.objectGroup.remove(v.group); this.mobViews.delete(id); }}+ // Per-frame mob position smoothing — mirrors the player view's lerp so a+ // server step (every MOB_MOVE_MS) reads as a glide, never a jump.+ _updateMobs() {+ for (const [, v] of this.mobViews) {+ if (!v.group.visible) continue;+ v.group.position.x += (v.target.x - v.group.position.x) * MOVE_LERP;+ v.group.position.z += (v.target.z - v.group.position.z) * MOVE_LERP;+ }+ }++ // Hostile-engaged cue: a mob chasing a player glows red (emissive). Cleared the+ // moment it drops aggro, so the threat state is always legible at a glance.+ _setMobAggro(v, on) {+ if (v.aggro === on || !v.body?.material) return;+ v.aggro = on;+ const m = v.body.material;+ m.emissive = new Color(on ? 0xff2a1a : 0x000000);+ m.emissiveIntensity = on ? 0.6 : 0;+ m.needsUpdate = true;+ }+// Override seam for T8. Baseline: a colour-coded stand-in per mob kind._buildMobView(mob) {const g = new Group();@@ -2071,6 +2104,58 @@ export class IsoGame {return msg;}+ // A mob landed a contact hit on the local player (Task 03): red screen flash, a+ // HUD toast, and a floating damage number above the avatar. The HP bar already+ // reflects the new value from the synced schema patch.+ _onHit(d) {+ const dmg = Math.max(0, Math.round(Number(d?.dmg) || 0));+ const by = d && d.byKind ? String(d.byKind) : 'an enemy';+ this._toast({ kind: 'combat', text: dmg > 0 ? `-${dmg} HP — ${by}` : `Hit by ${by}` });+ this._hurtFlash();+ if (dmg > 0) this._floatDamage(dmg);+ }++ // Brief red vignette over the viewport on taking damage. Self-removing and+ // never blocks input (pointer-events: none).+ _hurtFlash() {+ const el = document.createElement('div');+ el.setAttribute('aria-hidden', 'true');+ el.style.cssText =+ 'position:fixed;inset:0;z-index:60;pointer-events:none;' ++ 'box-shadow:inset 0 0 120px 40px rgba(220,30,20,0.55);opacity:0;';+ (this.root || document.body).appendChild(el);+ const anim = el.animate(+ [{ opacity: 0 }, { opacity: 1, offset: 0.18 }, { opacity: 0 }],+ { duration: 420, easing: 'ease-out' },+ );+ anim.onfinish = () => el.remove();+ anim.oncancel = () => el.remove();+ }++ // Floating "-N" damage number that rises from the local avatar's nameplate.+ _floatDamage(dmg) {+ const anchor = this._localView()?.label;+ if (!anchor) return;+ const r = anchor.getBoundingClientRect();+ const el = document.createElement('div');+ el.textContent = `-${dmg}`;+ el.setAttribute('aria-hidden', 'true');+ el.style.cssText =+ 'position:fixed;z-index:61;pointer-events:none;font:700 18px/1 system-ui,sans-serif;' ++ 'color:#ff5141;text-shadow:0 1px 2px rgba(0,0,0,0.7);' ++ `left:${Math.round(r.left + r.width / 2)}px;top:${Math.round(r.top)}px;transform:translate(-50%,0);`;+ document.body.appendChild(el);+ const anim = el.animate(+ [+ { transform: 'translate(-50%, 0)', opacity: 1 },+ { transform: 'translate(-50%, -40px)', opacity: 0 },+ ],+ { duration: 900, easing: 'ease-out' },+ );+ anim.onfinish = () => el.remove();+ anim.oncancel = () => el.remove();+ }+// A tap (not a drag) in the world. Two world interactions resolve from a pick:// click an adjacent tombstone to loot it, or click the pond (water / a shore// spot) to cast a line. Camera drags are filtered out before we get here.@@ -3523,6 +3608,7 @@ export class IsoGame {if (this._stepAccum >= this._stepInterval()) { this._stepAccum = 0; this._attemptStep(); }this._serviceInteraction(dt);for (const [, v] of this.players) v.tick(dt);+ this._updateMobs();this._updateCamera();this._updateLabels();this._updateNpcLabels();diff --git a/src/game/items.js b/src/game/items.jsindex 7358e5b31..0da651948 100644--- a/src/game/items.js+++ b/src/game/items.js@@ -13,8 +13,14 @@ export const ITEM_DISPLAY = {sword: { name: 'Sword', glyph: '⚔️' },wood: { name: 'Wood', glyph: '🪵' },stone: { name: 'Stone', glyph: '🪨' },- coal: { name: 'Coal', glyph: '🪨' },- fish: { name: 'Fish', glyph: '🐟' },+ coal: { name: 'Coal', glyph: '⚫' },+ fish: { name: 'Raw fish', glyph: '🐟' },+ cookedFish: { name: 'Cooked fish', glyph: '🍖' },+ bones: { name: 'Bones', glyph: '🦴' },+ hide: { name: 'Beast hide', glyph: '🟫' },+ healthPotion: { name: 'Health potion', glyph: '🧪' },+ dire_wolf: { name: 'Dire Wolf', glyph: '🐺' },+ war_boar: { name: 'War Boar', glyph: '🐗' },gold: { name: 'Gold', glyph: '🪙' },};diff --git a/src/game/play-systems.css b/src/game/play-systems.cssnew file mode 100644index 000000000..7edd882af--- /dev/null+++ b/src/game/play-systems.css@@ -0,0 +1,326 @@+/* Play systems HUD — economy, hotbar, inventory, skills, fishing.+ * Styled to the /play monochrome design tokens (declared on :root in+ * coincommunities.css): dark glass panels, white ink, 4px radii, light as the+ * only accent. Every interactive element has hover / active / focus states. */++#ps-hud {+ position: fixed;+ inset: 0;+ z-index: 23;+ pointer-events: none;+ font-family: inherit;+}+#ps-hud > * { pointer-events: auto; }++#ps-hud button {+ font-family: inherit;+ color: var(--cc-text);+ cursor: pointer;+}+#ps-hud button:focus-visible,+.ps-slot:focus-visible,+.ps-cell:focus-visible {+ outline: 2px solid var(--cc-edge-hi);+ outline-offset: 2px;+}++/* ---- Gold purse (top-left, under the coin banner) ---- */+.ps-gold {+ position: fixed;+ top: 78px;+ left: 14px;+ display: inline-flex;+ align-items: center;+ gap: 7px;+ padding: 6px 12px;+ background: var(--cc-panel);+ border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius);+ box-shadow: var(--cc-shadow);+ backdrop-filter: blur(10px);+ font-variant-numeric: tabular-nums;+}+.ps-gold-coin { font-size: 14px; filter: grayscale(0.2); }+.ps-gold-amt {+ font-size: 13px;+ font-weight: 700;+ letter-spacing: 0.02em;+ color: var(--cc-text);+}++/* ---- Right tool rail (inventory / skills) ---- */+.ps-rail {+ position: fixed;+ right: 14px;+ top: 50%;+ transform: translateY(-50%);+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.ps-rail-btn {+ width: 46px;+ height: 46px;+ display: grid;+ place-items: center;+ font-size: 20px;+ background: var(--cc-panel);+ border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius);+ box-shadow: var(--cc-shadow);+ backdrop-filter: blur(10px);+ filter: grayscale(1);+ transition: transform 0.1s ease, background 0.14s ease, border-color 0.14s ease, filter 0.16s ease;+}+.ps-rail-btn:hover { background: rgba(255, 255, 255, 0.12); border-color: var(--cc-edge-hi); transform: translateX(-3px); filter: grayscale(0); }+.ps-rail-btn:active { transform: translateX(-1px) scale(0.96); }+.ps-rail-btn.is-on { background: #fff; border-color: #fff; filter: grayscale(0); }+.ps-rail-btn.is-on span { filter: none; }++/* ---- Hotbar (bottom-center, above the emote tray) ---- */+.ps-hotbar {+ position: fixed;+ left: 50%;+ bottom: 74px;+ transform: translateX(-50%);+ display: flex;+ gap: 6px;+ padding: 7px;+ background: var(--cc-panel);+ border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius);+ box-shadow: var(--cc-shadow);+ backdrop-filter: blur(10px);+}+.ps-slot {+ position: relative;+ width: 46px;+ height: 46px;+ display: grid;+ place-items: center;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid transparent;+ border-radius: var(--cc-radius-sm);+ transition: transform 0.08s ease, background 0.12s ease, border-color 0.12s ease;+}+.ps-slot:hover { background: rgba(255, 255, 255, 0.12); border-color: var(--cc-edge); transform: translateY(-2px); }+.ps-slot.is-active { border-color: #fff; background: rgba(255, 255, 255, 0.16); box-shadow: var(--cc-glow); }+.ps-slot.is-empty { cursor: default; }+.ps-slot.is-empty:hover { transform: none; background: rgba(255, 255, 255, 0.04); border-color: transparent; }+.ps-slot-glyph { font-size: 22px; line-height: 1; }+.ps-slot-qty {+ position: absolute;+ right: 3px;+ bottom: 2px;+ font-size: 10px;+ font-weight: 700;+ color: var(--cc-text);+ text-shadow: 0 1px 2px #000;+ font-variant-numeric: tabular-nums;+}+.ps-slot-key {+ position: absolute;+ left: 3px;+ top: 1px;+ font-size: 9px;+ color: var(--cc-faint);+}++/* ---- Contextual action button (Cast / Equip rod) ---- */+.ps-action {+ position: fixed;+ left: 50%;+ bottom: 132px;+ transform: translateX(-50%);+ padding: 11px 22px;+ font-size: 13px;+ font-weight: 700;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--cc-ink);+ background: #fff;+ border: 1px solid #fff;+ border-radius: var(--cc-radius);+ box-shadow: var(--cc-shadow), var(--cc-glow);+ transition: transform 0.1s ease, filter 0.12s ease, opacity 0.12s ease;+ animation: ps-rise 0.18s ease both;+}+.ps-action:hover { filter: brightness(0.9); transform: translateX(-50%) translateY(-2px); }+.ps-action:active { transform: translateX(-50%) scale(0.97); }+.ps-action.is-disabled {+ background: var(--cc-panel);+ color: var(--cc-dim);+ border-color: var(--cc-edge);+ box-shadow: var(--cc-shadow);+ cursor: default;+}+.ps-action.is-disabled:hover { filter: none; transform: translateX(-50%); }+@keyframes ps-rise {+ from { opacity: 0; transform: translateX(-50%) translateY(8px); }+ to { opacity: 1; transform: translateX(-50%) translateY(0); }+}++/* ---- Panels (inventory / skills) ---- */+.ps-panel {+ position: fixed;+ right: 72px;+ top: 50%;+ transform: translateY(-50%);+ width: 300px;+ max-width: calc(100vw - 96px);+ max-height: 70vh;+ display: flex;+ flex-direction: column;+ background: var(--cc-panel);+ border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius);+ box-shadow: var(--cc-shadow);+ backdrop-filter: blur(14px);+ animation: ps-panel-in 0.16s ease both;+ overflow: hidden;+}+@keyframes ps-panel-in {+ from { opacity: 0; transform: translateY(-50%) translateX(10px); }+ to { opacity: 1; transform: translateY(-50%) translateX(0); }+}+.ps-panel-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 12px 14px;+ border-bottom: 1px solid var(--cc-edge-soft);+}+.ps-panel-title {+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: var(--cc-text);+}+.ps-x {+ width: 24px;+ height: 24px;+ display: grid;+ place-items: center;+ background: transparent;+ border: 1px solid transparent;+ border-radius: var(--cc-radius-sm);+ color: var(--cc-dim);+ font-size: 12px;+ transition: color 0.12s ease, border-color 0.12s ease, background 0.12s ease;+}+.ps-x:hover { color: var(--cc-text); background: rgba(255, 255, 255, 0.08); border-color: var(--cc-edge); }++/* Inventory grid */+.ps-inv-grid {+ display: grid;+ grid-template-columns: repeat(6, 1fr);+ gap: 5px;+ padding: 12px;+ overflow-y: auto;+}+.ps-cell {+ position: relative;+ aspect-ratio: 1;+ display: grid;+ place-items: center;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid var(--cc-edge-soft);+ border-radius: var(--cc-radius-sm);+ transition: transform 0.08s ease, background 0.12s ease, border-color 0.12s ease;+}+.ps-cell:hover { background: rgba(255, 255, 255, 0.12); border-color: var(--cc-edge); transform: translateY(-2px); }+.ps-cell.is-empty { background: rgba(255, 255, 255, 0.02); border-style: dashed; cursor: default; pointer-events: none; }+.ps-cell-glyph { font-size: 20px; }+.ps-cell-qty {+ position: absolute;+ right: 3px;+ bottom: 2px;+ font-size: 10px;+ font-weight: 700;+ text-shadow: 0 1px 2px #000;+ font-variant-numeric: tabular-nums;+}+.ps-inv-empty {+ grid-column: 1 / -1;+ padding: 26px 12px;+ text-align: center;+ font-size: 12px;+ line-height: 1.5;+ color: var(--cc-dim);+}+.ps-inv-hint {+ padding: 10px 14px;+ border-top: 1px solid var(--cc-edge-soft);+ font-size: 11px;+ color: var(--cc-faint);+}++/* Skills list */+.ps-skills-list { padding: 12px; display: flex; flex-direction: column; gap: 10px; overflow-y: auto; }+.ps-skill { display: flex; align-items: center; gap: 11px; }+.ps-skill-glyph { font-size: 20px; width: 26px; text-align: center; filter: grayscale(0.4); }+.ps-skill-body { flex: 1; min-width: 0; }+.ps-skill-top { display: flex; align-items: baseline; justify-content: space-between; margin-bottom: 4px; }+.ps-skill-name { font-size: 12px; color: var(--cc-text); }+.ps-skill-lvl { font-size: 11px; color: var(--cc-dim); font-variant-numeric: tabular-nums; }+.ps-skill-bar { height: 5px; background: rgba(255, 255, 255, 0.08); border-radius: 99px; overflow: hidden; }+.ps-skill-fill { display: block; height: 100%; background: #fff; border-radius: 99px; transition: width 0.4s ease; }++/* ---- Floating XP + level-up ---- */+.ps-xp-float {+ position: fixed;+ z-index: 40;+ transform: translate(-50%, 0);+ padding: 3px 9px;+ font-size: 12px;+ font-weight: 700;+ color: var(--cc-text);+ background: var(--cc-panel);+ border: 1px solid var(--cc-edge);+ border-radius: 99px;+ box-shadow: var(--cc-shadow);+ pointer-events: none;+ opacity: 0;+ transition: transform 1s ease, opacity 1s ease;+}+.ps-xp-float.is-up { transform: translate(-50%, -42px); opacity: 1; }++.ps-levelup {+ position: fixed;+ left: 50%;+ top: 34%;+ transform: translate(-50%, -50%) scale(0.9);+ z-index: 41;+ padding: 18px 28px;+ text-align: center;+ background: var(--cc-panel);+ border: 1px solid var(--cc-edge-hi);+ border-radius: var(--cc-radius);+ box-shadow: var(--cc-shadow), var(--cc-glow);+ backdrop-filter: blur(14px);+ pointer-events: none;+ opacity: 0;+ transition: transform 0.4s cubic-bezier(0.2, 0.9, 0.3, 1.2), opacity 0.4s ease;+}+.ps-levelup.is-show { transform: translate(-50%, -50%) scale(1); opacity: 1; }+.ps-levelup-mark { font-size: 11px; font-weight: 800; letter-spacing: 0.28em; color: var(--cc-dim); }+.ps-levelup-skill { margin-top: 6px; font-size: 18px; font-weight: 700; color: var(--cc-text); }++/* ---- Pulse (skills button on XP gain) ---- */+@keyframes ps-pulse-k {+ 0% { transform: scale(1); }+ 40% { transform: scale(1.14); }+ 100% { transform: scale(1); }+}+.ps-pulse { animation: ps-pulse-k 0.45s ease; }++/* ---- Responsive: tuck the HUD in on small screens ---- */+@media (max-width: 560px) {+ .ps-gold { top: 70px; left: 10px; }+ .ps-rail { top: auto; bottom: 150px; transform: none; right: 10px; }+ .ps-hotbar { bottom: 70px; gap: 4px; padding: 5px; }+ .ps-slot { width: 40px; height: 40px; }+ .ps-action { bottom: 126px; }+ .ps-panel { right: 10px; left: 10px; width: auto; max-width: none; }+}diff --git a/src/game/play-systems.js b/src/game/play-systems.jsnew file mode 100644index 000000000..73f88ff7e--- /dev/null+++ b/src/game/play-systems.js@@ -0,0 +1,555 @@+// Play systems — the gameplay layer grafted onto the /play coin worlds.+//+// /play is a free-roam social world (coincommunities.js). This module adds the+// game economy and activities ported from /game WITHOUT its low-poly tile world:+// a private inventory + hotbar + purse + skills HUD, and the spatial activities+// re-anchored to fixed features in continuous world space (the first being fishing+// at the ponds defined in multiplayer/src/world-features.js).+//+// Authority lives on the server (WalkRoom): this client renders the pond, plays+// the cast animation, and gates the Cast button, but every catch, XP gain and+// level-up is rolled server-side and streamed back over CommunityNet's+// profile/inv/xpgain/levelup/notice events. Nothing here is simulated locally.+//+// It owns its own DOM (a HUD appended to <body>, styled to the /play monochrome+// design tokens) and its own scene objects (the ponds + the live cast), and tears+// both down cleanly on leave() so switching coins never leaks meshes or panels.++import {+ Group, Mesh, Color, Vector3,+ CircleGeometry, RingGeometry, CylinderGeometry, SphereGeometry,+ MeshStandardMaterial, MeshBasicMaterial,+ BufferGeometry, Line, LineBasicMaterial, Float32BufferAttribute, DoubleSide,+} from 'three';++import { FISHING_SPOTS, nearestFishingSpot } from '../../multiplayer/src/world-features.js';+import { itemDisplay } from './items.js';+import './play-systems.css';++const SKILL_META = {+ fishing: { label: 'Fishing', glyph: '🎣' },+ cooking: { label: 'Cooking', glyph: '🍳' },+ woodcutting: { label: 'Woodcutting', glyph: '🪓' },+ mining: { label: 'Mining', glyph: '⛏️' },+ combat: { label: 'Combat', glyph: '⚔️' },+};+const SKILL_ORDER = ['fishing', 'cooking', 'woodcutting', 'mining', 'combat'];++// Small DOM factory mirroring the one coincommunities-ui.js uses, so the HUD reads+// the same way and stays dependency-free.+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 PlaySystems {+ /**+ * @param {object} opts+ * @param {import('three').Scene} opts.scene+ * @param {() => ({x,y,z,yaw,height})} opts.getPlayer local avatar pose + height+ * @param {object} opts.net CommunityNet instance (fish/equip/consume intents)+ * @param {object} opts.ui CommunityUI instance (toast)+ */+ constructor({ scene, getPlayer, net, ui }) {+ this.scene = scene;+ this.getPlayer = getPlayer;+ this.net = net;+ this.ui = ui;++ this.profile = null; // last full snapshot from the server+ this.skills = {}; // skill -> { level, xp, levelXp, nextXp }+ this.cap = 99;+ this._nearSpot = null; // nearest fishing spot when in range, else null+ this._cast = null; // active cast visual state+ this._t = 0; // animation clock+ this._invOpen = false;+ this._skillsOpen = false;++ this._pondGroup = null;+ this._buildScene();+ this._buildHud();+ }++ // ---------------------------------------------------------------- scene+ _buildScene() {+ const group = new Group();+ group.name = 'play-ponds';+ for (const spot of FISHING_SPOTS) {+ group.add(this._buildPond(spot));+ }+ this.scene.add(group);+ this._pondGroup = group;+ }++ // A pond: a dark reflective water disc, a bright rim, a soft pulsing marker ring+ // (so it reads as an interactable from across the plaza), and a few bank reeds.+ _buildPond(spot) {+ const g = new Group();+ g.position.set(spot.x, 0, spot.z);++ const water = new Mesh(+ new CircleGeometry(spot.r, 48),+ new MeshStandardMaterial({ color: 0x16323f, roughness: 0.18, metalness: 0.65, transparent: true, opacity: 0.94 }),+ );+ water.rotation.x = -Math.PI / 2;+ water.position.y = 0.04;+ water.receiveShadow = true;+ g.add(water);++ const rim = new Mesh(+ new RingGeometry(spot.r, spot.r + 0.45, 48),+ new MeshBasicMaterial({ color: 0xbfeaff, transparent: true, opacity: 0.45, side: DoubleSide }),+ );+ rim.rotation.x = -Math.PI / 2;+ rim.position.y = 0.05;+ g.add(rim);++ // Pulsing interactable marker just inside the rim.+ const marker = new Mesh(+ new RingGeometry(spot.r * 0.62, spot.r * 0.66, 48),+ new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.0, side: DoubleSide }),+ );+ marker.rotation.x = -Math.PI / 2;+ marker.position.y = 0.06;+ g.add(marker);+ g.userData.marker = marker;+ g.userData.spotId = spot.id;++ // Reeds around one arc of the bank.+ const reedMat = new MeshStandardMaterial({ color: 0x2f5d3a, roughness: 0.9 });+ for (let i = 0; i < 7; i++) {+ const a = (i / 7) * Math.PI * 0.9 - Math.PI * 0.2;+ const rr = spot.r + 0.35;+ const h = 0.7 + (i % 3) * 0.25;+ const reed = new Mesh(new CylinderGeometry(0.04, 0.06, h, 5), reedMat);+ reed.position.set(Math.cos(a) * rr, h / 2, Math.sin(a) * rr);+ reed.castShadow = true;+ g.add(reed);+ }+ return g;+ }++ // ---------------------------------------------------------------- HUD DOM+ _buildHud() {+ // Gold purse (top-left, under the coin banner).+ this.goldEl = el('span', { class: 'ps-gold-amt', text: '0' });+ this.gold = el('div', { class: 'ps-gold', title: 'Gold' }, [+ el('span', { class: 'ps-gold-coin', text: '🪙' }), this.goldEl,+ ]);++ // Right tool rail: inventory + skills toggles.+ this.invBtn = el('button', { class: 'ps-rail-btn', title: 'Inventory (backpack)', 'aria-label': 'Inventory', onclick: () => this.toggleInventory() }, [el('span', { text: '🎒' })]);+ this.skillsBtn = el('button', { class: 'ps-rail-btn', title: 'Skills', 'aria-label': 'Skills', onclick: () => this.toggleSkills() }, [el('span', { text: '📊' })]);+ this.rail = el('div', { class: 'ps-rail' }, [this.invBtn, this.skillsBtn]);++ // Hotbar (bottom-center, above the emote tray).+ this.hotbarEl = el('div', { class: 'ps-hotbar', role: 'toolbar', 'aria-label': 'Hotbar' });++ // Contextual action button (Cast / Equip rod), above the hotbar.+ this.actionBtn = el('button', { class: 'ps-action', hidden: true, onclick: () => this._onAction() });++ // Inventory panel.+ this.invGrid = el('div', { class: 'ps-inv-grid' });+ this.invPanel = el('div', { class: 'ps-panel ps-inv', hidden: true, role: 'dialog', 'aria-label': 'Inventory' }, [+ el('div', { class: 'ps-panel-head' }, [+ el('span', { class: 'ps-panel-title', text: 'Backpack' }),+ el('button', { class: 'ps-x', 'aria-label': 'Close', text: '✕', onclick: () => this.toggleInventory(false) }),+ ]),+ this.invGrid,+ el('div', { class: 'ps-inv-hint', text: 'Click a tool to equip it. Click food to eat.' }),+ ]);++ // Skills panel.+ this.skillsList = el('div', { class: 'ps-skills-list' });+ this.skillsPanel = el('div', { class: 'ps-panel ps-skills', hidden: true, role: 'dialog', 'aria-label': 'Skills' }, [+ el('div', { class: 'ps-panel-head' }, [+ el('span', { class: 'ps-panel-title', text: 'Skills' }),+ el('button', { class: 'ps-x', 'aria-label': 'Close', text: '✕', onclick: () => this.toggleSkills(false) }),+ ]),+ this.skillsList,+ ]);++ this.root = el('div', { id: 'ps-hud' }, [+ this.gold, this.rail, this.actionBtn, this.hotbarEl, this.invPanel, this.skillsPanel,+ ]);+ document.body.appendChild(this.root);++ this._renderHotbar();+ this._renderSkills();+ }++ // ---------------------------------------------------------------- data in+ setProfile(snap) {+ if (!snap || typeof snap !== 'object') return;+ this.profile = {+ gold: snap.gold | 0,+ hp: snap.hp | 0,+ maxHp: snap.maxHp | 0,+ inv: Array.isArray(snap.inv) ? snap.inv : [],+ hotbar: Array.isArray(snap.hotbar) ? snap.hotbar : [],+ activeSlot: Number.isFinite(snap.activeSlot) ? snap.activeSlot : -1,+ };+ this.cap = snap.cap || 99;+ this.skills = snap.skills || {};+ this._renderAll();+ }++ // Merge an economy delta (after a catch / eat / equip) onto the cached profile.+ applyInv(delta) {+ if (!this.profile || !delta) return;+ if (Array.isArray(delta.inv)) this.profile.inv = delta.inv;+ if (Array.isArray(delta.hotbar)) this.profile.hotbar = delta.hotbar;+ if (Number.isFinite(delta.activeSlot)) this.profile.activeSlot = delta.activeSlot;+ if (Number.isFinite(delta.gold)) this.profile.gold = delta.gold;+ if (Number.isFinite(delta.hp)) this.profile.hp = delta.hp;+ if (Number.isFinite(delta.maxHp)) this.profile.maxHp = delta.maxHp;+ this._renderHotbar();+ this._renderGold();+ if (this._invOpen) this._renderInventory();+ }++ onXpGain(g) {+ if (!g || !g.skill) return;+ this.skills[g.skill] = { level: g.level, xp: g.xp, levelXp: g.levelXp, nextXp: g.nextXp };+ this._floatXp(g.skill, g.amount);+ if (this._skillsOpen) this._renderSkills();+ this._pulse(this.skillsBtn);+ }++ onLevelup(l) {+ if (!l || !l.skill) return;+ const meta = SKILL_META[l.skill] || { label: l.skill, glyph: '✨' };+ this._celebrate(`${meta.glyph} ${meta.label} level ${l.level}`);+ this.ui?.toast?.(`${meta.label} is now level ${l.level}!`, 'info');+ }++ // Activity result. Fishing notices resolve the live cast (bite vs miss); the rest+ // surface as toasts. `kind` mirrors the server's notice vocabulary.+ onNotice(n) {+ if (!n) return;+ if (n.kind === 'fish' && this._cast && !this._cast.result) {+ this._cast.result = n.caught > 0 ? 'catch' : 'miss';+ }+ const tone = (n.kind === 'full' || n.kind === 'tool') ? 'warn' : 'info';+ if (n.text) this.ui?.toast?.(n.text, tone);+ }++ // ---------------------------------------------------------------- render+ _renderAll() {+ this._renderGold();+ this._renderHotbar();+ this._renderSkills();+ if (this._invOpen) this._renderInventory();+ }++ _renderGold() {+ this.goldEl.textContent = (this.profile?.gold ?? 0).toLocaleString();+ }++ _renderHotbar() {+ this.hotbarEl.replaceChildren();+ const hb = this.profile?.hotbar || [];+ const active = this.profile?.activeSlot ?? -1;+ for (let i = 0; i < (hb.length || 6); i++) {+ const slot = hb[i] || { item: '', qty: 0 };+ const disp = slot.item ? itemDisplay(slot.item) : null;+ const cell = el('button', {+ class: 'ps-slot' + (i === active ? ' is-active' : '') + (slot.item ? '' : ' is-empty'),+ title: disp ? disp.name : 'Empty slot',+ 'aria-label': disp ? `${disp.name}${i === active ? ', equipped' : ''}` : 'Empty slot',+ onclick: () => this.equipSlot(i === active ? -1 : i),+ }, [+ el('span', { class: 'ps-slot-glyph', text: disp ? disp.glyph : '' }),+ slot.qty > 1 ? el('span', { class: 'ps-slot-qty', text: String(slot.qty) }) : null,+ el('span', { class: 'ps-slot-key', text: String(i + 1) }),+ ]);+ this.hotbarEl.appendChild(cell);+ }+ }++ _renderInventory() {+ this.invGrid.replaceChildren();+ const inv = this.profile?.inv || [];+ const filled = inv.filter((s) => s.item).length;+ if (!filled) {+ this.invGrid.appendChild(el('div', { class: 'ps-inv-empty', text: 'Your backpack is empty. Cast a line at a pond to catch your first fish.' }));+ return;+ }+ inv.forEach((slot, i) => {+ if (!slot.item) { this.invGrid.appendChild(el('div', { class: 'ps-cell is-empty' })); return; }+ const disp = itemDisplay(slot.item);+ const cell = el('button', {+ class: 'ps-cell',+ title: disp.name,+ 'aria-label': `${slot.qty} ${disp.name}`,+ onclick: () => this._onInvClick(i, slot.item),+ }, [+ el('span', { class: 'ps-cell-glyph', text: disp.glyph }),+ slot.qty > 1 ? el('span', { class: 'ps-cell-qty', text: String(slot.qty) }) : null,+ ]);+ this.invGrid.appendChild(cell);+ });+ }++ _renderSkills() {+ this.skillsList.replaceChildren();+ for (const skill of SKILL_ORDER) {+ const meta = SKILL_META[skill];+ const s = this.skills[skill] || { level: 1, xp: 0, levelXp: 0, nextXp: null };+ const span = s.nextXp != null ? Math.max(1, s.nextXp - s.levelXp) : 1;+ const into = s.nextXp != null ? Math.max(0, Math.min(span, s.xp - s.levelXp)) : span;+ const pct = Math.round((into / span) * 100);+ const row = el('div', { class: 'ps-skill' }, [+ el('span', { class: 'ps-skill-glyph', text: meta.glyph }),+ el('div', { class: 'ps-skill-body' }, [+ el('div', { class: 'ps-skill-top' }, [+ el('span', { class: 'ps-skill-name', text: meta.label }),+ el('span', { class: 'ps-skill-lvl', text: s.nextXp == null ? `Lv ${s.level} · max` : `Lv ${s.level}` }),+ ]),+ el('div', { class: 'ps-skill-bar' }, [el('span', { class: 'ps-skill-fill', style: `width:${pct}%` })]),+ ]),+ ]);+ this.skillsList.appendChild(row);+ }+ }++ // ---------------------------------------------------------------- actions+ equipSlot(i) {+ this.net?.equip(i);+ // Optimistic so the hotbar feels instant; the server echoes `inv` to confirm.+ if (this.profile) { this.profile.activeSlot = i; this._renderHotbar(); }+ }++ _onInvClick(i, item) {+ // Edible → eat it; otherwise no-op (tools live on the hotbar already).+ const disp = itemDisplay(item);+ if (item === 'cookedFish' || item === 'healthPotion') {+ this.net?.consume({ zone: 'inv', i });+ } else {+ this.ui?.toast?.(`${disp.name} — ${item === 'fish' ? 'cook it at a campfire to make it edible.' : 'nothing to do with this yet.'}`, 'info');+ }+ }++ _onAction() {+ if (!this._nearSpot) return;+ this.castFish();+ }++ // Cast a line. Mirrors the server's preconditions for instant, honest feedback+ // (equip the rod if you're holding something else but own one), then spawns the+ // bobber/line visual and sends the intent. The catch/miss rides back as a notice.+ castFish() {+ if (this._cast) return; // one line in the water at a time+ const near = this._nearSpot;+ if (!near) { this.ui?.toast?.('Move next to a pond to cast.', 'warn'); return; }++ const holding = this._activeItem();+ if (holding !== 'rod') {+ const rodSlot = (this.profile?.hotbar || []).findIndex((s) => s.item === 'rod');+ if (rodSlot >= 0) { this.equipSlot(rodSlot); this.ui?.toast?.('Fishing rod equipped — cast again.', 'info'); return; }+ this.ui?.toast?.('You need a fishing rod to cast.', 'warn');+ return;+ }+ this._spawnCast(near);+ this.net?.fish();+ }++ _activeItem() {+ const hb = this.profile?.hotbar || [];+ const i = this.profile?.activeSlot ?? -1;+ return i >= 0 && hb[i] ? hb[i].item : '';+ }++ toggleInventory(force) {+ this._invOpen = force == null ? !this._invOpen : !!force;+ this.invPanel.hidden = !this._invOpen;+ this.invBtn.classList.toggle('is-on', this._invOpen);+ if (this._invOpen) this._renderInventory();+ }++ toggleSkills(force) {+ this._skillsOpen = force == null ? !this._skillsOpen : !!force;+ this.skillsPanel.hidden = !this._skillsOpen;+ this.skillsBtn.classList.toggle('is-on', this._skillsOpen);+ if (this._skillsOpen) this._renderSkills();+ }++ // ---------------------------------------------------------------- cast visual+ _spawnCast(near) {+ const p = this.getPlayer();+ const spot = near.spot;+ // Land the bobber on the near side of the water, between the angler and centre.+ const dx = p.x - spot.x, dz = p.z - spot.z;+ const dl = Math.hypot(dx, dz) || 1;+ const target = new Vector3(spot.x + (dx / dl) * spot.r * 0.55, 0.06, spot.z + (dz / dl) * spot.r * 0.55);+ const hand = new Vector3(p.x, (p.height || 1.6) * 0.62, p.z);++ const g = new Group();+ const bob = new Mesh(+ new SphereGeometry(0.12, 12, 10),+ new MeshStandardMaterial({ color: 0xffffff, emissive: 0x88bbff, emissiveIntensity: 0.5, roughness: 0.4 }),+ );+ g.add(bob);+ const ring = new Mesh(+ new RingGeometry(0.18, 0.28, 24),+ new MeshBasicMaterial({ color: 0xbfeaff, transparent: true, opacity: 0.0, side: DoubleSide }),+ );+ ring.rotation.x = -Math.PI / 2;+ ring.position.copy(target); ring.position.y = 0.06;+ g.add(ring);+ const lineGeo = new BufferGeometry();+ lineGeo.setAttribute('position', new Float32BufferAttribute([hand.x, hand.y, hand.z, target.x, target.y, target.z], 3));+ const line = new Line(lineGeo, new LineBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.45 }));+ g.add(line);+ this.scene.add(g);++ this._cast = { group: g, bob, ring, line, lineGeo, hand, target, start: this._t, result: null, resolvedAt: 0 };+ }++ _tickCast(dt) {+ const c = this._cast;+ if (!c) return;+ const age = this._t - c.start;+ const p = this.getPlayer();+ const hand = c.hand.set(p.x, (p.height || 1.6) * 0.62, p.z);++ // Fly out (0–0.28s): arc the bobber from hand to target.+ if (age < 0.28) {+ const k = age / 0.28;+ const x = hand.x + (c.target.x - hand.x) * k;+ const z = hand.z + (c.target.z - hand.z) * k;+ const y = hand.y + (c.target.y - hand.y) * k + Math.sin(k * Math.PI) * 1.2;+ c.bob.position.set(x, y, z);+ } else if (!c.result) {+ // Waiting for the bite: gentle bob + a slow ripple.+ c.bob.position.set(c.target.x, c.target.y + Math.sin(age * 4) * 0.05, c.target.z);+ c.ring.material.opacity = 0.25 + Math.sin(age * 4) * 0.12;+ const s = 1 + (age % 1.2);+ c.ring.scale.setScalar(s);+ } else {+ // Resolved.+ if (!c.resolvedAt) {+ c.resolvedAt = this._t;+ if (c.result === 'catch') { c.ring.material.color = new Color(0x9effa6); }+ }+ const ra = this._t - c.resolvedAt;+ if (c.result === 'catch') {+ // Sharp dip then a splash ring out.+ c.bob.position.set(c.target.x, Math.max(-0.1, c.target.y - ra * 1.4), c.target.z);+ c.ring.scale.setScalar(1 + ra * 5);+ c.ring.material.opacity = Math.max(0, 0.5 - ra);+ } else {+ c.bob.position.set(c.target.x, c.target.y + Math.sin(ra * 8) * 0.04, c.target.z);+ c.ring.material.opacity = Math.max(0, 0.25 - ra * 0.6);+ }+ if (ra > 0.6) { this._clearCast(); return; }+ }+ // Keep the line taut between hand and bobber.+ const pos = c.lineGeo.attributes.position;+ pos.setXYZ(0, hand.x, hand.y, hand.z);+ pos.setXYZ(1, c.bob.position.x, c.bob.position.y, c.bob.position.z);+ pos.needsUpdate = true;+ }++ _clearCast() {+ if (!this._cast) return;+ this.scene.remove(this._cast.group);+ this._cast.group.traverse((n) => {+ if (n.isMesh || n.isLine) { n.geometry?.dispose?.(); n.material?.dispose?.(); }+ });+ this._cast = null;+ }++ // ---------------------------------------------------------------- per-frame+ tick(dt) {+ this._t += dt;+ const p = this.getPlayer();++ // Nearest pond + range gate (mirrors the server's fishingSpotInRange).+ const near = nearestFishingSpot(p.x, p.z);+ this._nearSpot = near && near.gap <= 0 ? near : null;+ this._updateAction();++ // Pulse the marker ring of whichever pond is nearest so it reads as live.+ if (this._pondGroup) {+ const glow = 0.18 + Math.sin(this._t * 2) * 0.12;+ const nearId = this._nearSpot?.spot.id;+ this._pondGroup.children.forEach((g) => {+ const m = g.userData.marker;+ if (!m) return;+ m.material.opacity = g.userData.spotId === nearId ? glow + 0.25 : glow;+ });+ }++ this._tickCast(dt);+ }++ _updateAction() {+ const near = this._nearSpot;+ if (!near || this._cast) {+ if (!this.actionBtn.hidden) this.actionBtn.hidden = true;+ return;+ }+ const holding = this._activeItem();+ const hasRod = (this.profile?.hotbar || []).some((s) => s.item === 'rod');+ let label;+ if (holding === 'rod') label = '🎣 Cast line';+ else if (hasRod) label = '🎣 Equip rod';+ else label = '🎣 Need a fishing rod';+ this.actionBtn.textContent = label;+ this.actionBtn.classList.toggle('is-disabled', !hasRod);+ this.actionBtn.hidden = false;+ }++ // ---------------------------------------------------------------- fx+ _floatXp(skill, amount) {+ const meta = SKILL_META[skill] || { glyph: '✨' };+ const chip = el('div', { class: 'ps-xp-float', text: `${meta.glyph} +${amount} XP` });+ const r = this.skillsBtn.getBoundingClientRect();+ chip.style.left = `${r.left + r.width / 2}px`;+ chip.style.top = `${r.top}px`;+ document.body.appendChild(chip);+ requestAnimationFrame(() => chip.classList.add('is-up'));+ setTimeout(() => chip.remove(), 1100);+ }++ _celebrate(text) {+ const card = el('div', { class: 'ps-levelup' }, [+ el('div', { class: 'ps-levelup-mark', text: 'LEVEL UP' }),+ el('div', { class: 'ps-levelup-skill', text }),+ ]);+ document.body.appendChild(card);+ requestAnimationFrame(() => card.classList.add('is-show'));+ setTimeout(() => { card.classList.remove('is-show'); setTimeout(() => card.remove(), 400); }, 2200);+ }++ _pulse(node) {+ if (!node) return;+ node.classList.remove('ps-pulse');+ void node.offsetWidth; // restart the animation+ node.classList.add('ps-pulse');+ }++ // ---------------------------------------------------------------- teardown+ dispose() {+ this._clearCast();+ if (this._pondGroup) {+ this.scene.remove(this._pondGroup);+ this._pondGroup.traverse((n) => {+ if (n.isMesh || n.isLine) { n.geometry?.dispose?.(); const ms = Array.isArray(n.material) ? n.material : [n.material]; ms.forEach((m) => m?.dispose?.()); }+ });+ this._pondGroup = null;+ }+ this.root?.remove();+ document.querySelectorAll('.ps-xp-float, .ps-levelup').forEach((n) => n.remove());+ }+}diff --git a/src/walk-companion.js b/src/walk-companion.jsindex f3d56c404..18f0a1490 100644--- a/src/walk-companion.js+++ b/src/walk-companion.js@@ -310,7 +310,6 @@ class WalkCompanion {this.mounted = true;this._buildDom();- reserveWebGLContext();try {await this._buildScene();@@ -371,10 +370,10 @@ class WalkCompanion {_showError() {// Avatar couldn't load (offline / GLB 404). Don't leave a dead canvas —- // remove the host entirely; the toggle stays available to retry.+ // remove the host entirely; the toggle stays available to retry. The+ // WebGL budget was already released by _teardownScene (called first).if (this.host && this.host.parentNode) this.host.parentNode.removeChild(this.host);this.host = null;- releaseWebGLContext();this.mounted = false;}@@ -388,6 +387,9 @@ class WalkCompanion {renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5));renderer.setSize(CANVAS_W, CANVAS_H, false);this.renderer = renderer;+ // Count this context against the shared budget, paired with the+ // release in _teardownScene so reserve/release always balance.+ reserveWebGLContext();const scene = new Scene();this.scene = scene;