From 7f4b0e0d8438365940d0bde3094256a88d3c8422 Mon Sep 17 00:00:00 2001 From: jwinterm Date: Thu, 22 Oct 2026 15:24:46 -0400 Subject: [PATCH] fix(tavern): align speech, ambient life and default Adventurer --- docs/CHAT_AND_NOSTR.md | 44 +- docs/TAVERN_AND_MULTIPLAYER.md | 26 +- html/js/render/avatarVisuals.js | 16 +- html/js/render/charCustomize.js | 13 +- html/js/render/charSprites.js | 2 +- html/js/render/fancyRenderer.js | 36 +- html/js/render/tavernLife.js | 583 ++++++++++++++++++------- html/js/render/threeRenderer.js | 25 ++ html/tavern.html | 44 +- src/multiplayer/appearance.js | 5 +- src/multiplayer/tavernMap.js | 8 +- src/network/chat/ChatProvider.js | 4 +- src/network/chat/NostrChatProvider.js | 4 +- src/network/chat/SocketChatProvider.js | 4 +- src/network/chatHandler.js | 50 ++- src/network/chatHistoryManager.js | 11 +- src/network/socketHandlers.js | 4 +- src/network/tavernManager.js | 99 ++++- src/scripts/showcase-browser-smoke.js | 196 +++++++-- test/adventurerDefault.test.js | 151 +++++++ test/appearance.test.js | 9 +- test/chatProvider.test.js | 25 ++ test/entitlements.test.js | 6 +- test/identityService.test.js | 4 +- test/tavernBubbleLayout.test.js | 120 +++++ test/tavernChatClient.test.js | 91 ++++ test/tavernLife.test.js | 232 ++++++++++ test/tavernManager.test.js | 3 +- test/tavernSpeech.test.js | 325 ++++++++++++++ test/tavernThreeProjection.test.js | 72 +++ 30 files changed, 1895 insertions(+), 317 deletions(-) create mode 100644 test/adventurerDefault.test.js create mode 100644 test/tavernBubbleLayout.test.js create mode 100644 test/tavernChatClient.test.js create mode 100644 test/tavernLife.test.js create mode 100644 test/tavernSpeech.test.js create mode 100644 test/tavernThreeProjection.test.js diff --git a/docs/CHAT_AND_NOSTR.md b/docs/CHAT_AND_NOSTR.md index 3062075..12ecdd7 100644 --- a/docs/CHAT_AND_NOSTR.md +++ b/docs/CHAT_AND_NOSTR.md @@ -2,7 +2,9 @@ Chat has two layers: local delivery (Socket.IO plus Postgres history) and an optional nostr fan-out that carries the same conversation across servers and into the Smirk ecosystem. Both sit behind one -seam, so callers are identical either way. +seam, so callers are identical either way. Local chat does not require a relay or a wallet. +Smirk can sign messages with the player's Nostr identity; relay transport is configured separately +through `NOSTR_RELAYS` (default `wss://relay.smirk.cash`). Signing does not enable relay fan-out. ## The provider seam @@ -54,12 +56,13 @@ one object is the whole difference between the two identity models. ### Server bridge signer -The server signs every outbound global message with a single key from `NOSTR_BRIDGE_SK` +The server signs ordinary outbound global messages with a single key from `NOSTR_BRIDGE_SK` (`createBridgeSigner`, accepting an `nsec` or 64-hex secret). The player's display name rides in an `['n', name]` tag. This works for every player, including anonymous ones, but on nostr the whole server reads as one account. The bridge pubkey must be accepted by the relay's write policy, either by being a registered npub or by sitting in the relay write allowlist. With no key configured the -signer is `null` and global chat is receive-only. +signer is `null`: ordinary messages still deliver locally but are not bridge-published. Verified +client-signed messages can still publish without a bridge key when relay fan-out is enabled. ### Client per-player signing @@ -88,7 +91,7 @@ client server (ChatHandler) relay login); a valid signature by any other key is rejected with `pubkey-mismatch`. Content is capped at 280 characters. - `ChatHandler.handleSignedChatMessage` runs the sequence: rate limit, resolve the session's npub - from the database, verify, escape, relay. A session with no linked npub is told to sign in with + from the database, verify, check the chat ban, escape, relay. A failed ban lookup refuses delivery. A session with no linked npub is told to sign in with Smirk. The display name comes from `display_name` or `username`, falling back to the first 8 characters of the npub. - `NostrChatProvider.relaySignedEvent` performs local delivery and then `transport.publish(event)` @@ -96,9 +99,9 @@ client server (ChatHandler) relay - `html/js/smirkChatSign.js` is the client helper. It signs through `window.smirk.signNostrEvent` and emits `chat_signed`. Signing is attempted first; on `NOT_AUTHORIZED` it calls `getNostrPublicKey()` once to obtain the nostr scope grant and retries, the same pattern as `SmirkAuth`, so a returning - user sees a single approval. It resolves `false` whenever Smirk is unavailable or declines, and the - caller then falls back to the ordinary unsigned send. The helper is loaded on `tavern.html`, whose - send path tries it before `tavern_chat`. + user sees a single approval. The helper resolves `false` whenever Smirk is unavailable or declines. + The Tavern sends ordinary `tavern_chat` when no signer is available. Once signing is attempted, a + denial or failure shows a notice and sends nothing; it never silently switches to unsigned chat. The server registers the `chat_signed` socket event in `src/network/socketHandlers.js`. @@ -108,10 +111,10 @@ The game publishes each event to every relay in `NOSTR_RELAYS` and lets each rel reject it; there is no per-player routing or allowlist in game code. Reading is the mirror: subscribe to all relays and dedupe by event id. -| Player | Signs as | Reaches | +| Message | Signs as | Reaches | |--------|----------|---------| -| Anonymous | not signed | in-game chat only | -| Signed in with Smirk | own npub | in-game chat plus every relay whose write policy accepts that npub | +| Ordinary message, including anonymous | server bridge key if configured | in-game chat; optional bridge publication when enabled and configured | +| Verified client-signed message | own npub | in-game chat plus every relay whose write policy accepts that npub | A premium subscription also sets the player's entitlement tier, which unlocks cosmetics; see [MONETIZATION.md](MONETIZATION.md). Entitlements are per-pack tier based @@ -141,7 +144,8 @@ Relay admission is configured on the relay side, in the Smirk backend that front are escaped and capped at 200 characters for in-game rendering; the event published to nostr is the client's original, unmodified. - Chat bans are checked against `ChatHistoryManager.isUserChatBanned` before a message is published. - The tavern applies the same rate limiter and ban check before anything reaches global chat. + The tavern and signed path apply the same rate limiter and ban check before anything reaches global + chat. User/ban lookup failures refuse delivery; missing moderation evidence is not an allowed status. - Remote (relay-sourced) messages are escaped with `escapeChatText`, capped at 200 characters, attributed from the `n` tag or the first 8 characters of the author pubkey, and rate limited to `maxRemotePerMin` (120 per minute by default) so a hostile relay cannot flood in-game clients. @@ -152,6 +156,22 @@ Relay admission is configured on the relay side, in the Smirk backend that front - `NostrTransport` degrades to a warning and a no-op if `nostr-tools` or `ws` cannot load, so enabling nostr chat cannot crash the server. +## Tavern speech bubbles + +`chat_broadcast` and `chat_history` populate the log only. Display names and short public IDs are +not avatar identities: duplicate names, prefix collisions and relay posts must never select a speaker. + +After accepted local delivery, a trusted server-only `onLocalDelivery` callback emits `tavern_speech` only to the speaker's Tavern room, +with `{occupantId, text}`. The handle is the exact occupant ID already in that room's snapshots; text +is plain text for the renderer, not HTML. The server captures the current occupant and session before +async work and rechecks them after publishing. Leaving/rejoining or replacing the session suppresses +stale speech. This callback runs once after the local broadcast returns, before optional relay work, +so a pending or refused relay cannot delay or duplicate the bubble. It is never a wire/history field. +The client additionally requires that exact occupant in its current room snapshot. +Ordinary and verified signed sends use this path. Rejected messages, history and remote relay posts +do not produce speech. A bubble proves accepted local delivery, not persistence or relay acceptance: +optional relay failures can be contained after the provider has delivered locally. + ## Configuration | Variable | Meaning | @@ -161,7 +181,7 @@ Relay admission is configured on the relay side, in the Smirk backend that front | `NOSTR_RELAYS` | Comma-separated relay URLs. Default `wss://relay.smirk.cash`. | | `NOSTR_CHAT_TAG` | Shared channel topic. Default `wowngeon-global`. | | `NOSTR_CHAT_KIND` | Event kind. Default `1`. | -| `NOSTR_BRIDGE_SK` | Bridge secret key (`nsec` or 64-hex). Omit for receive-only global chat. | +| `NOSTR_BRIDGE_SK` | Bridge secret key (`nsec` or 64-hex). Omit to disable bridge signing of ordinary messages; client-signed publication is independent. | | `NOSTR_SERVER_ORIGIN` | Value for the `origin` tag on bridge-signed events. Falls back to `SERVER_ID`. | The full server environment template is `src/.env.example`. diff --git a/docs/TAVERN_AND_MULTIPLAYER.md b/docs/TAVERN_AND_MULTIPLAYER.md index e1e4836..591a30b 100644 --- a/docs/TAVERN_AND_MULTIPLAYER.md +++ b/docs/TAVERN_AND_MULTIPLAYER.md @@ -102,9 +102,11 @@ the flat `avatar` field remains as a compatibility shortcut and as the first dis sprite and skin loading. Normalization in `src/multiplayer/appearance.js` is total: an unknown avatar id collapses to -`default`, unknown equipment collapses to `none` per slot, and unknown tints, skin tones, and hair +`char-villager` (Adventurer), including the legacy `default` alias. Unknown equipment collapses to `none` per slot, and unknown tints, skin tones, and hair colors collapse to their defaults. Flat colour avatars carry no equipment or colour detail; 3D model -avatars carry colours but no 2D equipment overlays; character avatars carry both. +avatars carry colours but no 2D equipment overlays; character avatars carry both. The free Adventurer +card is visible in every projection picker. Its topdown sprite does not require a premium environment +pack; switching projection preserves the saved identity and existing pack restrictions. The contract is renderer-agnostic: @@ -224,9 +226,16 @@ governs them. Message text is escaped at publish time because delivery is trusted-escaped and rendered as HTML on the client. -Speech bubbles resolve the speaker from the occupant list **by display name**. The chat provider -publishes a short `publicId`, never the raw socket id, so anything keying bubbles off `socketId` -never fires. +Accepted live speech uses the room-only `tavern_speech` event and the exact occupant handle already +present in its room snapshot. Names, global public IDs, history and remote relay events never identify +a bubble speaker. Local delivery emits the bubble before any pending relay publication completes; +this does not claim relay delivery. Bubbles render literal text above the character, wrap within the +viewport, expire, and are removed when the occupant leaves. See [CHAT_AND_NOSTR.md](CHAT_AND_NOSTR.md). + +Ambient actors follow room semantics: patrons spend most of their time in table seats, with one short +excursion at a time and a shared quiet interval. The waitress follows table-service stops; the +barkeep stays in the connected floor lane behind the counter. Rooms missing suitable furniture +omit these actors. Decorative movement does not alter server player collision or authority. ## Chain ambience @@ -341,9 +350,10 @@ For the isolated, gameplay-only Tavern browser smoke, run `npm run test:showcase `src`. It starts a fresh loopback server and two anonymous browser contexts, with no database, wallet, purchase, or queue/race flow. Mica receives synthetic `roguelike-interior` and `iso-dungeon` pack grants from the source-owned default catalog to prove permitted character drawing and Iso rendering. -Moth receives the catalog's zero-grant snapshot and must retain original-only access. Both balances +Moth receives the catalog's zero-grant snapshot and must retain original-only access. The smoke also submits one local message, checks its literal chat line and exact speaker bubble in +both views, and verifies the zero-grant Adventurer picker and real character draw path. Both balances remain zero; neither fixture represents a purchase or production entitlement. Screenshots and a JSON result go to a unique directory under `~/Build/wowngeon/showcase-browser`; pass `-- --output-root ` to choose another output root. The browser blocks requests outside its loopback server. A local browser route injects a 404 -for the generated Wownero skin sheet so its readable failed-asset state is checked consistently, -whether or not that ignored asset is present on the workstation. +for each of the three registered generated skin sheets so their failed-asset state is checked +consistently, whether or not these ignored assets are present on the workstation. diff --git a/html/js/render/avatarVisuals.js b/html/js/render/avatarVisuals.js index 0ba3058..9682c37 100644 --- a/html/js/render/avatarVisuals.js +++ b/html/js/render/avatarVisuals.js @@ -6,7 +6,7 @@ var RK = root.RK = root.RK || {}; var DEFAULT_EQUIPMENT = { body: 'none', head: 'none', shield: 'none', weapon: 'none' }; - var DEFAULT_APPEARANCE = { avatar: 'default', tint: 'none', equipment: DEFAULT_EQUIPMENT }; + var DEFAULT_APPEARANCE = { avatar: 'char-villager', tint: 'none', equipment: DEFAULT_EQUIPMENT }; var loading = {}; function normalize(appearance) { @@ -20,7 +20,8 @@ return (skin && skin.pack) || 'generated-skins'; } if (kind === 'model3d') return 'kenney-3d-characters'; - return 'roguelike-interior'; + // Built-in characters and color identities are free, independent of environment packs. + return null; } function kindFor(appearance, projection) { @@ -88,17 +89,6 @@ opts = opts || {}; var ap = normalize(appearance); var projection = opts.projection || 'legacy-rot'; - // A player who never customized arrives as avatar 'default' (or an unknown id), which is not - // a char/skin/model and would fall to the grey circle. On the TAVERN canvas path, coerce it - // to a real Kenney character so nobody is a grey dot in a room of people. But NOT on - // 'legacy-rot' (the single-player dungeon): there RenderEngine falls back to the original @ - // hero TILE, which is what an un-customized player expects (grey circle was a canvas-only - // problem). iso/3d keep their own fallbacks below. - if (ap && projection !== 'iso' && projection !== '3d' && projection !== 'legacy-rot') { - var a = ap.avatar; - var known = (RK.isChar && RK.isChar(a)) || (RK.isSkin && RK.isSkin(a)) || (a && /^kenney-/.test(a)); - if (!known) ap = Object.assign({}, ap, { avatar: 'char-villager' }); - } var kind = kindFor(ap, projection); var pack = packFor(ap, kind, projection); var visual = { diff --git a/html/js/render/charCustomize.js b/html/js/render/charCustomize.js index a997e51..9018242 100644 --- a/html/js/render/charCustomize.js +++ b/html/js/render/charCustomize.js @@ -28,12 +28,13 @@ function baseAppearances() { var list = [ - { id: 'default', label: 'Adventurer', kind: 'color', color: '#9aa4b2' }, + { id: 'char-villager', label: 'Adventurer', kind: 'char' }, { id: 'green', label: 'Verdant', kind: 'color', color: '#3fb950' }, { id: 'amber', label: 'Amber', kind: 'color', color: '#d29922' }, { id: 'red', label: 'Crimson', kind: 'color', color: '#f85149' } ]; for (var cid in (RK.CHARS || {})) { + if (cid === 'char-villager') continue; var c = RK.CHARS[cid]; list.push({ id: cid, label: c.label || cid, kind: 'char' }); } @@ -50,7 +51,7 @@ function baseAppearance(id) { var all = baseAppearances(); for (var i = 0; i < all.length; i++) if (all[i].id === id) return all[i]; - return all[0]; + return all.find(function (a) { return a.id === 'char-villager'; }) || null; } // The base appearance catalog. Kept for existing callers that expect a flat list. @@ -59,10 +60,10 @@ RK.normalizeAppearance = function (input) { if (input && input.appearance && !input.avatar) input = input.appearance; if (typeof input === 'string') input = { avatar: input }; - input = input || {}; + if (!input || typeof input !== 'object') input = {}; - var avatar = input.avatar || input.id || 'default'; - if (!baseAppearance(avatar) || baseAppearance(avatar).id !== avatar) avatar = 'default'; + var avatar = input.avatar || input.id || 'char-villager'; + if (avatar === 'default' || !baseAppearance(avatar) || baseAppearance(avatar).id !== avatar) avatar = 'char-villager'; var base = baseAppearance(avatar); var isChar = !!(RK.isChar && RK.isChar(avatar)); @@ -134,6 +135,8 @@ function appearanceVisibleInProjection(a, projection) { if (!a) return false; + // The free default remains selectable across projections; this does not unlock a mode. + if (a.id === 'char-villager') return true; if (projection === 'topdown') return a.kind === 'color' || a.kind === 'char' || a.kind === 'skin'; if (projection === 'iso') return hasIsoCharacter(a); if (projection === '3d') return a.kind === 'model3d'; diff --git a/html/js/render/charSprites.js b/html/js/render/charSprites.js index d2983d0..54e7708 100644 --- a/html/js/render/charSprites.js +++ b/html/js/render/charSprites.js @@ -103,7 +103,7 @@ // Curated humanoid characters (verified non-empty, by sight), one tile index each. RK.CHARS = { - 'char-villager': { id: 'char-villager', label: 'Villager', frame: 270 }, + 'char-villager': { id: 'char-villager', label: 'Adventurer', frame: 270 }, 'char-elder': { id: 'char-elder', label: 'Elder', frame: 271 }, 'char-barbarian': { id: 'char-barbarian', label: 'Barbarian', frame: 324 }, 'char-monk': { id: 'char-monk', label: 'Monk', frame: 379 }, diff --git a/html/js/render/fancyRenderer.js b/html/js/render/fancyRenderer.js index c63a3ae..0276654 100644 --- a/html/js/render/fancyRenderer.js +++ b/html/js/render/fancyRenderer.js @@ -71,6 +71,7 @@ this._sizeKey = key; this._hadRoom = hasRoom; } + this._lastScene = scene; this._syncEntities(scene); }; @@ -292,11 +293,38 @@ var cell = this.cell, seen = {}, RKr = window.RK, focusFallback = null; for (var i = 0; i < scene.entities.length; i++) { var e = scene.entities[i]; + var isAvatar = e.kind === 'avatar' || e.kind === 'player'; + var visual = isAvatar && RKr && RKr.avatarVisuals && RKr.avatarVisuals.resolve( + e.appearance || { avatar: e.avatar }, { projection: 'topdown', context: 'tavern', entity: e }); + if (visual) e = Object.assign({}, e, { appearance: visual.appearance, avatar: visual.appearance.avatar }); seen[e.id] = true; - var wantSkin = !!(RKr && RKr.isSkin && RKr.isSkin(e.avatar)); - var wantChar = !!(RKr && RKr.isChar && RKr.isChar(e.avatar)); - if (wantSkin && !RKr.skinSheet(e.avatar)) RKr.loadSkin(e.avatar); // lazy fetch - if (wantChar && !RKr.charAtlas()) RKr.loadCharAtlas(); + var allowed = !visual || visual.allowed; + var wantSkin = !!(allowed && RKr && RKr.isSkin && RKr.isSkin(e.avatar)); + var wantChar = !!(allowed && RKr && RKr.isChar && RKr.isChar(e.avatar)); + if (visual && (wantSkin || wantChar)) { + var self = this; + if (!this._onAvatarReady) this._onAvatarReady = function () { + if (!self.app || self._avatarRepaintQueued || !self._lastScene) return; + // A failed load is not readiness; do not schedule a retry loop. + var ready = self._lastScene.entities.some(function (entity) { + if (entity.kind !== 'avatar' && entity.kind !== 'player') return false; + var v = RKr.avatarVisuals.resolve(entity.appearance || { avatar: entity.avatar }, { projection: 'topdown' }); + var sprite = self.sprites[entity.id]; + return (!sprite || sprite.kind !== v.kind) && v.allowed && ((v.kind === 'char' && RKr.charAtlas && RKr.charAtlas()) || + (v.kind === 'skin' && RKr.skinSheet && RKr.skinSheet(v.appearance.avatar))); + }); + if (!ready) return; + self._avatarRepaintQueued = true; + root.requestAnimationFrame(function () { + self._avatarRepaintQueued = false; + if (self.app && self._lastScene) self._syncEntities(self._lastScene); + }); + }; + RKr.avatarVisuals.ensureCanvasReady(visual, this._onAvatarReady); + } else { + if (wantSkin && !RKr.skinSheet(e.avatar)) RKr.loadSkin(e.avatar); + if (wantChar && !RKr.charAtlas()) RKr.loadCharAtlas(); + } var kind = (wantSkin && RKr.skinSheet(e.avatar)) ? 'skin' : (wantChar && RKr.charAtlas()) ? 'char' : 'circle'; diff --git a/html/js/render/tavernLife.js b/html/js/render/tavernLife.js index a826f87..9927517 100644 --- a/html/js/render/tavernLife.js +++ b/html/js/render/tavernLife.js @@ -42,7 +42,8 @@ var CAT_LINES = ["meow", "mrrrow", "prrrrp", "hisss", "...", "mew"]; var WELCOME_LINES = ["Welcome!", "Pull up a stool.", "New face, nice.", "Come in, sit down."]; - function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; } + function pick(arr, random) { return arr[Math.floor((random || Math.random)() * arr.length)]; } + function between(random, min, max) { return min + random() * (max - min); } // ---- NPC definitions -------------------------------------------------------- // NPCs are identified by a prefix so they don't collide with real socket ids. @@ -56,32 +57,108 @@ avatar: avatar, appearance: { avatar: avatar, tint: 'none', equipment: { body: 'none', head: 'none', shield: 'none', weapon: 'none' } }, x: x, y: y, facing: 'down', + homeX: x, homeY: y, targetX: x, targetY: y, moveCooldown: 0, - sitTimer: 0, - // Stagger the first lines so entering the room feels conversational instead of every - // patron opening a bubble on the same frame. - speechTimer: opts.speechTimer == null ? 1800 + Math.random() * 7000 : opts.speechTimer, + phase: opts.phase || 'idle', + phaseUntil: opts.phaseUntil || 0, + speechTimer: opts.speechTimer == null ? 1800 : opts.speechTimer, speech: null, speechUntil: 0, color: opts.color || '#d7dbe0', label: opts.label || null, role: opts.role || 'patron', - roamArea: opts.roamArea || null + roleArea: opts.roleArea || null, + serviceStops: opts.serviceStops || null, + serviceIndex: opts.serviceIndex || 0, + excursionTarget: null }; } - function bartendersArea(cols, rows) { - // Behind the bar: the row between the top wall and the counter (y=1). Sealed off by the - // counter, so the bartender stays back there and never wanders onto the customer floor. - return { minY: 1, maxY: 1, minX: 3, maxX: Math.max(5, cols - 5) }; + var CARDINAL_STEPS = [ + { x: 0, y: -1, facing: 'up' }, + { x: -1, y: 0, facing: 'left' }, + { x: 1, y: 0, facing: 'right' }, + { x: 0, y: 1, facing: 'down' } + ]; + + function tileAt(scene, x, y) { + if (!scene || x < 0 || y < 0 || x >= scene.cols || y >= scene.rows || !scene.grid || !scene.grid[y]) return null; + return scene.grid[y][x]; } - function patronsArea(cols, rows) { - // Patrons roam the middle/lower floor. - return { minY: 3, maxY: rows - 2, minX: 1, maxX: cols - 2 }; + + function isWalkable(scene, x, y) { + var tile = tileAt(scene, x, y); + if (tile == null) return false; + var definition = scene.legend && scene.legend[tile]; + if (definition && typeof definition.solid === 'boolean') return !definition.solid; + return tile === 'floor' || tile === 'chair' || tile === 'door' || tile === 'rug'; } - function catArea(cols, rows) { - // The customer floor (in front of the bar): not behind the counter, not the walls. - return { minY: 4, maxY: rows - 2, minX: 1, maxX: cols - 2 }; + + function cellsFor(scene, predicate) { + var cells = []; + for (var y = 0; y < scene.rows; y++) { + for (var x = 0; x < scene.cols; x++) { + if (predicate(x, y, tileAt(scene, x, y))) cells.push({ x: x, y: y }); + } + } + return cells; + } + + function semanticBarArea(scene) { + var best = null; + for (var y = 0; y < scene.rows; y++) { + var x = 0; + while (x < scene.cols) { + if (tileAt(scene, x, y) !== 'bar') { x++; continue; } + var start = x; + while (x + 1 < scene.cols && tileAt(scene, x + 1, y) === 'bar') x++; + var end = x; + if (end > start && y > 0) { + var candidate = { minX: start + 1, maxX: end - 1, minY: y - 1, maxY: y - 1, counterY: y }; + var lane = cellsFor(scene, function (cx, cy) { + return cx >= candidate.minX && cx <= candidate.maxX && cy === candidate.minY + && tileAt(scene, cx, cy) === 'floor'; + }); + if (lane.length && (!best || end - start > best.length)) { + best = { area: candidate, length: end - start, cells: lane }; + } + } + x++; + } + } + return best; + } + + function semanticTablesAndSeats(scene) { + var tables = cellsFor(scene, function (x, y, tile) { return tile === 'table'; }); + var pairs = []; + for (var i = 0; i < tables.length; i++) { + var table = tables[i]; + var seat = { x: table.x, y: table.y + 1 }; + if (tileAt(scene, seat.x, seat.y) === 'chair') pairs.push({ table: table, seat: seat }); + } + return pairs; + } + + function tableServiceStops(scene, tables) { + var stops = []; + for (var i = 0; i < tables.length; i++) { + var table = tables[i].table; + var candidates = [ + { x: table.x, y: table.y - 1 }, + { x: table.x - 1, y: table.y }, + { x: table.x + 1, y: table.y } + ]; + for (var j = 0; j < candidates.length; j++) { + var point = candidates[j]; + if (!isWalkable(scene, point.x, point.y) || tileAt(scene, point.x, point.y) !== 'floor') continue; + if (!stops.some(function (existing) { return existing.x === point.x && existing.y === point.y; })) { + stops.push(point); + break; + } + } + } + return stops; } // ---- Speech bubbles --------------------------------------------------------- @@ -93,29 +170,51 @@ var BUBBLE_FADE = 500; function measureBubble(ctx, text) { + var key = ctx.canvas.width + ':' + ctx.canvas.height + ':' + text; + var cache = ctx._tavernBubbleLayouts || (ctx._tavernBubbleLayouts = new Map()); + if (cache.has(key)) return cache.get(key); ctx.font = BUBBLE_FONT; - var metrics = ctx.measureText(text); - var w = Math.ceil(metrics.width) + BUBBLE_PADDING * 2; - var h = 22 + BUBBLE_PADDING * 2; - return { w: w, h: h }; + var lineHeight = 16; + var width = Math.max(1, Math.min(320, ctx.canvas.width - 8) - BUBBLE_PADDING * 2); + var lines = [], current = ''; + Array.from(text).forEach(function (letter) { + if (letter === '\n') { lines.push(current); current = ''; return; } + if (current && ctx.measureText(current + letter).width > width) { + lines.push(current); current = ''; + } + current += letter; + }); + if (current || !lines.length) lines.push(current); + var maxLines = Math.max(1, Math.floor((ctx.canvas.height - 8 - BUBBLE_PADDING * 2) / lineHeight)); + if (lines.length > maxLines) { + lines = lines.slice(0, maxLines); + var last = lines.pop(); + while (last && ctx.measureText(last + '…').width > width) last = Array.from(last).slice(0, -1).join(''); + lines.push(last + '…'); + } + var widest = Math.max.apply(null, lines.map(function (line) { return ctx.measureText(line).width; })); + var layout = { w: Math.min(width, Math.ceil(widest)) + BUBBLE_PADDING * 2, + h: lines.length * lineHeight + BUBBLE_PADDING * 2, lines: lines, lineHeight: lineHeight }; + if (cache.size >= 32) cache.delete(cache.keys().next().value); + cache.set(key, layout); + return layout; } function drawBubble(ctx, x, y, text, alpha) { - if (alpha <= 0 || !text) return; + if (alpha <= 0 || !text || x < 0 || y < 0 || x > ctx.canvas.width || y > ctx.canvas.height) return; var dim = measureBubble(ctx, text); var bw = dim.w, bh = dim.h; - // Clamp so the bubble stays on screen. var bx = Math.max(4, Math.min(x - bw / 2, ctx.canvas.width - bw - 4)); var by = y - bh - BUBBLE_TAIL; - if (by < 4) by = y + BUBBLE_TAIL + 4; // flip below if no room above + if (by < 4) by = y + BUBBLE_TAIL + 4; + by = Math.max(4, Math.min(by, ctx.canvas.height - bh - 4)); + var above = by + bh <= y; ctx.save(); ctx.globalAlpha = alpha; ctx.font = BUBBLE_FONT; ctx.textBaseline = 'middle'; - ctx.textAlign = 'center'; - - // Bubble body (rounded rect). + ctx.textAlign = 'left'; ctx.fillStyle = 'rgba(18,24,32,0.94)'; ctx.strokeStyle = 'rgba(120,140,165,0.55)'; ctx.lineWidth = 1.5; @@ -124,24 +223,24 @@ ctx.fill(); ctx.stroke(); - // Tail pointer. - var tailX = Math.max(bx + 12, Math.min(x, bx + bw - 12)); - ctx.fillStyle = 'rgba(18,24,32,0.94)'; + var tailX = Math.max(bx + 5, Math.min(x, bx + bw - 5)); + var edgeY = above ? by + bh : by; ctx.beginPath(); - ctx.moveTo(tailX - 5, by + bh); - ctx.lineTo(tailX + 5, by + bh); - ctx.lineTo(tailX, by + bh + (by < y ? BUBBLE_TAIL : -BUBBLE_TAIL)); + ctx.moveTo(tailX - 5, edgeY); + ctx.lineTo(tailX + 5, edgeY); + ctx.lineTo(tailX, edgeY + (above ? BUBBLE_TAIL : -BUBBLE_TAIL)); ctx.closePath(); ctx.fill(); - - // Text. ctx.fillStyle = '#e8edf3'; - ctx.fillText(text, bx + bw / 2, by + bh / 2); + dim.lines.forEach(function (line, index) { + ctx.fillText(line, bx + BUBBLE_PADDING, + by + BUBBLE_PADDING + dim.lineHeight * (index + 0.5)); + }); ctx.restore(); } // ---- The TavernLife controller ---------------------------------------------- - function TavernLife(host, getScene, getCell) { + function TavernLife(host, getScene, getCell, options) { this.host = host; this.getScene = getScene; this.getCell = getCell || function () { return 24; }; @@ -152,7 +251,14 @@ this._raf = null; this._lastTick = 0; this._spawned = false; - this._realBubbles = {}; // socketId -> { text, until } from real chat + this._realBubbles = Object.create(null); // socketId -> { text, until } from real chat + options = options || {}; + this._now = typeof options.now === 'function' ? options.now : function () { return Date.now(); }; + this._random = typeof options.random === 'function' ? options.random : function () { return Math.random(); }; + this._projectEntityHead = typeof options.projectEntityHead === 'function' ? options.projectEntityHead : null; + this._barCells = []; + this._excursionOwner = null; + this._nextExcursionAt = 0; } TavernLife.prototype._ensureOverlay = function () { @@ -177,129 +283,265 @@ TavernLife.prototype.spawn = function () { if (this._spawned) return; - this._spawned = true; var scene = this.getScene(); - if (!scene) return; - var cols = scene.cols, rows = scene.rows; - var grid = scene.grid; + if (!scene || !scene.grid || !scene.cols || !scene.rows) return; - // Find walkable tiles for spawning. - function isFloor(x, y) { - return y >= 0 && y < rows && x >= 0 && x < cols && grid[y] && grid[y][x] === 'floor'; - } - function findFloor(cx, cy) { - for (var r = 1; r < 8; r++) { - for (var dy = -r; dy <= r; dy++) { - for (var dx = -r; dx <= r; dx++) { - var x = cx + dx, y = cy + dy; - if (isFloor(x, y)) return { x: x, y: y }; - } - } - } - return { x: 1, y: 1 }; - } + // A designed room is opt-in for ambient actors. Without both semantic bar and + // table/chair structure, do not invent coordinates or fall back onto arbitrary floor. + var bar = semanticBarArea(scene); + var tablePairs = semanticTablesAndSeats(scene); + if (!bar || !tablePairs.length) return; - // Bartender BEHIND the bar (row 1, between the top wall and the counter). - var barSpot = findFloor(Math.floor(cols / 2), 1); - var bartender = makeNPC('bartender', 'bartender', 'char-merchant', barSpot.x, barSpot.y, { - label: 'Bartender', color: '#c9a25e', role: 'bartender', - roamArea: bartendersArea(cols, rows) + var now = this._now(); + this._barCells = bar.cells; + var barStart = bar.cells[Math.floor(bar.cells.length / 2)]; + var bartender = makeNPC('bartender', 'bartender', 'char-merchant', barStart.x, barStart.y, { + label: 'Barkeep', color: '#c9a25e', role: 'bartender', roleArea: bar.area, + phase: 'stationed', phaseUntil: now + between(this._random, 9000, 17000), + speechTimer: between(this._random, 9000, 17000) }); + bartender.barCells = bar.cells; this.npcs.push(bartender); - // 2-3 patrons near tables (middle area). + // Four guests begin on actual chairs below actual tables. Their seats are stable + // home coordinates, not random floor tiles that merely look like sitting. var patronAvatars = ['char-villager', 'char-elder', 'char-bard', 'char-wizard', 'char-ranger', 'char-rogue']; var patronColors = ['#7eb6c9', '#c9a0d4', '#a0c97e', '#d4b0a0', '#8fa0d4']; - var numPatrons = 2 + Math.floor(Math.random() * 2); - for (var i = 0; i < numPatrons; i++) { - var px = 4 + Math.floor(Math.random() * (cols - 8)); - var py = 5 + Math.floor(Math.random() * (rows - 8)); - var spot = findFloor(px, py); - this.npcs.push(makeNPC('patron' + i, 'patron', patronAvatars[i % patronAvatars.length], - spot.x, spot.y, { - label: 'Patron', color: patronColors[i % patronColors.length], - roamArea: patronsArea(cols, rows), - sitTimer: 2000 + Math.random() * 4000 - })); + var desiredPatrons = Math.min(4, tablePairs.length); + var selectedSeats = []; + for (var p = 0; p < desiredPatrons; p++) { + var seatIndex = desiredPatrons === 1 ? 0 : Math.floor(p * (tablePairs.length - 1) / (desiredPatrons - 1)); + var pair = tablePairs[seatIndex]; + if (selectedSeats.some(function (seat) { return seat.x === pair.seat.x && seat.y === pair.seat.y; })) continue; + selectedSeats.push(pair.seat); + this.npcs.push(makeNPC('patron' + p, 'patron', patronAvatars[p % patronAvatars.length], pair.seat.x, pair.seat.y, { + label: 'Patron', color: patronColors[p % patronColors.length], + role: 'patron', roleArea: { minX: 1, maxX: scene.cols - 2, minY: 3, maxY: scene.rows - 2 }, + phase: 'seated', phaseUntil: now + between(this._random, 90000, 180000), + speechTimer: between(this._random, 9000, 22000) + })); } - // A tavern cat: a random pixel cat from the Pet Cats Pack that wanders the floor. - var catSpot = findFloor(4, rows - 4); - var cat = makeNPC('cat', 'cat', null, catSpot.x, catSpot.y, { - label: null, color: '#e8a060', role: 'cat', roamArea: catArea(cols, rows) - }); - cat.catSprite = (RK.randomCatId ? RK.randomCatId() : 'cat3'); - this.npcs.push(cat); + // The server-authoritative layout supplies table waypoints. The server remains + // unaware of these client-only decorative actors. + var stops = tableServiceStops(scene, tablePairs); + if (stops.length) { + var waitressStart = stops[0]; + var waitress = makeNPC('waitress', 'waitress', 'char-villager', waitressStart.x, waitressStart.y, { + label: 'Waitress', color: '#e1c17a', role: 'waitress', + roleArea: { minX: 1, maxX: scene.cols - 2, minY: 3, maxY: scene.rows - 2 }, + serviceStops: stops, serviceIndex: 0, + phase: 'serving', phaseUntil: now + between(this._random, 4500, 7000), + speechTimer: between(this._random, 14000, 26000) + }); + this.npcs.push(waitress); + } + + // Keep the existing cat, but give it long rests and short paths so it reads as + // occasional background life instead of another continuously roaming guest. + var catCells = cellsFor(scene, function (x, y, tile) { + return tile === 'floor' && x > 1 && x < scene.cols - 2 && y >= 4 && y < scene.rows - 2; + }).filter(function (point) { return !this._occupiedByOther(null, point.x, point.y); }, this); + if (catCells.length) { + var catSpot = catCells[Math.floor(this._random() * catCells.length)]; + var cat = makeNPC('cat', 'cat', null, catSpot.x, catSpot.y, { + label: null, color: '#e8a060', role: 'cat', + roleArea: { minX: 2, maxX: scene.cols - 3, minY: 4, maxY: scene.rows - 3 }, + phase: 'resting', phaseUntil: now + between(this._random, 9000, 17000), + speechTimer: between(this._random, 18000, 30000) + }); + cat.catSprite = (RK.randomCatId ? RK.randomCatId() : 'cat3'); + this.npcs.push(cat); + } + this._spawned = true; }; - TavernLife.prototype._pickTarget = function (npc, scene) { - var area = npc.roamArea; - if (!area) return; - var grid = scene.grid; - var cols = scene.cols, rows = scene.rows; - for (var tries = 0; tries < 12; tries++) { - var tx = area.minX + Math.floor(Math.random() * (area.maxX - area.minX + 1)); - var ty = area.minY + Math.floor(Math.random() * (area.maxY - area.minY + 1)); - if (ty >= 0 && ty < rows && tx >= 0 && tx < cols && grid[ty] && grid[ty][tx] === 'floor') { - npc.targetX = tx; - npc.targetY = ty; - return; + TavernLife.prototype._isRoleCell = function (npc, scene, x, y) { + if (!isWalkable(scene, x, y)) return false; + var area = npc.roleArea; + if (area && (x < area.minX || x > area.maxX || y < area.minY || y > area.maxY)) return false; + if (npc.role === 'patron') { + return Math.abs(x - npc.homeX) + Math.abs(y - npc.homeY) <= 3; + } + if (npc.role === 'bartender') return tileAt(scene, x, y) === 'floor'; + if (npc.role === 'waitress') return tileAt(scene, x, y) === 'floor'; + if (npc.role === 'cat') return tileAt(scene, x, y) === 'floor'; + return false; + }; + + TavernLife.prototype._occupiedByOther = function (npc, x, y) { + return this.npcs.some(function (other) { + return other !== npc && other.x === x && other.y === y; + }); + }; + + TavernLife.prototype._findPath = function (npc, scene, target) { + if (!target || !this._isRoleCell(npc, scene, target.x, target.y) || this._occupiedByOther(npc, target.x, target.y)) return null; + if (npc.x === target.x && npc.y === target.y) return []; + var startKey = npc.x + ',' + npc.y; + var queue = [{ x: npc.x, y: npc.y }]; + var visited = new Set([startKey]); + var previous = new Map(); + while (queue.length) { + var point = queue.shift(); + for (var i = 0; i < CARDINAL_STEPS.length; i++) { + var step = CARDINAL_STEPS[i]; + var nx = point.x + step.x, ny = point.y + step.y; + var key = nx + ',' + ny; + if (visited.has(key) || !this._isRoleCell(npc, scene, nx, ny) || this._occupiedByOther(npc, nx, ny)) continue; + visited.add(key); + previous.set(key, { from: point.x + ',' + point.y, step: step }); + if (nx === target.x && ny === target.y) { + var path = []; + var cursor = key; + while (cursor !== startKey) { + var entry = previous.get(cursor); + var parts = cursor.split(','); + path.unshift({ x: Number(parts[0]), y: Number(parts[1]), facing: entry.step.facing }); + cursor = entry.from; + } + return path; + } + queue.push({ x: nx, y: ny }); } } + return null; }; - TavernLife.prototype._moveNPC = function (npc, scene, dt) { - if (npc.sitTimer > 0) { - npc.sitTimer -= dt; - return; - } - npc.moveCooldown -= dt; - if (npc.moveCooldown > 0) return; - - // Arrived at target? - if (npc.x === npc.targetX && npc.y === npc.targetY) { - var sitTime = npc.role === 'cat' ? 1000 + Math.random() * 2000 : 3000 + Math.random() * 5000; - npc.sitTimer = sitTime; - this._pickTarget(npc, scene); - return; - } - - // Step toward target (one tile, cardinal only). - var dx = npc.targetX - npc.x; - var dy = npc.targetY - npc.y; - var stepX = 0, stepY = 0; - if (Math.abs(dx) >= Math.abs(dy) && dx !== 0) stepX = Math.sign(dx); - else if (dy !== 0) stepY = Math.sign(dy); - else if (dx !== 0) stepX = Math.sign(dx); - - var nx = npc.x + stepX, ny = npc.y + stepY; - var grid = scene.grid; - if (ny >= 0 && ny < scene.rows && nx >= 0 && nx < scene.cols && grid[ny] && grid[ny][nx] === 'floor') { - npc.x = nx; npc.y = ny; - if (stepX < 0) npc.facing = 'left'; - else if (stepX > 0) npc.facing = 'right'; - else if (stepY < 0) npc.facing = 'up'; - else if (stepY > 0) npc.facing = 'down'; - } else { - // Blocked: pick a new target. - this._pickTarget(npc, scene); - } - // Cat moves faster; bartender slower. - npc.moveCooldown = npc.role === 'cat' ? 280 : npc.role === 'bartender' ? 500 : 380; + TavernLife.prototype._setTarget = function (npc, target) { + if (!target) return false; + npc.targetX = target.x; + npc.targetY = target.y; + return true; }; - TavernLife.prototype._maybeSpeak = function (npc, now) { + TavernLife.prototype._stepTowardTarget = function (npc, scene, dt) { + if (npc.x === npc.targetX && npc.y === npc.targetY) return true; + npc.moveCooldown = Math.max(0, npc.moveCooldown - dt); + if (npc.moveCooldown > 0) return false; + var path = this._findPath(npc, scene, { x: npc.targetX, y: npc.targetY }); + if (!path || !path.length) return false; + var next = path[0]; + // Recheck immediately before moving: actors may have changed occupancy this frame. + if (!this._isRoleCell(npc, scene, next.x, next.y) || this._occupiedByOther(npc, next.x, next.y)) return false; + npc.x = next.x; + npc.y = next.y; + npc.facing = next.facing; + npc.moveCooldown = npc.role === 'waitress' ? 850 : npc.role === 'bartender' ? 1200 : npc.role === 'cat' ? 1400 : 1000; + return npc.x === npc.targetX && npc.y === npc.targetY; + }; + + TavernLife.prototype._startPatronExcursion = function (npc, scene, now) { + var candidates = cellsFor(scene, function (x, y, tile) { + return tile === 'floor' && Math.abs(x - npc.homeX) + Math.abs(y - npc.homeY) > 0 && + Math.abs(x - npc.homeX) + Math.abs(y - npc.homeY) <= 3 && + x > 1 && x < scene.cols - 2 && y >= 3 && y < scene.rows - 2; + }); + var reachable = candidates.filter(function (point) { + return !this._occupiedByOther(npc, point.x, point.y) && !!this._findPath(npc, scene, point); + }, this); + if (!reachable.length) { + npc.phaseUntil = now + between(this._random, 30000, 50000); + return false; + } + var target = reachable[Math.floor(this._random() * reachable.length)]; + npc.excursionTarget = target; + npc.phase = 'outbound'; + npc.phaseUntil = 0; + this._setTarget(npc, target); + this._excursionOwner = npc.id; + return true; + }; + + TavernLife.prototype._updatePatron = function (npc, scene, now) { + if (npc.phase === 'seated') { + if (now >= npc.phaseUntil && !this._excursionOwner && now >= this._nextExcursionAt) { + this._startPatronExcursion(npc, scene, now); + } + return; + } + if (npc.phase === 'outbound' && npc.x === npc.targetX && npc.y === npc.targetY) { + npc.phase = 'pausing'; + npc.phaseUntil = now + between(this._random, 2500, 5000); + } else if (npc.phase === 'pausing' && now >= npc.phaseUntil) { + npc.phase = 'returning'; + this._setTarget(npc, { x: npc.homeX, y: npc.homeY }); + } else if (npc.phase === 'returning' && npc.x === npc.homeX && npc.y === npc.homeY) { + npc.phase = 'seated'; + npc.excursionTarget = null; + npc.phaseUntil = now + between(this._random, 90000, 180000); + this._excursionOwner = null; + this._nextExcursionAt = now + between(this._random, 45000, 90000); + } + }; + + TavernLife.prototype._updateWaitress = function (npc, now) { + if (npc.phase === 'walking' && npc.x === npc.targetX && npc.y === npc.targetY) { + npc.phase = 'serving'; + npc.phaseUntil = now + between(this._random, 5000, 9000); + return; + } + if (npc.phase !== 'serving' || now < npc.phaseUntil || !npc.serviceStops || !npc.serviceStops.length) return; + npc.serviceIndex = (npc.serviceIndex + 1) % npc.serviceStops.length; + this._setTarget(npc, npc.serviceStops[npc.serviceIndex]); + npc.phase = 'walking'; + } + + + TavernLife.prototype._updateBartender = function (npc, now) { + if (npc.phase === 'stationed' && now >= npc.phaseUntil) { + var cells = (npc.barCells || []).filter(function (point) { + return !(point.x === npc.x && point.y === npc.y) && !this._occupiedByOther(npc, point.x, point.y) && !!this._findPath(npc, this.getScene(), point); + }, this); + if (cells.length) { + // Walk to a nearby point along the counter, then pause to serve. + cells.sort(function (a, b) { + return Math.abs(a.x - npc.x) - Math.abs(b.x - npc.x); + }); + var near = cells.slice(0, Math.min(4, cells.length)); + this._setTarget(npc, near[Math.floor(this._random() * near.length)]); + npc.phase = 'working'; + } else { + npc.facing = npc.facing === 'left' ? 'right' : 'left'; + npc.phaseUntil = now + between(this._random, 7000, 14000); + } + } + if (npc.phase === 'working' && npc.x === npc.targetX && npc.y === npc.targetY) { + npc.phase = 'stationed'; + npc.phaseUntil = now + between(this._random, 9000, 18000); + } + }; + + TavernLife.prototype._updateCat = function (npc, scene, now) { + if (npc.phase === 'resting' && now >= npc.phaseUntil) { + var candidates = cellsFor(scene, function (x, y, tile) { + return tile === 'floor' && Math.abs(x - npc.x) + Math.abs(y - npc.y) > 0 && + Math.abs(x - npc.x) + Math.abs(y - npc.y) <= 2 && this._isRoleCell(npc, scene, x, y); + }.bind(this)).filter(function (point) { + return !this._occupiedByOther(npc, point.x, point.y) && !!this._findPath(npc, scene, point); + }, this); + if (candidates.length) { + this._setTarget(npc, candidates[Math.floor(this._random() * candidates.length)]); + npc.phase = 'walking'; + } else npc.phaseUntil = now + between(this._random, 8000, 14000); + } + if (npc.phase === 'walking' && npc.x === npc.targetX && npc.y === npc.targetY) { + npc.phase = 'resting'; + npc.phaseUntil = now + between(this._random, 9000, 18000); + } + }; + + TavernLife.prototype._maybeSpeak = function (npc, now, dt) { if (npc.speech && now < npc.speechUntil) return; - npc.speechTimer -= 16; + npc.speechTimer -= dt; if (npc.speechTimer > 0) return; var lines; if (npc.role === 'bartender') lines = BARTENDER_LINES; else if (npc.role === 'cat') lines = CAT_LINES; else lines = PATRON_LINES; - npc.speech = pick(lines); + npc.speech = pick(lines, this._random); npc.speechUntil = now + BUBBLE_DURATION; - npc.speechTimer = 8000 + Math.random() * 12000; // next speech gap - if (npc.role === 'cat') npc.speechTimer = 6000 + Math.random() * 10000; + npc.speechTimer = between(this._random, 18000, 32000); }; // Inject NPC entities into a scene so the renderer draws them. @@ -328,15 +570,26 @@ return scene; }; - // Show a speech bubble for a real player (called on chat_broadcast). + // Show a speech bubble for a real player (called by the explicit tavern_speech mapping). TavernLife.prototype.showPlayerBubble = function (socketId, text) { - this._realBubbles[socketId] = { text: text, until: Date.now() + BUBBLE_DURATION }; + if (typeof socketId !== 'string' || typeof text !== 'string' || !text.trim()) return; + this._realBubbles[socketId] = { text: text.slice(0, 200), until: this._now() + BUBBLE_DURATION }; }; - // Get the screen position of an entity for a given renderer/cell size. - // This is renderer-agnostic: top-down uses grid coords * cell; iso uses projection. + // Project the top of an entity, before the viewport transform scales its rendered size. TavernLife.prototype._entityScreenPos = function (e, scene, cell, mode) { var pos; + if (mode === '3d' && this._projectEntityHead) { + var projected = this._projectEntityHead(e); + if (!projected || !Number.isFinite(projected.x) || !Number.isFinite(projected.y)) return null; + // The 3D callback returns viewport-relative pixels, so do not apply the 2D + // canvas transform again. + return { x: projected.x, y: projected.y }; + } + var humanoid = e.role !== 'cat' && (!e.kind || e.kind === 'avatar' || e.kind === 'player'); + var visual = (mode === 'iso' || humanoid) && RK.avatarVisuals && RK.avatarVisuals.resolve(e.appearance || { avatar: e.avatar }, { + projection: mode === 'iso' ? 'iso' : 'topdown', entity: e + }); if (mode === 'iso') { // Match IsoRenderer._project: originX = margin + rows * tileW/2 + tileW; originY = margin + imageH var tileW = (RK.isoAssets && RK.isoAssets.tile && RK.isoAssets.tile.w) || 84; @@ -349,13 +602,21 @@ x: originX + (e.x - e.y) * tileW / 2, y: originY + (e.x + e.y) * tileH / 2 }; + // Iso character images are anchored at their feet, above the floor diamond. + var character = visual && visual.allowed && visual.character; + pos.y += character ? tileH * 0.95 - (character.imageH || 92) : -8; } else if (mode === '3d') { - // 3D renderer uses Three.js; we can't easily get screen coords. - // Skip speech bubbles for 3D mode. return null; } else { - // top-down / ascii / fancy: grid coords * cell - pos = { x: e.x * cell + cell / 2, y: e.y * cell + cell / 2 }; + var head = 0.2; + if (mode === 'ascii') head = 0; + else if (visual && visual.allowed && visual.kind === 'char') head = -0.9; + else if (visual && visual.allowed && visual.kind === 'skin') { + var skin = RK.SKINS && RK.SKINS[visual.appearance.avatar]; + head = RK.skinSheetFailed && RK.skinSheetFailed(visual.appearance.avatar) + ? -0.9 : 1 - ((skin && skin.scale) || 1.7); + } + pos = { x: (e.x + 0.5) * cell, y: (e.y + head) * cell }; } var view = this._viewTransform; if (view) return { x: view.left + pos.x * view.scaleX, y: view.top + pos.y * view.scaleY }; @@ -375,10 +636,17 @@ var remaining = npc.speechUntil - now; if (remaining < BUBBLE_FADE) alpha = remaining / BUBBLE_FADE; var pos = this._entityScreenPos(npc, scene, cell, mode); - if (pos) drawBubble(ctx, pos.x, pos.y - cell * 0.3 * ((this._viewTransform && this._viewTransform.scaleY) || 1), npc.speech, alpha); + if (pos) drawBubble(ctx, pos.x, pos.y, npc.speech, alpha); } - // Real player bubbles (from chat). + // Remove departed visits as well as expired messages, even when no NPC can spawn. + var present = new Set(scene.entities.filter(function (entity) { return !entity._npc; }) + .map(function (entity) { return entity.id; })); + var bubbles = this._realBubbles; + Object.keys(bubbles).forEach(function (id) { + if (!present.has(id) || now >= bubbles[id].until) delete bubbles[id]; + }); + // Real player bubbles (from accepted room speech). var occupants = scene.entities; for (var j = 0; j < occupants.length; j++) { var e = occupants[j]; @@ -392,21 +660,28 @@ var rRemaining = bubble.until - now; if (rRemaining < BUBBLE_FADE) rAlpha = rRemaining / BUBBLE_FADE; var rPos = this._entityScreenPos(e, scene, cell, mode); - if (rPos) drawBubble(ctx, rPos.x, rPos.y - cell * 0.3 * ((this._viewTransform && this._viewTransform.scaleY) || 1), bubble.text, rAlpha); + if (rPos) drawBubble(ctx, rPos.x, rPos.y, bubble.text, rAlpha); } }; // Main update: called every frame via rAF. TavernLife.prototype.update = function (scene, cell, mode) { - if (!scene || !this._spawned) return; - var now = Date.now(); - var dt = now - (this._lastTick || now); + if (!scene) return; + var now = this._now(); + var dt = this._lastTick ? Math.max(0, Math.min(1000, now - this._lastTick)) : 0; this._lastTick = now; - // Update NPC movement and speech. + // Update role-specific schedules before taking at most one cardinal path step. for (var i = 0; i < this.npcs.length; i++) { - this._moveNPC(this.npcs[i], scene, dt); - this._maybeSpeak(this.npcs[i], now); + var actor = this.npcs[i]; + if (actor.role === 'patron') this._updatePatron(actor, scene, now); + else if (actor.role === 'waitress') this._updateWaitress(actor, now); + else if (actor.role === 'bartender') this._updateBartender(actor, now); + else if (actor.role === 'cat') this._updateCat(actor, scene, now); + if (actor.phase === 'outbound' || actor.phase === 'returning' || actor.phase === 'walking' || actor.phase === 'working') { + this._stepTowardTarget(actor, scene, dt); + } + this._maybeSpeak(actor, now, dt); } // Update NPC entity positions in the scene. @@ -477,8 +752,8 @@ TavernLife.prototype.welcomeBubbles = function () { // Make the bartender greet when the player joins. if (this.npcs.length > 0 && this.npcs[0].role === 'bartender') { - var now = Date.now(); - this.npcs[0].speech = pick(WELCOME_LINES); + var now = this._now(); + this.npcs[0].speech = pick(WELCOME_LINES, this._random); this.npcs[0].speechUntil = now + BUBBLE_DURATION; this.npcs[0].speechTimer = 5000; } diff --git a/html/js/render/threeRenderer.js b/html/js/render/threeRenderer.js index 1e95673..42c078d 100644 --- a/html/js/render/threeRenderer.js +++ b/html/js/render/threeRenderer.js @@ -919,6 +919,31 @@ return true; }; + // Project the live interpolated mesh head into the host's CSS viewport. The chat overlay + // uses viewport pixels, so neither the 2D camera nor device-pixel scaling belongs here. + ThreeRenderer.prototype.projectEntityHead = function (id) { + if (this._destroyed || !this.renderer || !this.camera || + !Object.prototype.hasOwnProperty.call(this.entities, id)) return null; + var entity = this.entities[id]; + if (!entity || !entity.obj || entity.obj.visible === false) return null; + var canvas = this.renderer.domElement; + if (!canvas || !canvas.getBoundingClientRect || !this.host.getBoundingClientRect) return null; + var rect = canvas.getBoundingClientRect(), host = this.host.getBoundingClientRect(); + if (!(rect.width > 0 && rect.height > 0 && host.width > 0 && host.height > 0)) return null; + // Both fitted character models and the built-in avatar fallback are below two units. + var head = new this.THREE.Vector3(0, 2, 0); + entity.obj.updateWorldMatrix(true, false); + entity.obj.localToWorld(head); + this.camera.updateMatrixWorld(); + head.project(this.camera); + if (![head.x, head.y, head.z].every(Number.isFinite) || + Math.abs(head.x) > 1 || Math.abs(head.y) > 1 || Math.abs(head.z) > 1) return null; + var x = rect.left - host.left + (head.x + 1) * rect.width / 2; + var y = rect.top - host.top + (1 - head.y) * rect.height / 2; + if (x < 0 || y < 0 || x > host.width || y > host.height) return null; + return { x: x, y: y }; + }; + ThreeRenderer.prototype.destroy = function () { this._destroyed = true; if (this._raf) cancelAnimationFrame(this._raf); diff --git a/html/tavern.html b/html/tavern.html index fdb6f4c..87bedf0 100644 --- a/html/tavern.html +++ b/html/tavern.html @@ -518,6 +518,11 @@ // Spawn client-side NPCs (bartender, patrons, cat) for a lively tavern. tavernLife = new RK.TavernLife(stageEl, function () { return currentScene; }, function () { return currentRenderer && currentRenderer.cell || 24; + }, { + projectEntityHead: function (entity) { + return currentRenderer && typeof currentRenderer.projectEntityHead === 'function' + ? currentRenderer.projectEntityHead(entity.id) : null; + } }); tavernLife.setMode(currentMode || 'tiles'); tavernLife.spawn(); @@ -565,27 +570,17 @@ var isGlobal = !m.scope || m.scope === 'global'; if (!isGlobal && m.scope !== state.channel) return; addChatLine(m.username, m.message); - // Speech bubble above the speaker's avatar. - // - // This used to key off `m.socketId`, which the chat provider deliberately stopped - // sending (it publishes a short `publicId` instead so the raw socket id never leaves the - // server), so the bubble branch simply never ran and nobody in the tavern ever spoke - // visibly. Resolve the speaker from the occupant list by display name instead, which - // needs no additional identity on the wire. - if (tavernLife) { - var speaker = null; - for (var oi = 0; oi < state.occupants.length; oi++) { - if (state.occupants[oi] && state.occupants[oi].name === m.username) { - speaker = state.occupants[oi]; - break; - } - } - if (speaker) { - // m.message is server-escaped HTML; strip tags for the bubble. - var text = m.message ? m.message.replace(/<[^>]*>/g, '') : ''; - tavernLife.showPlayerBubble(speaker.id, text); - } - } + }); + // Only the server's accepted, room-scoped event can identify a live speaker. + // Global messages, relay deliveries and history never imply a room occupant. + socket.on('tavern_speech', function (m) { + if (!m || typeof m.occupantId !== 'string' || typeof m.text !== 'string') return; + if (!tavernLife) return; + var present = state.occupants.some(function (o) { return o && o.id === m.occupantId; }); + if (present) tavernLife.showPlayerBubble(m.occupantId, m.text); + }); + socket.on('status_update', function (n) { + if (n && typeof n.message === 'string') addSystemLine(n.message); }); socket.on('tavern_notice', function (n) { if (n && n.message) addSystemLine(n.message); @@ -622,11 +617,10 @@ e.preventDefault(); var text = chatInput.value; if (text && text.trim()) { - // Try to post under the player's OWN Smirk npub (per-player identity); fall back to - // the normal unsigned send if Smirk signing isn't available/declined. - if (window.smirkChatSign) { + // A declined/failed signing request is not permission to send unsigned chat. + if (window.smirkChatSign && window.smirk && typeof window.smirk.signNostrEvent === 'function') { window.smirkChatSign(socket, text.trim(), 'wowngeon-global').then(function (signed) { - if (!signed) socket.emit('tavern_chat', { text: text }); + if (!signed) addSystemLine('Message not sent. Signing was declined or unavailable.'); }); } else { socket.emit('tavern_chat', { text: text }); diff --git a/src/multiplayer/appearance.js b/src/multiplayer/appearance.js index a6249d9..7d08fe6 100644 --- a/src/multiplayer/appearance.js +++ b/src/multiplayer/appearance.js @@ -100,8 +100,9 @@ function normalizeAppearance(input = {}) { if (typeof input === 'string') input = { avatar: input }; if (!input || typeof input !== 'object') input = {}; - let avatar = input.avatar || input.id || 'default'; - if (!isValidAvatar(avatar)) avatar = 'default'; + let avatar = input.avatar || input.id || 'char-villager'; + // Retain legacy input compatibility while giving every default a real free character. + if (avatar === 'default' || !isValidAvatar(avatar)) avatar = 'char-villager'; if (!isCharAvatar(avatar) && !isModel3dAvatar(avatar)) { return { avatar, tint: 'none', equipment: { ...DEFAULT_EQUIPMENT } }; diff --git a/src/multiplayer/tavernMap.js b/src/multiplayer/tavernMap.js index dda99e0..326118a 100644 --- a/src/multiplayer/tavernMap.js +++ b/src/multiplayer/tavernMap.js @@ -34,12 +34,12 @@ function buildDefaultTavern(cols = 28, rows = 15) { for (let x = 3; x < cols - 3; x += 4) set(x, 0, 'W'); for (let y = 4; y < rows - 3; y += 4) { set(0, y, 'W'); set(cols - 1, y, 'W'); } - // The bar: a counter across the top interior (row 2), a shelf of bottles behind it (row 1), - // and a keg (barrel) bracketing each end. Row 1 is the bartender's space, sealed off by the - // counter; players can't get behind it. + // The bar: a counter across the top interior (row 2), two bottle shelves as endcaps behind + // it (row 1), and a keg bracketing each end. The open row between the endcaps is a legal + // bartender lane, while the counter still seals it off from the customer floor. const barY = 2, barX0 = 3, barX1 = cols - 5; for (let x = barX0; x <= barX1; x++) set(x, barY, '='); - for (let x = barX0; x <= barX1; x += 2) set(x, barY - 1, 'h'); // bottles behind the bar + set(barX0, barY - 1, 'h'); set(barX1, barY - 1, 'h'); // bottle-shelf endcaps, clear staff lane set(barX0 - 1, barY, 'k'); set(barX1 + 1, barY, 'k'); // kegs bracket the counter // Tables (each with a chair below it), spread across the main floor with walkable aisles. diff --git a/src/network/chat/ChatProvider.js b/src/network/chat/ChatProvider.js index 41cc486..8c066a7 100644 --- a/src/network/chat/ChatProvider.js +++ b/src/network/chat/ChatProvider.js @@ -22,6 +22,8 @@ class ChatProvider { * @param {number} [msg.ts] Timestamp (ms). * @param {string} [msg.socketId] * @param {number|null} [msg.userId] + * @param {function} [msg.onLocalDelivery] Trusted server callback, once after local emit. + * Never persisted, broadcast or forwarded to a relay; not a relay acknowledgement. */ async publish(msg) { // eslint-disable-line no-unused-vars throw new Error('ChatProvider.publish not implemented'); @@ -42,7 +44,7 @@ class ChatProvider { * Deliver a message whose nostr event was signed by the CLIENT (per-player identity, Phase 2). * The base/local provider has no relay, so it just delivers the message in-game: the signed * `event` is ignored. NostrChatProvider overrides this to ALSO publish the pre-signed event. - * @param {object} req { event, scope, username, text, ts, socketId, userId } + * @param {object} req { event, scope, username, text, ts, socketId, userId, onLocalDelivery } */ async relaySignedEvent({ event, ...msg } = {}) { // eslint-disable-line no-unused-vars return this.publish({ scope: 'global', ...msg }); diff --git a/src/network/chat/NostrChatProvider.js b/src/network/chat/NostrChatProvider.js index f5ed41e..40b2ff2 100644 --- a/src/network/chat/NostrChatProvider.js +++ b/src/network/chat/NostrChatProvider.js @@ -133,8 +133,8 @@ class NostrChatProvider extends ChatProvider { // (escaped text, exactly like a normal global message) and publishes the pre-signed event to // the relays WITHOUT re-signing, so it carries the player's OWN npub, not the bridge. The // signed id is marked seen so the relay round-trip doesn't re-deliver it. - async relaySignedEvent({ event, username, text, ts, socketId, userId } = {}) { - await this.local.publish({ scope: 'global', username, text, ts, socketId, userId }); + async relaySignedEvent({ event, username, text, ts, socketId, userId, onLocalDelivery } = {}) { + await this.local.publish({ scope: 'global', username, text, ts, socketId, userId, onLocalDelivery }); if (this._globalEnabled() && event && event.id) { this._markSeen(event.id); try { await this.transport.publish(event); } diff --git a/src/network/chat/SocketChatProvider.js b/src/network/chat/SocketChatProvider.js index 4ec280f..c50833d 100644 --- a/src/network/chat/SocketChatProvider.js +++ b/src/network/chat/SocketChatProvider.js @@ -27,7 +27,7 @@ class SocketChatProvider extends ChatProvider { } async publish(msg = {}) { - const { scope = 'global', username, text, ts = Date.now(), socketId = null, userId = null } = msg; + const { scope = 'global', username, text, ts = Date.now(), socketId = null, userId = null, onLocalDelivery = null } = msg; // Defense in depth (S1): never broadcast the raw full socket.id to other clients; it is // a hijackable handle. Derive a short, non-sensitive public id for display/attribution. @@ -44,12 +44,14 @@ class SocketChatProvider extends ChatProvider { } else { this.io.emit('chat_broadcast', { username, message: text, timestamp: ts, publicId }); } + if (typeof onLocalDelivery === 'function') onLocalDelivery(); return; } // Room-scoped (e.g. tavern): delivered only to occupants of that room. The `scope` // field lets a room client filter these from any global broadcasts it also receives. this.io.to(scope).emit('chat_broadcast', { username, message: text, timestamp: ts, publicId, scope }); + if (typeof onLocalDelivery === 'function') onLocalDelivery(); } async getHistory({ scope = 'global', limit = 50 } = {}) { diff --git a/src/network/chatHandler.js b/src/network/chatHandler.js index 83c770d..9f39885 100644 --- a/src/network/chatHandler.js +++ b/src/network/chatHandler.js @@ -84,6 +84,7 @@ class ChatHandler { * Handle incoming chat messages with rate limiting */ async handleChatMessage(socket, msg, additionalHandlers = {}) { + const postingSession = this._captureChatSession(socket); try { // Rate limiting keys on stable id + IP so reconnecting can't reset the counter. const rlId = stableId(socket, this.gameModeManager?.sessionManager); @@ -117,7 +118,7 @@ class ChatHandler { } // If not a command, broadcast as chat message - await this._handleChatBroadcast(socket, msg); + await this._handleChatBroadcast(socket, msg, additionalHandlers.acceptedSpeech, postingSession); } catch (error) { console.error('Chat handler error:', error); @@ -132,7 +133,7 @@ class ChatHandler { * login), moderates, then relays it: the provider publishes the pre-signed event to nostr under * the player's npub, not the bridge. Serves lobby and tavern, both of which render global scope. */ - async handleSignedChatMessage(socket, payload) { + async handleSignedChatMessage(socket, payload, acceptedSpeech = null) { try { const rlId = stableId(socket, this.gameModeManager?.sessionManager); const rlIp = clientIp(socket); @@ -167,20 +168,35 @@ class ChatHandler { maxLen: 280 }); if (!verdict.ok) { - if (this.debugManager.CONSOLE_LOGGING) console.warn('[chat] signed event rejected:', verdict.reason); + if (this.debugManager?.CONSOLE_LOGGING) console.warn('[chat] signed event rejected:', verdict.reason); this.broadcastManager.sendStatusUpdate(socket.id, 'warning', 'Your signed message could not be verified.'); return; } + try { + if (await this.chatHistory.isUserChatBanned(userId, { strict: true })) { + this.broadcastManager.sendStatusUpdate(socket.id, 'error', 'You have been banned from chat.'); + return; + } + } catch (_) { + this.broadcastManager.sendStatusUpdate(socket.id, 'error', 'Chat moderation is temporarily unavailable.'); + return; + } + if (this.gameModeManager.sessionManager.sessions.get(socket.id) !== session || session.id !== userId) return; const username = row.display_name || row.username || String(npub).slice(0, 8); const text = escapeChatText(verdict.content, 200); // Delivers in-game (escaped) + relays the client-signed event to nostr under the player's npub. await this.chatProvider.relaySignedEvent({ - event, scope: 'global', username, text, ts: Date.now(), socketId: socket.id, userId + event, scope: 'global', username, text, ts: Date.now(), socketId: socket.id, userId, + onLocalDelivery: () => { + if (this.gameModeManager.sessionManager.sessions.get(socket.id) === session && session.id === userId + && typeof acceptedSpeech === 'function') acceptedSpeech(verdict.content.slice(0, 200)); + } }); } catch (err) { console.error('Signed chat handler error:', err.message); + this.broadcastManager.sendStatusUpdate(socket.id, 'error', 'Signed chat could not be delivered. Please try again.'); } } @@ -340,7 +356,15 @@ class ChatHandler { } } - async _handleChatBroadcast(socket, msg) { + _captureChatSession(socket) { + const sessions = this.gameModeManager?.sessionManager?.sessions; + const session = sessions?.get(socket.id); + const userId = session?.id; + return { userId, isCurrent: () => socket.disconnected !== true + && sessions?.get(socket.id) === session && session?.id === userId }; + } + + async _handleChatBroadcast(socket, msg, acceptedSpeech = null, postingSession = this._captureChatSession(socket)) { if (typeof msg !== 'string') return; const trimmed = msg.trim(); if (!trimmed) return; @@ -359,20 +383,25 @@ class ChatHandler { try { const userRow = await this.gameModeManager.getOrCreateUser(socket.id); userId = userRow?.id || null; + if (!userId) throw new Error('Chat user lookup did not resolve a user.'); - if (userId && await this.chatHistory.isUserChatBanned(userId)) { + if (userId && await this.chatHistory.isUserChatBanned(userId, { strict: true })) { this.broadcastManager.sendStatusUpdate(socket.id, 'error', 'You have been banned from chat.'); return; } } catch (e) { - // Continue without user lookup - allow message + // Unknown moderation cannot authorize a global message. if (this.debugManager?.CONSOLE_LOGGING) { console.warn('User lookup for chat failed:', e.message); } + this.broadcastManager.sendStatusUpdate(socket.id, 'error', 'Chat moderation is temporarily unavailable.'); + return; } } + if (!postingSession.isCurrent() || (postingSession.userId != null && userId !== postingSession.userId)) return; + // Additional rate limit for broadcast messages (more restrictive) const now = Date.now(); const last = this._chatLastSent.get(socket.id) || 0; @@ -397,14 +426,17 @@ class ChatHandler { .slice(0, MAX_MESSAGE_LENGTH); const username = socket.id.substring(0, 6); - // The provider broadcasts and saves to history (fire-and-forget). + // Await local provider acceptance before room speech can be emitted. await this.chatProvider.publish({ scope: 'global', username: username, text: safe, ts: now, socketId: socket.id, - userId: userId + userId: userId, + onLocalDelivery: () => { + if (postingSession.isCurrent() && typeof acceptedSpeech === 'function') acceptedSpeech(trimmed); + } }); } diff --git a/src/network/chatHistoryManager.js b/src/network/chatHistoryManager.js index 7177e35..19f1a9f 100644 --- a/src/network/chatHistoryManager.js +++ b/src/network/chatHistoryManager.js @@ -295,16 +295,23 @@ class ChatHistoryManager { * @param {number} userId - User ID to check * @returns {boolean} True if user is banned */ - async isUserChatBanned(userId) { - if (!userId || !this.db) return false; + async isUserChatBanned(userId, { strict = false } = {}) { + if (!userId || !this.db) { + if (strict) throw new Error('Chat moderation is temporarily unavailable.'); + return false; + } try { const result = await this.db.query( 'SELECT chat_banned FROM users WHERE id = $1', [userId] ); + if (strict && typeof result.rows[0]?.chat_banned !== 'boolean') { + throw new Error('Chat moderation is temporarily unavailable.'); + } return result.rows[0]?.chat_banned === true; } catch (error) { + if (strict) throw new Error('Chat moderation is temporarily unavailable.'); console.error('Failed to check chat ban status:', error.message); return false; } diff --git a/src/network/socketHandlers.js b/src/network/socketHandlers.js index bf48926..d47c64b 100644 --- a/src/network/socketHandlers.js +++ b/src/network/socketHandlers.js @@ -857,6 +857,7 @@ class SocketHandlers { }; on('chat message', (msg) => this.chatHandler.handleChatMessage(socket, msg, { + acceptedSpeech: this.tavernManager.captureSpeech(socket), // Legacy text command has no client contribution, but still consumes the already // published one-time server offer with an empty clientSeed. handleGameQueue: (commandSocket) => runAdmission('chat_game_queue', @@ -865,7 +866,8 @@ class SocketHandlers { handleStatsRequest: (socket) => this.handleStatsRequest(socket) })); // Client-signed global chat event (posts under the player's own Smirk npub). - on('chat_signed', (payload) => this.chatHandler.handleSignedChatMessage(socket, payload)); + on('chat_signed', (payload) => this.chatHandler.handleSignedChatMessage( + socket, payload, this.tavernManager.captureSpeech(socket))); on('player_move', (moveData) => this.movementManager.handleMove(socket.id, moveData)); on('disconnect', () => this.handleDisconnect(socket)); on('debug_ping', (data) => this.handleDebugPing(socket, data)); diff --git a/src/network/tavernManager.js b/src/network/tavernManager.js index ea7aab3..d014d78 100644 --- a/src/network/tavernManager.js +++ b/src/network/tavernManager.js @@ -38,6 +38,7 @@ class TavernManager { this._lastMoveAt = new Map(); // socketId -> timestamp this.chatCooldownMs = 900; // per-occupant chat flood guard this._lastChatAt = new Map(); // socketId -> timestamp + this._chatInFlight = new Map(); // socketId -> unique send admission token this._tickInterval = null; this.entitlementProvider = entitlementProvider; @@ -169,40 +170,89 @@ class TavernManager { if (!this.enabled) return; const occ = this.room.getOccupant(socket.id); if (!occ) return; // must be in the tavern to talk + const speech = this._captureSpeech(socket); let text = (data && typeof data.text === 'string') ? data.text.trim() : ''; if (!text) return; if (text.length > TavernManager.MAX_CHAT_LENGTH) text = text.slice(0, TavernManager.MAX_CHAT_LENGTH); const now = Date.now(); - if (now - (this._lastChatAt.get(socket.id) || 0) < this.chatCooldownMs) { + if (this._chatInFlight.has(socket.id) + || now - (this._lastChatAt.get(socket.id) || 0) < this.chatCooldownMs) { // Tell the sender instead of silently dropping: a silent drop with a cleared // input reads as "my message disappeared". this._notice(socket, 'Easy, wait a moment before your next message.'); return; } - const moderation = await this._moderateChat(socket); - if (!moderation.allowed) { - this._notice(socket, moderation.message); - return; + // Claim synchronously before moderation can yield. A failed lookup releases the claim + // without imposing a new cooldown; accepted delivery keeps the existing cooldown policy. + const admission = {}; + this._chatInFlight.set(socket.id, admission); + try { + const moderation = await this._moderateChat(socket); + if (!moderation.allowed) { + this._notice(socket, moderation.message); + return; + } + if (!speech.isCurrent()) return; + this._lastChatAt.set(socket.id, now); + + const username = occ.name || String(socket.id).slice(0, 6); + // Global chat remains trusted-escaped HTML. Speech uses the original plain text. + const provider = this.globalChatProvider || this.chatProvider; + const scope = this.globalChatProvider ? 'global' : this.channel; + await provider.publish({ + scope, + username, + text: escapeHtml(text), + ts: now, + socketId: socket.id, + userId: moderation.userId, + onLocalDelivery: () => { + // Relay fan-out can remain pending after accepted local delivery. + if (this._chatInFlight.get(socket.id) === admission) this._chatInFlight.delete(socket.id); + speech.accept(text); + } + }); + } finally { + // A later send, including on the same visit, may already own another admission. + if (this._chatInFlight.get(socket.id) === admission) this._chatInFlight.delete(socket.id); } + } - this._lastChatAt.set(socket.id, now); + // Capture before async authentication/publishing. A new visit on the same socket is a + // different Occupant and must never inherit a delayed message from the previous visit. + captureSpeech(socket) { + return this._captureSpeech(socket)?.accept || null; + } - const username = occ.name || String(socket.id).slice(0, 6); - // Escape here: delivery is trusted-escaped and rendered as HTML on the client. Routing to - // global chat (persisted, broadcast to everyone, relayed over nostr when enabled) keeps the - // tavern in one global conversation; tavern-scoped is used when no global provider exists. - const provider = this.globalChatProvider || this.chatProvider; - const scope = this.globalChatProvider ? 'global' : this.channel; - provider.publish({ - scope, - username, - text: escapeHtml(text), - ts: now, - socketId: socket.id, - userId: moderation.userId + _captureSpeech(socket) { + const occ = this.enabled && this.room.getOccupant(socket.id); + if (!occ) return null; + const sessions = this.chatModeration?.sessionManager?.sessions; + const session = sessions?.get(socket.id); + const userId = session?.id; + const isCurrent = () => this.enabled && socket.disconnected !== true + && this.room.getOccupant(socket.id) === occ + && sessions?.get(socket.id) === session && session?.id === userId; + let delivered = false; + return { + isCurrent, + accept: (text) => { + if (delivered) return; + delivered = true; + if (isCurrent()) this._emitSpeech(occ, text); + } + }; + } + + _emitSpeech(occ, text) { + if (!this.enabled || this.room.getOccupant(occ.id) !== occ) return; + if (typeof text !== 'string' || !text.trim()) return; + // Occupant handles already belong to this room snapshot. Never add them to global chat. + this.io.to(this.channel).emit('tavern_speech', { + occupantId: occ.id, text: text.slice(0, TavernManager.MAX_CHAT_LENGTH) }); } @@ -237,15 +287,18 @@ class TavernManager { const row = mod.getOrCreateUser ? await mod.getOrCreateUser(socket.id) : null; userId = row?.id || null; } catch (e) { - if (this.debugManager?.CONSOLE_LOGGING) console.warn('[Tavern] chat user lookup failed:', e.message); + return { allowed: false, message: 'Chat moderation is temporarily unavailable.', userId: null }; } + if (!userId && mod.getOrCreateUser) { + return { allowed: false, message: 'Chat moderation is temporarily unavailable.', userId: null }; + } if (userId && mod.chatHistory?.isUserChatBanned) { let banned = false; try { - banned = await mod.chatHistory.isUserChatBanned(userId); + banned = await mod.chatHistory.isUserChatBanned(userId, { strict: true }); } catch (e) { - if (this.debugManager?.CONSOLE_LOGGING) console.warn('[Tavern] ban lookup failed:', e.message); + return { allowed: false, message: 'Chat moderation is temporarily unavailable.', userId }; } if (banned) return { allowed: false, message: 'You have been banned from chat.', userId }; } @@ -261,6 +314,7 @@ class TavernManager { const existed = this.room.removeOccupant(socketId); this._lastMoveAt.delete(socketId); this._lastChatAt.delete(socketId); + this._chatInFlight.delete(socketId); if (existed) { const sock = socket || (this.io.sockets?.sockets?.get?.(socketId)); if (sock) sock.leave(this.channel); @@ -281,6 +335,7 @@ class TavernManager { } this._lastMoveAt.clear(); this._lastChatAt.clear(); + this._chatInFlight.clear(); } } diff --git a/src/scripts/showcase-browser-smoke.js b/src/scripts/showcase-browser-smoke.js index d6ebcbc..7ecdd17 100644 --- a/src/scripts/showcase-browser-smoke.js +++ b/src/scripts/showcase-browser-smoke.js @@ -3,7 +3,7 @@ // Local browser checks cover the real TavernManager, pack-gated rendering, and a client-only // account/payout visibility matrix. They do not start the application entrypoint, database, live // wallet, payment handlers, or multiplayer queue. Mica receives synthetic Interior and Iso grants; -// Moth receives the source-owned zero-grant catalog fixture and must remain original-only. +// Moth receives the source-owned zero-grant catalog fixture and the free Adventurer baseline. const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); @@ -12,6 +12,7 @@ const { Server } = require('socket.io'); const { chromium } = require('playwright-core'); const TavernManager = require('../network/tavernManager'); const Entitlements = require('../multiplayer/entitlements'); +const SocketChatProvider = require('../network/chat/SocketChatProvider'); const ROOT = path.resolve(__dirname, '../..'); const HTML_ROOT = path.join(ROOT, 'html'); @@ -270,18 +271,18 @@ async function main() { io, tickMs: 50, entitlementProvider: entitlementsForSocket, - globalChatProvider: { - publish(message) { - io.emit('chat_broadcast', { - scope: 'global', username: message.username, message: message.text - }); - } - } + // The production local provider invokes onLocalDelivery after the accepted chat + // broadcast. It has no history manager here, so this remains local and ephemeral. + globalChatProvider: new SocketChatProvider({ io }) }); const browserFailures = []; const blockedExternal = []; const clientsByRole = new Map(); - const expectedMissingSkin = '/assets/generated/wownero_walk.webp'; + const expectedMissingSkinPaths = [ + '/assets/generated/monero_knight_walk.webp', + '/assets/generated/wownero_walk.webp', + '/assets/generated/operative_walk.webp' + ]; const observedHttpFailures = []; app.use((req, res, next) => { @@ -367,11 +368,13 @@ async function main() { } }); const page = await context.newPage(); - await page.route(`**${expectedMissingSkin}`, route => route.fulfill({ - status: 404, - contentType: 'text/plain', - body: 'Generated skin failure fixture' - })); + for (const skinPath of expectedMissingSkinPaths) { + await page.route(`**${skinPath}`, route => route.fulfill({ + status: 404, + contentType: 'text/plain', + body: 'Generated skin failure fixture' + })); + } page.on('response', response => { if (response.status() >= 400) { observedHttpFailures.push({ path: new URL(response.url()).pathname, status: response.status() }); @@ -381,7 +384,7 @@ async function main() { page.on('console', message => { if (message.type() !== 'error') return; const expectedAssetFailure = message.text().includes('Failed to load resource') - && observedHttpFailures.some(f => f.status === 404 && f.path === expectedMissingSkin); + && observedHttpFailures.some(f => f.status === 404 && expectedMissingSkinPaths.includes(f.path)); if (!expectedAssetFailure) browserFailures.push(message.text()); }); views[role] = { context, page }; @@ -458,7 +461,9 @@ async function main() { const appearance = RK.avatarVisuals.resolve({ avatar: 'default' }, { projection: 'topdown' }); return { canUse: Object.fromEntries(ids.map(id => [id, RK.canUsePack(id)])), + canUseModes: Object.fromEntries(['tiles', 'ascii', 'iso', '3d'].map(id => [id, RK.canUseMode(id)])), resolvedDefaultPack: appearance.pack, + resolvedDefaultAvatar: appearance.appearance && appearance.appearance.avatar, resolvedDefaultAllowed: appearance.allowed, activeTopdownPack: RK.activePackId('topdown'), credits: RK.entitlements.credits, @@ -470,25 +475,66 @@ async function main() { && !packPolicy.moth.canUse['generated-skins'] && !packPolicy.moth.canUse['iso-dungeon'] && !packPolicy.moth.canUse['roguelike-dungeon'] && !packPolicy.moth.canUse['iso-medieval'] && !packPolicy.moth.canUse['kenney-3d-characters'], 'Moth did not retain original-only zero-grant policy'); - assert(packPolicy.moth.resolvedDefaultPack === 'roguelike-interior' - && !packPolicy.moth.resolvedDefaultAllowed && packPolicy.moth.activeTopdownPack === 'original' + assert(packPolicy.moth.resolvedDefaultPack === null + && packPolicy.moth.resolvedDefaultAvatar === 'char-villager' && packPolicy.moth.resolvedDefaultAllowed + && packPolicy.moth.activeTopdownPack === 'original' && packPolicy.moth.credits === 0 && packPolicy.moth.totalCreditsPurchased === 0, - 'Moth default character or active tileset bypassed the real pack policy'); + 'Moth free Adventurer or active tileset did not match the real zero-grant policy'); + // The character policy is independent of the tileset policy: Moth keeps the free + // Adventurer avatar while the paid Interior, Iso, and 3D modes remain locked. + const mothPicker = views.moth.page; + await mothPicker.locator('#customizeBtn').click(); + const adventurerCard = mothPicker.locator('.rk-avatar-grid .rk-option-card').filter({ hasText: 'Adventurer' }); + await adventurerCard.waitFor({ state: 'visible' }); + const adventurerState = await adventurerCard.evaluate(node => { + const rect = node.getBoundingClientRect(); + return { + selected: node.classList.contains('is-selected'), + locked: node.classList.contains('is-locked'), + visible: rect.width > 0 && rect.height > 0, + label: node.innerText.trim() + }; + }); + assert(adventurerState.selected && !adventurerState.locked && adventurerState.visible, + 'The free Adventurer was not visibly selected in Moth’s picker'); + const paidModeStates = await mothPicker.evaluate(() => Object.fromEntries(['iso', '3d'].map(id => { + const mode = RK.RENDER_MODES.find(item => item.id === id); + const button = Array.from(document.querySelectorAll('.rk-mode-grid .rk-mode-card')) + .find(node => node.textContent.includes(mode.label)); + return [id, { allowed: RK.canUseMode(id), locked: !!button?.classList.contains('is-locked'), + disabled: button?.getAttribute('aria-disabled') === 'true' }]; + }))); + assert(!paidModeStates.iso.allowed && paidModeStates.iso.locked && paidModeStates.iso.disabled + && !paidModeStates['3d'].allowed && paidModeStates['3d'].locked && paidModeStates['3d'].disabled, + 'Moth’s paid Iso or 3D render mode was not locked in the picker'); + const adventurerScreenshot = 'tavern-free-adventurer-picker.png'; + await mothPicker.screenshot({ path: path.join(outputDir, adventurerScreenshot), fullPage: true }); + await mothPicker.locator('.rk-customize-shell .rk-cancel').click(); assert(packPolicy.mica.canUse.original && packPolicy.mica.canUse['roguelike-interior'] && packPolicy.mica.canUse['iso-dungeon'] && !packPolicy.mica.canUse['generated-skins'] && !packPolicy.mica.canUse['roguelike-dungeon'] && !packPolicy.mica.canUse['iso-medieval'] && !packPolicy.mica.canUse['kenney-3d-characters'], 'Mica fixture did not match its two explicit pack grants'); - assert(packPolicy.mica.resolvedDefaultPack === 'roguelike-interior' + assert(packPolicy.mica.resolvedDefaultPack === null && packPolicy.mica.resolvedDefaultAvatar === 'char-villager' && packPolicy.mica.resolvedDefaultAllowed && packPolicy.mica.credits === 0 && packPolicy.mica.totalCreditsPurchased === 0, - 'Mica synthetic character grant changed the no-funds balance or failed to permit the asset'); + 'Mica’s free Adventurer or no-funds balance did not match the fixture'); for (const { page } of Object.values(views)) { await page.evaluate(() => { - const original = RK.drawCharTileCanvas; - window.__showcaseCharTileDraws = 0; - RK.drawCharTileCanvas = function () { - window.__showcaseCharTileDraws += 1; - return original.apply(this, arguments); + const original = RK.avatarVisuals.drawTopdownWorld; + window.__showcasePlayerCharacterDraws = { + count: 0, charVillagerSeen: false, nonCanonicalAvatarSeen: false + }; + RK.avatarVisuals.drawTopdownWorld = function (ctx, visual, entity) { + const drawn = original.apply(this, arguments); + if (drawn && entity && entity.you === true) { + window.__showcasePlayerCharacterDraws.count += 1; + if (visual && visual.appearance && visual.appearance.avatar === 'char-villager') { + window.__showcasePlayerCharacterDraws.charVillagerSeen = true; + } else { + window.__showcasePlayerCharacterDraws.nonCanonicalAvatarSeen = true; + } + } + return drawn; }; }); } @@ -497,22 +543,29 @@ async function main() { await views.moth.page.locator('#name').fill('Moth'); await views.moth.page.locator('#joinBtn').click(); await Promise.all(Object.values(views).map(({ page }) => page.locator('#stage canvas.rk-canvas').waitFor({ state: 'visible' }))); - await views.mica.page.waitForFunction(() => RK.charAtlas() && window.__showcaseCharTileDraws > 0, + await views.mica.page.waitForFunction(() => RK.charAtlas() && window.__showcasePlayerCharacterDraws.count > 0, + undefined, { timeout: 5000 }); + await views.moth.page.waitForFunction(() => RK.charAtlas() && window.__showcasePlayerCharacterDraws.count > 0, undefined, { timeout: 5000 }); const characterRenderProof = {}; for (const role of ['mica', 'moth']) { characterRenderProof[role] = await views[role].page.evaluate(() => ({ atlasReady: !!RK.charAtlas(), - drawCalls: window.__showcaseCharTileDraws, + playerDraws: window.__showcasePlayerCharacterDraws, + resolvedDefaultAvatar: RK.avatarVisuals.resolve({ avatar: 'default' }, { projection: 'topdown' }).appearance.avatar, defaultAllowed: RK.avatarVisuals.resolve({ avatar: 'default' }, { projection: 'topdown' }).allowed })); } - assert(characterRenderProof.mica.atlasReady && characterRenderProof.mica.drawCalls > 0 - && characterRenderProof.mica.defaultAllowed, 'Permitted synthetic Interior character was not actually drawn'); - assert(characterRenderProof.moth.drawCalls === 0 && !characterRenderProof.moth.defaultAllowed, - 'Original-only free client unexpectedly drew a gated character'); + assert(characterRenderProof.mica.atlasReady && characterRenderProof.mica.playerDraws.count > 0 + && characterRenderProof.mica.defaultAllowed, 'Mica’s permitted character was not actually drawn'); + assert(characterRenderProof.moth.atlasReady && characterRenderProof.moth.playerDraws.count > 0 + && characterRenderProof.moth.playerDraws.charVillagerSeen + && !characterRenderProof.moth.playerDraws.nonCanonicalAvatarSeen + && characterRenderProof.moth.resolvedDefaultAvatar === 'char-villager' + && characterRenderProof.moth.defaultAllowed, + 'The free Moth avatar did not render as the canonical Adventurer'); await views.mica.page.screenshot({ - path: path.join(outputDir, 'tavern-synthetic-interior-character.png'), fullPage: true + path: path.join(outputDir, 'tavern-mica-synthetic-interior-tileset.png'), fullPage: true }); await pageWaitFor(() => manager.room.size === 2, 3000, 'Two browser clients joined TavernManager'); assert(clientsByRole.size === 2, 'Both page-owned client ids were not registered'); @@ -521,10 +574,67 @@ async function main() { assert(manager.room.getOccupant(ids.mica)?.name === 'Mica', 'Mica page id does not map to its server occupant'); assert(manager.room.getOccupant(ids.moth)?.name === 'Moth', 'Moth page id does not map to its server occupant'); + const speechText = 'Room check & hello'; + for (const { page } of Object.values(views)) { + await page.evaluate(expected => { + window.__showcaseSpeechCalls = []; + window.__showcaseSpeechPaints = []; + window.__showcaseSpeechAnchors = []; + window.__showcaseExpectedSpeechText = expected; + const proto = RK.TavernLife.prototype; + const show = proto.showPlayerBubble; + proto.showPlayerBubble = function (id, text) { + window.__showcaseSpeechCalls.push({ id, text }); + return show.call(this, id, text); + }; + const screenPos = proto._entityScreenPos; + proto._entityScreenPos = function (entity) { + const point = screenPos.apply(this, arguments); + if (entity && this._realBubbles && this._realBubbles[entity.id] + && this._realBubbles[entity.id].text === expected && point) { + window.__showcaseSpeechAnchors.push({ id: entity.id, x: point.x, y: point.y }); + } + return point; + }; + const fillText = CanvasRenderingContext2D.prototype.fillText; + CanvasRenderingContext2D.prototype.fillText = function (text) { + if (text === window.__showcaseExpectedSpeechText) window.__showcaseSpeechPaints.push(text); + return fillText.apply(this, arguments); + }; + }, speechText); + } const chatInput = views.mica.page.locator('#chatInput'); - await chatInput.fill('Room check'); + await chatInput.fill(speechText); await views.mica.page.locator('#chatForm button[type="submit"]').click(); - await views.moth.page.locator('#chatLog').getByText('Room check').waitFor(); + for (const { page } of Object.values(views)) { + await page.locator('#chatLog .cline').filter({ hasText: speechText }).waitFor(); + await page.waitForFunction(expected => window.__showcaseSpeechCalls.length === 1 + && window.__showcaseSpeechCalls[0].text === expected + && window.__showcaseSpeechPaints.length > 0, speechText); + } + const speechProof = {}; + const speechScreenshots = {}; + for (const role of ['mica', 'moth']) { + speechProof[role] = await views[role].page.evaluate(() => { + const lines = Array.from(document.querySelectorAll('#chatLog .cline')) + .filter(node => node.textContent.includes(window.__showcaseExpectedSpeechText)); + return { + calls: window.__showcaseSpeechCalls, + paints: window.__showcaseSpeechPaints.length, + anchors: window.__showcaseSpeechAnchors, + exactTextLineCount: lines.length, + injectedBoldElements: lines.reduce((sum, line) => sum + line.querySelectorAll('b').length, 0) + }; + }); + assert(speechProof[role].calls.length === 1 && speechProof[role].calls[0].id === ids.mica + && speechProof[role].calls[0].text === speechText && speechProof[role].paints > 0 + && speechProof[role].anchors.some(anchor => anchor.id === ids.mica) + && speechProof[role].exactTextLineCount === 1 && speechProof[role].injectedBoldElements === 0, + `${role} did not render one escaped speech bubble above the exact Mica occupant`); + const filename = `tavern-${role}-accepted-chat-bubble.png`; + await views[role].page.screenshot({ path: path.join(outputDir, filename), fullPage: true }); + speechScreenshots[role] = filename; + } const keyboard = views.mica.page; const micaStart = { ...manager.room.getOccupant(ids.mica) }; @@ -669,8 +779,13 @@ async function main() { await mobilePage.locator('#leaveSpectateBtn').click(); await mobilePage.waitForFunction(() => document.activeElement === document.querySelector('#tavernDpad [data-dir="up"]')); - const unexpectedHttpFailures = observedHttpFailures.filter(f => !(f.status === 404 && f.path === expectedMissingSkin)); - assert(observedHttpFailures.some(f => f.status === 404 && f.path === expectedMissingSkin), 'Expected missing generated skin was not requested'); + const observedMissingSkinPaths = new Set(observedHttpFailures + .filter(f => f.status === 404 && expectedMissingSkinPaths.includes(f.path)) + .map(f => f.path)); + assert(expectedMissingSkinPaths.every(skinPath => observedMissingSkinPaths.has(skinPath)), + 'The local fixture did not exercise each registered generated-skin fallback'); + const unexpectedHttpFailures = observedHttpFailures.filter(f => f.status !== 404 + || !expectedMissingSkinPaths.includes(f.path)); assert(unexpectedHttpFailures.length === 0, `Unexpected HTTP failures: ${JSON.stringify(unexpectedHttpFailures)}`); assert(blockedExternal.length === 0, `Browser attempted external network access: ${blockedExternal.join(', ')}`); assert(browserFailures.length === 0, `Browser errors: ${browserFailures.join(' | ')}`); @@ -687,20 +802,23 @@ async function main() { ok: true, scope: 'local Tavern lifecycle/graphics smoke plus a client-only account visibility matrix; no paid gameplay, queue/race transitions, database, or live wallet', origin: '127.0.0.1 loopback only', - fixture: 'Mica receives synthetic roguelike-interior and iso-dungeon grants; Moth receives the authoritative zero-grant, original-only snapshot; both have zero balances and no purchase, skin or 3D grant', + fixture: 'Mica receives synthetic roguelike-interior and iso-dungeon grants; Moth receives the authoritative zero-grant, original-only snapshot and free Adventurer; both have zero balances and no purchase, skin or 3D grant', clients: { count: clientsByRole.size, mappedByPageOwnedSocketId: true }, packPolicy, + freeAdventurerPicker: { moth: adventurerState, paidModes: paidModeStates, screenshot: adventurerScreenshot }, characterRenderProof, modes: modeResults, - chat: 'broadcast to both clients', + chat: { acceptedRoomSpeech: speechProof, screenshots: speechScreenshots, text: speechText }, keyboardFocusGuards: ['input', 'select', 'contenteditable'], mobile, activeArena: { desktop: desktopArena, mobile: mobileArena, arenaReceivesSafeInitialFocus: true, tavernFocusRestored: true }, missingGeneratedSkin: skinFailure, + missingGeneratedSkinFixturePaths: expectedMissingSkinPaths, accountUi, tavernAccountLink, screenshots: { - syntheticInteriorCharacter: 'tavern-synthetic-interior-character.png', + micaSyntheticInteriorTileset: 'tavern-mica-synthetic-interior-tileset.png', + freeAdventurerPicker: adventurerScreenshot, freeOriginalBaseline: screenshotPaths.moth, desktopIso: 'tavern-desktop-iso.png', mobile: screenshotPaths, smirkAccount: tavernAccountLink.screenshots diff --git a/test/adventurerDefault.test.js b/test/adventurerDefault.test.js new file mode 100644 index 0000000..83a3c30 --- /dev/null +++ b/test/adventurerDefault.test.js @@ -0,0 +1,151 @@ +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); +const Appearance = require('../src/multiplayer/appearance'); +const Entitlements = require('../src/multiplayer/entitlements'); + +// Only DOM/canvas/Pixi primitives and atlas I/O are replaced. Catalogs, entitlement +// resolution, normalization, customizer, and both renderer paths are production code. +function kit() { + const frames = [], loads = [], draws = []; + let ready = false; + const ctx = new Proxy({}, { get(target, key) { return target[key] || (() => {}); } }); + function element(tag) { + const e = { tagName: tag, style: {}, children: [], className: '', textContent: '', + appendChild(c) { this.children.push(c); c.parentNode = this; }, + removeChild(c) { this.children = this.children.filter(x => x !== c); c.parentNode = null; }, + getContext: () => ctx, setAttribute() {}, addEventListener() {} }; + e.classList = { add(c) { if (!e.className.split(' ').includes(c)) e.className += ' ' + c; }, + remove(c) { e.className = e.className.split(' ').filter(x => x !== c).join(' '); }, + contains(c) { return e.className.split(' ').includes(c); } }; + Object.defineProperty(e, 'innerHTML', { set() { e.children = []; } }); + return e; + } + const document = { createElement: element, head: element('head'), body: element('body'), getElementById: () => null }; + const context = { document, localStorage: { getItem: () => null, setItem() {} }, + Image: class {}, console, Date, requestAnimationFrame(fn) { frames.push(fn); }, cancelAnimationFrame() {} }; + context.window = context; + vm.createContext(context); + for (const file of ['charSprites', 'skins', 'assetPacks', 'charCustomize', 'avatarVisuals', 'tileRenderer', 'fancyRenderer']) { + vm.runInContext(fs.readFileSync(path.join(__dirname, '../html/js/render/' + file + '.js'), 'utf8'), context); + } + const RK = context.RK; + RK.setEntitlementSnapshot(Entitlements.snapshotForUser({ credits: 0, total_credits_purchased: 0 })); + RK.charAtlas = () => ready ? {} : null; + RK.loadCharAtlas = fn => { if (fn) loads.push(fn); }; + RK.drawCharTileCanvas = (...args) => { draws.push(args); return true; }; + RK.drawCharCompositeCanvas = () => ready; + return { RK, frames, loads, draws, document, ctx, element, + ready() { ready = true; }, complete() { loads.splice(0).forEach(fn => fn()); } }; +} +function descendants(e) { return [e, ...e.children.flatMap(descendants)]; } +function scene(id, appearance = { avatar: 'default' }) { + return { cols: 1, rows: 1, grid: [['floor']], legend: { floor: { color: '#654321' } }, + entities: [{ id, kind: 'avatar', x: 0, y: 0, appearance }] }; +} +function tiled(k) { + k.RK.themeAtlas = () => null; k.RK.tileMap = () => ({}); k.RK.roomReady = () => false; + const r = new k.RK.TileRenderer(k.element('host')); + for (const name of ['_collectEmitters', '_snapshot', '_ensureEmbers', '_composite', '_startLoop']) r[name] = () => {}; + return r; +} +function fancy(k) { + const r = Object.create(k.RK.FancyRenderer.prototype); + Object.assign(r, { app: {}, cell: 24, sprites: {}, entityLayer: { addChild() {}, removeChild() {} } }); + const made = []; + for (const [method, kind] of [['_makeCharSprite', 'char'], ['_makeSkinSprite', 'skin'], ['_makeSprite', 'circle']]) { + r[method] = e => { made.push({ kind, e }); return { destroy() {} }; }; + } + r.show = s => { r._lastScene = s; r._syncEntities(s); }; + return { r, made }; +} + +test('client and server normalize defaults and preserve every valid catalog identity and character fields', () => { + const { RK } = kit(); + const inputs = [undefined, null, {}, 'default', 'unknown', { appearance: { avatar: 'default' } }, + ...Appearance.avatarIds().map(avatar => ({ avatar, tint: 'moss', colors: { base: 'teal', hair: 'silver' }, equipment: { body: 'mail', weapon: 'bow' } }))]; + for (const input of inputs) expect(RK.normalizeAppearance(input)).toEqual(Appearance.normalizeAppearance(input)); + expect(RK.appearances().filter(a => a.id === 'char-villager').map(a => a.label)).toEqual(['Adventurer']); + expect(RK.appearances().some(a => a.id === 'default')).toBe(false); +}); + +test.each(['ascii', 'topdown', 'iso', '3d'])('Adventurer is selected and remains the same saved identity in %s picker', projection => { + const k = kit(); k.ready(); + const saved = []; + k.RK.openCustomize('default', ap => saved.push(ap), { projection }); + const nodes = descendants(k.document.body); + const cards = nodes.filter(e => e.classList.contains('rk-option-card')); + const adventurers = cards.filter(e => e.children.some(c => c.textContent === 'Adventurer')); + expect(adventurers).toHaveLength(1); + expect(adventurers[0].classList.contains('is-selected')).toBe(true); + nodes.find(e => e.classList.contains('rk-save')).onclick(); + expect(saved[0]).toEqual(Appearance.normalizeAppearance('char-villager')); + expect(k.RK.canUsePack('kenney-3d-characters')).toBe(false); +}); + +test.each(['green', 'char-ranger'])('opening another projection preserves saved %s identity', avatar => { + const k = kit(); k.ready(); const saved = []; + const ap = { avatar, colors: { base: 'teal', hair: 'silver' }, equipment: { weapon: 'bow' } }; + k.RK.openCustomize(ap, value => saved.push(value), { projection: 'ascii' }); + descendants(k.document.body).find(e => e.classList.contains('rk-save')).onclick(); + expect(saved[0]).toEqual(Appearance.normalizeAppearance(ap)); +}); + +test('actual FREE catalog permits character rendering without unlocking premium environments or skins', () => { + const { RK } = kit(); + expect(RK.canUsePack('roguelike-interior')).toBe(false); + for (const id of ['char-villager', 'char-ranger']) { + const visual = RK.avatarVisuals.resolve(id, { projection: 'topdown' }); + expect(visual.allowed).toBe(true); expect(visual.pack).toBeNull(); + } + expect(RK.avatarVisuals.resolve('monero-knight', { projection: 'topdown' }).allowed).toBe(false); + expect(RK.avatarVisuals.resolve('char-villager', { projection: '3d' }).allowed).toBe(false); + expect(RK.avatarVisuals.resolve('green', { projection: 'topdown' }).appearance.avatar).toBe('green'); +}); + +test('actual tiled FREE path repaints a canonical default character after atlas completion', () => { + const k = kit(), r = tiled(k); + r.render(scene('first')); r.render(scene('latest')); + expect(k.draws).toHaveLength(0); + k.ready(); k.complete(); + expect(k.frames).toHaveLength(1); k.frames.shift()(); + expect(k.draws.some(args => args[1] === k.RK.CHARS['char-villager'].frame)).toBe(true); + expect(k.frames).toHaveLength(0); +}); + +test('Fancy uses canonical appearance, redraws latest entities once, and keeps valid colors', () => { + const k = kit(), { r, made } = fancy(k); + r.show(scene('first')); r.show(scene('latest')); + expect(made.every(x => x.kind === 'circle')).toBe(true); + k.ready(); k.complete(); expect(k.frames).toHaveLength(1); k.frames.shift()(); + expect(made.filter(x => x.kind === 'char').map(x => [x.e.id, x.e.avatar])).toEqual([['latest', 'char-villager']]); + const explicit = scene('saved', { avatar: 'char-ranger', colors: { base: 'teal' } }); + explicit.entities[0].avatar = 'default'; + r.show(explicit); + expect(r.sprites.saved.e.appearance).toEqual(Appearance.normalizeAppearance(explicit.entities[0].appearance)); + r.show(scene('color', { avatar: 'green' })); + expect(r.sprites.color.kind).toBe('circle'); expect(r.sprites.color.e.avatar).toBe('green'); +}); + +test('Fancy never spins on failed atlas completion or repaints after destruction', () => { + const k = kit(), { r } = fancy(k); + r.show(scene('pending')); k.complete(); expect(k.frames).toHaveLength(0); + r.show(scene('retry')); k.ready(); k.complete(); expect(k.frames).toHaveLength(1); + r.app = null; const before = r.sprites; k.frames.shift()(); expect(r.sprites).toBe(before); +}); + + +test('Fancy default normalization never turns monsters, features, items, or cats into humanoid avatars', () => { + const k = kit(), { r, made } = fancy(k); k.ready(); + const mixed = scene('adventurer'); + for (const kind of ['monster', 'feature', 'item', 'cat']) { + mixed.entities.push({ id: kind, kind, x: 0, y: 0, color: '#f85149', char: kind === 'cat' ? 'c' : '~' }); + } + r.show(mixed); + expect(made.filter(x => x.kind === 'char').map(x => x.e.id)).toEqual(['adventurer']); + for (const entity of mixed.entities.slice(1)) { + expect(r.sprites[entity.id].kind).toBe('circle'); + expect(r.sprites[entity.id].e).toBe(entity); + expect(entity.avatar).toBeUndefined(); + } +}); diff --git a/test/appearance.test.js b/test/appearance.test.js index 44045c1..debe1e6 100644 --- a/test/appearance.test.js +++ b/test/appearance.test.js @@ -39,11 +39,8 @@ describe('appearance catalog normalization', () => { }); }); - test('falls back unknown avatars to default', () => { - expect(Appearance.normalizeAppearance('rainbow')).toEqual({ - avatar: 'default', - tint: 'none', - equipment: { body: 'none', head: 'none', shield: 'none', weapon: 'none' } - }); + test.each([undefined, null, {}, 'default', 'rainbow'])('normalizes legacy and missing defaults to the free Adventurer (%p)', input => { + expect(Appearance.normalizeAppearance(input)).toEqual(Appearance.normalizeAppearance('char-villager')); + expect(Appearance.normalizeAppearance(input).avatar).toBe('char-villager'); }); }); diff --git a/test/chatProvider.test.js b/test/chatProvider.test.js index b978db5..ac3c257 100644 --- a/test/chatProvider.test.js +++ b/test/chatProvider.test.js @@ -67,3 +67,28 @@ describe('SocketChatProvider', () => { expect(shut).toBe(false); }); }); + +describe('trusted local delivery boundary', () => { + test.each(['global', 'tavern:main'])('callback follows successful local emit and is never a payload/history field: %s', async scope => { + const io = makeFakeIo(); + const saved = []; + const provider = new SocketChatProvider({ io, historyManager: { saveMessage: async message => { saved.push(message); }, getRecentMessages: async () => [] } }); + const delivered = jest.fn(() => { + expect(io.emitted.some(e => e.event === 'chat_broadcast')).toBe(true); + }); + await provider.publish({ scope, username: 'Speaker', text: 'hello', onLocalDelivery: delivered }); + expect(delivered).toHaveBeenCalledTimes(1); + expect(io.emitted.every(e => !Object.hasOwn(e.payload, 'onLocalDelivery'))).toBe(true); + expect(saved.every(message => !Object.hasOwn(message, 'onLocalDelivery'))).toBe(true); + await provider.getHistory({ scope }); + expect(delivered).toHaveBeenCalledTimes(1); + }); + + test('failed local emit never invokes delivery even though the publisher rejects', async () => { + const delivered = jest.fn(); + const io = { emit() { throw new Error('disposable local emit failure'); } }; + const provider = new SocketChatProvider({ io }); + await expect(provider.publish({ scope: 'global', text: 'refused', onLocalDelivery: delivered })).rejects.toThrow(); + expect(delivered).not.toHaveBeenCalled(); + }); +}); diff --git a/test/entitlements.test.js b/test/entitlements.test.js index d502f7d..facdb76 100644 --- a/test/entitlements.test.js +++ b/test/entitlements.test.js @@ -7,8 +7,8 @@ describe('cosmetic entitlements', () => { expect(Entitlements.canUsePack(entitlements, 'generated-skins')).toBe(false); expect(Entitlements.canUsePack(entitlements, 'kenney-3d-characters')).toBe(false); - expect(Entitlements.normalizeAppearance({ avatar: 'monero-knight' }, entitlements).avatar).toBe('default'); - expect(Entitlements.normalizeAppearance({ avatar: 'kenney-survivor-male' }, entitlements).avatar).toBe('default'); + expect(Entitlements.normalizeAppearance({ avatar: 'monero-knight' }, entitlements).avatar).toBe('char-villager'); + expect(Entitlements.normalizeAppearance({ avatar: 'kenney-survivor-male' }, entitlements).avatar).toBe('char-villager'); }); test('graduated ladder: credit spend unlocks packs by threshold', () => { @@ -32,7 +32,7 @@ describe('cosmetic entitlements', () => { expect(entitlements.packs['generated-skins']).toBe(true); expect(entitlements.packs['kenney-3d-characters']).toBe(false); expect(Entitlements.normalizeAppearance({ avatar: 'monero-knight' }, entitlements).avatar).toBe('monero-knight'); - expect(Entitlements.normalizeAppearance({ avatar: 'kenney-survivor-male' }, entitlements).avatar).toBe('default'); + expect(Entitlements.normalizeAppearance({ avatar: 'kenney-survivor-male' }, entitlements).avatar).toBe('char-villager'); }); test('appearance catalog reports all premium avatar ids, including 3D models', () => { diff --git a/test/identityService.test.js b/test/identityService.test.js index 9fee30e..397e137 100644 --- a/test/identityService.test.js +++ b/test/identityService.test.js @@ -81,8 +81,8 @@ describe('IdentityService', () => { const snapshot = await svc.saveAppearanceForSocket(makeSocket(), { avatar: 'monero-knight' }); - expect(snapshot.appearance.avatar).toBe('default'); - expect(db.state.user.appearance.avatar).toBe('default'); + expect(snapshot.appearance.avatar).toBe('char-villager'); + expect(db.state.user.appearance.avatar).toBe('char-villager'); }); test('allows an explicitly granted pack appearance', async () => { diff --git a/test/tavernBubbleLayout.test.js b/test/tavernBubbleLayout.test.js new file mode 100644 index 0000000..2496ea5 --- /dev/null +++ b/test/tavernBubbleLayout.test.js @@ -0,0 +1,120 @@ +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +function fixture(width = 320, height = 300) { + let now = 1000; + const painted = [], bodies = []; + const ctx = { + clearRect() { painted.length = 0; bodies.length = 0; }, save() {}, restore() {}, + beginPath() {}, fill() {}, stroke() {}, moveTo() {}, lineTo() {}, closePath() {}, + roundRect(x, y, w, h) { bodies.push({ x, y, w, h }); }, + measureText(text) { return { width: Array.from(text).length * 7 }; }, + fillText(text, x, y) { painted.push({ text, x, y }); } + }; + const canvas = { style: {}, width, height, getContext: () => ctx }; + ctx.canvas = canvas; + const bounds = () => ({ left: 0, top: 0, width, height }); + const host = { style: {}, clientWidth: width, clientHeight: height, + appendChild(c) { c.parentNode = this; }, getBoundingClientRect: bounds, + querySelector: () => ({ width, height, getBoundingClientRect: bounds }) }; + const root = { RK: {}, CanvasRenderingContext2D: function () {}, document: { createElement: () => canvas } }; + root.CanvasRenderingContext2D.prototype.roundRect = function () {}; + vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../html/js/render/tavernLife.js'), 'utf8'), { window: root }); + const scene = { cols: 8, rows: 5, grid: Array.from({ length: 5 }, () => Array(8).fill('floor')), + entities: [{ id: 'speaker', x: 2, y: 2 }] }; + const life = new root.RK.TavernLife(host, () => scene, () => 24, { now: () => now }); + return { life, scene, painted, bodies, ctx, root, draw: () => life.update(scene, 24, 'tiles'), advance: ms => { now += ms; } }; +} + +describe('Tavern accepted speech layout', () => { + test('an actor-free authored room still paints accepted speech as literal text', () => { + const f = fixture(); + f.life.spawn(); + expect(f.life._spawned).toBe(false); + const text = 'Cheers & hello 🙂'; + f.life.showPlayerBubble('speaker', text); f.draw(); + expect(f.painted.map(p => p.text).join('')).toBe(text); + expect(f.bodies.length).toBeGreaterThan(0); + }); + + test('long unbroken and Unicode text wraps inside a narrow viewport', () => { + const f = fixture(160, 300), text = 'a'.repeat(90) + '🙂'.repeat(10) + ' & hello'; + f.life.showPlayerBubble('speaker', text); f.draw(); + expect(f.painted.length).toBeGreaterThan(1); + expect(f.painted.map(p => p.text).join('')).toBe(text); + for (const body of f.bodies) { + expect(body.x).toBeGreaterThanOrEqual(0); + expect(body.x + body.w).toBeLessThanOrEqual(160); + expect(body.y).toBeGreaterThanOrEqual(0); + expect(body.y + body.h).toBeLessThanOrEqual(300); + } + for (const line of f.painted) expect(line.text.includes('�')).toBe(false); + }); + + test('character bubbles anchor above sprite heads before viewport scaling', () => { + const f = fixture(); + f.root.RK.avatarVisuals = { resolve: () => ({ kind: 'char', allowed: true }) }; + const speaker = f.scene.entities[0]; + speaker.y = 4; + const point = f.life._entityScreenPos(speaker, f.scene, 24, 'tiles'); + const spriteTop = (speaker.y + 1) * 24 - 1.8 * 24; + expect(point.y).toBeLessThan(spriteTop); + f.life._viewTransform = { left: 13, top: 17, scaleX: 2, scaleY: 0.5 }; + const scaled = f.life._entityScreenPos(speaker, f.scene, 24, 'tiles'); + expect(scaled).toEqual({ x: 13 + point.x * 2, y: 17 + point.y * 0.5 }); + f.life._viewTransform = null; + expect(f.life._entityScreenPos(speaker, f.scene, 24, 'ascii').y).toBe(speaker.y * 24); + f.life.showPlayerBubble('speaker', 'hello'); f.draw(); + expect(f.bodies.every(body => body.y + body.h < spriteTop)).toBe(true); + }); + + test('actual default normalization never gives a cat a humanoid head position', () => { + const f = fixture(); + for (const name of ['charSprites', 'charCustomize', 'avatarVisuals']) { + vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../html/js/render/' + name + '.js'), 'utf8'), { window: f.root }); + } + expect(f.root.RK.avatarVisuals.resolve({ avatar: null }, { projection: 'topdown' }).kind).toBe('char'); + const cat = { x: 2, y: 3, role: 'cat', avatar: null, appearance: { avatar: null } }; + const point = f.life._entityScreenPos(cat, f.scene, 24, 'tiles'); + expect(point.y).toBeCloseTo((cat.y + 0.2) * 24); + expect(f.life._entityScreenPos({ ...cat, role: undefined, kind: 'cat' }, f.scene, 24, 'tiles')).toEqual(point); + }); + + test('failed skins anchor at the Adventurer fallback head', () => { + const f = fixture(); + const speaker = f.scene.entities[0]; + f.root.RK.avatarVisuals = { resolve: () => ({ kind: 'skin', allowed: true, appearance: { avatar: 'failed-skin' } }) }; + f.root.RK.SKINS = { 'failed-skin': { scale: 2.5 } }; + f.root.RK.skinSheetFailed = () => false; + expect(f.life._entityScreenPos(speaker, f.scene, 24, 'tiles').y).toBeCloseTo((speaker.y - 1.5) * 24); + f.root.RK.skinSheetFailed = () => true; + expect(f.life._entityScreenPos(speaker, f.scene, 24, 'tiles').y).toBeCloseTo((speaker.y - 0.9) * 24); + }); + + test('Iso bubbles use the selected character image height above its floor anchor', () => { + const f = fixture(); + f.root.RK.avatarVisuals = { resolve: () => ({ allowed: true, character: { imageH: 110 } }) }; + const speaker = f.scene.entities[0]; + const point = f.life._entityScreenPos(speaker, f.scene, 24, 'iso'); + const floor = 28 + 184 + (speaker.x + speaker.y) * 42 / 2; + expect(point.y).toBeCloseTo(floor + 42 * 0.95 - 110); + }); + + test('departure removes old speech before the same handle can return', () => { + const f = fixture(); + f.life.showPlayerBubble('speaker', 'old visit'); f.draw(); + f.scene.entities = []; f.draw(); + expect(Object.keys(f.life._realBubbles)).toEqual([]); + f.scene.entities = [{ id: 'speaker', x: 2, y: 2 }]; f.draw(); + expect(f.painted).toEqual([]); + }); + + test('offscreen speakers do not pin bubbles to a viewport edge; expiry still cleans up', () => { + const f = fixture(); + f.life.showPlayerBubble('speaker', 'hello'); f.scene.entities[0].x = -20; f.draw(); + expect(f.painted).toEqual([]); + f.advance(10000); f.draw(); + expect(Object.keys(f.life._realBubbles)).toEqual([]); + }); +}); diff --git a/test/tavernChatClient.test.js b/test/tavernChatClient.test.js new file mode 100644 index 0000000..586f3d0 --- /dev/null +++ b/test/tavernChatClient.test.js @@ -0,0 +1,91 @@ +const fs = require('fs'); +const vm = require('vm'); + +function client(wallet) { + const html = fs.readFileSync(require.resolve('../html/tavern.html'), 'utf8'); + // Execute the page's actual chat wiring with a small DOM, without booting renderers/network. + const script = html.slice(html.indexOf('// ---- Chat '), html.indexOf('// ---- Input ')); + const handlers = {}; + const elements = []; + const form = {}; + const context = { + socket: { on: (name, fn) => { handlers[name] = fn; }, emit: jest.fn() }, + window: { smirk: wallet }, state: { channel: 'tavern:main', occupants: [ + { id: 'same-prefix-one', name: 'Same name' }, { id: 'same-prefix-two', name: 'Same name' } + ] }, tavernLife: { showPlayerBubble: jest.fn() }, + chatInput: { value: 'hello' }, chatForm: { addEventListener: (_, fn) => { form.submit = fn; } }, + chatLog: { appendChild: el => elements.push(el), childElementCount: 0 }, + document: { createElement: () => ({ firstChild: {}, insertAdjacentHTML() {} }) } + }; + vm.createContext(context); + vm.runInContext(fs.readFileSync(require.resolve('../html/js/smirkChatSign.js'), 'utf8'), context); + vm.runInContext(script, context); + return { ...context, handlers, form, elements }; +} + +test('only room speech targets an exact occupant, never global names/prefixes or history', () => { + const c = client(); + c.handlers.chat_broadcast({ username: 'Same name', message: 'remote', publicId: 'same-prefix' }); + c.handlers.chat_history({ messages: [{ username: 'Same name', message: 'old' }] }); + expect(c.tavernLife.showPlayerBubble).not.toHaveBeenCalled(); + c.handlers.tavern_speech({ occupantId: 'same-prefix', text: 'guess' }); + expect(c.tavernLife.showPlayerBubble).not.toHaveBeenCalled(); + c.handlers.tavern_speech({ occupantId: 'same-prefix-two', text: ' & welcome' }); + expect(c.tavernLife.showPlayerBubble).toHaveBeenCalledWith('same-prefix-two', ' & welcome'); +}); + +test('a declined signature never becomes unsigned chat or an optimistic bubble', async () => { + const c = client({ signNostrEvent: async () => { throw Object.assign(new Error('declined'), { code: 'USER_REJECTED' }); } }); + c.form.submit({ preventDefault() {} }); + await new Promise(setImmediate); + expect(c.socket.emit).not.toHaveBeenCalled(); + expect(c.tavernLife.showPlayerBubble).not.toHaveBeenCalled(); + expect(c.elements.some(el => /not sent/i.test(el.textContent))).toBe(true); +}); + +test('without a signer ordinary chat still waits for server acceptance', () => { + const c = client(); + c.form.submit({ preventDefault() {} }); + expect(c.socket.emit).toHaveBeenCalledWith('tavern_chat', { text: 'hello' }); + expect(c.tavernLife.showPlayerBubble).not.toHaveBeenCalled(); +}); + + +test('server moderation/verification refusal is visible without speech', () => { + const c = client(); + c.handlers.status_update({ type: 'error', message: 'Signed message could not be verified.' }); + expect(c.elements.some(el => /verified/.test(el.textContent))).toBe(true); + expect(c.tavernLife.showPlayerBubble).not.toHaveBeenCalled(); +}); + + +test('actual Tavern join wires 3D bubble projection to the current renderer, with safe fallback', () => { + const html = fs.readFileSync(require.resolve('../html/tavern.html'), 'utf8'); + const script = html.slice(html.indexOf("socket.on('tavern_joined'"), html.indexOf("socket.on('blockheight'")); + let joined; + let options; + const element = { classList: { add() {}, remove() {} }, setAttribute() {} }; + const context = { + socket: { on: (_, fn) => { joined = fn; } }, state: {}, currentScene: {}, currentMode: '3d', + currentRenderer: { projectEntityHead: jest.fn(() => ({ x: 50, y: 70 })) }, + RK: { loadMode: () => '3d', TavernLife: function (_host, _scene, _cell, opts) { + options = opts; + return { setMode() {}, spawn() {}, welcomeBubbles() {} }; + } }, + clearJoinAttempt() {}, applyFull() {}, rebuildScene() {}, buildModebar() {}, setMode() {}, + mountChainAmbience() {}, startRafLoop() {}, setStatus() {}, + joinPanel: element, modebar: element, stageEl: element, chatPanel: element, + tavernDpad: element, movementHint: element, watchGamesBtn: element + }; + vm.createContext(context); + vm.runInContext(script, context); + joined({ you: 'speaker', state: {} }); + expect(options.projectEntityHead({ id: 'speaker' })).toEqual({ x: 50, y: 70 }); + expect(context.currentRenderer.projectEntityHead).toHaveBeenCalledWith('speaker'); + const replacement = { projectEntityHead: jest.fn(() => null) }; + context.currentRenderer = replacement; + expect(options.projectEntityHead({ id: 'speaker' })).toBeNull(); + expect(replacement.projectEntityHead).toHaveBeenCalledWith('speaker'); + context.currentRenderer = {}; + expect(options.projectEntityHead({ id: 'speaker' })).toBeNull(); +}); diff --git a/test/tavernLife.test.js b/test/tavernLife.test.js new file mode 100644 index 0000000..807ce2d --- /dev/null +++ b/test/tavernLife.test.js @@ -0,0 +1,232 @@ +const fs = require('fs'); +const vm = require('vm'); +const sceneApi = require('../html/js/render/sceneModel'); +const { TAVERN_LAYOUT } = require('../src/multiplayer/tavernMap'); + +function loadTavernLife() { + function CanvasRenderingContext2D() {} + const browser = { + CanvasRenderingContext2D, + requestAnimationFrame: () => 1, + cancelAnimationFrame: () => {}, + document: { createElement: () => ({ getContext: () => null }) } + }; + vm.runInNewContext(fs.readFileSync(require.resolve('../html/js/render/tavernLife.js'), 'utf8'), { window: browser }); + return browser.RK.TavernLife; +} + +function makeScene(layout = TAVERN_LAYOUT) { + return sceneApi.sceneFromTavern({ + cols: layout[0].length, + rows: layout.length, + layout, + occupants: [] + }); +} + +function createLife(layout = TAVERN_LAYOUT, random = () => 0.5) { + const scene = makeScene(layout); + let now = 1; + const host = { querySelector: () => null, style: {}, appendChild: () => {} }; + const TavernLife = loadTavernLife(); + const life = new TavernLife(host, () => scene, () => 24, { now: () => now, random }); + life.spawn(); + life.injectInto(scene); + return { + life, + scene, + advance(ms) { + now += ms; + life.update(scene, 24, 'tiles'); + } + }; +} + +function smallDesignedRoom(blockStaffLane = false) { + const rows = [ + '########', + blockStaffLane ? '#.hhhh.#' : '#......#', + '#.=====#', + '#......#', + '#..T...#', + '#..c...#', + '#......#', + '########' + ]; + return rows; +} + +describe('tavern ambient life', () => { + test('the authored bar lane is one connected walkable staff route', () => { + const scene = makeScene(); + const barY = scene.grid.findIndex(row => row.includes('bar')); + const laneY = barY - 1; + const counterXs = scene.grid[barY].map((tile, x) => tile === 'bar' ? x : -1).filter(x => x >= 0); + const firstCounter = Math.min(...counterXs); + const lastCounter = Math.max(...counterXs); + const lane = []; + for (let x = 0; x < scene.cols; x++) { + if (x > firstCounter && x < lastCounter && scene.grid[laneY][x] === 'floor') lane.push({ x, y: laneY }); + } + expect(lane.length).toBeGreaterThan(1); + const seen = new Set(); + const queue = [lane[0]]; + while (queue.length) { + const point = queue.shift(); + const key = `${point.x},${point.y}`; + if (seen.has(key)) continue; + seen.add(key); + for (const next of [ + { x: point.x - 1, y: point.y }, { x: point.x + 1, y: point.y }, + { x: point.x, y: point.y - 1 }, { x: point.x, y: point.y + 1 } + ]) { + if (next.x >= 0 && next.x < scene.cols && next.y >= 0 && next.y < scene.rows && + !seen.has(`${next.x},${next.y}`) && scene.legend[scene.grid[next.y][next.x]]?.solid === false) { + queue.push(next); + } + } + } + expect(lane.every(point => seen.has(`${point.x},${point.y}`))).toBe(true); + expect(scene.grid[barY].filter(tile => tile === 'bar').length).toBeGreaterThan(lane.length); + }); + + test('starts patrons on real chairs, keeps the barkeep in the staff lane, and routes the waitress between tables', () => { + const { life, scene, advance } = createLife(); + const patrons = life.npcs.filter(npc => npc.role === 'patron'); + const bartender = life.npcs.find(npc => npc.role === 'bartender'); + const waitress = life.npcs.find(npc => npc.role === 'waitress'); + const tableCells = []; + for (let y = 0; y < scene.rows; y++) { + for (let x = 0; x < scene.cols; x++) { + if (scene.grid[y][x] === 'table') tableCells.push({ x, y }); + } + } + expect(patrons).toHaveLength(4); + expect(new Set(patrons.map(npc => `${npc.x},${npc.y}`)).size).toBe(patrons.length); + for (const patron of patrons) { + expect(scene.grid[patron.y][patron.x]).toBe('chair'); + expect(tableCells.some(table => table.x === patron.homeX && table.y + 1 === patron.homeY)).toBe(true); + expect(patron.phase).toBe('seated'); + } + expect(bartender).toBeDefined(); + expect(life._isRoleCell(bartender, scene, bartender.x, bartender.y)).toBe(true); + expect(waitress).toBeDefined(); + + const barY = scene.grid.findIndex(row => row.includes('bar')); + const laneY = barY - 1; + const lane = scene.grid[laneY].map((tile, x) => tile === 'floor' ? x : -1).filter(x => x >= 0); + const bartenderVisited = new Set(); + const waitressVisited = new Set(); + const patronMoved = new Map(patrons.map(npc => [npc.id, false])); + const patronSeatedTicks = new Map(patrons.map(npc => [npc.id, 0])); + const outingStarts = []; + const outingReturns = []; + let activeExcursionTicks = 0; + let previous = new Map(life.npcs.map(npc => [npc.id, { x: npc.x, y: npc.y }])); + + for (let i = 0; i < 360; i++) { + advance(1000); + const activePatrons = patrons.filter(npc => npc.phase !== 'seated'); + expect(activePatrons.length).toBeLessThanOrEqual(1); + if (activePatrons.length) activeExcursionTicks++; + for (const npc of life.npcs) { + const old = previous.get(npc.id); + const distance = Math.abs(npc.x - old.x) + Math.abs(npc.y - old.y); + expect(distance).toBeLessThanOrEqual(1); + if (distance) expect(distance).toBe(1); + if (npc.role === 'bartender') { + expect(npc.y).toBe(laneY); + expect(lane).toContain(npc.x); + bartenderVisited.add(`${npc.x},${npc.y}`); + } else if (npc.role === 'patron') { + expect(Math.abs(npc.x - npc.homeX) + Math.abs(npc.y - npc.homeY)).toBeLessThanOrEqual(3); + expect(['chair', 'floor']).toContain(scene.grid[npc.y][npc.x]); + if (distance) patronMoved.set(npc.id, true); + if (npc.phase === 'seated') { + expect(npc.x).toBe(npc.homeX); + expect(npc.y).toBe(npc.homeY); + patronSeatedTicks.set(npc.id, patronSeatedTicks.get(npc.id) + 1); + } + if (npc.phase === 'outbound' && !previous.get(`${npc.id}:outing`)) { + outingStarts.push((i + 1) * 1000); + } + const wasReturning = previous.get(`${npc.id}:returning`) === true; + if (wasReturning && npc.phase === 'seated') outingReturns.push((i + 1) * 1000); + previous.set(`${npc.id}:outing`, npc.phase === 'outbound' || npc.phase === 'pausing' || npc.phase === 'returning'); + previous.set(`${npc.id}:returning`, npc.phase === 'returning'); + } else if (npc.role === 'waitress') { + expect(scene.grid[npc.y][npc.x]).toBe('floor'); + expect(npc.y).toBeGreaterThanOrEqual(3); + waitressVisited.add(`${npc.x},${npc.y}`); + } + previous.set(npc.id, { x: npc.x, y: npc.y }); + } + } + + expect(bartenderVisited.size).toBeGreaterThan(1); + expect(waitressVisited.size).toBeGreaterThan(2); + expect([...patronMoved.values()].some(Boolean)).toBe(true); + expect(outingReturns.length).toBeGreaterThanOrEqual(1); + expect(outingStarts.length).toBeGreaterThanOrEqual(outingReturns.length); + for (let i = 1; i < outingStarts.length; i++) { + const previousReturn = outingReturns.filter(time => time < outingStarts[i]).at(-1); + expect(previousReturn).toBeDefined(); + expect(outingStarts[i] - previousReturn).toBeGreaterThanOrEqual(45000); + } + expect(activeExcursionTicks).toBeLessThan(360 * 0.2); + for (const patron of patrons) { + expect(patronSeatedTicks.get(patron.id)).toBeGreaterThan(360 * 0.75); + } + expect(patrons.some(npc => npc.phase === 'seated' && npc.x === npc.homeX && npc.y === npc.homeY)).toBe(true); + }); + + test('leaves designed rooms without semantic tables and chairs actor-free', () => { + const layout = TAVERN_LAYOUT.map(row => row.replace(/T|c/g, '.')); + const { life } = createLife(layout); + expect(life.npcs).toEqual([]); + expect(life._spawned).toBe(false); + }); + + test('uses semantic seats and bar space in a compact designed room', () => { + const { life, scene } = createLife(smallDesignedRoom()); + expect(life.npcs.map(npc => npc.role)).toEqual(['bartender', 'patron', 'waitress', 'cat']); + const bartender = life.npcs[0]; + const patron = life.npcs.find(npc => npc.role === 'patron'); + const waitress = life.npcs.find(npc => npc.role === 'waitress'); + expect(scene.grid[bartender.y][bartender.x]).toBe('floor'); + expect(bartender.roleArea.minX).toBeLessThanOrEqual(bartender.x); + expect(bartender.roleArea.maxX).toBeGreaterThanOrEqual(bartender.x); + expect(scene.grid[patron.y][patron.x]).toBe('chair'); + expect(scene.grid[waitress.y][waitress.x]).toBe('floor'); + }); + + test('does not invent actors when a semantic bar has no walkable staff lane', () => { + const { life } = createLife(smallDesignedRoom(true)); + expect(life.npcs).toEqual([]); + expect(life._spawned).toBe(false); + }); + + test('does not spawn a barkeep on walkable non-floor staff tiles', () => { + const layout = smallDesignedRoom().slice(); + layout[1] = '#.rrrr.#'; + const { life } = createLife(layout); + expect(life.npcs).toEqual([]); + expect(life._spawned).toBe(false); + }); + + test('preserves player-bubble identity and uses an optional viewport-relative 3D head projection', () => { + const scene = makeScene(); + let now = 500; + const TavernLife = loadTavernLife(); + const life = new TavernLife({}, () => scene, null, { + now: () => now, + projectEntityHead: entity => ({ x: entity.x + 7, y: entity.y + 11 }) + }); + life.showPlayerBubble('socket-1', 'hello'); + expect(life._realBubbles['socket-1']).toEqual({ text: 'hello', until: 4700 }); + expect(life._entityScreenPos({ x: 3, y: 4 }, scene, 24, '3d')).toEqual({ x: 10, y: 15 }); + now = 1000; + life.showPlayerBubble('socket-1', 'again'); + expect(life._realBubbles['socket-1'].until).toBe(5200); + }); +}); diff --git a/test/tavernManager.test.js b/test/tavernManager.test.js index e5b494e..367c328 100644 --- a/test/tavernManager.test.js +++ b/test/tavernManager.test.js @@ -123,7 +123,8 @@ describe('TavernManager', () => { const mgr = new TavernManager({ io }); const s = makeFakeSocket('a', io); await mgr.join(s, { appearance: { avatar: 'monero-knight' } }); - expect(mgr.room.getOccupant('a').avatar).toBe('default'); + expect(mgr.room.getOccupant('a').avatar).not.toBe('monero-knight'); + expect(TavernManager.AVATARS).toContain(mgr.room.getOccupant('a').avatar); const paid = new TavernManager({ io, diff --git a/test/tavernSpeech.test.js b/test/tavernSpeech.test.js new file mode 100644 index 0000000..efc6ce9 --- /dev/null +++ b/test/tavernSpeech.test.js @@ -0,0 +1,325 @@ +const TavernManager = require('../src/network/tavernManager'); +const ChatHandler = require('../src/network/chatHandler'); +const ChatHistoryManager = require('../src/network/chatHistoryManager'); +const SocketChatProvider = require('../src/network/chat/SocketChatProvider'); +const { loadNostrTools } = require('../src/utils/nostrLoader'); +const { finalizeEvent } = loadNostrTools(); + +function deferred() { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; } +function fixture({ db = null, moderation = null, provider = null } = {}) { + const io = { emitted: [], emit(event, payload) { this.emitted.push({ event, payload, channel: null }); }, + to(channel) { return { emit: (event, payload) => this.emitted.push({ event, payload, channel }) }; } }; + const socket = { id: 'shared-prefix-speaker', emit: jest.fn(), join() {}, leave() {} }; + const sessions = new Map([[socket.id, { id: 7 }]]); + const gameModeManager = { db, sessionManager: { sessions }, getOrCreateUser: jest.fn(async () => ({ id: 7 })) }; + const history = new ChatHistoryManager({ db }); + const local = provider || new SocketChatProvider({ io }); + const manager = new TavernManager({ io, globalChatProvider: local, chatModeration: moderation || { + sessionManager: gameModeManager.sessionManager, chatHistory: history, getOrCreateUser: gameModeManager.getOrCreateUser + } }); + manager.enabled = true; + const handler = new ChatHandler({ io, db, gameModeManager, debugManager: {}, rateLimiter: { checkLimit: async () => ({ allowed: true }), recordAttempt: async () => {} }, broadcastManager: { sendStatusUpdate: jest.fn() } }); + handler.chatProvider = local; + return { io, socket, manager, handler, sessions, speech: () => io.emitted.filter(e => e.event === 'tavern_speech') }; +} +const secret = Uint8Array.from({ length: 32 }, (_, i) => i + 1); +function signed(text = 'Signed & welcome') { + return finalizeEvent({ kind: 1, created_at: Math.floor(Date.now() / 1000), content: text, tags: [['t', 'wowngeon-global']] }, secret); +} +function database({ banned = false, banFailure = false } = {}) { + return { query: jest.fn(async sql => { + if (sql.includes('SELECT chat_banned')) { + if (banFailure) throw new Error('fixture moderation unavailable'); + return { rows: [{ chat_banned: banned }] }; + } + return { rows: [{ smirk_public_key: signed().pubkey, display_name: 'Same name' }] }; + }) }; +} + +afterEach(() => jest.restoreAllMocks()); + +test('accepted ordinary speech is room-scoped, exact occupant, plain text; global delivery has no raw ID', async () => { + const f = fixture({ db: database() }); + try { + await f.manager.join(f.socket, { name: 'Same name' }); + await f.manager.join({ ...f.socket, id: 'shared-prefix-other' }, { name: 'Same name' }); + await f.manager.chat(f.socket, { text: ' & welcome' }); + expect(f.speech()).toEqual([{ channel: f.manager.channel, event: 'tavern_speech', payload: { + occupantId: f.socket.id, text: ' & welcome' + } }]); + const global = f.io.emitted.find(e => e.event === 'chat_broadcast'); + expect(global.channel).toBeNull(); + expect(global.payload.message).toBe('<hello> & welcome'); + expect(JSON.stringify(global.payload)).not.toContain(f.socket.id); + } finally { f.handler.shutdown(); } +}); + +test('publish acceptance is awaited; leave/rejoin while publishing cannot speak for the replacement', async () => { + const pending = deferred(); + let deliver; + const f = fixture({ db: database(), provider: { publish: jest.fn(message => { deliver = message.onLocalDelivery; return pending.promise; }) } }); + try { + await f.manager.join(f.socket, { name: 'Same name' }); + const sending = f.manager.chat(f.socket, { text: 'stale' }); + await new Promise(setImmediate); + expect(f.speech()).toEqual([]); + f.manager.leave(f.socket); + await f.manager.join(f.socket, { name: 'Same name' }); + deliver(); + pending.resolve(); + await sending; + expect(f.speech()).toEqual([]); + } finally { f.handler.shutdown(); } +}); + +test.each(['banned', 'ban database failure', 'user lookup failure', 'publish failure', 'rate limited', 'rate lookup failure'])( + 'ordinary rejected message has no speech: %s', async reason => { + const f = fixture({ db: database({ banned: reason === 'banned', banFailure: reason === 'ban database failure' }) }); + jest.spyOn(console, 'error').mockImplementation(() => {}); + if (reason === 'user lookup failure') f.manager.chatModeration.getOrCreateUser = async () => { throw new Error('lookup unavailable'); }; + if (reason === 'publish failure') f.manager.globalChatProvider.publish = async () => { throw new Error('publish unavailable'); }; + if (reason === 'rate lookup failure') f.manager.chatModeration.rateLimiter = { checkLimit: async () => { throw new Error('limiter unavailable'); } }; + if (reason === 'rate limited') f.manager.chatModeration.rateLimiter = { checkLimit: async () => ({ allowed: false }) }; + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + await f.manager.chat(f.socket, { text: 'not accepted' }).catch(() => {}); + expect(f.speech()).toEqual([]); + expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toEqual([]); + } finally { f.handler.shutdown(); } + }); + +test('valid signed speech uses authenticated content and the current room occupant', async () => { + const f = fixture({ db: database() }); + try { + await f.manager.join(f.socket, { name: 'Different avatar label' }); + await f.handler.handleSignedChatMessage(f.socket, { event: signed() }, f.manager.captureSpeech(f.socket)); + expect(f.speech()[0]).toMatchObject({ channel: f.manager.channel, payload: { occupantId: f.socket.id, text: signed().content } }); + } finally { f.handler.shutdown(); } +}); + +test.each(['bad signature', 'banned', 'ban database failure', 'session changed', 'left room', 'publish failure', 'rate limited'])( + 'signed rejection/stale acceptance has no bubble: %s', async reason => { + const f = fixture({ db: database({ banned: reason === 'banned', banFailure: reason === 'ban database failure' }) }); + jest.spyOn(console, 'error').mockImplementation(() => {}); + if (reason === 'rate limited') f.handler.rateLimiter = { checkLimit: async () => ({ allowed: false }) }; + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + const accept = f.manager.captureSpeech(f.socket); + if (reason === 'session changed' || reason === 'left room' || reason === 'publish failure') { + f.handler.chatProvider.relaySignedEvent = async (message) => { + if (reason === 'session changed') f.sessions.set(f.socket.id, { id: 9 }); + if (reason === 'left room') { f.manager.leave(f.socket); await f.manager.join(f.socket, { name: 'Speaker' }); } + if (reason === 'publish failure') throw new Error('publish unavailable'); + message.onLocalDelivery(); + }; + } + const event = signed(); + if (reason === 'bad signature') event.content += 'tampered'; + await f.handler.handleSignedChatMessage(f.socket, { event }, accept); + expect(f.speech()).toEqual([]); + } finally { f.handler.shutdown(); } + }); + + +test.each(['chat message', 'chat_signed'])('real socket dispatch binds current room speech: %s', async eventName => { + const SocketHandlers = require('../src/network/socketHandlers'); + const f = fixture({ db: database() }); + const callbacks = new Map(); + f.socket.on = (event, fn) => callbacks.set(event, fn); + const dispatch = Object.assign(Object.create(SocketHandlers.prototype), { + connectionHandler: { handleConnection: async () => ({}) }, + _emitFairnessOffer() {}, _emitIdentity: async () => {}, + tavernManager: f.manager, chatHandler: f.handler + }); + f.handler.addressManager = { detectInText: () => null }; + f.handler.sendChatHistoryToUser = async () => {}; + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + await dispatch.handleConnection(f.socket); + callbacks.get(eventName)(eventName === 'chat_signed' ? { event: signed() } : 'ordinary hello'); + await new Promise(setImmediate); + expect(f.speech()[0]).toMatchObject({ channel: f.manager.channel, payload: { occupantId: f.socket.id } }); + } finally { f.handler.shutdown(); } +}); + +test('session replacement during ordinary publish suppresses the captured bubble', async () => { + const f = fixture({ db: database() }); + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + f.manager.globalChatProvider.publish = async message => { f.sessions.set(f.socket.id, { id: 8 }); message.onLocalDelivery(); }; + await f.manager.chat(f.socket, { text: 'old session' }); + expect(f.speech()).toEqual([]); + } finally { f.handler.shutdown(); } +}); + +test('leaving during moderation cannot publish for a new visit on the same socket', async () => { + const f = fixture({ db: database() }); + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + f.manager.chatModeration.getOrCreateUser = async () => { + f.manager.leave(f.socket); + await f.manager.join(f.socket, { name: 'Speaker' }); + return { id: 7 }; + }; + await f.manager.chat(f.socket, { text: 'old visit' }); + expect(f.speech()).toEqual([]); + expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toEqual([]); + } finally { f.handler.shutdown(); } +}); + +test.each([undefined, null, 0, 'false'])('strict real ban reader refuses unknown/malformed status: %p', async chat_banned => { + const history = new ChatHistoryManager({ db: { query: async () => ({ rows: [{ chat_banned }] }) } }); + await expect(history.isUserChatBanned(7, { strict: true })).rejects.toThrow(); +}); + +test('ephemeral Tavern without global moderation still delivers accepted room speech', async () => { + const f = fixture(); + f.manager.globalChatProvider = null; + try { + await f.manager.join(f.socket, { name: 'Guest' }); + await f.manager.chat(f.socket, { text: 'local only' }); + expect(f.speech()[0]).toMatchObject({ channel: f.manager.channel, payload: { occupantId: f.socket.id, text: 'local only' } }); + } finally { f.handler.shutdown(); } +}); + + +test('deferred moderation admits only one concurrent send and one accepted bubble', async () => { + const pending = deferred(); + const f = fixture({ db: database() }); + const lookup = jest.fn(() => pending.promise); + f.manager.chatModeration.getOrCreateUser = lookup; + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + const first = f.manager.chat(f.socket, { text: 'first' }); + const second = f.manager.chat(f.socket, { text: 'second' }); + await second; + expect(lookup).toHaveBeenCalledTimes(1); + expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toEqual([]); + pending.resolve({ id: 7 }); + await first; + expect(f.io.emitted.filter(e => e.event === 'chat_broadcast').map(e => e.payload.message)).toEqual(['first']); + expect(f.speech().map(e => e.payload.text)).toEqual(['first']); + expect(f.manager._chatInFlight.size).toBe(0); + } finally { pending.resolve({ id: 7 }); f.handler.shutdown(); } +}); + +test('session switch during deferred moderation refuses before publishing', async () => { + const pending = deferred(); + const f = fixture({ db: database() }); + f.manager.chatModeration.getOrCreateUser = () => pending.promise; + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + const sending = f.manager.chat(f.socket, { text: 'stale account' }); + f.sessions.set(f.socket.id, { id: 8 }); + pending.resolve({ id: 7 }); + await sending; + expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toEqual([]); + expect(f.speech()).toEqual([]); + expect(f.manager._chatInFlight.size).toBe(0); + } finally { pending.resolve({ id: 7 }); f.handler.shutdown(); } +}); + +test('failed moderation releases admission without suppressing an explicit immediate retry', async () => { + const f = fixture({ db: database() }); + const lookup = jest.fn().mockRejectedValueOnce(new Error('lookup unavailable')).mockResolvedValue({ id: 7 }); + f.manager.chatModeration.getOrCreateUser = lookup; + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + await f.manager.chat(f.socket, { text: 'refused' }); + await f.manager.chat(f.socket, { text: 'explicit retry' }); + expect(f.speech().map(e => e.payload.text)).toEqual(['explicit retry']); + } finally { f.handler.shutdown(); } +}); + +test.each(['ordinary', 'signed'])('local %s speech does not wait for pending/rejected relay or duplicate later', async kind => { + const NostrChatProvider = require('../src/network/chat/NostrChatProvider'); + let rejectRelay; + const relay = new Promise((_, reject) => { rejectRelay = reject; }); + relay.catch(() => {}); + const f = fixture({ db: database() }); + const transport = { publish: jest.fn(() => relay) }; + const provider = new NostrChatProvider({ local: new SocketChatProvider({ io: f.io }), transport, + signer: { sign: template => ({ ...template, id: 'synthetic-bridge-event' }) } }); + f.manager.globalChatProvider = provider; + f.handler.chatProvider = provider; + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + const sending = kind === 'signed' + ? f.handler.handleSignedChatMessage(f.socket, { event: signed() }, f.manager.captureSpeech(f.socket)) + : f.manager.chat(f.socket, { text: 'immediate local speech' }); + await new Promise(setImmediate); + expect(transport.publish).toHaveBeenCalled(); + expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toHaveLength(1); + expect(f.speech()).toHaveLength(1); + const localSpeech = f.speech()[0]; + rejectRelay(new Error('disposable relay refuses')); + await sending; + expect(f.speech()).toEqual([localSpeech]); + } finally { rejectRelay(new Error('dispose pending relay')); f.handler.shutdown(); } +}); + +test('ordinary global session switch during deferred real moderation refuses before local delivery', async () => { + const pending = deferred(); + const f = fixture({ db: database() }); + f.handler.gameModeManager.getOrCreateUser = () => pending.promise; + f.handler.addressManager = { detectInText: () => null }; + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + const sending = f.handler.handleChatMessage(f.socket, 'stale global message', { acceptedSpeech: f.manager.captureSpeech(f.socket) }); + await new Promise(setImmediate); + f.sessions.set(f.socket.id, { id: 8 }); + pending.resolve({ id: 7 }); + await sending; + expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toEqual([]); + expect(f.speech()).toEqual([]); + } finally { pending.resolve({ id: 7 }); f.handler.shutdown(); } +}); + +test('accepted room capability is single-use, including stale callback then restored session', async () => { + const f = fixture({ db: database() }); + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + const accepted = f.manager.captureSpeech(f.socket); + accepted('first'); + accepted('duplicate'); + expect(f.speech().map(e => e.payload.text)).toEqual(['first']); + const stale = f.manager.captureSpeech(f.socket); + const originalSession = f.sessions.get(f.socket.id); + f.sessions.set(f.socket.id, { id: 8 }); + stale('stale'); + f.sessions.set(f.socket.id, originalSession); + stale('cannot resurrect'); + expect(f.speech().map(e => e.payload.text)).toEqual(['first']); + } finally { f.handler.shutdown(); } +}); + +test('an earlier pending relay cannot release a later send admission on the same visit', async () => { + const NostrChatProvider = require('../src/network/chat/NostrChatProvider'); + const relay = deferred(); + const moderation = deferred(); + const f = fixture({ db: database() }); + const clock = jest.spyOn(Date, 'now').mockReturnValue(1800000000000); + const lookup = jest.fn().mockResolvedValueOnce({ id: 7 }).mockImplementation(() => moderation.promise); + f.manager.chatModeration.getOrCreateUser = lookup; + f.manager.globalChatProvider = new NostrChatProvider({ local: new SocketChatProvider({ io: f.io }), + transport: { publish: jest.fn().mockImplementationOnce(() => relay.promise).mockResolvedValue() }, + signer: { sign: template => ({ ...template, id: 'synthetic-bridge-event' }) } }); + try { + await f.manager.join(f.socket, { name: 'Speaker' }); + const first = f.manager.chat(f.socket, { text: 'first' }); + await new Promise(setImmediate); + expect(f.speech().map(e => e.payload.text)).toEqual(['first']); + clock.mockReturnValue(1800000000000 + f.manager.chatCooldownMs + 1); + const second = f.manager.chat(f.socket, { text: 'second' }); + expect(lookup).toHaveBeenCalledTimes(2); + relay.resolve(); + await first; + const third = f.manager.chat(f.socket, { text: 'third' }); + await new Promise(setImmediate); + expect(lookup).toHaveBeenCalledTimes(2); + moderation.resolve({ id: 7 }); + await Promise.all([second, third]); + expect(f.io.emitted.filter(e => e.event === 'chat_broadcast').map(e => e.payload.message)).toEqual(['first', 'second']); + expect(f.speech().map(e => e.payload.text)).toEqual(['first', 'second']); + } finally { relay.resolve(); moderation.resolve({ id: 7 }); f.handler.shutdown(); clock.mockRestore(); } +}); diff --git a/test/tavernThreeProjection.test.js b/test/tavernThreeProjection.test.js new file mode 100644 index 0000000..3518111 --- /dev/null +++ b/test/tavernThreeProjection.test.js @@ -0,0 +1,72 @@ +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +function fixture() { + const root = { RK: {} }; + vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../html/js/render/threeRenderer.js'), 'utf8'), { window: root }); + const renderer = Object.create(root.RK.ThreeRenderer.prototype); + const projected = { x: 0, y: 0, z: 0 }; + const local = []; + renderer.THREE = { Vector3: class { + constructor(x, y, z) { this.x = x; this.y = y; this.z = z; } + project(camera) { camera.observedWorld = [this.x, this.y, this.z]; Object.assign(this, projected); return this; } + } }; + renderer.host = { getBoundingClientRect: () => ({ left: 100, top: 60, width: 600, height: 400 }) }; + renderer.renderer = { domElement: { width: 1200, height: 800, + getBoundingClientRect: () => ({ left: 110, top: 70, width: 500, height: 300 }) } }; + renderer.camera = { updateMatrixWorld: jest.fn() }; + renderer.entities = { speaker: { obj: { + position: { x: 3, y: 0.1, z: -2 }, + updateWorldMatrix: jest.fn(), + localToWorld(v) { local.push([v.x, v.y, v.z]); v.x += this.position.x; v.y += this.position.y; v.z += this.position.z; return v; } + } } }; + return { renderer, projected, local }; +} + +describe('Tavern 3D speech projection', () => { + test('uses the current mesh position and CSS canvas bounds without device-pixel multiplication', () => { + const { renderer, local } = fixture(); + expect(renderer.projectEntityHead('speaker')).toEqual({ x: 260, y: 160 }); + expect(local).toEqual([[0, 2, 0]]); + expect(renderer.camera.observedWorld).toEqual([3, 2.1, -2]); + expect(renderer.entities.speaker.obj.updateWorldMatrix).toHaveBeenCalledWith(true, false); + }); + + test('tracks the live camera projection and resized viewport', () => { + const { renderer, projected } = fixture(); + projected.x = 0.5; projected.y = -0.5; + expect(renderer.projectEntityHead('speaker')).toEqual({ x: 385, y: 235 }); + renderer.renderer.domElement.getBoundingClientRect = () => ({ left: 100, top: 60, width: 300, height: 200 }); + expect(renderer.projectEntityHead('speaker')).toEqual({ x: 225, y: 150 }); + }); + + test.each(['x', 'y', 'z'])('suppresses an avatar outside the %s clip plane', axis => { + const { renderer, projected } = fixture(); + projected[axis] = 1.01; + expect(renderer.projectEntityHead('speaker')).toBeNull(); + projected[axis] = -1.01; + expect(renderer.projectEntityHead('speaker')).toBeNull(); + projected[axis] = NaN; + expect(renderer.projectEntityHead('speaker')).toBeNull(); + }); + + test('suppresses points outside the host even when the canvas is panned', () => { + const { renderer } = fixture(); + renderer.renderer.domElement.getBoundingClientRect = () => ({ left: -500, top: 60, width: 500, height: 300 }); + expect(renderer.projectEntityHead('speaker')).toBeNull(); + }); + + test('removed, hidden, destroyed, and zero-size renderers have no bubble position', () => { + const { renderer } = fixture(); + expect(renderer.projectEntityHead('absent')).toBeNull(); + expect(renderer.projectEntityHead('__proto__')).toBeNull(); + renderer.entities.speaker.obj.visible = false; + expect(renderer.projectEntityHead('speaker')).toBeNull(); + renderer.entities.speaker.obj.visible = true; + renderer.host.getBoundingClientRect = () => ({ left: 0, top: 0, width: 0, height: 0 }); + expect(renderer.projectEntityHead('speaker')).toBeNull(); + renderer._destroyed = true; + expect(renderer.projectEntityHead('speaker')).toBeNull(); + }); +});