BlueGit

timfa questward

remove obsolete docs

timfa Tim Falken · pushed by timfa

Authored 2026-09-08 · 2 months ago

Hash
f96c21d5a3e89ff9e6cbc6a379d1911c287d439c
Parent
ac2f632a
3 files changed +0 −4435
docs/FEATURES.md deleted +0 −369
@@ -1,369 +0,0 @@
1 # Feature implementation tracker
2
3 Living companion to `questward_server_technical_design_v0.6.md`.
4 Statuses: **not implemented** · **partial** · **full**.
5
6 Each entry is a short note on behaviour and where the code lives. Update this file in the same commit as the feature it describes.
7
8 ---
9
10 ## World coordinates and spatial hierarchy
11
12 **Status:** full
13 **Spec:** World tile coordinates are canonical. Chunks are 16×16 tiles; regions are 4×4 chunks. Negative coordinates use true floor division. Positions are scoped by **dimensionId** (default `overworld`); chunk/region keys are `dim|x,y`.
14 **Code:** `server/src/world/coordinates.js`, `shared/world/dimensions.js`, tests in `server/tests/coordinates.test.js`
15
16 ## Interior dimensions
17
18 **Status:** partial
19 **Spec:** Besides the **overworld**, the world may contain named **dimensions** (caves, houses, …), each with its own chunk grid, default ground, open/closed map, **lighting mode** (`dayNight` / `alwaysLit` / `alwaysDark`), and **season mode** (`auto` / `summer` / `spring` / `autumn` / `winter`; autumn→fall art). Soft-delete marks a non-overworld dim unusable; after **7 days** it is purged (chunks + metadata). Cancel deletion before purge. **Doorway** blocks (`ladder` / `door` / `hole` / `cave`) teleport the player to `{ targetDimensionId, tileX, tileY }` (server-authoritative). Characters persist `dimension_id` + visits for quest conditions. Editor: searchable dim picker with inline create; per-dim settings while selected.
20 **Code:** `shared/world/dimensions.js`, `server/src/persistence/worldDb.js` (`world_dimensions`), `server/src/simulation/simulation.js` (`#relocateCharacterThroughDoorway`), `client/src/editor/dimensionCombobox.js`, `BlockType.doorway`
21
22 ## Ground and block tile layers
23
24 **Status:** full
25 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, **dirt** (outdoor seasonal, soft-terrain blendable like grass), wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants.
26 **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
27
28 ## Open and closed chunks
29
30 **Status:** full
31 **Spec:** Never-edited chunks are closed grass. Closed chunks can be replicated but cannot be entered; pathfinding treats them as impassable. Open chunks draw a red border on edges that touch a closed neighbour.
32 **Code:** `server/src/world/chunkData.js` (`open` flag), `server/src/world/chunkFlags.js`, `server/src/simulation/simulation.js` (`isEnterable`, `#walkableFor`, `closedEdges`), `client/src/render/worldView.js` (`#rebuildChunkEdges`)
33
34 ## ECS registry and components
35
36 **Status:** full
37 **Spec:** Entities are compositions of components with integer tile positions. Live components include `position`, `movement`, `path`, `appearance`, `character`, `networkIdentity`, `chunkLoader`, and `persistent`. Global `EntityId`s are used for storage, networking and transfer; each worker uses compact recycled `EntityHandle`s for hot ECS arrays.
38 **Code:** `server/src/ecs/world.js`, `server/src/ecs/serialize.js`, `server/src/ecs/components.js`
39
40 ## Simulation tick
41
42 **Status:** full
43 **Spec:** Fixed tick from `WorldSettings.simulationTickHz` (default 20 Hz). Commands drain at tick boundaries, then activation, movement, transfers, and ghost exchange. Multiple isolated simulation workers.
44 **Code:** `server/src/simulation/simulation.js` (`step`), `server/src/index.js`
45
46 ## Authored world and runtime state persistence
47
48 **Status:** full
49 **Spec:** `world.sqlite` holds revisioned authored chunks, live world settings, and settings/chunk changelogs. `state.sqlite` holds accounts, characters, and runtime entity state. Databases live under `server/data/` and use Node's SQLite binding.
50 **Code:** `server/src/persistence/database.js`, `worldDb.js`, `stateDb.js`
51
52 ## World revisions and pending editor saves
53
54 **Status:** partial
55 **Spec:** Editor chunk saves write a pending world revision. The running process stays pinned to the map revision loaded at startup until an admin **Apply now** (in-process reload). Live world settings do not use this path. Code updates use the midnight deploy path (see **Midnight restart and Git deploy**).
56 **Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
57
58 ## World settings
59
60 **Status:** full
61 **Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, **Equipment Stats**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Equipment Stats** edits worn combat bonuses as piece×tier tables (category dropdown: metal armour, leather armour, melee/ranged weapons, magic staves, wizard armour, clothing); multi-stat cells (e.g. leather Agility+Defence) are independent inputs. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
62 **Code:** `shared/definitions/worldSettings.js`, `shared/definitions/equipmentStatCategories.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
63
64 ## Baked lighting
65
66 **Status:** full
67 **Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on furniture (tables, marketplace counters, crafting stations, ore nodes, cauldron) to let light through while remaining impassable. Set `blocksLight: "partial"` on standing trees so the ray continues but each canopy tile adds +1 to falloff distance; **tree stumps** (`*-stump` state from woodcutting) clear that occlusion at runtime via live chunk snapshots (same dynamic path as torches, without rebaking). Store a 16×16 intensity map (0–255, smoothstep falloff by effective tile distance). Torch range is 8 tiles; furnace is 4.
68 **Code:** `server/src/lighting/baker.js`, `shared/lighting/raycast.js`, `shared/definitions/tiles.js` (`LightOcclusion` / `blocksLight`), tests in `server/tests/lighting.test.js`
69
70 ## World editor (server)
71
72 **Status:** full
73 **Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`, neighbor-connect autotile), **wooden tables** (`BlockType.table`, magenta autotile `0`–`15` tinted per wood tier; joins only the same material), and **Central Exchange staff** spawners are placeable.
74 **Code:** `server/src/editor/service.js`
75
76 ## World editor (client)
77
78 **Status:** full
79 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: spring/summer/fall/winter, which also updates Season preview), open/closed, right-side **Changelog / Console** tabs (console streams live server output to admins), night preview slider, **season preview** dropdown, world-settings modal, **Dimension settings…** opens a modal (lighting / season / default ground / soft-delete), **Quests** and **Dialogues** buttons under Settings (see docs/QUESTS.md), save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
80 **Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
81
82 ## Per-chunk changelog
83
84 **Status:** full
85 **Spec:** Each save stores who, when, and structured bullets of ground/block/spawner/open-closed diffs.
86 **Code:** `server/src/editor/service.js` (`diffChunks`), `server/src/persistence/worldDb.js` (`world_chunk_edit_log`), tests in `server/tests/editor-diff.test.js`
87
88 ## WebSocket gateway
89
90 **Status:** full
91 **Spec:** JSON WebSocket on `/ws`, HTTP static files for the client. Connections belong to the gateway. Clients send intentions that are queued onto the simulation tick. Editor messages are admin-only.
92 **Code:** `server/src/gateway/websocket.js`, `server/src/gateway/http.js`, `server/src/index.js`
93
94 ## Authentication (auth.timfalken.com)
95
96 **Status:** partial
97 **Spec:** OAuth2 authorization-code flow via **auth.timfalken.com**. Sign in at `/auth/login`; callback at `/auth/callback` sets an HttpOnly session cookie. WebSocket `/ws` requires that cookie (or stub mode). The **first account** to sign in becomes a **game admin**; further admins are granted in the world editor **Settings → Admins** tab (username must have signed in once). Removing the last admin is blocked; removing yourself requires confirmation. `GET /settings/export` returns a JSON data export (integrator requirement). Stub mode (`QUESTWARD_AUTH_STUB=1` or missing client secret) keeps dev `admin-<n>` identities (all admins).
98 **Code:** `server/src/auth/`, `server/src/gateway/http.js`, `server/src/gateway/websocket.js`, `client/src/net/auth.js`, `client/src/editor/settingsModal.js` (Admins tab), tests in `server/tests/authAccounts.test.js`
99
100 ## Stub authentication (dev only)
101
102 **Status:** full (when stub mode active)
103 **Spec:** Each connection is `admin-<n>` with full admin rights when OAuth is not configured.
104 **Code:** `server/src/auth/stub.js`
105
106 ## Characters
107
108 **Status:** full
109 **Spec:** Unlimited characters per account, one in the world. First name is not globally unique; last name is globally unique per account; first+last unique per account, case-insensitive. Male/female body. Spawn requires an open tile. The login screen lists characters first; **Create Character** opens a modal (**Appearance** / **Clothing** tabs) and successful creation enters the world immediately. New characters receive **Starter Equipment** / inventory from live world settings (origin: “Received from the gods”), then **creation clothing** on top: cotton shirt + chosen cotton trousers/shorts/skirt, each with an HSL dye (same controls as hair). Existing characters are unaffected.
110 **Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`, `shared/items/starterLoadout.js`, `shared/items/createClothing.js`, `client/index.html`, `client/src/play/createClothingControls.js`
111
112 ## Character deletion and inheritance
113
114 **Status:** full
115 **Spec:** 24h delayed delete, cancellable. Notify via stub log (or email when present). Names and surname claims are freed on permanent delete. Inventory, equipment, carried coins, and vault move to the account inheritance tab, claimable at a bank into another character's vault.
116 **Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js` (`account_inheritance`)
117
118 ## 3×3 chunk replication
119
120 **Status:** full
121 **Spec:** Entity and ground-item replication uses the current chunk and eight neighbours. Map tiles (static snapshots) default to a **5×5** ring (`STATIC_CHUNK_RADIUS = 2`); clients may request **Short** viewing distance so the map ring matches the 3×3 entity ring. Closed chunks are still sent. Afterwards the gateway sends `ENTITY_SPAWN`, compact `ENTITY_MOVE` (tile + gait) and `ENTITY_DESPAWN`; appearance and path stay off the move payload. Tile deltas are not used yet because live tile edits wait for Apply now. Visible chunks may be owned by different workers; the gateway never reassigns regions for rendering.
122 **Code:** `server/src/simulation/simulation.js` (`snapshotsForView`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`), `shared/graphics/settings.js`
123
124 ## Click-to-move and A\* pathfinding
125
126 **Status:** full
127 **Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Entities do **not** block each other’s movement (players and mobs pass through). Occupied tiles are still preferred-away for mob wander goals and required to be clear for melee attack stance. Client spreads stacked entities evenly on a circle (`ENTITY_STACK_SPREAD_DIAMETER_PX`, centred on the tile) with a short lerp into place; within-tile y-sort still uses each sprite’s visual Y. Server commits integer tiles on the movement cadence. Neighbour expansion prefers steps that most reduce Manhattan distance to the goal; remaining ties break by axis — **players prefer vertical**, **mobs prefer horizontal** — so mutual approaches are less likely to oscillate sideways.
128 **Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`, `walkableFor`, `isClearStanding`)
129
130 ## Global walk/run cadence
131
132 **Status:** full
133 **Spec:** Walk 2 tiles/s, run double. Movement ticks at run rate. `SetGait` chooses every-other vs every movement tick.
134 **Code:** `server/src/simulation/workerWorld.js` (`#stepMovement`, `#setGait`)
135
136 ## Client movement interpolation
137
138 **Status:** full
139 **Spec:** Client lerps sprites between replicated tiles over the walk or run interval from world settings.
140 **Code:** `client/src/render/worldView.js` (`moveEntity`, `update`)
141
142 ## Play viewport and camera
143
144 **Status:** full
145 **Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Tiles and chunk atlases more than half a tile outside the screen (zoom-aware) are not drawn and skip per-frame lighting work. Hovering another player shows their first name; clicking them inspects instead of issuing move.
146 **Code:** `client/src/render/worldView.js` (`#cullOffscreenDrawables`, `#drawBounds`), `client/src/play/main.js`, `client/index.html`
147
148 ## Client graphics settings
149
150 **Status:** full
151 **Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer. **Soft terrain** On/Off (default **On**) edge-blends `blendable` ground tiles (grass, dirt) into differing neighbours along **cardinal** edges only: outer edge pixel 50% neighbour, next pixel 25% (softer 40%/20% when both sides are blendable); baked at chunk atlas time. The settings panel blocks world clicks while open.
152 **Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `client/src/render/chunkBake.js`, `shared/render/softTerrain.js`, `server/src/gateway/websocket.js`
153
154 ## Night shading
155
156 **Status:** full
157 **Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. With **Soft** lighting, baked ground/block atlases sample a per-chunk lightmap with neighbour blending; **Simple** lighting uses a flat per-tile intensity (no corner blend). **Animated liquid water** uses the same lit values via shader uniforms. **Light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`spring` / `summer` / `fall` / `winter`) for seasonal tile visuals (types without a spring sprite fall back to summer).
158 **Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
159
160 ## FrameworkV3 client bootstrap
161
162 **Status:** full
163 **Spec:** FrameworkV3 is a git submodule at `client/frameworkv3`, built first via `npm run build:client`. Game code lives in `client/src`. Server does not import it.
164 **Code:** `.gitmodules`, `client/frameworkv3`, `client/scripts/build-framework.mjs`
165
166 ## Sprite size, pivot and Y-sort
167
168 **Status:** full
169 **Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets. Immobile ≤16×16 blocks bake into per-row chunk strips; taller sprites stay individually Y-sorted.
170 **Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`, tests in `server/tests/pivot.test.js`
171
172 ## Visual tile states
173
174 **Status:** full
175 **Spec:** Each ground and block type has a folder of PNG states. Non-seasonal types use the first alphabetical file as the default; outdoor seasonal types prefer `summer` (or legacy `grass`). States are visual only; the game may set a named state (for example a door or ore). For outdoor types that expose summer/fall/winter (optional `spring`), calendar season overrides authored state in play — spring uses `spring` when present, otherwise summer; the editor Season preview (and Shift+wheel on seasonal tools) chooses which seasonal look to show while editing. Indoor types (floors, walls, furniture) do not need seasonal art. The editor wheel cycles states; hover previews the selected tool on the target tile.
176 **Code:** `server/src/assets/spriteCatalog.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `client/src/editor/main.js`, `client/src/render/worldView.js`, tests in `server/tests/tile-states.test.js`, `server/tests/season.test.js`
177
178 ## Region workers and cross-worker transfer
179
180 **Status:** full
181 **Spec:** Isolated simulation workers own regions. Default is two in-process workers behind a clone-on-boundary protocol (`SIMULATION_WORKER_MODE=thread` uses `worker_threads`). Neighbour-sticky assignment; an entity that steps into a foreign region is frozen, accepted on the destination, then removed from the source (one authoritative copy). Ghost occupancy is visible for pathfinding. Dynamic load rebalance is later.
182 **Code:** `server/src/simulation/simulation.js`, `workerWorld.js`, `inProcessWorker.js`, `threadWorker.js`, tests in `server/tests/worker-*.test.js`
183
184 ## ChunkLoader activation and unload persistence
185
186 **Status:** full
187 **Spec:** Players carry `ChunkLoader` (3×3 simulating chunks, 3×3 resident regions). Chunks with no simulation refs stay dormant in memory. Regions with no residency refs unload after `regionUnloadGracePeriodMs`. Persistent entities are written on unload and restored on the next load; non-persistent entities are discarded.
188 **Code:** `server/src/simulation/chunkLoader.js`, `server/src/simulation/simulation.js`, `server/src/persistence/stateDb.js` (`persistent_entities`)
189
190 ## Midnight restart and Git deploy
191
192 **Status:** full
193 **Spec:** The live process periodically `git fetch`es and compares `HEAD` to `origin/<branch>` (default `master`). When the remote is **ahead**, a graceful restart is scheduled for the next **server-local midnight**. From **3 hours before** midnight, every connected player gets a **permanent toast** with a live countdown. At midnight the server writes `server/data/restart-request.json`, force-logs out sessions, unloads/persists the world, and exits. **systemd** (`Restart=always`) relaunches via `deploy/start-server.sh`, which **always** hard-resets to `origin/<branch>`, pulls, runs `npm install`, then starts Node — including after crashes or power loss (intentional, so a fixed commit can recover a bad build). Install with `sudo ./deploy/install-service.sh`. World editor **Console** tab streams live server stdout to admins.
194 **Code:** `shared/deploy/schedule.js`, `server/src/deploy/`, `server/src/index.js`, `server/src/logging/consoleCapture.js`, `deploy/start-server.sh`, `deploy/install-service.sh`, `deploy/questward.service`, `client/src/play/toasts.js`, `client/src/editor/main.js`, tests in `server/tests/deploy.test.js`
195
196 ## Spawners
197
198 **Status:** full
199 **Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include **deer**, **rats**, and **chickens** (white deer-shaped placeholder sprite); the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, chickens, etc.) can always fight back when attacked (retaliate on first swing); **rats are aggressive** and auto-engage players within 5 tiles with line of sight. **Humanoid** spawners (incl. town guards / exchange) have an editor **Aggressive** flag for the same in-range aggro; Aggressive forces **Bounty** to 0. Spawner **Level** sets skills/HP and **spell cast chance %** (= level, capped 1–100; shown as a label, not editable).; courier pigeons cannot.
200 **Code:** `server/src/simulation/spawners.js`, `server/src/simulation/workerWorld.js`, `server/src/world/chunkData.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/src/editor/tileConfigModal.js`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`, `client/assets/mobs/chicken/`
201
202 ## Mob definitions (content schema)
203
204 **Status:** partial
205 **Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill`, `drops`, `sells`. Drops support `chance`, fixed `quantity`, or inclusive `quantityMin`/`quantityMax`. **Chicken** always drops **1–3 feathers** and has a **20%** chance of an **egg**. **Dialogue trees** are world-scoped assets (Dialogues editor); humanoid spawners assign `config.dialogueId`. See [`docs/QUESTS.md`](QUESTS.md).
206 **Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `server/src/combat/service.js` (`rollDropQuantity`)
207
208 ## Quests
209
210 **Status:** partial
211 **Spec:** Full design in [`docs/QUESTS.md`](QUESTS.md). World editor **Quests** / **Dialogues** buttons (under Settings) author world-scoped defs. Spawners link `dialogueId`; unique dialogues require one spawner with `maxAlive: 1`. Shared `ConditionSet` (AND + per-clause NOT). Play **Quests** UI + step-complete toast “Quest objectives achieved”. Progress / journal / `dialogueHeard` in `state.sqlite`.
212 **Code:** `shared/quests/`, `server/src/quests/`, `server/src/persistence/worldDb.js`, `server/src/persistence/stateDb.js`, `client/src/editor/questsModal.js`, `client/src/editor/dialoguesModal.js`, `client/src/play/quests.js`, `client/src/play/dialogue.js`
213
214 ## Character logout resume
215
216 **Status:** full
217 **Spec:** Despawning a character (logout / disconnect) writes their live tile to `characters`. The next login reloads that row after despawn and resumes there (or the nearest free enterable tile within a short spiral if blocked), instead of jumping to a distant world spawn.
218 **Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
219
220 ## Combat resolution (rolls)
221
222 **Status:** partial
223 **Spec:** Authoritative server rolls; clients only show outcomes. **Melee & ranged (physical):** roll hit skill vs defender **Dexterity (agility)** — miss if attack roll < agility roll, hit on tie or higher; on hit roll damage skill (Strength for melee, Dexterity for ranged) for `baseDamage + roll − 1`; on hit defender rolls Defence — **block** if defence roll > attacker's to-hit roll; otherwise apply damage. **Effective combat levels** add worn equipment tier bonuses to damage/agility/defence rolls (e.g. Strength 10 + bronze weapon +1 → damage roll uses 11). Hit skills (Club/Sword fighting, Archery) use base skill only. XP only on damage hits. **Attack types** (slashing / piercing / blunt) are defined on weapons; mob weak/resist multipliers remain later. **Magic:** roll Magic vs per-spell **difficulty** (contest, tie or higher succeeds); on success roll Mind for damage; multiply by elemental weak ×2 / neutral ×1 / resistant ×0.5; non-damage spells only need a successful cast roll then apply an effect. Spell defs + live cast/impact in `shared/definitions/spells.js` / `server/src/spells/` (starter Light + Spark). More spells and LOS polish remain later.
224 **Code:** `shared/combat/rolls.js`, `shared/combat/magic.js`, `shared/definitions/spells.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `server/src/combat/service.js`, `server/src/spells/service.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/magic.test.js`, `server/tests/spells.test.js`, `server/tests/equipment.test.js`
225
226 ## Combat, skills, groups, pigeons
227
228 **Status:** partial (melee + ranged bows + starter spells live; groups later)
229 **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer, chickens) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Ranged:** bow in weapon + arrows in offhand; Archery hit / Dexterity damage; arrow projectiles lerp toward the target’s **live client visual pose** (misses use a fixed fly-by tile). Server resolves the hit immediately; **HP bar / flash / damage numbers wait until the projectile lands** on each client. **Magic:** cast UI + Light/Spark; spell projectiles likewise track moving targets; spell impacts are delayed on the server to match travel time. **Health** skill sets max HP; taking damage awards Health XP equal to damage taken (lethal hits grant none). Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Groups and broader non-combat skill XP remain later.
230 **Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `shared/definitions/rangedItems.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `server/src/spells/service.js`, `client/src/play/skills.js`, `client/src/play/main.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js`, `server/tests/ranged.test.js` (+ combat/follow/courier/spells tests)
231
232 ## Player death and respawn
233
234 **Status:** full
235 **Spec:** When a **player** reaches **0 HP**, they **die** immediately (authoritative on the server):
236
237 1. **Corpse drops** on the death tile: a **bones** ground item and a **skull** ground item (new item definitions + sprites). These use normal ground-item rules (pickup, despawn timer). Inventory/equipment are **not** dropped by default (death penalty is the corpse markers + travel to church — revisit if PK/loot rules are added later).
238 2. **Combat ends** for the dead player and anyone targeting them (clear engage both ways). The dead player cannot move, attack, follow, pick up, bank, chat-actions that affect the world, or otherwise act until they respawn.
239 3. **Death modal (client):** a blocking modal that is the **only** interactable UI while dead (world clicks, hotkeys, bag, etc. are ignored). Copy states that the player is dead; primary action is **Respawn**. Closing the tab/disconnect while dead keeps them dead until they log in and respawn (or auto-prompt the same modal on re-enter).
240 4. **Respawn:** server moves the character to the **nearest church altar** block (Chebyshev / path distance TBD — prefer enterable tile adjacent to the altar if the altar tile itself is impassable). New **block type: church altar** (`BlockType` + editor placeable + sprite folder), passable or adjacent-use like bank (exact interaction: respawn destination only for now, not a usable station).
241 5. After respawn the player is restored to **full Health** and **full Stamina** (max from skills), cleared of death state, and may fight again.
242
243 **TODO:** Revisit player-loot penalties if PK rules are added.
244 **Code:** `shared/definitions/items.js`, `shared/definitions/tiles.js`, `shared/protocol/constants.js`, `server/src/combat/service.js`, `server/src/simulation/simulation.js`, `server/src/simulation/workerWorld.js`, `server/src/persistence/stateDb.js`, `server/src/gateway/websocket.js`, `client/src/play/death.js`, tests in `server/tests/death.test.js`
245
246 ## Equipment tiers and worn stat bonuses
247
248 **Status:** partial
249 **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). **Worn combat bonuses** come from live world setting `equipmentStatBonuses` (editor **Equipment Stats** tab); defaults seed from `TIER_STAT_BONUS` (full helms +1 Defence). Leather armour can grant Agility and Defence independently; wizard armour Magic and Defence; clothing Defence. Magic casting uses worn Magic/Mind gear bonuses the same way physical combat uses Strength/Agility/Defence. Tools (pickaxes) gate on Mining and do not use the bonus tables. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
250 **Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`shirt`, `shorts`, `skirt`, `trousers`, `sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. **Dual-channel tint** (red = shaft/wood, blue = tip/string; white unchanged): arrows, hafted tools, **bows** / unstrung bows under `items/bow/` (`bow`, `unstrung-bow`, `bowstring` magenta, `bow-equip`). Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
251 **TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
252 **Code:** `shared/definitions/materialTiers.js`, `shared/definitions/equipmentStatCategories.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/definitions/rangedItems.js`, `shared/definitions/tierFamilies.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`, `server/tests/ranged.test.js`
253
254 ## Gathering, crafting, and production skills
255
256 **Status:** partial (mining + smelting + pickaxe/axe/bow craft chains + pine woodcutting + cotton/flower/herb herbalism live)
257 **Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. Tree / flower / herb **regrow** uses the four-way growth season (spring Mar–May, summer Jun–Aug, fall Sep–Nov, winter Dec–Feb): **summer & fall** keep base exhaust time, **winter** doubles it, **spring** is 25% faster (`×0.75`). **Herbalism (plants):** **Flower** nodes need **no tool** (~1s); each flower block carries a fixed colour tint (chosen on respawn / editor place) and picking yields that colour, stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). **Ranged craft:** woodworking → arrow shafts / unstrung bows; anvil → arrow tips; spinning wheel → bowstring from yarn; crafting bench → feather + shaft + tip → arrow, and unstrung bow + bowstring → bow (wood + matching cloth). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer; craft panel supports **Craft**, **Craft X**, and **Craft all** with a progress bar that restarts on each continuing batch step. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
258 **Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/definitions/rangedItems.js`, `shared/crafting/tierRecipes.js`, `shared/world/season.js` (`treeStumpStateForSeason`, `growthSeasonIdAt`, `scaleRegrowDurationMs`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/play/crafting.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`, `server/tests/ranged.test.js`, `server/tests/season.test.js`
259
260 ## Cloth, dyes, and tailoring
261
262 **Status:** partial (cotton loop + flower dyes + shirt/shorts/skirt/trousers/sweater live; higher cloth sources TBD)
263 **Spec:** **Cloth tiers** (same skill gates/ranks as metal/wood): Cotton, Wool, Linen, Cashmere, Silk, Fairy silk, Dragonweave. Shared magenta sprites under `items/cloth` (`wool` fibre, `yarn`, `cloth`) and `items/clothing` (`shirt`, `shorts`, `skirt`, `trousers`, `sweater` + equip) tinted per tier (or optional dye colour on clothing instances). **Spinning wheel** (Tailoring): fibre → yarn. **Loom**: yarn → cloth. **Tailor bench** UI is template-first: pick clothing template (**shirt**, **shorts**, **skirt**, **trousers**, **sweater**) → cloth tier → optional dye from bag → sidebar shows resolved ingredients (shirt/shorts/skirt/trousers = **1 cloth**; sweater = 3 yarn). Skirts are not tight-fit (unlike shorts). Display names are tiered (`Cotton shirt`, …). Historic item id 5 remains the cotton shirt. Crafted clothing can carry `instance.dyeColor`; otherwise material tint. **Flowers** (9 colours) brew 1:1 into **dye** bottles at a cauldron (needs **glass bottles** / `potion-0`). Two different dye colours mix paint-style (weighted by fill); bottle count follows inserted dyes; fill packs with overflow into the next bottle (extra glass only if overflow needs more bottles than inputs). Cannot mix flowers with dyes in one brew. Dye uses on tailor consume one fill level per craft.
264 **TODO (sources):** shear animals / pick plants for wool–silk; fairy silk + dragonweave as mob drops later.
265 **Later design (document only for now):**
266 - **Wizard cloth gear** — robes and similar give Magic skill bonuses (`EquipmentKind.wizardCloth`).
267 - **Cosmetic cloth gear** — sum equipped cosmetic item tiers as **Style points** (quests / exclusive areas).
268 - **Warm clothing** — sweaters and other warm pieces reduce cold-season debuffs (e.g. winter halves stamina regen; each warm-equipped slot except hands mitigates; full warm set nullifies cold; summer reverses). **Padding** from cloth + matching-tier plate at a crafting bench → **padded armour** per slot.
269 **Code:** `shared/definitions/materialTiers.js` (`ClothTier`), `shared/definitions/clothItems.js`, `shared/definitions/dyes.js`, `shared/crafting/tailor.js`, `shared/crafting/stationRecipes.js`, `server/src/alchemy/service.js`, `server/src/crafting/service.js`, `server/src/gathering/service.js`, `client/src/play/crafting.js`, `client/src/play/alchemy.js`
270
271 ## Crafting stations
272
273 **Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
274 **Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles, shafts, unstrung bows); crafting bench joins finished parts (pickaxe/axe head + handle, arrows, strung bows). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, **spinning wheel**, **loom**, and **tailor** craft UIs use a single-axis material dropdown so tier variants share one recipe cell. **Crafting bench** alone shows **paired metal/wood labels** (e.g. `Bronze/Pine`) because it mixes metal tools with wood bows on the same tier rank. **Hard rule (all stations + cauldron, player and scripts):** items in station slots are never committed out of the inventory — slots are a reservation/view over the bag (**client-side UI**; even if it looks like mats sit in the station, they do not). Server soft-tracks steps/claims only and consumes on successful craft/brew. Closing the UI, cancelling, or dying mid-craft/brew cannot destroy reserved mats. Station progress is **per player**, not tile-global. See `.cursor/rules/station-inventory.mdc`.
275 **TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
276 **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
277
278 ## Stamina and running
279
280 **Status:** full
281 **Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows vertical **HP** (always) and **stamina** bars bottom-right.
282 **Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
283
284 ## Alchemy / cauldron
285
286 **Status:** partial (starter herb potions + failed-effect list + status ticks live; more recipes TBD)
287 **Spec:** **Herbalism** gathers flowers, cotton, and **24 folklore herbs** (`BlockType.herbPlant`). Flowers/cotton need **no tool**; clipper herbs require **plant clippers** and Herbalism gates by tier. **Alchemy** cauldron tabs **Alchemy** / **Dyes**. Starter potions: **Lesser health tonic** (thyme→heat→mint→stir; health regen 1/s for 10s, re-drink extends), **Lesser haste draught** (2 mint→heat→stir→lavender→cool; stamina regen 1/s for 10s), **Strength potion** (3 thyme→stir→2 nettle→heat; +5 Strength for 1 min), **Clarity potion** (rosemary→cool→2 chamomile→stir; +5 Mind for 1 min). Failed brews hash to unstable effects: stamina drain 1/s 15s, weak glow light 10s, shrink to 50% scale 30s, blindness 20s (extra darkness + local vision bubble). Active effects show as HUD icons left of the HP/stamina bars (`assets/status-effects/`; hover shows description + remaining time). Opening needs empty glass bottles. **Dyes** unchanged (flowers).
288 **Code:** `shared/definitions/alchemy.js`, `shared/statusEffects/rules.js`, `shared/statusEffects/display.js`, `server/src/statusEffects/service.js`, `client/src/play/statusEffects.js`, `shared/definitions/herbs.js`, `server/src/alchemy/service.js`, `server/src/items/bags.js`, `client/src/render/worldView.js`, tests in `server/tests/alchemy.test.js`, `server/tests/herbalism.test.js`
289
290 ### Folklore herb associations (design only — not in code)
291
292 Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3 / 4 / 4 / 4 / 4** for T1–T7.
293
294 | Tier | Herb | Associations |
295 | --- | --- | --- |
296 | 1 | Mint | Refreshment, stamina, antidotes |
297 | 1 | Garlic | Undead protection, disease resistance |
298 | 2 | Thyme | Courage, vitality, resistance |
299 | 2 | Sage | Healing, wisdom, longevity |
300 | 2 | Rosemary | Memory, protection, clarity |
301 | 3 | Lavender | Sleep, calm, dreams |
302 | 3 | Chamomile | Restoration, sleep, soothing |
303 | 3 | Nettle | Vigour, resilience, protection |
304 | 4 | Yarrow | Wound healing, battle medicine |
305 | 4 | Juniper | Purification, disease resistance |
306 | 4 | Elder | Spirits, protection, healing |
307 | 4 | Rue | Curse resistance, purification |
308 | 5 | Valerian | Sleep, sedation, tranquillity |
309 | 5 | Mugwort | Dreams, visions, divination |
310 | 5 | Wormwood | Poison resistance, spirits, bitterness |
311 | 5 | St. John's wort | Holy protection, dispel darkness |
312 | 6 | Hawthorn | Fey, barriers, enchantment |
313 | 6 | Foxglove | Fairy magic, heart magic, poison |
314 | 6 | Mistletoe | Life, fertility, druidic magic |
315 | 6 | Datura | Visions, insanity, spirit walking |
316 | 7 | Belladonna | Poison, hallucination, witchcraft |
317 | 7 | Henbane | Trance, madness, sleep, poison |
318 | 7 | Mandrake | Powerful potions, curses, life magic |
319 | 7 | Aconite | Werewolves, lethal poison, curses |
320
321 ## Inventory, items, equipment, ground drops
322
323 **Status:** full
324 **Spec:** 32-slot inventory, stacking, equipment slots (head, chest, legs, boots, weapon, **offhand** for shields/arrows) with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. **Equip draw order (back → front):** boots → chest → weapon → legs → hair (if visible) → head → offhand — so weapons sit above the shirt but under trousers/skirts (legs may cover shirt hem; art should avoid bad waist overlap). New characters receive world **Starter Equipment** / inventory, then creation clothing dyes on top (see **Characters**). Right-click bag items for Send / Equip / Drop / Eat (food; apples, eggs, …); paper can be written into unique **letter** instances (signed on Save; only the signer may edit). Equipping always takes **one** item from a stack (never the whole stack); unequipping returns one item and merges into an existing compatible inventory stack when stack rules allow. Equip enforces tier min-skill gates. Eating food heals (see Health skill).
325 **Code:** `shared/definitions/items.js` (`EQUIPMENT_DRAW_ORDER`), `shared/appearance/hair.js` (`composeAppearanceLayers`), `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
326
327 ## Proximity chat
328
329 **Status:** full
330 **Spec:** Enter opens a bottom chat line (max `chatMaxCharacters`, default 100). Enter trims and sends; Escape cancels. The speaker always sees their own bubble. Other players receive server-side obfuscation: full text within 8 tiles, linear falloff to silent at 16 tiles. At 0% readability the bubble is not sent.
331 **Code:** `shared/speech/proximity.js`, `server/src/chat/speech.js`, `client/src/play/chat.js`, tests in `server/tests/proximity-speech.test.js`
332
333 ## Friends
334
335 **Status:** full
336 **Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
337 **Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
338
339 ## Hair & barber
340
341 **Status:** full
342 **Spec:** Character creation **Appearance** tab picks a hair style (per sex body folder) plus hue/saturation/darkness; live preview tints magenta hair sprites (no clothing on that tab). The **Clothing** tab shows the same body/hair with cotton shirt + legs and per-piece dyes. Hair is stored on the character and drawn as a head overlay unless headgear is worn (item defs may set `equipment.keepHair` to keep hair under a hat — none yet). Placeable **Barber** blocks reopen the hair UI to restyle (preview hides headgear).
343 **Code:** `shared/appearance/hair.js`, `server/src/barber/service.js`, `client/src/play/hairControls.js`, `client/src/play/barber.js`, `client/src/play/createClothingControls.js`, `client/assets/blocks/barber/`
344
345 ## Bounty offices
346
347 **Status:** full
348 **Spec:** Placeable **Bounty Office** blocks. Interacting opens a modal with two tabs:
349
350 1. **Place / raise bounty** — Search a character by first + last name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success). You cannot place a bounty on yourself.
351 2. **My bounty** — Shows how much coin is currently on **your** head. You may **pay toward** that bounty from inventory at **10 coins paid → 1 bounty coin cleared** (capped at the remaining bounty; only complete 10-coin multiples are spent). Bounty also **decays by 1 coin per calendar day** at local midnight (lazy apply when read).
352
353 **Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer's bank**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.
354
355 **Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
356
357 **Code:** `shared/bounty/pricing.js`, `shared/definitions/tiles.js` (`BlockType.bountyOffice`), `server/src/bounty/service.js`, `server/src/courier/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/bounty.js`, `client/assets/blocks/bounty-office/`, tests in `server/tests/bounty.test.js`
358
359 ## Banking, cheques, shops, player-driven marketplace
360
361 **Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
362 **Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free; closing the UI or walking away from that counter releases the clerk so wander resumes, unless another player is still using the same staff station. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
363 **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
364
365 ## Player scripting (AFK / offline)
366
367 **Status:** not implemented
368 **Spec:** Full language + UI + online/AFK/offline behaviour is documented in [`docs/SCRIPTS.md`](SCRIPTS.md). Scripts are a sandboxed, server-interpreted language that emits normal player intents. Names match **exactly** (case-insensitive). `find` / nearest only searches the **visible 3×3** chunks (what a player sees). `@` variables + `set` hold targets/coords for waypoints; `go` fails beyond **2 chunks** (`Too far away.`). Universal `can <action>` dry-runs any verb. Station/cauldron state is **per player**; station slots never commit items out of the bag until craft/brew succeeds. AFK auto-start after **30 minutes** idle. Death while scripting stops the script and fully logs the instance out. Friends/barber/follow/graphics/editor are out of scope. Architecture hooks remain in design doc §18.
369 **Code:** — (planned: `shared/scripts/`, `server/src/scripts/`, `client/src/play/scripts.js`, state DB script rows)
@@ -1,369 +0,0 @@
1# Feature implementation tracker
2
3Living companion to `questward_server_technical_design_v0.6.md`.
4Statuses: **not implemented** · **partial** · **full**.
5
6Each entry is a short note on behaviour and where the code lives. Update this file in the same commit as the feature it describes.
7
8---
9
10## World coordinates and spatial hierarchy
11
12**Status:** full
13**Spec:** World tile coordinates are canonical. Chunks are 16×16 tiles; regions are 4×4 chunks. Negative coordinates use true floor division. Positions are scoped by **dimensionId** (default `overworld`); chunk/region keys are `dim|x,y`.
14**Code:** `server/src/world/coordinates.js`, `shared/world/dimensions.js`, tests in `server/tests/coordinates.test.js`
15
16## Interior dimensions
17
18**Status:** partial
19**Spec:** Besides the **overworld**, the world may contain named **dimensions** (caves, houses, …), each with its own chunk grid, default ground, open/closed map, **lighting mode** (`dayNight` / `alwaysLit` / `alwaysDark`), and **season mode** (`auto` / `summer` / `spring` / `autumn` / `winter`; autumn→fall art). Soft-delete marks a non-overworld dim unusable; after **7 days** it is purged (chunks + metadata). Cancel deletion before purge. **Doorway** blocks (`ladder` / `door` / `hole` / `cave`) teleport the player to `{ targetDimensionId, tileX, tileY }` (server-authoritative). Characters persist `dimension_id` + visits for quest conditions. Editor: searchable dim picker with inline create; per-dim settings while selected.
20**Code:** `shared/world/dimensions.js`, `server/src/persistence/worldDb.js` (`world_dimensions`), `server/src/simulation/simulation.js` (`#relocateCharacterThroughDoorway`), `client/src/editor/dimensionCombobox.js`, `BlockType.doorway`
21
22## Ground and block tile layers
23
24**Status:** full
25**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, **dirt** (outdoor seasonal, soft-terrain blendable like grass), wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants.
26**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
27
28## Open and closed chunks
29
30**Status:** full
31**Spec:** Never-edited chunks are closed grass. Closed chunks can be replicated but cannot be entered; pathfinding treats them as impassable. Open chunks draw a red border on edges that touch a closed neighbour.
32**Code:** `server/src/world/chunkData.js` (`open` flag), `server/src/world/chunkFlags.js`, `server/src/simulation/simulation.js` (`isEnterable`, `#walkableFor`, `closedEdges`), `client/src/render/worldView.js` (`#rebuildChunkEdges`)
33
34## ECS registry and components
35
36**Status:** full
37**Spec:** Entities are compositions of components with integer tile positions. Live components include `position`, `movement`, `path`, `appearance`, `character`, `networkIdentity`, `chunkLoader`, and `persistent`. Global `EntityId`s are used for storage, networking and transfer; each worker uses compact recycled `EntityHandle`s for hot ECS arrays.
38**Code:** `server/src/ecs/world.js`, `server/src/ecs/serialize.js`, `server/src/ecs/components.js`
39
40## Simulation tick
41
42**Status:** full
43**Spec:** Fixed tick from `WorldSettings.simulationTickHz` (default 20 Hz). Commands drain at tick boundaries, then activation, movement, transfers, and ghost exchange. Multiple isolated simulation workers.
44**Code:** `server/src/simulation/simulation.js` (`step`), `server/src/index.js`
45
46## Authored world and runtime state persistence
47
48**Status:** full
49**Spec:** `world.sqlite` holds revisioned authored chunks, live world settings, and settings/chunk changelogs. `state.sqlite` holds accounts, characters, and runtime entity state. Databases live under `server/data/` and use Node's SQLite binding.
50**Code:** `server/src/persistence/database.js`, `worldDb.js`, `stateDb.js`
51
52## World revisions and pending editor saves
53
54**Status:** partial
55**Spec:** Editor chunk saves write a pending world revision. The running process stays pinned to the map revision loaded at startup until an admin **Apply now** (in-process reload). Live world settings do not use this path. Code updates use the midnight deploy path (see **Midnight restart and Git deploy**).
56**Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
57
58## World settings
59
60**Status:** full
61**Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, **Equipment Stats**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Equipment Stats** edits worn combat bonuses as piece×tier tables (category dropdown: metal armour, leather armour, melee/ranged weapons, magic staves, wizard armour, clothing); multi-stat cells (e.g. leather Agility+Defence) are independent inputs. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
62**Code:** `shared/definitions/worldSettings.js`, `shared/definitions/equipmentStatCategories.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
63
64## Baked lighting
65
66**Status:** full
67**Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on furniture (tables, marketplace counters, crafting stations, ore nodes, cauldron) to let light through while remaining impassable. Set `blocksLight: "partial"` on standing trees so the ray continues but each canopy tile adds +1 to falloff distance; **tree stumps** (`*-stump` state from woodcutting) clear that occlusion at runtime via live chunk snapshots (same dynamic path as torches, without rebaking). Store a 16×16 intensity map (0–255, smoothstep falloff by effective tile distance). Torch range is 8 tiles; furnace is 4.
68**Code:** `server/src/lighting/baker.js`, `shared/lighting/raycast.js`, `shared/definitions/tiles.js` (`LightOcclusion` / `blocksLight`), tests in `server/tests/lighting.test.js`
69
70## World editor (server)
71
72**Status:** full
73**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`, neighbor-connect autotile), **wooden tables** (`BlockType.table`, magenta autotile `0`–`15` tinted per wood tier; joins only the same material), and **Central Exchange staff** spawners are placeable.
74**Code:** `server/src/editor/service.js`
75
76## World editor (client)
77
78**Status:** full
79**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: spring/summer/fall/winter, which also updates Season preview), open/closed, right-side **Changelog / Console** tabs (console streams live server output to admins), night preview slider, **season preview** dropdown, world-settings modal, **Dimension settings…** opens a modal (lighting / season / default ground / soft-delete), **Quests** and **Dialogues** buttons under Settings (see docs/QUESTS.md), save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
80**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
81
82## Per-chunk changelog
83
84**Status:** full
85**Spec:** Each save stores who, when, and structured bullets of ground/block/spawner/open-closed diffs.
86**Code:** `server/src/editor/service.js` (`diffChunks`), `server/src/persistence/worldDb.js` (`world_chunk_edit_log`), tests in `server/tests/editor-diff.test.js`
87
88## WebSocket gateway
89
90**Status:** full
91**Spec:** JSON WebSocket on `/ws`, HTTP static files for the client. Connections belong to the gateway. Clients send intentions that are queued onto the simulation tick. Editor messages are admin-only.
92**Code:** `server/src/gateway/websocket.js`, `server/src/gateway/http.js`, `server/src/index.js`
93
94## Authentication (auth.timfalken.com)
95
96**Status:** partial
97**Spec:** OAuth2 authorization-code flow via **auth.timfalken.com**. Sign in at `/auth/login`; callback at `/auth/callback` sets an HttpOnly session cookie. WebSocket `/ws` requires that cookie (or stub mode). The **first account** to sign in becomes a **game admin**; further admins are granted in the world editor **Settings → Admins** tab (username must have signed in once). Removing the last admin is blocked; removing yourself requires confirmation. `GET /settings/export` returns a JSON data export (integrator requirement). Stub mode (`QUESTWARD_AUTH_STUB=1` or missing client secret) keeps dev `admin-<n>` identities (all admins).
98**Code:** `server/src/auth/`, `server/src/gateway/http.js`, `server/src/gateway/websocket.js`, `client/src/net/auth.js`, `client/src/editor/settingsModal.js` (Admins tab), tests in `server/tests/authAccounts.test.js`
99
100## Stub authentication (dev only)
101
102**Status:** full (when stub mode active)
103**Spec:** Each connection is `admin-<n>` with full admin rights when OAuth is not configured.
104**Code:** `server/src/auth/stub.js`
105
106## Characters
107
108**Status:** full
109**Spec:** Unlimited characters per account, one in the world. First name is not globally unique; last name is globally unique per account; first+last unique per account, case-insensitive. Male/female body. Spawn requires an open tile. The login screen lists characters first; **Create Character** opens a modal (**Appearance** / **Clothing** tabs) and successful creation enters the world immediately. New characters receive **Starter Equipment** / inventory from live world settings (origin: “Received from the gods”), then **creation clothing** on top: cotton shirt + chosen cotton trousers/shorts/skirt, each with an HSL dye (same controls as hair). Existing characters are unaffected.
110**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`, `shared/items/starterLoadout.js`, `shared/items/createClothing.js`, `client/index.html`, `client/src/play/createClothingControls.js`
111
112## Character deletion and inheritance
113
114**Status:** full
115**Spec:** 24h delayed delete, cancellable. Notify via stub log (or email when present). Names and surname claims are freed on permanent delete. Inventory, equipment, carried coins, and vault move to the account inheritance tab, claimable at a bank into another character's vault.
116**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js` (`account_inheritance`)
117
118## 3×3 chunk replication
119
120**Status:** full
121**Spec:** Entity and ground-item replication uses the current chunk and eight neighbours. Map tiles (static snapshots) default to a **5×5** ring (`STATIC_CHUNK_RADIUS = 2`); clients may request **Short** viewing distance so the map ring matches the 3×3 entity ring. Closed chunks are still sent. Afterwards the gateway sends `ENTITY_SPAWN`, compact `ENTITY_MOVE` (tile + gait) and `ENTITY_DESPAWN`; appearance and path stay off the move payload. Tile deltas are not used yet because live tile edits wait for Apply now. Visible chunks may be owned by different workers; the gateway never reassigns regions for rendering.
122**Code:** `server/src/simulation/simulation.js` (`snapshotsForView`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`), `shared/graphics/settings.js`
123
124## Click-to-move and A\* pathfinding
125
126**Status:** full
127**Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Entities do **not** block each other’s movement (players and mobs pass through). Occupied tiles are still preferred-away for mob wander goals and required to be clear for melee attack stance. Client spreads stacked entities evenly on a circle (`ENTITY_STACK_SPREAD_DIAMETER_PX`, centred on the tile) with a short lerp into place; within-tile y-sort still uses each sprite’s visual Y. Server commits integer tiles on the movement cadence. Neighbour expansion prefers steps that most reduce Manhattan distance to the goal; remaining ties break by axis — **players prefer vertical**, **mobs prefer horizontal** — so mutual approaches are less likely to oscillate sideways.
128**Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`, `walkableFor`, `isClearStanding`)
129
130## Global walk/run cadence
131
132**Status:** full
133**Spec:** Walk 2 tiles/s, run double. Movement ticks at run rate. `SetGait` chooses every-other vs every movement tick.
134**Code:** `server/src/simulation/workerWorld.js` (`#stepMovement`, `#setGait`)
135
136## Client movement interpolation
137
138**Status:** full
139**Spec:** Client lerps sprites between replicated tiles over the walk or run interval from world settings.
140**Code:** `client/src/render/worldView.js` (`moveEntity`, `update`)
141
142## Play viewport and camera
143
144**Status:** full
145**Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Tiles and chunk atlases more than half a tile outside the screen (zoom-aware) are not drawn and skip per-frame lighting work. Hovering another player shows their first name; clicking them inspects instead of issuing move.
146**Code:** `client/src/render/worldView.js` (`#cullOffscreenDrawables`, `#drawBounds`), `client/src/play/main.js`, `client/index.html`
147
148## Client graphics settings
149
150**Status:** full
151**Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer. **Soft terrain** On/Off (default **On**) edge-blends `blendable` ground tiles (grass, dirt) into differing neighbours along **cardinal** edges only: outer edge pixel 50% neighbour, next pixel 25% (softer 40%/20% when both sides are blendable); baked at chunk atlas time. The settings panel blocks world clicks while open.
152**Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `client/src/render/chunkBake.js`, `shared/render/softTerrain.js`, `server/src/gateway/websocket.js`
153
154## Night shading
155
156**Status:** full
157**Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. With **Soft** lighting, baked ground/block atlases sample a per-chunk lightmap with neighbour blending; **Simple** lighting uses a flat per-tile intensity (no corner blend). **Animated liquid water** uses the same lit values via shader uniforms. **Light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`spring` / `summer` / `fall` / `winter`) for seasonal tile visuals (types without a spring sprite fall back to summer).
158**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
159
160## FrameworkV3 client bootstrap
161
162**Status:** full
163**Spec:** FrameworkV3 is a git submodule at `client/frameworkv3`, built first via `npm run build:client`. Game code lives in `client/src`. Server does not import it.
164**Code:** `.gitmodules`, `client/frameworkv3`, `client/scripts/build-framework.mjs`
165
166## Sprite size, pivot and Y-sort
167
168**Status:** full
169**Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets. Immobile ≤16×16 blocks bake into per-row chunk strips; taller sprites stay individually Y-sorted.
170**Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`, tests in `server/tests/pivot.test.js`
171
172## Visual tile states
173
174**Status:** full
175**Spec:** Each ground and block type has a folder of PNG states. Non-seasonal types use the first alphabetical file as the default; outdoor seasonal types prefer `summer` (or legacy `grass`). States are visual only; the game may set a named state (for example a door or ore). For outdoor types that expose summer/fall/winter (optional `spring`), calendar season overrides authored state in play — spring uses `spring` when present, otherwise summer; the editor Season preview (and Shift+wheel on seasonal tools) chooses which seasonal look to show while editing. Indoor types (floors, walls, furniture) do not need seasonal art. The editor wheel cycles states; hover previews the selected tool on the target tile.
176**Code:** `server/src/assets/spriteCatalog.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `client/src/editor/main.js`, `client/src/render/worldView.js`, tests in `server/tests/tile-states.test.js`, `server/tests/season.test.js`
177
178## Region workers and cross-worker transfer
179
180**Status:** full
181**Spec:** Isolated simulation workers own regions. Default is two in-process workers behind a clone-on-boundary protocol (`SIMULATION_WORKER_MODE=thread` uses `worker_threads`). Neighbour-sticky assignment; an entity that steps into a foreign region is frozen, accepted on the destination, then removed from the source (one authoritative copy). Ghost occupancy is visible for pathfinding. Dynamic load rebalance is later.
182**Code:** `server/src/simulation/simulation.js`, `workerWorld.js`, `inProcessWorker.js`, `threadWorker.js`, tests in `server/tests/worker-*.test.js`
183
184## ChunkLoader activation and unload persistence
185
186**Status:** full
187**Spec:** Players carry `ChunkLoader` (3×3 simulating chunks, 3×3 resident regions). Chunks with no simulation refs stay dormant in memory. Regions with no residency refs unload after `regionUnloadGracePeriodMs`. Persistent entities are written on unload and restored on the next load; non-persistent entities are discarded.
188**Code:** `server/src/simulation/chunkLoader.js`, `server/src/simulation/simulation.js`, `server/src/persistence/stateDb.js` (`persistent_entities`)
189
190## Midnight restart and Git deploy
191
192**Status:** full
193**Spec:** The live process periodically `git fetch`es and compares `HEAD` to `origin/<branch>` (default `master`). When the remote is **ahead**, a graceful restart is scheduled for the next **server-local midnight**. From **3 hours before** midnight, every connected player gets a **permanent toast** with a live countdown. At midnight the server writes `server/data/restart-request.json`, force-logs out sessions, unloads/persists the world, and exits. **systemd** (`Restart=always`) relaunches via `deploy/start-server.sh`, which **always** hard-resets to `origin/<branch>`, pulls, runs `npm install`, then starts Node — including after crashes or power loss (intentional, so a fixed commit can recover a bad build). Install with `sudo ./deploy/install-service.sh`. World editor **Console** tab streams live server stdout to admins.
194**Code:** `shared/deploy/schedule.js`, `server/src/deploy/`, `server/src/index.js`, `server/src/logging/consoleCapture.js`, `deploy/start-server.sh`, `deploy/install-service.sh`, `deploy/questward.service`, `client/src/play/toasts.js`, `client/src/editor/main.js`, tests in `server/tests/deploy.test.js`
195
196## Spawners
197
198**Status:** full
199**Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include **deer**, **rats**, and **chickens** (white deer-shaped placeholder sprite); the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, chickens, etc.) can always fight back when attacked (retaliate on first swing); **rats are aggressive** and auto-engage players within 5 tiles with line of sight. **Humanoid** spawners (incl. town guards / exchange) have an editor **Aggressive** flag for the same in-range aggro; Aggressive forces **Bounty** to 0. Spawner **Level** sets skills/HP and **spell cast chance %** (= level, capped 1–100; shown as a label, not editable).; courier pigeons cannot.
200**Code:** `server/src/simulation/spawners.js`, `server/src/simulation/workerWorld.js`, `server/src/world/chunkData.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/src/editor/tileConfigModal.js`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`, `client/assets/mobs/chicken/`
201
202## Mob definitions (content schema)
203
204**Status:** partial
205**Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill`, `drops`, `sells`. Drops support `chance`, fixed `quantity`, or inclusive `quantityMin`/`quantityMax`. **Chicken** always drops **1–3 feathers** and has a **20%** chance of an **egg**. **Dialogue trees** are world-scoped assets (Dialogues editor); humanoid spawners assign `config.dialogueId`. See [`docs/QUESTS.md`](QUESTS.md).
206**Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `server/src/combat/service.js` (`rollDropQuantity`)
207
208## Quests
209
210**Status:** partial
211**Spec:** Full design in [`docs/QUESTS.md`](QUESTS.md). World editor **Quests** / **Dialogues** buttons (under Settings) author world-scoped defs. Spawners link `dialogueId`; unique dialogues require one spawner with `maxAlive: 1`. Shared `ConditionSet` (AND + per-clause NOT). Play **Quests** UI + step-complete toast “Quest objectives achieved”. Progress / journal / `dialogueHeard` in `state.sqlite`.
212**Code:** `shared/quests/`, `server/src/quests/`, `server/src/persistence/worldDb.js`, `server/src/persistence/stateDb.js`, `client/src/editor/questsModal.js`, `client/src/editor/dialoguesModal.js`, `client/src/play/quests.js`, `client/src/play/dialogue.js`
213
214## Character logout resume
215
216**Status:** full
217**Spec:** Despawning a character (logout / disconnect) writes their live tile to `characters`. The next login reloads that row after despawn and resumes there (or the nearest free enterable tile within a short spiral if blocked), instead of jumping to a distant world spawn.
218**Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
219
220## Combat resolution (rolls)
221
222**Status:** partial
223**Spec:** Authoritative server rolls; clients only show outcomes. **Melee & ranged (physical):** roll hit skill vs defender **Dexterity (agility)** — miss if attack roll < agility roll, hit on tie or higher; on hit roll damage skill (Strength for melee, Dexterity for ranged) for `baseDamage + roll − 1`; on hit defender rolls Defence — **block** if defence roll > attacker's to-hit roll; otherwise apply damage. **Effective combat levels** add worn equipment tier bonuses to damage/agility/defence rolls (e.g. Strength 10 + bronze weapon +1 → damage roll uses 11). Hit skills (Club/Sword fighting, Archery) use base skill only. XP only on damage hits. **Attack types** (slashing / piercing / blunt) are defined on weapons; mob weak/resist multipliers remain later. **Magic:** roll Magic vs per-spell **difficulty** (contest, tie or higher succeeds); on success roll Mind for damage; multiply by elemental weak ×2 / neutral ×1 / resistant ×0.5; non-damage spells only need a successful cast roll then apply an effect. Spell defs + live cast/impact in `shared/definitions/spells.js` / `server/src/spells/` (starter Light + Spark). More spells and LOS polish remain later.
224**Code:** `shared/combat/rolls.js`, `shared/combat/magic.js`, `shared/definitions/spells.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `server/src/combat/service.js`, `server/src/spells/service.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/magic.test.js`, `server/tests/spells.test.js`, `server/tests/equipment.test.js`
225
226## Combat, skills, groups, pigeons
227
228**Status:** partial (melee + ranged bows + starter spells live; groups later)
229**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer, chickens) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Ranged:** bow in weapon + arrows in offhand; Archery hit / Dexterity damage; arrow projectiles lerp toward the target’s **live client visual pose** (misses use a fixed fly-by tile). Server resolves the hit immediately; **HP bar / flash / damage numbers wait until the projectile lands** on each client. **Magic:** cast UI + Light/Spark; spell projectiles likewise track moving targets; spell impacts are delayed on the server to match travel time. **Health** skill sets max HP; taking damage awards Health XP equal to damage taken (lethal hits grant none). Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Groups and broader non-combat skill XP remain later.
230**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `shared/definitions/rangedItems.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `server/src/spells/service.js`, `client/src/play/skills.js`, `client/src/play/main.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js`, `server/tests/ranged.test.js` (+ combat/follow/courier/spells tests)
231
232## Player death and respawn
233
234**Status:** full
235**Spec:** When a **player** reaches **0 HP**, they **die** immediately (authoritative on the server):
236
2371. **Corpse drops** on the death tile: a **bones** ground item and a **skull** ground item (new item definitions + sprites). These use normal ground-item rules (pickup, despawn timer). Inventory/equipment are **not** dropped by default (death penalty is the corpse markers + travel to church — revisit if PK/loot rules are added later).
2382. **Combat ends** for the dead player and anyone targeting them (clear engage both ways). The dead player cannot move, attack, follow, pick up, bank, chat-actions that affect the world, or otherwise act until they respawn.
2393. **Death modal (client):** a blocking modal that is the **only** interactable UI while dead (world clicks, hotkeys, bag, etc. are ignored). Copy states that the player is dead; primary action is **Respawn**. Closing the tab/disconnect while dead keeps them dead until they log in and respawn (or auto-prompt the same modal on re-enter).
2404. **Respawn:** server moves the character to the **nearest church altar** block (Chebyshev / path distance TBD — prefer enterable tile adjacent to the altar if the altar tile itself is impassable). New **block type: church altar** (`BlockType` + editor placeable + sprite folder), passable or adjacent-use like bank (exact interaction: respawn destination only for now, not a usable station).
2415. After respawn the player is restored to **full Health** and **full Stamina** (max from skills), cleared of death state, and may fight again.
242
243**TODO:** Revisit player-loot penalties if PK rules are added.
244**Code:** `shared/definitions/items.js`, `shared/definitions/tiles.js`, `shared/protocol/constants.js`, `server/src/combat/service.js`, `server/src/simulation/simulation.js`, `server/src/simulation/workerWorld.js`, `server/src/persistence/stateDb.js`, `server/src/gateway/websocket.js`, `client/src/play/death.js`, tests in `server/tests/death.test.js`
245
246## Equipment tiers and worn stat bonuses
247
248**Status:** partial
249**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). **Worn combat bonuses** come from live world setting `equipmentStatBonuses` (editor **Equipment Stats** tab); defaults seed from `TIER_STAT_BONUS` (full helms +1 Defence). Leather armour can grant Agility and Defence independently; wizard armour Magic and Defence; clothing Defence. Magic casting uses worn Magic/Mind gear bonuses the same way physical combat uses Strength/Agility/Defence. Tools (pickaxes) gate on Mining and do not use the bonus tables. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
250**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`shirt`, `shorts`, `skirt`, `trousers`, `sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. **Dual-channel tint** (red = shaft/wood, blue = tip/string; white unchanged): arrows, hafted tools, **bows** / unstrung bows under `items/bow/` (`bow`, `unstrung-bow`, `bowstring` magenta, `bow-equip`). Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
251**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
252**Code:** `shared/definitions/materialTiers.js`, `shared/definitions/equipmentStatCategories.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/definitions/rangedItems.js`, `shared/definitions/tierFamilies.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`, `server/tests/ranged.test.js`
253
254## Gathering, crafting, and production skills
255
256**Status:** partial (mining + smelting + pickaxe/axe/bow craft chains + pine woodcutting + cotton/flower/herb herbalism live)
257**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. Tree / flower / herb **regrow** uses the four-way growth season (spring Mar–May, summer Jun–Aug, fall Sep–Nov, winter Dec–Feb): **summer & fall** keep base exhaust time, **winter** doubles it, **spring** is 25% faster (`×0.75`). **Herbalism (plants):** **Flower** nodes need **no tool** (~1s); each flower block carries a fixed colour tint (chosen on respawn / editor place) and picking yields that colour, stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). **Ranged craft:** woodworking → arrow shafts / unstrung bows; anvil → arrow tips; spinning wheel → bowstring from yarn; crafting bench → feather + shaft + tip → arrow, and unstrung bow + bowstring → bow (wood + matching cloth). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer; craft panel supports **Craft**, **Craft X**, and **Craft all** with a progress bar that restarts on each continuing batch step. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
258**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/definitions/rangedItems.js`, `shared/crafting/tierRecipes.js`, `shared/world/season.js` (`treeStumpStateForSeason`, `growthSeasonIdAt`, `scaleRegrowDurationMs`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/play/crafting.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`, `server/tests/ranged.test.js`, `server/tests/season.test.js`
259
260## Cloth, dyes, and tailoring
261
262**Status:** partial (cotton loop + flower dyes + shirt/shorts/skirt/trousers/sweater live; higher cloth sources TBD)
263**Spec:** **Cloth tiers** (same skill gates/ranks as metal/wood): Cotton, Wool, Linen, Cashmere, Silk, Fairy silk, Dragonweave. Shared magenta sprites under `items/cloth` (`wool` fibre, `yarn`, `cloth`) and `items/clothing` (`shirt`, `shorts`, `skirt`, `trousers`, `sweater` + equip) tinted per tier (or optional dye colour on clothing instances). **Spinning wheel** (Tailoring): fibre → yarn. **Loom**: yarn → cloth. **Tailor bench** UI is template-first: pick clothing template (**shirt**, **shorts**, **skirt**, **trousers**, **sweater**) → cloth tier → optional dye from bag → sidebar shows resolved ingredients (shirt/shorts/skirt/trousers = **1 cloth**; sweater = 3 yarn). Skirts are not tight-fit (unlike shorts). Display names are tiered (`Cotton shirt`, …). Historic item id 5 remains the cotton shirt. Crafted clothing can carry `instance.dyeColor`; otherwise material tint. **Flowers** (9 colours) brew 1:1 into **dye** bottles at a cauldron (needs **glass bottles** / `potion-0`). Two different dye colours mix paint-style (weighted by fill); bottle count follows inserted dyes; fill packs with overflow into the next bottle (extra glass only if overflow needs more bottles than inputs). Cannot mix flowers with dyes in one brew. Dye uses on tailor consume one fill level per craft.
264**TODO (sources):** shear animals / pick plants for wool–silk; fairy silk + dragonweave as mob drops later.
265**Later design (document only for now):**
266- **Wizard cloth gear** — robes and similar give Magic skill bonuses (`EquipmentKind.wizardCloth`).
267- **Cosmetic cloth gear** — sum equipped cosmetic item tiers as **Style points** (quests / exclusive areas).
268- **Warm clothing** — sweaters and other warm pieces reduce cold-season debuffs (e.g. winter halves stamina regen; each warm-equipped slot except hands mitigates; full warm set nullifies cold; summer reverses). **Padding** from cloth + matching-tier plate at a crafting bench → **padded armour** per slot.
269**Code:** `shared/definitions/materialTiers.js` (`ClothTier`), `shared/definitions/clothItems.js`, `shared/definitions/dyes.js`, `shared/crafting/tailor.js`, `shared/crafting/stationRecipes.js`, `server/src/alchemy/service.js`, `server/src/crafting/service.js`, `server/src/gathering/service.js`, `client/src/play/crafting.js`, `client/src/play/alchemy.js`
270
271## Crafting stations
272
273**Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
274**Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles, shafts, unstrung bows); crafting bench joins finished parts (pickaxe/axe head + handle, arrows, strung bows). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, **spinning wheel**, **loom**, and **tailor** craft UIs use a single-axis material dropdown so tier variants share one recipe cell. **Crafting bench** alone shows **paired metal/wood labels** (e.g. `Bronze/Pine`) because it mixes metal tools with wood bows on the same tier rank. **Hard rule (all stations + cauldron, player and scripts):** items in station slots are never committed out of the inventory — slots are a reservation/view over the bag (**client-side UI**; even if it looks like mats sit in the station, they do not). Server soft-tracks steps/claims only and consumes on successful craft/brew. Closing the UI, cancelling, or dying mid-craft/brew cannot destroy reserved mats. Station progress is **per player**, not tile-global. See `.cursor/rules/station-inventory.mdc`.
275**TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
276**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
277
278## Stamina and running
279
280**Status:** full
281**Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows vertical **HP** (always) and **stamina** bars bottom-right.
282**Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
283
284## Alchemy / cauldron
285
286**Status:** partial (starter herb potions + failed-effect list + status ticks live; more recipes TBD)
287**Spec:** **Herbalism** gathers flowers, cotton, and **24 folklore herbs** (`BlockType.herbPlant`). Flowers/cotton need **no tool**; clipper herbs require **plant clippers** and Herbalism gates by tier. **Alchemy** cauldron tabs **Alchemy** / **Dyes**. Starter potions: **Lesser health tonic** (thyme→heat→mint→stir; health regen 1/s for 10s, re-drink extends), **Lesser haste draught** (2 mint→heat→stir→lavender→cool; stamina regen 1/s for 10s), **Strength potion** (3 thyme→stir→2 nettle→heat; +5 Strength for 1 min), **Clarity potion** (rosemary→cool→2 chamomile→stir; +5 Mind for 1 min). Failed brews hash to unstable effects: stamina drain 1/s 15s, weak glow light 10s, shrink to 50% scale 30s, blindness 20s (extra darkness + local vision bubble). Active effects show as HUD icons left of the HP/stamina bars (`assets/status-effects/`; hover shows description + remaining time). Opening needs empty glass bottles. **Dyes** unchanged (flowers).
288**Code:** `shared/definitions/alchemy.js`, `shared/statusEffects/rules.js`, `shared/statusEffects/display.js`, `server/src/statusEffects/service.js`, `client/src/play/statusEffects.js`, `shared/definitions/herbs.js`, `server/src/alchemy/service.js`, `server/src/items/bags.js`, `client/src/render/worldView.js`, tests in `server/tests/alchemy.test.js`, `server/tests/herbalism.test.js`
289
290### Folklore herb associations (design only — not in code)
291
292Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3 / 4 / 4 / 4 / 4** for T1–T7.
293
294| Tier | Herb | Associations |
295| --- | --- | --- |
296| 1 | Mint | Refreshment, stamina, antidotes |
297| 1 | Garlic | Undead protection, disease resistance |
298| 2 | Thyme | Courage, vitality, resistance |
299| 2 | Sage | Healing, wisdom, longevity |
300| 2 | Rosemary | Memory, protection, clarity |
301| 3 | Lavender | Sleep, calm, dreams |
302| 3 | Chamomile | Restoration, sleep, soothing |
303| 3 | Nettle | Vigour, resilience, protection |
304| 4 | Yarrow | Wound healing, battle medicine |
305| 4 | Juniper | Purification, disease resistance |
306| 4 | Elder | Spirits, protection, healing |
307| 4 | Rue | Curse resistance, purification |
308| 5 | Valerian | Sleep, sedation, tranquillity |
309| 5 | Mugwort | Dreams, visions, divination |
310| 5 | Wormwood | Poison resistance, spirits, bitterness |
311| 5 | St. John's wort | Holy protection, dispel darkness |
312| 6 | Hawthorn | Fey, barriers, enchantment |
313| 6 | Foxglove | Fairy magic, heart magic, poison |
314| 6 | Mistletoe | Life, fertility, druidic magic |
315| 6 | Datura | Visions, insanity, spirit walking |
316| 7 | Belladonna | Poison, hallucination, witchcraft |
317| 7 | Henbane | Trance, madness, sleep, poison |
318| 7 | Mandrake | Powerful potions, curses, life magic |
319| 7 | Aconite | Werewolves, lethal poison, curses |
320
321## Inventory, items, equipment, ground drops
322
323**Status:** full
324**Spec:** 32-slot inventory, stacking, equipment slots (head, chest, legs, boots, weapon, **offhand** for shields/arrows) with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. **Equip draw order (back → front):** boots → chest → weapon → legs → hair (if visible) → head → offhand — so weapons sit above the shirt but under trousers/skirts (legs may cover shirt hem; art should avoid bad waist overlap). New characters receive world **Starter Equipment** / inventory, then creation clothing dyes on top (see **Characters**). Right-click bag items for Send / Equip / Drop / Eat (food; apples, eggs, …); paper can be written into unique **letter** instances (signed on Save; only the signer may edit). Equipping always takes **one** item from a stack (never the whole stack); unequipping returns one item and merges into an existing compatible inventory stack when stack rules allow. Equip enforces tier min-skill gates. Eating food heals (see Health skill).
325**Code:** `shared/definitions/items.js` (`EQUIPMENT_DRAW_ORDER`), `shared/appearance/hair.js` (`composeAppearanceLayers`), `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
326
327## Proximity chat
328
329**Status:** full
330**Spec:** Enter opens a bottom chat line (max `chatMaxCharacters`, default 100). Enter trims and sends; Escape cancels. The speaker always sees their own bubble. Other players receive server-side obfuscation: full text within 8 tiles, linear falloff to silent at 16 tiles. At 0% readability the bubble is not sent.
331**Code:** `shared/speech/proximity.js`, `server/src/chat/speech.js`, `client/src/play/chat.js`, tests in `server/tests/proximity-speech.test.js`
332
333## Friends
334
335**Status:** full
336**Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
337**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
338
339## Hair & barber
340
341**Status:** full
342**Spec:** Character creation **Appearance** tab picks a hair style (per sex body folder) plus hue/saturation/darkness; live preview tints magenta hair sprites (no clothing on that tab). The **Clothing** tab shows the same body/hair with cotton shirt + legs and per-piece dyes. Hair is stored on the character and drawn as a head overlay unless headgear is worn (item defs may set `equipment.keepHair` to keep hair under a hat — none yet). Placeable **Barber** blocks reopen the hair UI to restyle (preview hides headgear).
343**Code:** `shared/appearance/hair.js`, `server/src/barber/service.js`, `client/src/play/hairControls.js`, `client/src/play/barber.js`, `client/src/play/createClothingControls.js`, `client/assets/blocks/barber/`
344
345## Bounty offices
346
347**Status:** full
348**Spec:** Placeable **Bounty Office** blocks. Interacting opens a modal with two tabs:
349
3501. **Place / raise bounty** — Search a character by first + last name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success). You cannot place a bounty on yourself.
3512. **My bounty** — Shows how much coin is currently on **your** head. You may **pay toward** that bounty from inventory at **10 coins paid → 1 bounty coin cleared** (capped at the remaining bounty; only complete 10-coin multiples are spent). Bounty also **decays by 1 coin per calendar day** at local midnight (lazy apply when read).
352
353**Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer's bank**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.
354
355**Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
356
357**Code:** `shared/bounty/pricing.js`, `shared/definitions/tiles.js` (`BlockType.bountyOffice`), `server/src/bounty/service.js`, `server/src/courier/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/bounty.js`, `client/assets/blocks/bounty-office/`, tests in `server/tests/bounty.test.js`
358
359## Banking, cheques, shops, player-driven marketplace
360
361**Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
362**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free; closing the UI or walking away from that counter releases the clerk so wander resumes, unless another player is still using the same staff station. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
363**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
364
365## Player scripting (AFK / offline)
366
367**Status:** not implemented
368**Spec:** Full language + UI + online/AFK/offline behaviour is documented in [`docs/SCRIPTS.md`](SCRIPTS.md). Scripts are a sandboxed, server-interpreted language that emits normal player intents. Names match **exactly** (case-insensitive). `find` / nearest only searches the **visible 3×3** chunks (what a player sees). `@` variables + `set` hold targets/coords for waypoints; `go` fails beyond **2 chunks** (`Too far away.`). Universal `can <action>` dry-runs any verb. Station/cauldron state is **per player**; station slots never commit items out of the bag until craft/brew succeeds. AFK auto-start after **30 minutes** idle. Death while scripting stops the script and fully logs the instance out. Friends/barber/follow/graphics/editor are out of scope. Architecture hooks remain in design doc §18.
369**Code:** — (planned: `shared/scripts/`, `server/src/scripts/`, `client/src/play/scripts.js`, state DB script rows)
docs/QUESTS.md deleted +0 −405
@@ -1,405 +0,0 @@
1 # Quests & NPC dialogue (world editor)
2
3 **Status:** partial (v1 runtime + editors; polish / graph / effects UI later)
4 **Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules
5
6 Quests and NPC dialogue are **admin-authored content**. Authors create and edit them entirely in the **world editor**. Runtime evaluation is **server-authoritative**; clients only display dialogue UI and quest log snapshots.
7
8 This document is the product + data + editor spec for implementation.
9
10 ---
11
12 ## 1. Goals
13
14 - Author **quests** and **dialogue trees** as world-scoped assets (editors under **World settings**).
15 - Assign a dialogue to a **humanoid spawner** by reference (`dialogueId`); show assignment counts; support **unique** dialogues.
16 - Progress quests via **objectives** with shared multi-condition sets (including negations) and per-step **journal** text.
17 - Dialogue: line gifts, player-choice triggers, or **auto-branches**; track **dialogueHeard** per step; **interrupt on attack**.
18 - Player **Quests** UI: list + split detail (journal | step/objectives).
19 - Fail safe: broken references fail closed; editor validation catches unique/assignment rules.
20
21 ---
22
23 ## 2. Persistence & identity
24
25 | Asset | Storage | Apply model |
26 |-------|---------|-------------|
27 | **Quest definitions** | `world.sqlite` (revisioned with map) | Editor save → pending; **Apply now** → live |
28 | **Dialogue trees** | `world.sqlite` (revisioned with map) — **not** embedded in chunk JSON | Same as quests |
29 | **Spawner → dialogue link** | Chunk spawner `config.dialogueId` (string \| null) | Saved with the chunk |
30 | **Quest progress** | `state.sqlite` (`questState`) | Live |
31 | **Dialogue heard** | `state.sqlite` (`dialogueHeard`) | Live |
32
33 ### 2.1 IDs
34
35 - **Quest id:** stable slug (`deliver-tin-ore`). Prefer immutable after publish.
36 - **Quest step id:** stable within quest; conditions also use **1-based index** in `steps[]` (§4).
37 - **Dialogue id:** stable world-scoped id (`smith-intro`). Keys `dialogueHeard`, conditions, spawner assignment.
38 - **Dialogue step id / trigger id:** stable within that dialogue.
39 - **NPC reference in quests:** prefer **spawner id** + optional display-name hint — not transient entity ids.
40
41 ### 2.2 World settings: Quests & Dialogues editors
42
43 In the world editor chrome, place **Quests** and **Dialogues** as **separate buttons directly under the Settings button** (same control stack, not tabs inside the Settings modal).
44
45 | Button | Purpose |
46 |--------|---------|
47 | **Settings** | Existing world settings |
48 | **Quests** | CRUD all quest defs (id, title, steps, objectives, rewards, validation) |
49 | **Dialogues** | CRUD all dialogue trees (id, unique flag, steps, exits, validation) |
50
51 Both editors are **world-global** (not per-chunk). Saves go through the same admin auth + revision story as other authored world data.
52
53 **Dialogues list columns:** id, label/title, step count, **`unique`**, **assigned spawner count**, validation warnings.
54
55 **Delete dialogue:** warn if any spawner still references it; optionally block delete until unassigned.
56
57 ### 2.3 Spawner assignment
58
59 On a **humanoid / talkable** spawner:
60
61 - Dropdown: **Dialogue** → none, or pick from world dialogue list (show id + unique badge).
62 - Stores `config.dialogueId` only (no inline tree on the spawner).
63
64 **Assignment count:** Dialogues editor shows how many spawners currently reference each `dialogueId` (scan loaded/pending world chunks, or maintain an index on save). Click-through list of assignees (chunk + spawner label) is nice-to-have in v1.
65
66 ### 2.4 Unique dialogues
67
68 ```text
69 DialogueTree.unique: boolean // default false
70 ```
71
72 When `unique === true`:
73
74 1. **At most one spawner** in the world may have `config.dialogueId` equal to that id.
75 2. That spawner’s **`maxAlive` must be `1`** (editor clamps / blocks save otherwise; server normalize rejects Apply if violated).
76
77 Editor UX:
78
79 - Toggling **Unique** on while 2+ spawners assigned → block or offer “unassign others / cancel”.
80 - Assigning a unique dialogue to a second spawner → block with clear error.
81 - Setting `maxAlive > 1` on a spawner that holds a unique dialogue → block or force `maxAlive = 1`.
82
83 Non-unique dialogues may be shared by many spawners (and many alive NPCs); `dialogueHeard` is still keyed by `dialogueId`+`stepId` (shared script progress).
84
85 ---
86
87 ## 3. Quest definition shape
88
89 ```text
90 Quest {
91 questId: string
92 title: string
93 description: string // player-facing log blurb (in-universe)
94 steps: Step[] // ordered progression
95 rewards?: Reward[] // granted on final step complete
96 cancelable?: boolean // default false in v1
97 }
98 ```
99
100 ### 3.1 Steps & objectives
101
102 A quest advances one **step** at a time. Each step has one or more **objectives**. Each objective has a player-facing **text** and a **ConditionSet** (multiple conditions with optional negation). The step completes only when **all** objectives on that step are done (AND).
103
104 ```text
105 Step {
106 stepId: string
107 title: string
108 description: string
109 completionJournalText: string
110 objectives: Objective[] // ≥ 1; all must complete
111 onEnter?: Effect[]
112 onComplete?: Effect[]
113 }
114
115 Objective {
116 objectiveId: string
117 text: string // HUD / detail line
118 when: ConditionSet // objective complete when set passes (or event latch inside set)
119 }
120 ```
121
122 **Advancement:**
123
124 1. While a step is active, the server tracks which `objectiveId`s are satisfied.
125 2. When every objective on the step is complete → append journal line → `state` `n` → `n+1` or `completed` + rewards → show toast **“Quest objectives achieved”**. Clicking the toast opens the **Quests** detail modal on **that quest**.
126 3. Client: completed objectives struck through.
127
128 ### 3.2 Condition sets (quests + dialogue)
129
130 Shared in `shared/`. Evaluated **only on the server**.
131
132 ```text
133 ConditionSet {
134 all: ConditionClause[] // every clause must pass (AND); empty = always true
135 }
136
137 ConditionClause {
138 not?: boolean // default false; if true, invert the condition result
139 condition: Condition
140 }
141 ```
142
143 **Semantics:** `all` clauses AND-ed. “Has item X, but **not** quest completed Y” → two clauses, second with `not: true` (or use a dedicated negative kind — prefer **`not` on the clause** so every kind is invertible).
144
145 Used by:
146
147 - quest **objectives** (`when`)
148 - dialogue **triggers** (`when` — hide if fail)
149 - dialogue **auto-branches** (`when` — first branch whose set passes)
150
151 Editor: condition picker rows with a **NOT** toggle per row; add/remove rows.
152
153 #### Condition kinds
154
155 | Kind | Fields | Meaning |
156 |------|--------|---------|
157 | `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) has ≥ N |
158 | `atTile` | `dimensionId`, `tileX`, `tileY` | Exact tile in that dimension (default `overworld`) |
159 | `nearTile` | `dimensionId`, `tileX`, `tileY`, `range` (≥ 1) | Chebyshev ≤ range in dim |
160 | `inRect` | `dimensionId`, `minTileX`, `minTileY`, `maxTileX`, `maxTileY` | Inclusive AABB in dim |
161 | `atChunk` | `dimensionId`, `chunkX`, `chunkY` | Player chunk in dim |
162 | `inDimension` | `dimensionId` | Currently in that dimension |
163 | `hasVisitedDimension` | `dimensionId` | Has entered that dim at least once |
164 | `questState` | `questId`, `state` | Equals `not-started` \| `completed` \| number `n` |
165 | `questStepAtLeast` | `questId`, `step` (≥ 1) | Active index ≥ step **or** `completed` |
166 | `dialogueHeard` | `dialogueId`, `stepId` | Heard row exists |
167 | `dialogueTrigger` | `dialogueId`, `trigger` | **Latch:** player chose that trigger (quest objectives) |
168 | `hpAtLeast` | `amount` (≥ 0) | Current HP ≥ amount |
169 | `staminaAtLeast` | `amount` (≥ 0) | Current stamina ≥ amount |
170 | `hpPercentAtLeast` | `percent` (0–100) | currentHP / maxHP × 100 ≥ percent |
171 | `staminaPercentAtLeast` | `percent` (0–100) | currentStamina / maxStamina × 100 ≥ percent |
172 | `skillLevelAtLeast` | `skillId`, `level` (1–99) | `skillLevel(skills, skillId) ≥ level` |
173 | `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Kills while this quest step active |
174 | `interactBlock` | `dimensionId`, tile and/or `blockTypeId` | Successful interact (once per quest step) |
175
176 **Notes:**
177
178 - Prefer **`not` + `hasItem`** over a separate `lacksItem` kind (legacy alias ok). Same for `dialogueNotHeard` → `not` + `dialogueHeard`.
179 - Thresholds use **≥** (“above or equal”); document in editor labels as “at least”.
180 - Max HP / max stamina = same formulas the play sim already uses for the character.
181 - Unknown ids → clause **fails closed** (raw condition false; with `not`, that becomes true — authors should avoid dangling ids; validation warns).
182 - Kill attribution = existing combat kill credit.
183
184 ### 3.3 Rewards & effects (v1)
185
186 | Kind | Fields |
187 |------|--------|
188 | `giveItem` | `itemId`, `quantity` |
189 | `giveXp` | `skillId`, `amount` |
190 | `takeItem` | `itemId`, `quantity` |
191 | `startQuest` | `questId` |
192
193 Sources: quest `onEnter` / `onComplete`, dialogue **line**, **trigger**, **branch**.
194 Full bag → vault via carrier pigeon.
195
196 ---
197
198 ## 4. Character quest state & journal
199
200 ### 4.0 Quest state
201
202 ```text
203 QuestStateValue = "not-started" | number | "completed"
204 // number = 1-based index of current incomplete step
205 ```
206
207 ```text
208 CharacterQuest {
209 questId: string
210 state: QuestStateValue
211 completedObjectiveIds: string[]
212 counters: { [key: string]: number }
213 startedAt?, completedAt?
214 }
215 ```
216
217 Missing row ⇒ `not-started`. Conditions read `state` only; counters/objectives are runtime detail for UI + event objectives.
218
219 ### 4.0b Dialogue heard
220
221 ```text
222 dialogueHeard (characterId, dialogueId, stepId, heardAt)
223 UNIQUE (characterId, dialogueId, stepId)
224 ```
225
226 Insert on step **enter** (first time). Permanent in v1. Gate repeat gifts with `when` sets (`not` + `dialogueHeard`, `not` + `hasItem`, etc.).
227
228 ### 4.0c Journal
229
230 ```text
231 QuestJournalEntry { questId, stepId, text, writtenAt }
232 ```
233
234 Append-only; text frozen at write time.
235
236 ---
237
238 ## 4.1 Player UI — Quests
239
240 - **Quests** HUD control → list modal: active (`state` number) first, **completed** at bottom; hide `not-started`.
241 - Detail modal: left journal (this quest), right step description + objectives (strikethrough when done).
242 - **Step-complete toast:** text **“Quest objectives achieved”**. Click → open quest detail for the quest that just advanced (same modal stack as the Quests button).
243
244 ---
245
246 ## 5. Dialogue (world asset + spawner link)
247
248 ### 5.1 Shape
249
250 ```text
251 DialogueTree {
252 dialogueId: string
253 label: string // editor list title
254 unique: boolean // default false; see §2.4
255 steps: DialogueStep[]
256 entryStepId?: string
257 }
258
259 DialogueStep {
260 stepId: string
261 label: string
262 lines: DialogueLine[]
263 itemRewards?: { itemId: number, quantity: number }[] // after lines, before exit
264 exit:
265 | { kind: "triggers", triggers: DialogueTrigger[] }
266 | { kind: "branches", branches: DialogueBranch[] }
267 | { kind: "end" }
268 }
269
270 DialogueLine {
271 speaker: "npc" | "player"
272 text: string
273 effects?: Effect[]
274 }
275
276 DialogueTrigger {
277 trigger: string
278 label: string // editor
279 text: string // player button
280 nextStepId: string | null // null → end
281 when?: ConditionSet // hide if fail; omit = always show
282 effects?: Effect[]
283 }
284
285 DialogueBranch {
286 label?: string
287 when: ConditionSet // empty all[] = always
288 nextStepId: string | null
289 effects?: Effect[]
290 }
291 ```
292
293 **End rules:** null `nextStepId`, `exit.kind: "end"`, no matching branch, or no visible triggers → **close dialogue**.
294
295 ### 5.2 Runtime
296
297 1. Talk to NPC whose spawner has `dialogueId` → load world DialogueTree → open `entryStepId`.
298 2. Enter step → insert `dialogueHeard` if new → play lines (apply line effects).
299 3. On **advance** after the last line: grant `itemRewards` (bag first, overflow to bank/vault), show reward notices in the dialogue UI, then evaluate exit.
300 4. Triggers / branches / end as authored (conditions see items already granted).
301 5. **Interrupt:** if the NPC is **attacked** (takes a hostile hit / combat engagement against it) while a player has this dialogue open → **immediately close** that dialogue session (no further lines, choices, or pending line effects). Re-talk required. Does not roll back already-applied effects or heard rows.
302
303 ### 5.3 Editor (Dialogues panel)
304
305 - List + inspector (graph canvas = v1.1).
306 - Per dialogue: id, label, **unique**, assignment count, steps, exit modes, shared condition-set picker (with NOT).
307 - Validation: unique rules (§2.4), missing refs, empty texts, unreachable steps.
308
309 ### 5.4 Spawner modal
310
311 Humanoid: **Dialogue** dropdown bound to world dialogues (not an inline tree editor). Link to “Open in Dialogues editor” optional.
312
313 ---
314
315 ## 6. How quests start
316
317 `startQuest` effect → `not-started` → `1`. Block if already numeric or `completed` (v1 no repeats).
318
319 ---
320
321 ## 7. Implementation plan (phased)
322
323 1. Shared `Condition` / `ConditionSet` / `Effect` in `shared/`.
324 2. World DB: quest defs + dialogue trees; state: `questState`, `dialogueHeard`, journal.
325 3. World settings **Quests** + **Dialogues** editors; spawner `dialogueId` + unique/maxAlive validation; assignment counts.
326 4. Editor unsaved-chunk guard (§9) — may already ship.
327 5. Runtime dialogue + combat interrupt; line/trigger/branch effects.
328 6. Quest engine + Quests HUD.
329 7. Apply revision + tests (conditions+NOT, unique, interrupt, heard, journal).
330
331 ---
332
333 ## 8. Edge cases (resolved)
334
335 | Topic | Decision |
336 |-------|----------|
337 | Unique + 2 assignees | Editor/server reject until ≤ 1 |
338 | Unique + maxAlive ≠ 1 | Reject / clamp to 1 |
339 | Mark unique while assigned elsewhere | Must unassign others first |
340 | Shared (non-unique) dialogue | Many spawners OK; heard shared by dialogueId |
341 | Spawner dialogueId missing tree | Talk no-ops / error log; fail closed |
342 | NPC attacked mid-dialogue | Session closes immediately |
343 | Player walks away / disconnect | Close session (no progress loss beyond already applied) |
344 | `not` + unknown id | Raw false → NOT true — validation must warn on unknown ids |
345 | Thresholds | All “at least” (≥) |
346 | Parallel quests | Yes; soft cap ~20 active |
347 | One step per quest | Yes (single numeric state) |
348 | Apply mid-dialogue | Close sessions |
349
350 ### 8.1 Open product choices (see §12)
351
352 Small list of remaining decisions before / during implementation — none are architectural blockers if defaults in §12 are accepted.
353
354 ---
355
356 ## 9. World editor: unsaved chunk navigation & Save affordance
357
358 Independent of quests; ship with this plan’s commit.
359
360 ### 9.1 Dirty state
361
362 - Baseline when chunk loads / after save; paint/spawner edits → dirty; structural compare.
363
364 ### 9.2 Navigate away
365
366 Modal: Cancel / Discard / Save then navigate.
367
368 ### 9.3 Save button
369
370 Disabled when clean; enabled + blinking when dirty.
371
372 ---
373
374 ## 10. Authority & safety
375
376 - Client never decides conditions, heard, quest state, or effects.
377 - Choose payload: `dialogueId`, `stepId`, `trigger`; server re-evaluates `when`.
378 - Branches and interrupts are server-side.
379 - Unique / maxAlive enforced on save and Apply.
380
381 ---
382
383 ## 11. Feasibility
384
385 **High–medium.** World-scoped dialogue assets + assignment is cleaner than per-spawner trees. ConditionSet + `not` covers “A but not B” without exploding kind count. Combat interrupt is a small session hook.
386
387 Hardest: event wiring for quest objectives + revision/orphan UX. Graph canvas still v1.1.
388
389 ---
390
391 ## 12. Defaults if unspecified (implementation may proceed)
392
393 Accept these unless overridden:
394
395 1. **Condition polarity:** per-clause `not?: boolean` inside `ConditionSet.all` (no separate OR groups in v1; use multiple ordered dialogue branches for OR).
396 2. **Thresholds:** all ≥ (“at least”).
397 3. **Interrupt:** any hostile damage/engagement **on the NPC** closes dialogue for whoever was talking to it (not only if the talker is the attacker).
398 4. **Unique conflict:** editor **blocks** the illegal save (does not auto-unassign silently).
399 5. **Assignment count:** computed from pending/applied chunk spawners when opening Dialogues editor (accurate enough for v1).
400 6. **`lacksItem` / `dialogueNotHeard`:** not separate kinds; use `not` + positive kind (editor may offer presets).
401 7. **Objectives:** one objective completes when its entire `ConditionSet` is true (event kinds latch once true).
402 8. **Editors placement:** **Quests** and **Dialogues** buttons stacked **under** the Settings button (separate modals, not Settings tabs).
403 9. **Step-complete toast:** “Quest objectives achieved”; click opens that quest’s detail modal.
404
405 **Not blocking for v1:** graph canvas, script verbs, repeatable quests, localization, visual tile picker.
@@ -1,405 +0,0 @@
1# Quests & NPC dialogue (world editor)
2
3**Status:** partial (v1 runtime + editors; polish / graph / effects UI later)
4**Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules
5
6Quests and NPC dialogue are **admin-authored content**. Authors create and edit them entirely in the **world editor**. Runtime evaluation is **server-authoritative**; clients only display dialogue UI and quest log snapshots.
7
8This document is the product + data + editor spec for implementation.
9
10---
11
12## 1. Goals
13
14- Author **quests** and **dialogue trees** as world-scoped assets (editors under **World settings**).
15- Assign a dialogue to a **humanoid spawner** by reference (`dialogueId`); show assignment counts; support **unique** dialogues.
16- Progress quests via **objectives** with shared multi-condition sets (including negations) and per-step **journal** text.
17- Dialogue: line gifts, player-choice triggers, or **auto-branches**; track **dialogueHeard** per step; **interrupt on attack**.
18- Player **Quests** UI: list + split detail (journal | step/objectives).
19- Fail safe: broken references fail closed; editor validation catches unique/assignment rules.
20
21---
22
23## 2. Persistence & identity
24
25| Asset | Storage | Apply model |
26|-------|---------|-------------|
27| **Quest definitions** | `world.sqlite` (revisioned with map) | Editor save → pending; **Apply now** → live |
28| **Dialogue trees** | `world.sqlite` (revisioned with map) — **not** embedded in chunk JSON | Same as quests |
29| **Spawner → dialogue link** | Chunk spawner `config.dialogueId` (string \| null) | Saved with the chunk |
30| **Quest progress** | `state.sqlite` (`questState`) | Live |
31| **Dialogue heard** | `state.sqlite` (`dialogueHeard`) | Live |
32
33### 2.1 IDs
34
35- **Quest id:** stable slug (`deliver-tin-ore`). Prefer immutable after publish.
36- **Quest step id:** stable within quest; conditions also use **1-based index** in `steps[]` (§4).
37- **Dialogue id:** stable world-scoped id (`smith-intro`). Keys `dialogueHeard`, conditions, spawner assignment.
38- **Dialogue step id / trigger id:** stable within that dialogue.
39- **NPC reference in quests:** prefer **spawner id** + optional display-name hint — not transient entity ids.
40
41### 2.2 World settings: Quests & Dialogues editors
42
43In the world editor chrome, place **Quests** and **Dialogues** as **separate buttons directly under the Settings button** (same control stack, not tabs inside the Settings modal).
44
45| Button | Purpose |
46|--------|---------|
47| **Settings** | Existing world settings |
48| **Quests** | CRUD all quest defs (id, title, steps, objectives, rewards, validation) |
49| **Dialogues** | CRUD all dialogue trees (id, unique flag, steps, exits, validation) |
50
51Both editors are **world-global** (not per-chunk). Saves go through the same admin auth + revision story as other authored world data.
52
53**Dialogues list columns:** id, label/title, step count, **`unique`**, **assigned spawner count**, validation warnings.
54
55**Delete dialogue:** warn if any spawner still references it; optionally block delete until unassigned.
56
57### 2.3 Spawner assignment
58
59On a **humanoid / talkable** spawner:
60
61- Dropdown: **Dialogue** → none, or pick from world dialogue list (show id + unique badge).
62- Stores `config.dialogueId` only (no inline tree on the spawner).
63
64**Assignment count:** Dialogues editor shows how many spawners currently reference each `dialogueId` (scan loaded/pending world chunks, or maintain an index on save). Click-through list of assignees (chunk + spawner label) is nice-to-have in v1.
65
66### 2.4 Unique dialogues
67
68```text
69DialogueTree.unique: boolean // default false
70```
71
72When `unique === true`:
73
741. **At most one spawner** in the world may have `config.dialogueId` equal to that id.
752. That spawner’s **`maxAlive` must be `1`** (editor clamps / blocks save otherwise; server normalize rejects Apply if violated).
76
77Editor UX:
78
79- Toggling **Unique** on while 2+ spawners assigned → block or offer “unassign others / cancel”.
80- Assigning a unique dialogue to a second spawner → block with clear error.
81- Setting `maxAlive > 1` on a spawner that holds a unique dialogue → block or force `maxAlive = 1`.
82
83Non-unique dialogues may be shared by many spawners (and many alive NPCs); `dialogueHeard` is still keyed by `dialogueId`+`stepId` (shared script progress).
84
85---
86
87## 3. Quest definition shape
88
89```text
90Quest {
91 questId: string
92 title: string
93 description: string // player-facing log blurb (in-universe)
94 steps: Step[] // ordered progression
95 rewards?: Reward[] // granted on final step complete
96 cancelable?: boolean // default false in v1
97}
98```
99
100### 3.1 Steps & objectives
101
102A quest advances one **step** at a time. Each step has one or more **objectives**. Each objective has a player-facing **text** and a **ConditionSet** (multiple conditions with optional negation). The step completes only when **all** objectives on that step are done (AND).
103
104```text
105Step {
106 stepId: string
107 title: string
108 description: string
109 completionJournalText: string
110 objectives: Objective[] // ≥ 1; all must complete
111 onEnter?: Effect[]
112 onComplete?: Effect[]
113}
114
115Objective {
116 objectiveId: string
117 text: string // HUD / detail line
118 when: ConditionSet // objective complete when set passes (or event latch inside set)
119}
120```
121
122**Advancement:**
123
1241. While a step is active, the server tracks which `objectiveId`s are satisfied.
1252. When every objective on the step is complete → append journal line → `state` `n` → `n+1` or `completed` + rewards → show toast **“Quest objectives achieved”**. Clicking the toast opens the **Quests** detail modal on **that quest**.
1263. Client: completed objectives struck through.
127
128### 3.2 Condition sets (quests + dialogue)
129
130Shared in `shared/`. Evaluated **only on the server**.
131
132```text
133ConditionSet {
134 all: ConditionClause[] // every clause must pass (AND); empty = always true
135}
136
137ConditionClause {
138 not?: boolean // default false; if true, invert the condition result
139 condition: Condition
140}
141```
142
143**Semantics:** `all` clauses AND-ed. “Has item X, but **not** quest completed Y” → two clauses, second with `not: true` (or use a dedicated negative kind — prefer **`not` on the clause** so every kind is invertible).
144
145Used by:
146
147- quest **objectives** (`when`)
148- dialogue **triggers** (`when` — hide if fail)
149- dialogue **auto-branches** (`when` — first branch whose set passes)
150
151Editor: condition picker rows with a **NOT** toggle per row; add/remove rows.
152
153#### Condition kinds
154
155| Kind | Fields | Meaning |
156|------|--------|---------|
157| `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) has ≥ N |
158| `atTile` | `dimensionId`, `tileX`, `tileY` | Exact tile in that dimension (default `overworld`) |
159| `nearTile` | `dimensionId`, `tileX`, `tileY`, `range` (≥ 1) | Chebyshev ≤ range in dim |
160| `inRect` | `dimensionId`, `minTileX`, `minTileY`, `maxTileX`, `maxTileY` | Inclusive AABB in dim |
161| `atChunk` | `dimensionId`, `chunkX`, `chunkY` | Player chunk in dim |
162| `inDimension` | `dimensionId` | Currently in that dimension |
163| `hasVisitedDimension` | `dimensionId` | Has entered that dim at least once |
164| `questState` | `questId`, `state` | Equals `not-started` \| `completed` \| number `n` |
165| `questStepAtLeast` | `questId`, `step` (≥ 1) | Active index ≥ step **or** `completed` |
166| `dialogueHeard` | `dialogueId`, `stepId` | Heard row exists |
167| `dialogueTrigger` | `dialogueId`, `trigger` | **Latch:** player chose that trigger (quest objectives) |
168| `hpAtLeast` | `amount` (≥ 0) | Current HP ≥ amount |
169| `staminaAtLeast` | `amount` (≥ 0) | Current stamina ≥ amount |
170| `hpPercentAtLeast` | `percent` (0–100) | currentHP / maxHP × 100 ≥ percent |
171| `staminaPercentAtLeast` | `percent` (0–100) | currentStamina / maxStamina × 100 ≥ percent |
172| `skillLevelAtLeast` | `skillId`, `level` (1–99) | `skillLevel(skills, skillId) ≥ level` |
173| `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Kills while this quest step active |
174| `interactBlock` | `dimensionId`, tile and/or `blockTypeId` | Successful interact (once per quest step) |
175
176**Notes:**
177
178- Prefer **`not` + `hasItem`** over a separate `lacksItem` kind (legacy alias ok). Same for `dialogueNotHeard` → `not` + `dialogueHeard`.
179- Thresholds use **≥** (“above or equal”); document in editor labels as “at least”.
180- Max HP / max stamina = same formulas the play sim already uses for the character.
181- Unknown ids → clause **fails closed** (raw condition false; with `not`, that becomes true — authors should avoid dangling ids; validation warns).
182- Kill attribution = existing combat kill credit.
183
184### 3.3 Rewards & effects (v1)
185
186| Kind | Fields |
187|------|--------|
188| `giveItem` | `itemId`, `quantity` |
189| `giveXp` | `skillId`, `amount` |
190| `takeItem` | `itemId`, `quantity` |
191| `startQuest` | `questId` |
192
193Sources: quest `onEnter` / `onComplete`, dialogue **line**, **trigger**, **branch**.
194Full bag → vault via carrier pigeon.
195
196---
197
198## 4. Character quest state & journal
199
200### 4.0 Quest state
201
202```text
203QuestStateValue = "not-started" | number | "completed"
204// number = 1-based index of current incomplete step
205```
206
207```text
208CharacterQuest {
209 questId: string
210 state: QuestStateValue
211 completedObjectiveIds: string[]
212 counters: { [key: string]: number }
213 startedAt?, completedAt?
214}
215```
216
217Missing row ⇒ `not-started`. Conditions read `state` only; counters/objectives are runtime detail for UI + event objectives.
218
219### 4.0b Dialogue heard
220
221```text
222dialogueHeard (characterId, dialogueId, stepId, heardAt)
223UNIQUE (characterId, dialogueId, stepId)
224```
225
226Insert on step **enter** (first time). Permanent in v1. Gate repeat gifts with `when` sets (`not` + `dialogueHeard`, `not` + `hasItem`, etc.).
227
228### 4.0c Journal
229
230```text
231QuestJournalEntry { questId, stepId, text, writtenAt }
232```
233
234Append-only; text frozen at write time.
235
236---
237
238## 4.1 Player UI — Quests
239
240- **Quests** HUD control → list modal: active (`state` number) first, **completed** at bottom; hide `not-started`.
241- Detail modal: left journal (this quest), right step description + objectives (strikethrough when done).
242- **Step-complete toast:** text **“Quest objectives achieved”**. Click → open quest detail for the quest that just advanced (same modal stack as the Quests button).
243
244---
245
246## 5. Dialogue (world asset + spawner link)
247
248### 5.1 Shape
249
250```text
251DialogueTree {
252 dialogueId: string
253 label: string // editor list title
254 unique: boolean // default false; see §2.4
255 steps: DialogueStep[]
256 entryStepId?: string
257}
258
259DialogueStep {
260 stepId: string
261 label: string
262 lines: DialogueLine[]
263 itemRewards?: { itemId: number, quantity: number }[] // after lines, before exit
264 exit:
265 | { kind: "triggers", triggers: DialogueTrigger[] }
266 | { kind: "branches", branches: DialogueBranch[] }
267 | { kind: "end" }
268}
269
270DialogueLine {
271 speaker: "npc" | "player"
272 text: string
273 effects?: Effect[]
274}
275
276DialogueTrigger {
277 trigger: string
278 label: string // editor
279 text: string // player button
280 nextStepId: string | null // null → end
281 when?: ConditionSet // hide if fail; omit = always show
282 effects?: Effect[]
283}
284
285DialogueBranch {
286 label?: string
287 when: ConditionSet // empty all[] = always
288 nextStepId: string | null
289 effects?: Effect[]
290}
291```
292
293**End rules:** null `nextStepId`, `exit.kind: "end"`, no matching branch, or no visible triggers → **close dialogue**.
294
295### 5.2 Runtime
296
2971. Talk to NPC whose spawner has `dialogueId` → load world DialogueTree → open `entryStepId`.
2982. Enter step → insert `dialogueHeard` if new → play lines (apply line effects).
2993. On **advance** after the last line: grant `itemRewards` (bag first, overflow to bank/vault), show reward notices in the dialogue UI, then evaluate exit.
3004. Triggers / branches / end as authored (conditions see items already granted).
3015. **Interrupt:** if the NPC is **attacked** (takes a hostile hit / combat engagement against it) while a player has this dialogue open → **immediately close** that dialogue session (no further lines, choices, or pending line effects). Re-talk required. Does not roll back already-applied effects or heard rows.
302
303### 5.3 Editor (Dialogues panel)
304
305- List + inspector (graph canvas = v1.1).
306- Per dialogue: id, label, **unique**, assignment count, steps, exit modes, shared condition-set picker (with NOT).
307- Validation: unique rules (§2.4), missing refs, empty texts, unreachable steps.
308
309### 5.4 Spawner modal
310
311Humanoid: **Dialogue** dropdown bound to world dialogues (not an inline tree editor). Link to “Open in Dialogues editor” optional.
312
313---
314
315## 6. How quests start
316
317`startQuest` effect → `not-started` → `1`. Block if already numeric or `completed` (v1 no repeats).
318
319---
320
321## 7. Implementation plan (phased)
322
3231. Shared `Condition` / `ConditionSet` / `Effect` in `shared/`.
3242. World DB: quest defs + dialogue trees; state: `questState`, `dialogueHeard`, journal.
3253. World settings **Quests** + **Dialogues** editors; spawner `dialogueId` + unique/maxAlive validation; assignment counts.
3264. Editor unsaved-chunk guard (§9) — may already ship.
3275. Runtime dialogue + combat interrupt; line/trigger/branch effects.
3286. Quest engine + Quests HUD.
3297. Apply revision + tests (conditions+NOT, unique, interrupt, heard, journal).
330
331---
332
333## 8. Edge cases (resolved)
334
335| Topic | Decision |
336|-------|----------|
337| Unique + 2 assignees | Editor/server reject until ≤ 1 |
338| Unique + maxAlive ≠ 1 | Reject / clamp to 1 |
339| Mark unique while assigned elsewhere | Must unassign others first |
340| Shared (non-unique) dialogue | Many spawners OK; heard shared by dialogueId |
341| Spawner dialogueId missing tree | Talk no-ops / error log; fail closed |
342| NPC attacked mid-dialogue | Session closes immediately |
343| Player walks away / disconnect | Close session (no progress loss beyond already applied) |
344| `not` + unknown id | Raw false → NOT true — validation must warn on unknown ids |
345| Thresholds | All “at least” (≥) |
346| Parallel quests | Yes; soft cap ~20 active |
347| One step per quest | Yes (single numeric state) |
348| Apply mid-dialogue | Close sessions |
349
350### 8.1 Open product choices (see §12)
351
352Small list of remaining decisions before / during implementation — none are architectural blockers if defaults in §12 are accepted.
353
354---
355
356## 9. World editor: unsaved chunk navigation & Save affordance
357
358Independent of quests; ship with this plan’s commit.
359
360### 9.1 Dirty state
361
362- Baseline when chunk loads / after save; paint/spawner edits → dirty; structural compare.
363
364### 9.2 Navigate away
365
366Modal: Cancel / Discard / Save then navigate.
367
368### 9.3 Save button
369
370Disabled when clean; enabled + blinking when dirty.
371
372---
373
374## 10. Authority & safety
375
376- Client never decides conditions, heard, quest state, or effects.
377- Choose payload: `dialogueId`, `stepId`, `trigger`; server re-evaluates `when`.
378- Branches and interrupts are server-side.
379- Unique / maxAlive enforced on save and Apply.
380
381---
382
383## 11. Feasibility
384
385**High–medium.** World-scoped dialogue assets + assignment is cleaner than per-spawner trees. ConditionSet + `not` covers “A but not B” without exploding kind count. Combat interrupt is a small session hook.
386
387Hardest: event wiring for quest objectives + revision/orphan UX. Graph canvas still v1.1.
388
389---
390
391## 12. Defaults if unspecified (implementation may proceed)
392
393Accept these unless overridden:
394
3951. **Condition polarity:** per-clause `not?: boolean` inside `ConditionSet.all` (no separate OR groups in v1; use multiple ordered dialogue branches for OR).
3962. **Thresholds:** all ≥ (“at least”).
3973. **Interrupt:** any hostile damage/engagement **on the NPC** closes dialogue for whoever was talking to it (not only if the talker is the attacker).
3984. **Unique conflict:** editor **blocks** the illegal save (does not auto-unassign silently).
3995. **Assignment count:** computed from pending/applied chunk spawners when opening Dialogues editor (accurate enough for v1).
4006. **`lacksItem` / `dialogueNotHeard`:** not separate kinds; use `not` + positive kind (editor may offer presets).
4017. **Objectives:** one objective completes when its entire `ConditionSet` is true (event kinds latch once true).
4028. **Editors placement:** **Quests** and **Dialogues** buttons stacked **under** the Settings button (separate modals, not Settings tabs).
4039. **Step-complete toast:** “Quest objectives achieved”; click opens that quest’s detail modal.
404
405**Not blocking for v1:** graph canvas, script verbs, repeatable quests, localization, visual tile picker.
questward_server_technical_design_v0.6.md deleted +0 −3661
@@ -1,3661 +0,0 @@
1 ---
2 title: Questward Server Technical Design
3 version: 0.21
4 status: proposed
5 format: living-design-document
6 ---
7
8 # Questward Server Technical Design
9
10 **Version:** 0.21
11 **Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
12 **Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
13
14 # 1. Design goals
15
16 - Support a large tile-based MMO world without simulating unused areas.
17
18 - Keep the server fully authoritative: clients send actions and
19 intentions, never authoritative state changes.
20
21 - Authenticate accounts via auth.timfalken.com (with an `admin-<n>` stub
22 until that service is live). An account may have unlimited characters,
23 one in the world at a time, with delayed deletion and an inheritance
24 bank tab.
25
26 - Use ECS composition for entities and systems, while using chunks and
27 regions for spatial ownership and simulation lifecycle.
28
29 - Allow simulation work to scale across Node.js workers and permit
30 entities to cross worker-managed region boundaries safely.
31
32 - Keep client replication small: a player receives only the current
33 16×16 chunk and the eight neighbouring chunks.
34
35 - Keep authored world data separate from ephemeral simulation state.
36
37 - Persist only entities that explicitly need persistence; ordinary
38 spawned mobs disappear when their chunk is unloaded.
39
40 - Avoid constant chunk writes. Normal chunk persistence occurs on
41 unload; graceful shutdown is implemented as a forced unload of all
42 resident chunks.
43
44 - Provide an admin-only graphical world editor for painting tiles,
45 opening or closing chunks, and placing/configuring spawners, with a
46 per-chunk changelog of who changed what and when. Unedited chunks are
47 grass-only and closed.
48
49 - Automatically schedule a graceful midnight restart when live code or
50 authored world data changes, with an admin-triggered immediate restart
51 path.
52
53 - Reserve a clean control abstraction for a later sandboxed player
54 scripting language without requiring the scripting system in the
55 initial release.
56
57 - Build the player-facing client on the shared FrameworkV3 library, vendored
58 as a git submodule and built first so game-specific client code can layer
59 on top of it, while keeping the server-side ECS an implementation detail of
60 the backend. World sprites may be any size; each uses a centred pivot
61 8 pixels from the sprite bottom. The play viewport stays
62 centered on the local player.
63
64 - Authoritative movement is tile-to-tile at a **global** walk/run cadence
65 (default walk 2 tiles/s, run double), not a per-mob speed. Admins edit
66 that cadence and other tick timers in a world-settings modal. Saving
67 those settings applies immediately to the live world. World
68 calendar time is server time minus 1200 years. At night the client
69 darkens unlit tiles (how dark is a world setting); static light reach
70 is baked by raycast when a chunk is saved.
71
72 - Give every player a 32-slot inventory in which stackable items occupy a
73 single slot, and treat dropped items as temporary, non-blocking ground
74 objects rather than tile occupancy.
75
76 - Make ordinary communication spatial rather than global: nearby speech is
77 progressively degraded by distance, while long-distance exchange is a
78 physical item or currency delivery by carrier pigeon. A letter is simply a
79 paper item with player-written text.
80
81 - Support persistent player groups without turning them into an instant
82 long-distance chat channel.
83
84 - Provide a shared, unlimited player bank near the marketplace, with later
85 banks all reading the same vault, plus bearer cheques and free pigeon
86 deposits.
87
88 - Make the central marketplace an order-matching service rather than a public
89 auction list, with durable escrow and asynchronous pigeon delivery.
90
91 - Keep the economy predominantly player-driven: most ingredients are gathered,
92 final goods are normally crafted by players, and finished-item drops come from
93 enemies/bosses rather than ordinary NPC shops.
94
95 - Let every combatant — players and other mobs — attack. Melee requires an
96 adjacent tile including diagonals; ranged attacks and spells use the range
97 of the weapon or spell. A hit roll uses the weapon skill; damage uses
98 Strength, Dexterity or Mind. Attack XP is split equally between those two
99 skills.
100
101 - Let shop NPCs sell items at a seed value that lerps toward the last
102 player-market sale price over a configurable duration (default one hour),
103 with a hidden per-shop discount.
104 Item inspection shows name, description, origin and the undiscounted
105 current value, refreshed at most once per minute.
106
107 - Use skill-based progression with no player classes. Every gameplay action is
108 governed by a skill and awards XP to that skill when successfully performed.
109 Combat is the explicit dual-skill exception: hit skill and damage skill
110 share the XP.
111
112 # 2. Core world model
113
114 ## 2.1 Spatial hierarchy
115
116 World
117 └── Region: 4 × 4 chunks
118 └── Chunk: 16 × 16 tiles
119 └── Tile
120
121 One chunk contains 256 tiles. One region is 64×64 tiles and contains 16
122 chunks (4,096 tiles). World tile coordinates are canonical; chunk and
123 region coordinates are derived from them.
124
125 chunkX = floor(tileX / 16)
126 chunkY = floor(tileY / 16)
127 regionX = floor(chunkX / 4)
128 regionY = floor(chunkY / 4)
129
130 If negative world coordinates are allowed, use true floor division
131 rather than JavaScript integer truncation.
132
133 ## 2.2 Three independent spatial states
134
135 The design deliberately separates region residency, chunk simulation,
136 and client visibility.
137
138 | **Concern** | **Unit** | **Meaning** |
139 |-------------|----------|------------------------------------------------------------------------------------------------|
140 | Residency | Region | Whether the region and its required chunk data exist in server memory and have a worker owner. |
141 | Simulation | Chunk | Whether ECS systems actively simulate entities and gameplay in this chunk. |
142 | Visibility | Chunk | Whether a specific client is subscribed to the chunk and receives its snapshot/deltas. |
143
144 ## 2.3 Region states
145
146 UNLOADED
147 ↓ load
148 RESIDENT
149 ↓ no residency references + grace period
150 UNLOADED
151
152 A resident region is assigned to exactly one simulation worker. An
153 unloaded region has no active ECS representation.
154
155 ## 2.4 Chunk states
156
157 DORMANT ⇄ SIMULATING
158
159 A dormant chunk can remain resident in memory while normal gameplay
160 systems ignore it. A simulating chunk participates in movement, combat,
161 AI, spawners and other active systems.
162
163 # 3. Tile layers and occupancy
164
165 ## 3.1 Ground layer
166
167 Every tile has a ground type. Ground is visual only. It does not by
168 itself block movement, cause collision, or create gameplay behaviour.
169
170 TileGround {
171 groundTypeId: GroundTypeId
172 }
173
174 ## 3.2 Block layer
175
176 A tile may also contain one block. The block is the actual world object
177 standing on the tile and can determine collision and behaviour.
178
179 TileBlock {
180 blockTypeId: BlockTypeId \| null
181 config?: BlockConfig
182 }
183
184 Examples include walls, doors, trees, torches and other lights, containers,
185 spawners, marketplace counters and banks. Block definitions determine
186 properties such as passability, interaction behaviour, whether a block
187 participates in navigation, and whether it emits light (`lightRangeTiles`).
188
189 ## 3.3 MOBile entities
190
191 A moving game entity — player, enemy, animal, NPC or any other mobile
192 actor — is represented by an ECS entity rather than being painted into
193 the static tile map. A mobile entity may inhabit a tile in addition to
194 the tile’s ground and block layers, subject to collision rules.
195
196 Tile
197 ├── Ground (visual layer)
198 ├── Block (static/world-object layer; optional)
199 ├── Ground item stacks (ephemeral, non-blocking)
200 └── Mobile ECS entities (dynamic occupancy)
201
202 The spatial chunk index maintains which mobile entity IDs currently
203 occupy each tile, allowing collision, nearby queries and replication
204 without scanning the global ECS. Ground item stacks are indexed per
205 tile as well, but they never contribute to movement collision and never
206 prevent a mobile entity from standing on that tile.
207
208 # 4. ECS model
209
210 ## 4.1 Entity composition
211
212 Entities are numeric identities plus components. Behaviour comes from
213 systems querying component combinations rather than deep class
214 inheritance.
215
216 Player
217 Position
218 Movement
219 Health
220 Combat
221 Skills
222 Inventory
223 Currency
224 Equipment
225 Player
226 NetworkIdentity
227 ChunkLoader
228 Persistent
229
230 Ordinary enemy
231 Position
232 Movement
233 Health
234 Combat
235 Skills
236 Creature
237 AI
238
239 Named NPC
240 Position
241 Movement
242 Health
243 NPC
244 AI
245 Persistent
246
247 ## 4.2 Global identity versus local ECS handle
248
249 Use a globally meaningful EntityId for storage, networking and
250 cross-worker transfer, and a compact worker-local EntityHandle for hot
251 ECS arrays. A transferred entity keeps its EntityId but may receive a
252 different local handle on the destination worker.
253
254 ## 4.3 Recommended initial components
255
256 | **Category** | **Components** |
257 |----------------|----------------------------------------------|
258 | Spatial | Position, Movement, Path, Collision |
259 | Living | Health, Combat, Creature, Mob, Skills |
260 | Player | Player, NetworkIdentity, Inventory, Currency, Equipment |
261 | AI | AI, Target, BehaviourState |
262 | Lifecycle | ChunkLoader, Persistent, SpawnOrigin |
263 | Presentation | Renderable / Appearance |
264 | Future control | Controller / ScriptController / OfflineUntil |
265
266 # 5. ChunkLoader and simulation activation
267
268 ## 5.1 Generic ChunkLoader component
269
270 World activation is component-driven rather than player-specific. Any
271 entity may carry a ChunkLoader component that says “keep the surrounding
272 world resident and simulated”.
273
274 ChunkLoader {
275 simulationRadiusChunks: 1,
276 regionLoadRadius: 1
277 }
278
279 A normal player can therefore stimulate a 3×3 chunk area while keeping
280 the surrounding 3×3 regions resident. Bosses, travelling NPCs, machines,
281 scripted actors or administrative anchors can use the same mechanism.
282
283 ## 5.2 Reference counting
284
285 Chunk simulation and region residency should use reference counts.
286 Overlapping loaders increment the same references; leaving decrements
287 them. A chunk sleeps only when its simulation reference count reaches
288 zero. A region becomes eligible for unload only when its residency
289 references reach zero.
290
291 ## 5.3 Grace period
292
293 After the last residency reference disappears, retain the region briefly
294 before unloading. This prevents repeated SQLite reads and writes when a
295 loader oscillates around a boundary. The delay should be configurable.
296
297 # 6. Chunk lifecycle and persistence
298
299 ## 6.1 No periodic chunk saves
300
301 Normal gameplay does not periodically rewrite loaded chunks. A chunk is
302 saved as part of the unload path only.
303
304 Resident chunk
305 ↓ last residency / forced shutdown unload
306 Prepare unload
307 ↓
308 Persist required chunk state once
309 ↓
310 Persist required entities
311 ↓
312 Remove ECS/runtime representation
313
314 A graceful server restart does not introduce a second save mechanism. It
315 force-unloads every resident region/chunk, so the normal unload
316 persistence path remains the single source of truth.
317
318 ## 6.2 Persistent versus non-persistent entities
319
320 Persistence is an entity property, not a property of the chunk or
321 spawner. An entity with Persistent is serialised when its owning
322 chunk/region unloads. A non-persistent entity is simply discarded.
323
324 Non-persistent wolf
325 spawn → simulate → chunk unload → disappear
326
327 Persistent named NPC
328 load → simulate → chunk unload → save → recreate when area loads
329
330 ## 6.3 Persistent is independent of ChunkLoader
331
332 These traits must remain independent. A persistent entity does not
333 automatically keep its area active, and a ChunkLoader does not
334 automatically become persistent.
335
336 # 7. Storage architecture
337
338 ## 7.1 Separate authored world and runtime state
339
340 Use two SQLite databases with different responsibilities.
341
342 | **Database** | **Responsibility** |
343 |--------------|-----------------------------------------------------------------------------------------------------------------------------------------|
344 | world.sqlite | Admin-authored ground tiles, block tiles, light maps, live world settings and their edit log, spawner configuration, per-chunk editor changelogs, world revisions and world metadata. |
345 | state.sqlite | Accounts, characters, inventories, carried currency, character vaults, inheritance tabs, cheque reservations, skills, groups, courier cargo/transit, unexpired ground items, market orders/escrow/trades, per-item last player-market sale, persistent ECS entities, offline-script state, optional persistent runtime chunk overrides, and other durable live-game state. |
346
347 This prevents editor authoring changes from becoming entangled with live
348 player/entity persistence.
349
350 ## 7.2 Chunk writes in runtime state
351
352 If initial gameplay does not allow permanent tile/block modification,
353 runtime chunks require no writes at all. If permanent runtime world
354 changes are later added, dirty chunk overrides are held in memory and
355 written to state.sqlite only when that chunk unloads. Shutdown uses
356 forced unload and therefore follows the same rule.
357
358 ## 7.3 Central persistence service
359
360 Simulation workers should not independently compete for SQLite writes. A
361 persistence service owns the write connection, batches transactions, and
362 receives logical save requests from workers.
363
364 Simulation workers
365 │ save/unload messages
366 ▼
367 Persistence service
368 │
369 ▼
370 SQLite (WAL)
371
372 Live ECS state remains authoritative while loaded; SQLite is durable
373 state, not a per-tick synchronisation mechanism.
374
375 # 8. World authoring and revision model
376
377 ## 8.1 Admin-only world editor
378
379 The server includes a separate admin-only world editor UI. It is not
380 part of the normal player client.
381
382 - Display a 3×3 of 16×16 chunks, with the currently selected
383 chunk in the centre and a red border around that chunk.
384 Painting, open/closed, and changelog apply only to the
385 selected chunk; neighbours are visible for alignment and
386 baked lighting context.
387
388 - Provide Up, Down, Left and Right navigation buttons that move the
389 editor exactly one chunk in that direction.
390
391 - Show the current chunk coordinates prominently, and whether the chunk
392 is **open** or **closed**.
393
394 - Toggle the current chunk open or closed. Closed chunks remain visible
395 to nearby players but cannot be entered.
396
397 - Allow painting a ground type on a tile.
398
399 - Allow painting, replacing or erasing the block type on a tile.
400
401 - Hovering a tile in the selected chunk previews the selected tool there:
402 existing content on that layer is hidden and the tool's sprite is shown
403 where a click would place it.
404
405 - Mouse wheel cycles the **visual state** of the selected ground or block
406 type (see section 21.3). If the hovered tile already has that type, the
407 wheel also writes the new state onto it.
408
409 - Render both layers together so the block appears on top of the ground.
410
411 - Do not display ordinary mobile entities as editable map paint.
412
413 - Allow selecting/configuring special block types such as Spawner, Bank,
414 Marketplace and light-emitting blocks (`lightRangeTiles`).
415
416 - Open a **world settings** modal for global tick timers and constants
417 (movement cadence, night darkness, shop lerp duration, drop lifetime,
418 and other values listed in section 8.5). The form is categorised and
419 scrollable; a settings edit log sits beside it. Edited rows are marked
420 until Save, and only those rows are written.
421
422 - Provide a **night-to-day slider** that only previews lighting; it does
423 not change live world time. Preview uses the same baked light maps as
424 play, including light that reaches this chunk from neighbouring chunks.
425
426 - Later: allow configuring ground-item spawners analogously to mob
427 spawners. Exact item tables remain a later content decision.
428
429 - Save changes through an authenticated admin API; the browser never
430 opens SQLite directly.
431
432 - Show that chunk's changelog: a chronological list of saves, each with
433 which admin made the edit, when, and a bullet-point diff of the change.
434
435 The editor camera is **not** locked to a player character. It frames the
436 currently selected chunk. This is the only intended exception to the
437 player-centered play viewport in section 21.4.
438
439 ## 8.2 World editor save behaviour
440
441 Saving a **chunk** writes the authored result to world.sqlite. It does
442 not live-patch the currently running simulation map. Instead, the change
443 creates or updates a pending world revision and schedules a server
444 restart for the next server-local midnight (or Apply now).
445
446 Saving **world settings** is different: it updates the live settings
447 row immediately, records a settings changelog entry, and the running
448 process applies the new values without waiting for a world revision.
449
450 The running game remains pinned to the **chunk** world revision selected
451 at its own startup. This avoids a dangerous mixed state where some
452 loaded chunks use old authored data and newly loaded chunks use newer
453 editor data. Settings are not revision-pinned.
454
455 ## 8.3 Versioned authored chunks
456
457 A practical schema is to give every editor change a monotonically
458 increasing world revision. The game process pins one active revision for
459 its entire lifetime. Chunk lookup selects the latest authored version
460 not newer than that pinned revision.
461
462 world_revisions
463 revision_id
464 created_at
465 created_by
466 status // pending / active / superseded
467
468 world_chunk_versions
469 chunk_x
470 chunk_y
471 revision_id
472 open // player-enterable; default false until set
473 data_blob
474
475 world_meta
476 active_revision
477 pending_revision
478
479 world_settings
480 revision_id
481 settings_blob // historical snapshot copied onto a map revision
482
483 world_live_settings
484 id // singleton row, always 1
485 settings_blob // the live, immediately applied settings
486 updated_at
487 updated_by
488
489 world_settings_edit_log
490 log_id
491 editor_admin_id
492 edited_at
493 diff_entries // which options changed, from/to
494
495 world_chunk_edit_log
496 log_id
497 chunk_x
498 chunk_y
499 revision_id
500 editor_admin_id
501 edited_at
502 diff_entries // structured bullets for this save
503
504 On the next planned restart, startup promotes/selects the latest valid
505 pending revision before world loading begins.
506
507 ## 8.4 Per-chunk changelog
508
509 Every successful chunk save appends one changelog record for that chunk.
510 The record is durable in `world.sqlite` and is not gameplay state.
511
512 The server diffs the newly saved chunk against the previous authored
513 version of that same chunk (the latest `world_chunk_versions` row for
514 those coordinates that this save replaces). Unchanged tiles produce no
515 bullets. Each changed tile becomes one of:
516
517 ```text
518 - Ground at X, Y changed from Prev to New.
519 - Block <type> placed at X, Y.
520 - Block at X, Y changed from Prev to New.
521 - Chunk opened.
522 - Chunk closed.
523 ```
524
525 `X, Y` are world tile coordinates. `Prev` / `New` / `<type>` are the
526 ground or block definition display names. A block paint on an empty block
527 layer is a placement. Replacing one block type (or its config, such as a
528 spawner) with another is a change. Erasing a block is a removal. Ground is
529 never absent; a ground paint is always a change from one type to another.
530
531 The editor UI lists records newest-last or newest-first consistently, each
532 headed by admin identity and timestamp, with that save's bullets underneath.
533 The changelog is an audit trail, not an undo stack. Undo/redo remains an
534 open editor-UX decision. Derived light maps are not changelog bullets;
535 they are regenerated on save (section 8.6).
536
537 ## 8.5 World settings
538
539 Global gameplay constants live in authored `world_live_settings`. They
540 are **not** per-mob, **not** client-authored, and **not** pinned to a
541 map revision. Admins edit them from a large tabbed modal in the
542 world-editor UI. The modal fills most of the screen: the left pane has
543 category tabs (Simulation, Graphics, World, Characters, Communication,
544 Inventory, Economy) with one panel visible at a time; the right pane is
545 a settings edit log (which option changed, from/to, which admin,
546 date/time).
547
548 Rows the admin has edited in this session are marked with a distinct
549 background. Save writes **only** those dirty fields. The running
550 process applies them immediately (walk cadence, tick rate, night
551 darkness, bloom post-chain knobs, and other consumed timers). Chunk
552 **Apply now** is not required.
553
554 `nightDarkness` only darkens during dusk/night/dawn (peak hours 22–5).
555 Daytime hours 8–16 stay fully bright on the client. Editing night
556 darkness in the editor snaps the Night preview slider to night so the
557 change is visible immediately.
558
559 Minimum initial settings and defaults:
560
561 ```text
562 WorldSettings
563 - walkTilesPerSecond // default 2
564 - simulationTickHz // default 20; implementation default, still a setting
565 - shopPriceLerpDuration // default 1 hour
566 - groundItemDespawnDuration // default 10 minutes
567 - regionUnloadGracePeriod // configurable grace after last residency
568 - defaultGroundTypeId // grass used for never-edited chunks
569 - characterDeletionDelay // default 24 hours
570 - nightDarkness // default 0.72; 0 = no extra night darkening, 1 = fully black unlit tiles
571 - chatMaxCharacters // default 100; trimmed proximity-chat line length
572 - bloomThreshold // default 0.35; Framework bloom bright-pass
573 - bloomSoftKnee // default 0.3
574 - bloomIntensity // default 1.35
575 - bloomBlurSize // default 3
576 - bloomSaturation // default 1.15
577 - bloomColorPreserve // default 0.35
578 - bloomDilate // default 2; 0 disables dilate
579 - bloomScales // default 2; H/V blur scale pairs
580 - bloomHalfRes // default 1; 1 = half-res blur, 0 = full-res
581 ```
582
583 Running is always **double** walking speed. It is not a separate per-entity
584 field. From `walkTilesPerSecond`:
585
586 ```text
587 runTilesPerSecond = walkTilesPerSecond * 2 // default 4
588 movementTickHz = runTilesPerSecond // default 4 Hz
589 walk: commit a tile every 2 movement ticks
590 run: commit a tile every 1 movement tick
591 ```
592
593 All ground mobiles — players, enemies, NPCs — use this same cadence. A
594 mob definition does not set move speed. Gait (`walk` | `run`) is the only
595 per-entity choice; it selects every-other vs every movement tick.
596
597 Other tick-duration constants that already exist in this document (shop
598 lerp, ground-item despawn, residency grace, and later ones of the same
599 kind) are edited here rather than hardcoded. Adding a new global timer
600 means adding a field to `WorldSettings` and a row in this modal.
601
602 ## 8.6 Baked lighting
603
604 Light from authored blocks is precomputed when a chunk is saved, not
605 raytraced every simulation tick.
606
607 A block definition may set `lightRangeTiles > 0`. That tile is a static
608 light source. Light travels only through **passable** tiles (the same
609 passability as walking). Ground type does not block light. Mobiles and
610 ground items do not block light.
611
612 For every tile within a source's range, the baker runs a simple grid
613 raycast (for example Bresenham through tile centres). If the ray hits an
614 impassable block before the destination, that source does not light that
615 tile. A tile is lit if **any** source can reach it. Light **does** shine
616 across chunk boundaries.
617
618 Saving a chunk rebakes:
619
620 1. that chunk's 16×16 light map, and
621 2. every neighbouring chunk that could be affected (chunks within the
622 maximum `lightRangeTiles` of the saved chunk).
623
624 Neighbor rebakes use light sources and walls from the pending revision,
625 including the chunk just saved. Those neighbor light maps are written
626 into the same pending revision so play never mixes old and new lighting.
627
628 The light map is stored in the chunk `data_blob` as a 16×16 intensity
629 (0 = unreachable, 1–255 = falloff by distance from the strongest
630 reaching source). The client darkens tiles by that intensity at night,
631 so a torch fades tile-by-tile rather than lighting a hard disc. Peak
632 unlit darkness is `nightDarkness` (a live world setting). It is
633 replicated to clients in `CHUNK_SNAPSHOT` / `CHUNK_DELTA`.
634
635 On the client, immobile ground and ≤16×16 static blocks (plus their
636 bloom companions) are composited into per-chunk atlases when a snapshot
637 arrives: one ground image, one block strip per tile row (so Y-sort still
638 interleaves mobiles between rows), and one bloom image for the bloom
639 render layer. Blocks taller than 16×16 or with animation stay as
640 individual sprites. Night shade overlays darken the baked atlases per
641 tile; oversized sprites and mobiles instead receive a uniform shade from
642 the darkness of the tile they stand on.
643
644 Runtime door open/close does not rebake static light unless a later
645 iteration adds live lighting. Baked light is authored geometry.
646
647 The editor night-to-day slider interpolates preview ambient from full
648 night (dark except baked-lit tiles) to full day (no ambient darkening).
649 It does not persist and does not change server/world clock.
650
651 ## 8.7 Default chunks and open / closed
652
653 A chunk the editor has never saved does not exist in `world_chunk_versions`.
654 At runtime it is synthesised as:
655
656 - every tile `defaultGroundTypeId` (grass),
657 - no blocks,
658 - **closed**,
659 - no baked lights.
660
661 The world is therefore an infinite grass field until admins paint it, and
662 players cannot walk onto it until an admin **opens** the chunk.
663
664 **Closed** chunks can still appear in a player's 3×3 view. They cannot be
665 entered: `MOVE_TO`, pathfinding, spawning, and other player-entry actions
666 treat every tile in a closed chunk as impassable. Visibility and lighting
667 previews are unchanged. Where an **open** chunk shares an edge with a
668 closed (or never-edited) chunk, the client draws a red border on that
669 edge so players can see they cannot cross.
670
671 **Open** chunks are the playable map. Opening or closing is an authored
672 chunk flag, saved with the pending revision like paint.
673
674 Spawners in a closed chunk do not spawn. Ground movement, including AI,
675 does not step into a closed chunk. If a future bug or admin tool places an
676 entity there, it can still be replicated to observers, but players cannot
677 walk in after it.
678
679 # 9. Spawner blocks
680
681 ## 9.1 Spawner data
682
683 A Spawner is a block in the authored block layer, with per-instance
684 configuration stored as part of the chunk data.
685
686 SpawnerConfig {
687 spawnerId: SpawnerId,
688 mobTypeId: MobTypeId,
689 maxAlive: number,
690 spawnRangeTiles: number
691 }
692
693 Additional parameters such as minimum/maximum spawn delay can be added
694 later without changing the core model.
695
696 ## 9.2 Spawner editor
697
698 Selecting a Spawner tile in the world editor opens a configuration panel
699 containing at minimum: mob type, maximum alive count and spawn range.
700 Validation happens server-side before the pending world revision is
701 written.
702
703 ## 9.3 Spawned entity persistence
704
705 The spawner never decides whether its mob is persistent. The mob
706 definition/archetype does. When the spawner creates an entity, the
707 entity receives Persistent only if that mob type is defined as
708 persistent.
709
710 MobDefinition: deer
711 persistent = false
712
713 MobDefinition: named_guard_captain
714 persistent = true
715
716 ## 9.4 SpawnOrigin
717
718 Spawned mobs receive a SpawnOrigin component referencing the spawner.
719 This lets maxAlive count only entities belonging to that spawner and
720 avoids expensive geometric searches.
721
722 SpawnOrigin {
723 spawnerId: SpawnerId
724 }
725
726 For non-persistent mobs, disappearance on chunk unload naturally
727 decreases the count. For persistent mobs, SpawnOrigin is persisted so
728 the spawner can recognise an existing persistent instance even after it
729 has moved or been unloaded elsewhere. A lightweight persistence index by
730 spawnerId prevents duplicate persistent spawns.
731
732 ## 9.5 Spawner simulation
733
734 SpawnerSystem runs only while the spawner’s chunk is simulating **and
735 open**, and at a much lower frequency than movement. A spawn candidate
736 must satisfy block collision, bounds, an open chunk, and mobile-occupancy
737 rules. Ground type does not affect passability unless a later gameplay
738 system explicitly introduces a separate rule for it.
739
740 ## 9.6 Future ground-item spawners
741
742 Some items will later spawn naturally on the ground, using a world-editor
743 block analogous to a mob spawner. Those spawned stacks should use the same
744 non-blocking ground-item representation as player drops, but their lifetime,
745 respawn and `maxOnGround` rules belong to the spawner configuration rather
746 than the 10-minute player-drop timer.
747
748 Exact item lists, harvest interactions and spawner parameters are later
749 content decisions and do not block the inventory/bank model.
750
751 # 10. Startup and loading order
752
753 Loading order is explicit so authored world state exists before
754 persistent entities are instantiated into it.
755
756 > **1.** Start process and load configuration, including server time
757 > zone and storage paths.
758 >
759 > **2.** Open world.sqlite and validate/migrate its schema.
760 >
761 > **3.** Select/promote the world revision to use for this process and
762 > pin it for the lifetime of the process.
763 >
764 > **4.** Load static registries: ground definitions, block definitions,
765 > item definitions, material definitions, spell definitions, mob archetypes and component serializers.
766 >
767 > **5.** Open state.sqlite and run runtime-state migrations.
768 >
769 > **6.** Start the persistence service, durable domain services (such as courier, bank, market and shop-price services when enabled), region coordinator and simulation workers.
770 >
771 > **7.** Load the index of persistent entities that themselves require
772 > world activation (for example persistent ChunkLoaders or future
773 > offline scripted players).
774 >
775 > **8.** For each required region, load authored chunk data from the
776 > pinned world revision first.
777 >
778 > **9.** Apply any durable runtime chunk override state, if the game
779 > supports such modifications.
780 >
781 > **10.** Instantiate persistent entities into the already-created
782 > world/chunks.
783 >
784 > **11.** Recalculate ChunkLoader references and begin chunk simulation.
785 >
786 > **12.** Only after the world reports READY does the gateway accept
787 > normal player logins.
788
789 This ordering solves the bootstrap problem for persistent entities that
790 keep their own chunks active: a compact persistence index can locate
791 them without first loading the entire world.
792
793 # 11. Simulation workers and region ownership
794
795 ## 11.1 Ownership invariant
796
797 Exactly one worker authoritatively owns a region at any instant. Every
798 authoritative entity belongs to the worker that owns the entity’s
799 current region.
800
801 ## 11.2 Coordinator
802
803 A central region coordinator maintains RegionId → WorkerId and
804 assigns/migrates regions based on actual measured simulation effort,
805 while preferring neighbouring regions on the same worker when load
806 permits.
807
808 ## 11.3 Work measurement
809
810 - Average and high-percentile tick execution time.
811
812 - Number of simulating chunks.
813
814 - Number of active entities and AI entities.
815
816 - Pathfinding work and queued searches.
817
818 - Cross-worker boundary message volume.
819
820 - Backlog / tick lateness.
821
822 Actual time spent simulating is more important than raw player count or
823 raw region count.
824
825 ## 11.4 Node.js implementation
826
827 Simulation workers keep mutable ECS worlds isolated and talk only through
828 structured-cloneable messages. The default runtime is in-process workers
829 with clone-on-boundary (so the protocol is real even without OS threads).
830 `SIMULATION_WORKER_MODE=thread` runs the same `WorkerWorld` inside
831 `worker_threads`. Do not share a mutable ECS in SharedArrayBuffer.
832
833 A coordinator on the gateway thread owns region assignment (neighbour-sticky,
834 least-loaded tie-break), global EntityIds, transfer handoff, ghost exchange,
835 and SQLite. `SIMULATION_WORKERS` defaults to 2. Dynamic load rebalance is
836 later.
837
838 # 12. Cross-worker communication
839
840 ## 12.1 No remote mutation
841
842 A worker may inspect a limited read-only representation of neighbouring
843 entities but never directly mutates authoritative state owned by another
844 worker.
845
846 ## 12.2 Border ghosts
847
848 Neighbouring workers can exchange compact border/ghost entity data for
849 nearby interaction and AI: EntityId, position, collision footprint, type
850 and minimal combat metadata. Ghosts are not full ECS entities and are
851 never authoritative.
852
853 ## 12.3 Remote actions
854
855 Worker A goblin targets Player 42 (owned by Worker B)
856 Worker A → REMOTE_ACTION(attack intent) → Worker B
857 Worker B validates range/state and applies authoritative result
858
859 ## 12.4 Entity transfer
860
861 When an entity crosses from a region owned by Worker A into one owned by
862 Worker B, ownership is handed off at a simulation tick boundary using a
863 sequence-numbered transfer protocol. There is never more than one
864 authoritative copy.
865
866 A: prepare transfer
867 B: validate / accept
868 A: freeze at handoff boundary
869 B: instantiate authoritative entity at effective tick
870 Coordinator: update ownership mapping
871 A: remove authoritative copy
872
873 # 13. Server tick and stimulation
874
875 ## 13.1 Fixed simulation tick
876
877 Use a fixed server simulation tick. The default is 20 Hz (50 ms), stored
878 as `WorldSettings.simulationTickHz`. This is not a protocol promise.
879
880 Movement does **not** commit a new tile on every simulation tick. See
881 section 13.4.
882
883 1\. Drain validated incoming commands
884 2. Apply completed worker/entity transfers
885 3. Recalculate activation changes
886 4. Movement / collision
887 5. Combat
888 6. Scheduled AI
889 7. Scheduled spawners/environment, including ground-item expiry in simulating chunks
890 8. Produce cross-worker messages
891 9. Produce client replication deltas
892 10. Queue unload/persistence work
893
894 ## 13.2 Different system frequencies
895
896 Not every ECS system should run every tick. Ground movement commits only
897 on the global movement cadence (section 13.4). AI decisions, target
898 searches and spawner checks can run at lower frequencies. Sleeping chunks
899 are not “slow ticked”; they are omitted from normal simulation.
900
901 ## 13.3 Timestamp-based inactive progression
902
903 Long-lived timers such as growth, cooldowns, ground-item expiry and shop
904 price lerps should store future timestamps where possible. When an area
905 wakes, the system catches up from the timestamp instead of executing missed
906 ticks. An expired ground item is discarded on catch-up without ever
907 reappearing. Shop and tooltip prices are evaluated from last-sale timestamps
908 when observed; they are not ticked. Durations such as shop lerp and
909 ground-item despawn come from `WorldSettings`, not from hardcoded
910 literals in systems.
911
912 ## 13.4 Global movement cadence
913
914 All ground-moving entities share one walk speed and one run speed.
915
916 - Default walk: **2 tiles per second** (`walkTilesPerSecond`).
917 - Run: always **double** walk (default 4 tiles per second).
918 - Movement ticks fire at `runTilesPerSecond` (default 4 Hz).
919 - **Walk:** the entity may advance one path tile on every other movement
920 tick.
921 - **Run:** the entity may advance one path tile on every movement tick.
922
923 Mobs do not define their own move speed. `Movement.gait` is `walk` or
924 `run`. Players send `SetGait`. AI may set gait; it still uses the global
925 cadence. Flying pigeon transit is not this cadence; it keeps its own
926 route clock.
927
928 If the path is blocked on a movement tick, the entity stays on its tile
929 and retries on a later legal tick. Occupancy, combat range and pickup
930 always use the last committed tile.
931
932 ## 13.5 World calendar time
933
934 World time is server time **1:1**, in the same configured IANA zone used
935 for midnight restarts, with **1200 years subtracted** from the calendar
936 date. A server clock of 24 Aug 2026 21:00 is world 24 Aug 826 21:00.
937 Clock-of-day, including night, therefore matches the host's zone.
938
939 The gateway includes current world time (or server unix time plus the
940 year offset) in the status sent to clients so shading does not depend on
941 the player's device clock. Lighting is presentation; combat and movement
942 do not wait on the day/night overlay.
943
944 # 14. Client gateway and authority
945
946 ## 14.1 Stable connection ownership
947
948 Client WebSocket/TCP connections belong to a gateway rather than
949 simulation workers. When the player crosses into a region owned by
950 another worker, the socket stays connected to the same gateway; only
951 internal routing changes.
952
953 ## 14.2 Client commands are intentions
954
955 A client sends commands such as MoveTo, Interact, Attack, UseItem,
956 EquipItem, UnequipItem, SelectSpell, SetGait, DropItem, PickupItem, BankDeposit,
957 BankWithdraw, BuyFromShop or SendPigeon. The authenticated **account**
958 determines the actor; after character select, commands apply to that
959 account's **active character**. The
960 client never supplies an authoritative resulting position, health
961 value or inventory result.
962
963 ## 14.3 Input queue
964
965 Socket handlers validate message shape and enqueue commands. Simulation
966 workers consume commands at tick boundaries. WebSocket callbacks do not
967 mutate ECS state directly.
968
969 ## 14.4 Authentication
970
971 Live login uses **auth.timfalken.com**. The game server never stores a
972 password. It receives an authenticated account identity (and email) from
973 that service and maps it to a durable `accountId` in `state.sqlite`.
974
975 Until auth.timfalken.com is available, the gateway uses a **stub identity**:
976 each new connection is `admin-<n>`, where `n` is the number of currently
977 connected clients **including this one** (the first connection is
978 `admin-1`). Stub accounts are treated as admins so the world editor can be
979 used during development. Stub accounts have no email; deletion “emails”
980 are logged instead of sent.
981
982 When real auth ships, the stub is removed. Admin rights come from that
983 service, not from the `admin-` name prefix.
984
985 An account may have only **one active play session** at a time (one
986 character in the world).
987
988 ## 14.5 Characters
989
990 An account has unlimited characters and plays **one** at a time. First
991 login with no characters must create one before entering the world. Later
992 logins show a character-selection menu: create, choose, mark for deletion,
993 or cancel deletion.
994
995 Initial character setup (may change later):
996
997 ```text
998 CreateCharacter
999 - firstName // not globally unique
1000 - lastName // unique surname, owned by this account
1001 - sex // male | female
1002 ```
1003
1004 Rules:
1005
1006 - **Last names** are globally unique. The first character to take a surname
1007 claims it for that **account**. The same player may reuse that last name
1008 on their other characters. Another account cannot use it.
1009 - **First names** need not be unique globally.
1010 - For a given account, `firstName` + `lastName` must be unique among
1011 characters that still exist (including those pending deletion).
1012 - Uniqueness is case-insensitive; display uses the casing the player typed.
1013
1014 ```text
1015 Account
1016 - accountId
1017 - authSubject // from auth.timfalken.com, or stub admin-<n>
1018 - email? // from auth; absent on stub
1019 - surnameClaims[]
1020
1021 Character
1022 - characterId
1023 - accountId
1024 - firstName
1025 - lastName
1026 - sex
1027 - deletionScheduledAt? // null if not deleting
1028 - inventory, equipment, currency, vault, skills, ...
1029 ```
1030
1031 The in-world ECS player entity is a **character**, not the account.
1032
1033 ## 14.6 Character deletion and inheritance
1034
1035 From character select, the player may mark a character for deletion.
1036
1037 - The character cannot be played while deletion is pending.
1038 - Permanent delete happens after `characterDeletionDelay` (default **24
1039 hours**). Until then the player may cancel.
1040 - The server **always** notifies the account email when deletion is
1041 marked (and should notify again on cancel and on actual delete). Stub
1042 auth logs the message instead.
1043 - On permanent delete, the name pair is freed. If this account has no
1044 remaining characters with that last name, the surname claim is released.
1045 - Before the vault is moved, `BankService` voids outstanding filled
1046 cheques **issued by** this character (reservations return to the vault).
1047 - All items in inventory, equipment, carried currency, and the character
1048 vault are moved to that **account's inheritance bank tab**.
1049
1050 Any living character of the same account may, at a bank, **claim**
1051 inheritance stacks (and currency) into that character's own vault. Claiming
1052 is a move from the account tab to the character vault, not a second copy.
1053
1054 # 15. Client chunk subscription and replication
1055
1056 ## 15.1 3×3 visibility
1057
1058 A player receives the current chunk and the eight surrounding chunks, a
1059 maximum viewport of 48×48 tiles. Neighbouring **closed** chunks are still
1060 sent so scenery remains visible; the player simply cannot walk onto them.
1061
1062 ┌───┬───┬───┐
1063 │ V │ V │ V │
1064 ├───┼───┼───┤
1065 │ V │ P │ V │
1066 ├───┼───┼───┤
1067 │ V │ V │ V │
1068 └───┴───┴───┘
1069
1070 ## 15.2 Incremental subscription changes
1071
1072 Crossing one chunk east subscribes only the three newly visible eastern
1073 chunks and unsubscribes only the three old western chunks. The rest of
1074 the 3×3 view remains subscribed.
1075
1076 ## 15.3 Snapshots and deltas
1077
1078 Initial subscription sends a CHUNK_SNAPSHOT containing authored/runtime
1079 tile state, currently visible entities and unexpired ground item stacks.
1080 Afterwards, revisioned CHUNK_DELTA messages report tile changes, entity
1081 spawn/move/change/despawn events and ground-item appear/change/despawn
1082 events. Full chunks are not retransmitted every tick.
1083
1084 Entity `move` events carry the new integer tile and the current gait so
1085 the client can lerp over the walk or run interval. They do not carry a
1086 fractional in-between position. Smooth walking is a client visual lerp
1087 (section 21.5), not part of the replication payload.
1088
1089 Chunk snapshots include the baked light map (section 8.6).
1090
1091 Visible equipment is replicated as a compact appearance payload (body
1092 sprite plus worn overlay layers and recolour parameters), not as the
1093 entity's full inventory. Nearby clients can draw another player's armour
1094 without receiving their bags.
1095
1096 ## 15.4 Visibility can span workers
1097
1098 The gateway can source visible chunks from multiple workers. A player
1099 may be authoritative on Worker A while one or more of the eight
1100 neighbouring visible chunks are owned by Worker B. Client visibility
1101 must never force simulation-region reassignment.
1102
1103 # 16. Click-to-move and A\* pathfinding
1104
1105 ## 16.1 Command flow
1106
1107 Client: MOVE_TO(tileX, tileY)
1108 ↓
1109 Gateway validates/authenticates
1110 ↓
1111 Owning worker validates target
1112 ↓
1113 A\* calculates authoritative route
1114 ↓
1115 Path component attached/updated
1116 ↓
1117 MovementSystem advances the entity **one tile at a time** on the global
1118 walk/run cadence (section 13.4)
1119
1120 Authoritative `Position` is always an integer `tileX`, `tileY`. The server
1121 does not store a sub-tile location for walking mobiles. When a movement
1122 tick allows this gait to step, `MovementSystem` commits the next path
1123 tile in a single jump. Combat, occupancy, pickup and interaction all use
1124 that committed tile.
1125
1126 Flying pigeons still ignore the ground navigation grid, but their
1127 replicated ECS position is likewise a tile. The transit clock determines
1128 which tile they occupy at a given time; the client may lerp the sprite
1129 between those tiles like any other mobile.
1130
1131 ## 16.2 Initial A\* implementation
1132
1133 For normal player clicks within the visible 3×3 chunks, the search space
1134 is at most 48×48 = 2,304 tiles, so conventional A\* is a strong starting
1135 point.
1136
1137 - Binary heap priority queue for the open set.
1138
1139 - Manhattan heuristic for four-direction movement; octile heuristic if
1140 diagonal movement is later allowed.
1141
1142 - Reusable typed-array or pooled search buffers for hot paths to reduce
1143 allocation and garbage collection.
1144
1145 - Rate-limit path requests per player and avoid recalculation every
1146 tick.
1147
1148 - Use block passability, **open-chunk** bounds, and dynamic occupancy;
1149 ground is visual only. Tiles in closed or never-edited chunks are not
1150 legal path targets for players.
1151
1152 ## 16.3 Navigation revisions
1153
1154 Each chunk maintains a navigation revision that increments when a
1155 movement-affecting block changes. A path records the relevant revisions.
1156 Static geometry changes can invalidate paths; temporary mobile occupancy
1157 normally causes a short wait or small local re-path rather than
1158 rebuilding every path.
1159
1160 ## 16.4 Long-distance extension
1161
1162 If long-distance autonomous travel is added later, introduce
1163 hierarchical pathfinding: region graph → chunk portals/edges → local
1164 tile A\*. The client movement command interface does not need to change.
1165 Server movement remains discrete tile steps; only the path length changes.
1166
1167 # 17. Automatic update and restart scheduler
1168
1169 ## 17.1 Restart triggers
1170
1171 A graceful restart is scheduled for the next midnight in configured
1172 server-local time when either of these conditions occurs:
1173
1174 - A new commit is detected on origin/master. The master branch is the
1175 live branch.
1176
1177 - An administrator saves a world-editor change, creating/updating a
1178 pending authored world revision.
1179
1180 Multiple triggers coalesce into one scheduled restart. The scheduler
1181 stores all reasons so players and admins can see why a restart is
1182 pending.
1183
1184 ## 17.2 Detecting live-code changes
1185
1186 The running server periodically performs a non-destructive remote check,
1187 for example git fetch origin master followed by comparison of the
1188 running commit with origin/master. It does not update the checked-out
1189 code while the game is live.
1190
1191 ## 17.3 Server-local midnight
1192
1193 Midnight is calculated in a configured IANA time zone rather than by
1194 adding 24 hours to the current time. This keeps behaviour correct across
1195 daylight-saving transitions.
1196
1197 ## 17.4 Player-visible restart state
1198
1199 Restart status is part of the server status sent to clients. Connected
1200 players see that a restart is scheduled and the scheduled local time.
1201 The server can also issue configurable countdown notices as the restart
1202 approaches and includes the state immediately when a player logs in.
1203
1204 RestartStatus {
1205 scheduled: true,
1206 scheduledAt: timestamp,
1207 reasons: \["code-update", "world-update"\]
1208 }
1209
1210 ## 17.5 Manual admin restart
1211
1212 An authorised admin action can invoke the same graceful restart pipeline
1213 immediately. This is not a separate “hard restart” path; it differs only
1214 in scheduled time.
1215
1216 ## 17.6 Graceful restart sequence
1217
1218 > **1.** Enter `DRAINING` / `RESTARTING` state and reject new logins.
1219 >
1220 > **2.** Broadcast the final restart notice.
1221 >
1222 > **3.** Disconnect player sessions cleanly and persist session state.
1223 > Shutdown handling overrides normal offline-script retention so chunk
1224 > unload cannot be blocked by a retiring process.
1225 >
1226 > **4.** Stop accepting new gameplay commands and finish the current
1227 > safe tick boundary.
1228 >
1229 > **5.** Force-unload every resident region/chunk, ignoring normal
1230 > `ChunkLoader` references. This invokes the ordinary chunk/entity unload
1231 > persistence path exactly once.
1232 >
1233 > **6.** Flush the persistence service and close SQLite connections
1234 > cleanly.
1235 >
1236 > **7.** Atomically write a restart request manifest. It records the
1237 > restart reasons, whether a code deployment is requested, the target Git
1238 > commit if known, and the pending world revision if one exists.
1239 >
1240 > **8.** Exit the Node.js game process cleanly. At this point the game
1241 > process has no responsibility for updating or relaunching itself.
1242
1243 ## 17.7 systemd process supervisor
1244
1245 The production Node.js process is owned by a `systemd` service. `systemd`
1246 therefore already knows when the process has **fully exited**; no separate
1247 polling process is needed. Only after the previous `ExecStart` process is
1248 gone does `systemd` begin the next service start.
1249
1250 The preferred lifecycle is:
1251
1252 ```text
1253 Running Node.js server
1254 |
1255 | graceful planned restart or crash
1256 v
1257 Node.js process fully exits
1258 |
1259 v
1260 systemd starts the service again
1261 |
1262 +--> conditional update hook
1263 | |
1264 | +--> planned code deployment: git fetch/pull --ff-only
1265 | +--> world-only restart: no Git mutation
1266 | +--> crash/no restart manifest: no Git mutation
1267 |
1268 +--> optional dependency/build step if deployment changed code
1269 |
1270 v
1271 Start Node.js server
1272 |
1273 v
1274 Startup selects the new active world revision
1275 |
1276 v
1277 Gateway opens when the world reports READY
1278 ```
1279
1280 ### 17.7.1 Why Git pull must be conditional
1281
1282 A naive `ExecStartPre=git pull` on **every** restart is unsafe. Suppose a
1283 new commit is detected at 14:00 and correctly scheduled for midnight, but
1284 the game process crashes at 16:00. An unconditional pull would deploy the
1285 new commit immediately during crash recovery, bypassing the scheduled
1286 maintenance window.
1287
1288 Therefore the restart manifest distinguishes an intentional deployment
1289 restart from an ordinary process failure:
1290
1291 ```json
1292 {
1293 "reason": ["code-update", "world-update"],
1294 "deployCode": true,
1295 "targetCommit": "<optional commit hash>",
1296 "pendingWorldRevision": 184
1297 }
1298 ```
1299
1300 The manifest should be written using a temporary file plus atomic rename
1301 so the supervisor never consumes a half-written request. The supervisor
1302 consumes/removes the request only after it has successfully interpreted
1303 it.
1304
1305 If the Node.js process dies without a valid deployment request, `systemd`
1306 restarts the **currently checked-out version**. This gives fast crash
1307 recovery without prematurely deploying pending code.
1308
1309 ### 17.7.2 Suggested systemd shape
1310
1311 A production unit can conceptually look like this:
1312
1313 ```ini
1314 [Unit]
1315 Description=Questward Server
1316 After=network-online.target
1317 Wants=network-online.target
1318
1319 [Service]
1320 Type=simple
1321 User=questward
1322 Group=questward
1323 WorkingDirectory=/srv/questward/current
1324
1325 # This hook checks the restart manifest. It pulls/builds only when an
1326 # intentional deployment was requested. Prefixing with '+' optionally
1327 # allows the hook to run with privileges different from the game user.
1328 ExecStartPre=+/usr/local/sbin/questward-update-if-requested
1329 ExecStart=/usr/bin/node /srv/questward/current/dist/server.js
1330
1331 Restart=always
1332 RestartSec=5s
1333 TimeoutStopSec=120s
1334 KillSignal=SIGTERM
1335
1336 [Install]
1337 WantedBy=multi-user.target
1338 ```
1339
1340 `Restart=always` is appropriate here because an explicit
1341 `systemctl stop questward` does not cause systemd to restart the unit,
1342 while a clean in-game restart exit and an unexpected crash both do.
1343
1344 The exact paths, build command and privilege split are deployment
1345 details, but the important invariant is that the **Node.js process does
1346 not pull Git itself**.
1347
1348 ### 17.7.3 Code-update, world-update and crash behaviour
1349
1350 | Situation | Restart manifest | Git pull before restart | World revision |
1351 |---|---|---|---|
1352 | Scheduled code update | `deployCode=true` | Yes, fast-forward only | Activate pending revision if present |
1353 | World-editor-only update | `deployCode=false` | No | Activate pending revision |
1354 | Manual deployment restart | Explicit admin intent | As requested | Activate pending revision if present |
1355 | Unexpected Node.js crash | Missing/invalid | **No** | Continue current active revision |
1356 | `systemctl stop` | Irrelevant | No automatic restart | N/A |
1357
1358 This preserves the midnight deployment promise even when the game crashes
1359 before the scheduled maintenance window.
1360
1361 ## 17.8 Failure behaviour
1362
1363 Deployment should fail closed. If Git cannot fast-forward, a build or
1364 migration fails, or startup validation fails, the game must not open to
1365 players on a partially updated state. The update hook should log the
1366 failure clearly and return non-zero; systemd may retry according to its
1367 restart/start-limit policy. Databases remain intact, and backups or
1368 snapshots before schema migrations are recommended.
1369
1370 A failed **crash recovery** that did not request deployment must not
1371 silently switch to a newer Git commit as a recovery strategy.
1372
1373 # 18. Future player scripting architecture
1374
1375 ## 18.1 Scope
1376
1377 The custom scripting language is explicitly a later feature. Version 1
1378 only needs architectural hooks so adding scripts does not require
1379 replacing the player-control or simulation model.
1380
1381 ## 18.2 Controller abstraction
1382
1383 All player actions should already pass through an internal command
1384 interface. Manual client input is therefore one possible controller. A
1385 future script is another controller that emits the same validated action
1386 intentions.
1387
1388 ```text
1389 ClientController ─┐
1390 ├─> ActionCommand queue ─> authoritative game systems
1391 ScriptController ─┘
1392 ```
1393
1394 Scripts never mutate ECS components directly. They request actions such
1395 as MoveTo, Interact or Attack and receive the same validation as a human
1396 client.
1397
1398 ## 18.3 Online scripted mode
1399
1400 A logged-in player may enable the script while remaining connected and
1401 observing the game. Control mode explicitly determines whether manual
1402 input or the script is currently producing gameplay commands. The server
1403 remains authoritative either way.
1404
1405 ## 18.4 Logout with active script
1406
1407 If a player has configured offline script execution, logout removes the
1408 network/controller connection but keeps the player entity alive. The
1409 entity changes to an offline script-controlled state and continues
1410 acting until it dies or its configured offline duration expires.
1411
1412 Player online
1413 Player + NetworkIdentity + ChunkLoader + Controller
1414 ↓ logout with offline scripting
1415 Player + ScriptController + ChunkLoader + OfflineUntil
1416 ↓ death OR expiry
1417 persist player state → remove runtime entity
1418
1419 ## 18.5 Offline scripted players and loading
1420
1421 An offline scripted player must continue to stimulate the world it
1422 traverses, so it retains a ChunkLoader. This is powerful but potentially
1423 expensive: thousands of offline scripts could keep large parts of the
1424 world active. Offline duration, script CPU budget and concurrent
1425 offline-script limits therefore become explicit resource policy, not
1426 implementation accidents.
1427
1428 ## 18.6 Restart continuity
1429
1430 A planned restart persists the offline-script state and expiry time,
1431 force-unloads the old process, and rehydrates still-valid offline
1432 scripted players during startup. This is why the startup index for
1433 persistent ChunkLoaders is part of the base architecture.
1434
1435 ## 18.7 Scripting language safety requirements
1436
1437 When the language is implemented, it should be interpreted/compiled into
1438 a purpose-built sandbox rather than evaluated as JavaScript. At minimum
1439 it should enforce:
1440
1441 - No file-system, operating-system, database or arbitrary network
1442 access.
1443
1444 - No eval or escape into Node.js objects.
1445
1446 - Per-tick/per-event instruction budgets and bounded memory.
1447
1448 - Rate-limited expensive operations such as path requests and world
1449 queries.
1450
1451 - Capability-based read APIs for nearby visible/known world state.
1452
1453 - Action output only through the normal server command pipeline.
1454
1455 - Persistable script variables/state if offline execution must survive
1456 restarts.
1457
1458 - Deterministic or tightly controlled timing semantics where practical.
1459
1460 An event-driven language is preferable to running every player script
1461 continuously at full simulation frequency. Events such as arrival,
1462 attack, nearby entity changes or timer expiration can wake scripts only
1463 when useful.
1464
1465 # 19. Security and administration
1466
1467 - World-editor endpoints require an explicit admin role and separate
1468 server-side authorisation checks.
1469
1470 - Client-supplied entity/player IDs are never trusted as authority;
1471 authenticated connection/session context identifies the actor.
1472
1473 - World-editor data is validated against known ground, block, item and mob
1474 definitions before database write.
1475
1476 - Admin restart and deployment controls use the same authenticated
1477 administration layer.
1478
1479 - The Node.js game process should run as a dedicated unprivileged user.
1480 Where practical, source-update permission belongs only to the systemd
1481 update hook (for example a privileged `ExecStartPre` helper), leaving
1482 the running Node.js process unable to modify its own checkout.
1483
1484 - SQLite writes are parameterised and centralised through
1485 persistence/editor services.
1486
1487 - Inventory, vault, cheque and courier mutations are server-authoritative.
1488 Clients cannot invent cheque IDs, forge cargo, or credit a vault.
1489
1490 - Attack hit/miss and damage are server-authoritative. Clients cannot supply
1491 a roll or a damage result. Shop purchase prices are computed at buy time
1492 on the server.
1493
1494 # 20. Recommended process topology
1495
1496 ```text
1497 Clients
1498 |
1499 v
1500 WebSocket/API Gateway
1501 |
1502 +-- Region Coordinator ----> Simulation Worker A
1503 | <--> Simulation Worker B
1504 |
1505 +-- Communication Service --> proximity speech
1506 |
1507 +-- CourierService ---------> pigeon cargo / transit
1508 |
1509 +-- BankService ------------> shared vaults / cheques / reservations
1510 |
1511 +-- MarketService ----------> order book / escrow / trades / last-sale index
1512 |
1513 +-- Persistence Service ----> state.sqlite
1514 |
1515 +-- Admin / World Editor ---> world.sqlite
1516
1517 External process supervision:
1518 systemd ---> conditional deployment hook ---> Node.js relaunch
1519 ```
1520
1521 # 21. Player client architecture
1522
1523 ## 21.1 FrameworkV3 as a git submodule
1524
1525 The player-facing client is built on the shared FrameworkV3 library:
1526
1527 <https://gitlab.com/Timfa/frameworkv3>
1528
1529 FrameworkV3 contains generic reusable client-side code. Game-specific rendering,
1530 UI, input, assets and protocol handling live in this repository, on top of
1531 that library. They are not patched into FrameworkV3 unless they are genuinely
1532 reusable across games.
1533
1534 This repository vendors FrameworkV3 as a **git submodule** rather than
1535 copying its source or depending on an unpublished global install.
1536
1537 ```text
1538 mmo/
1539 client/
1540 frameworkv3/ # git submodule → gitlab.com/Timfa/frameworkv3
1541 src/ # this game's client: protocol, UI, world view, assets
1542 server/ # Node.js ECS backend; does not import FrameworkV3
1543 ```
1544
1545 The submodule path is `client/frameworkv3`. A clone of this repo is not
1546 client-buildable until submodules are present:
1547
1548 ```text
1549 git clone --recurse-submodules <this-repo>
1550 # or, in an existing checkout:
1551 git submodule update --init --recursive
1552 ```
1553
1554 The submodule records a **pinned commit**. Bumping FrameworkV3 is an explicit
1555 commit in this repository (new submodule SHA). Game code must not rely on an
1556 uncommitted dirty checkout of the submodule.
1557
1558 Build order:
1559
1560 ```text
1561 1. Build FrameworkV3 from client/frameworkv3
1562 2. Build this game's client against that output
1563 3. The Node.js server is a separate build and does not link FrameworkV3
1564 ```
1565
1566 The exact FrameworkV3 build command follows that project's own instructions.
1567 This game's client build must consume the framework's public/build artefacts,
1568 not fork its internals.
1569
1570 CI and developer machines check out submodules before the client job. A
1571 missing or uninitialized submodule is a failed client build, not a fallback
1572 to a system copy of FrameworkV3.
1573
1574 If this repo's `master` also ships the built web/desktop client from the
1575 same process that deploys the game server, a submodule bump is just another
1576 commit and follows the normal midnight restart/deploy path. The running
1577 Node.js game process still does not compile or import FrameworkV3.
1578
1579 The backend remains the authoritative Node.js ECS simulation described in this
1580 document. The client does **not** need to use ECS. It receives only a small
1581 3×3-chunk view plus player/UI state, so a conventional object/view-model model is
1582 simpler and entirely appropriate.
1583
1584 ## 21.2 Server/client model separation
1585
1586 Backend ECS components are not treated as a shared client object model. Network
1587 messages form the contract between the two sides.
1588
1589 ```text
1590 Authoritative Node.js ECS
1591 |
1592 | snapshots / deltas / UI state
1593 v
1594 Network protocol DTOs
1595 |
1596 v
1597 Built FrameworkV3 (from client/frameworkv3 submodule)
1598 |
1599 v
1600 This game's client code (client/src)
1601 ```
1602
1603 The two projects may share protocol schemas, enums or generated message types,
1604 but the client must not depend on the internal layout of ECS component storage.
1605 That allows server internals to be optimised without forcing corresponding
1606 client rewrites.
1607
1608 ## 21.3 Sprite size, pivot and Y-sort
1609
1610 World sprites may be any pixel size. The gameplay tile remains 16×16.
1611 Each sprite is placed with an automatic pivot: **horizontally centred**,
1612 and **8 pixels up from the bottom** of the sprite. That pivot sits on the
1613 tile centre, so a 16×16 sprite still fills the tile and a taller sprite
1614 stands on the same feet line and extends upward.
1615
1616 Each sprite kind — **grounds**, **blocks**, **items**, **mobs**, and
1617 **characters** — uses its own per-type asset folder
1618 (`client/assets/<kind>/<key>/`). Every base PNG in that folder is a
1619 **visual state**. Filenames ending in `-bloom`, `-equip`, or combinations
1620 such as `-equip-bloom` are **companions**, not states: `torch-bloom.png`
1621 is the bloom overlay for state `torch`, `{state}-equip.png` is the worn
1622 equipment overlay for that state, and `{state}-equip-bloom.png` is the
1623 bloom overlay for that equip sprite. Companions always live in the same
1624 folder as their base state and are never listed as placeable editor
1625 states. Image names follow `layer:key:state` (plus `:equip` / `:bloom`
1626 suffixes). States are not listed in the type definition: the first base
1627 filename in alphabetical (numeric) order is the default. A later gameplay
1628 system may set a named state on a placed tile (for example a door
1629 `closed` / `open`); unknown names fall back to the default. The editor
1630 mouse wheel cycles these states.
1631
1632 Bloom companions are drawn on a separate Framework **bloom** render
1633 layer that uses `Shader.getBloomPostChain(...)`. Bloom post-chain
1634 parameters are live world settings under the Graphics tab.
1635
1636 Each type definition may set sprite-sheet playback for every state PNG:
1637
1638 ```text
1639 frames // sub-images in the sheet; default 1
1640 framesPerRow // columns in the sheet; default 1
1641 animationSpeed // seconds per frame; 0 means still
1642 ```
1643
1644 Blocks and mobiles with oversized sprites are **Y-sorted**: sprites
1645 higher on the screen draw behind sprites lower on the screen, using the
1646 pivot's world Y (the occupied tile, or the interpolated foot position
1647 while walking). Ground tiles and the night overlay stay behind and in
1648 front of that pass respectively.
1649
1650 Nearest-neighbour sampling still applies so pixels stay sharp under
1651 viewport zoom. Zoom scales the whole view uniformly; it is not a
1652 per-sprite size override.
1653
1654 ## 21.4 Viewport, camera and zoom
1655
1656 In normal play the viewport is **always centered on the local player's
1657 character**. The camera does not free-pan. Scrolling the world happens
1658 only because the player moved.
1659
1660 The player may zoom in and out within configured minimum and maximum
1661 bounds (for example 1× to 4×; the exact numbers are a game setting). Zoom
1662 does not move the camera off the player and does not change server
1663 visibility: the client still receives only the 3×3 chunk window.
1664
1665 The admin world editor is the exception: it frames the selected 16×16
1666 chunk and navigates by chunk, as in section 8.1.
1667
1668 ## 21.5 Client movement interpolation
1669
1670 The server jumps mobiles from tile to tile. The client draws a visual
1671 lerp between the previous replicated tile and the new one over the
1672 interval implied by gait and `WorldSettings` (walk: `1 / walkTilesPerSecond`,
1673 run: half of that). If a delta arrives late, clamp the remaining lerp.
1674 That lerp is presentation only:
1675
1676 - Hit tests, range, pickup and occupancy use the authoritative tile.
1677 - A corrected server position snaps the interpolation target; the client
1678 does not accumulate drift.
1679 - Interpolation does not entitle the client to send fractional positions.
1680
1681 ## 21.6 Equipment layers and recolouring
1682
1683 A mob (including a player character) is drawn as a **stack of sprites**
1684 on the same tile: the body sprite (male or female from character
1685 sex, or the mob archetype body), then each piece of visible equipment.
1686 Overlays are not baked into the body art.
1687
1688 ```text
1689 draw order (back → front, default)
1690 1. body / mob base
1691 2. boots
1692 3. chest
1693 4. weapon
1694 5. legs
1695 6. hair (if visible; inserted before headgear)
1696 7. head
1697 8. off-hand
1698 ```
1699
1700 Slot draw order is data (`EQUIPMENT_DRAW_ORDER`) so a cloak or a two-handed sprite can be inserted
1701 without a renderer rewrite. Weapon sits above chest and under legs so bows/weapons
1702 read between shirt and trousers; clothing art should avoid bad waist overlap.
1703 Overlay sprites use the same automatic pivot
1704 as other world art (horizontal centre, 8 pixels from the bottom).
1705
1706 Equipment items stay in dedicated **equipment slots**, not in the 32
1707 inventory slots, while worn. `EquipItem(slotIndex)` moves a legal item
1708 from inventory into the matching equipment slot, returning any previously
1709 worn item to inventory if there is space. `UnequipItem(equipSlot)` does
1710 the reverse. The weapon equipment slot is what combat uses; it replaces
1711 the older “wielded flag on an inventory slot” idea.
1712
1713 Non-player mobs may carry an `Equipment` component or a simpler appearance
1714 list on the mob definition so a guard can show armour without a player
1715 inventory.
1716
1717 ```text
1718 Equipment
1719 - slots: { head?, chest?, legs?, boots?, weapon?, offhand?, ... }
1720
1721 ItemDefinition.equipment?
1722 - slot
1723 - overlaySpriteId
1724 - recolourableChannels?: ["metal"] // omitted if the art is not recoloured
1725 - materialId? // e.g. iron, steel; used with "metal"
1726 ```
1727
1728 Inventory icons and worn overlays may be different 16×16 files. Both are
1729 world sprites and both go through the size check.
1730
1731 ### Recolourable equipment
1732
1733 Some gear shares one overlay and is tinted per material. Metal armour is
1734 the initial case: iron, steel and later metals are not separate full-size
1735 art sets.
1736
1737 ```text
1738 MaterialDefinition
1739 - materialId // iron, steel, ...
1740 - displayName
1741 - channel // metal for armour; later channels may include cloth
1742 - colour // destination RGB for that channel
1743 ```
1744
1745 A recolourable overlay is authored as:
1746
1747 - the 16×16 overlay sprite, with shading in the channel regions, and
1748 - an optional 16×16 **channel mask** of the same dimensions, whose pixels
1749 name which recolour channel they belong to (for example a reserved mask
1750 colour meaning `metal`). Unmasked pixels are drawn unchanged.
1751
1752 At draw time, masked pixels keep the overlay’s relative brightness
1753 (highlights and shadows) and replace the hue/saturation with the
1754 item’s `MaterialDefinition.colour`. The client must not invent a colour;
1755 the server sends the material id (or the already-resolved colour) on the
1756 appearance layer.
1757
1758 Iron plate and steel plate therefore share `overlaySpriteId = platebody`
1759 and differ only by `materialId`. Non-metal unique art omits
1760 `recolourableChannels` and is blitted as authored.
1761
1762 Recolour happens on the client as a presentation step. It does not change
1763 item identity, combat stats or inventory. Nearby observers receive enough
1764 appearance data to apply the same layers and tints.
1765
1766 ## 21.7 World time and night shading
1767
1768 The client treats **world time** as server time minus 1200 years (section
1769 13.5). It uses that clock-of-day to shade the 3×3 view.
1770
1771 At night, tiles that the baked light map says are unreachable from any
1772 static light are drawn darker. Tiles a light can reach stay brighter.
1773 Light does not bleed through walls: the mask was raycast through passable
1774 tiles at editor save, including across chunk borders, so a torch on the
1775 edge of one chunk can light tiles in the next.
1776
1777 By day, ambient light is full and the baked mask does not darken the
1778 ground. The day/night curve (how dark “night” is, dusk length) can stay a
1779 world setting or a later tuning value; the invariant is that night uses
1780 baked reachability, not a per-frame raycast.
1781
1782 The world-editor night-to-day slider is the same shading function, driven
1783 by the slider instead of the clock, so an admin can preview a chunk at
1784 any light level without changing live world time.
1785
1786 # 22. Items, inventory and ground drops
1787
1788 ## 22.1 Item definitions
1789
1790 Every obtainable object is an `ItemDefinition`. Stacking, uniqueness and
1791 later economy rules are data on that definition, not special cases in UI
1792 code.
1793
1794 ```text
1795 ItemDefinition
1796 - itemId
1797 - displayName
1798 - description
1799 - seedValue // base price before player-market adaptation
1800 - stackable
1801 - maxStackSize // default 99 for stackable items
1802 - uniqueInstance // true for letters, filled cheques, and similar
1803 - category: ingredient | intermediate | finished | document | other
1804 - npcShopAllowed
1805 - gatherSources
1806 - craftingRecipe(s)
1807 - dropTableSources
1808 - attack?: AttackProfile // weapons; omitted for non-weapons
1809 - equipment?: // worn/wielded visuals; see 21.6
1810 slot
1811 overlaySpriteId
1812 recolourableChannels?
1813 materialId?
1814 ```
1815
1816 A stackable item with no instance data merges with an identical `itemId` in
1817 the same container up to `maxStackSize`. Unique-instance items never merge;
1818 each occupies its own slot at quantity 1.
1819
1820 **Currency is not an inventory item.** Carried money is a numeric `Currency`
1821 balance on the player. Banked money is a numeric balance on that player's
1822 vault. Coins do not occupy inventory slots and cannot be dropped on the
1823 ground in this model.
1824
1825 How most items are obtained is specified later. Two source families already
1826 fit this model without changing it:
1827
1828 - Ground-item spawners in the world editor, analogous to mob spawners.
1829 - Later harvesting from the environment by players.
1830
1831 Paper, blank cheques and letters are specified now because communication,
1832 banking and pigeons depend on them.
1833
1834 ## 22.2 Player inventory
1835
1836 A player inventory has exactly **32 slots**.
1837
1838 ```text
1839 Inventory
1840 - slots[32]: empty | ItemStack
1841
1842 ItemStack
1843 - itemId
1844 - quantity // 1 for unique-instance items
1845 - instance?: ItemInstance // present only when uniqueInstance is true
1846 - origin?: ItemOrigin // crafter or shop NPC; see 22.6
1847 ```
1848
1849 Rules:
1850
1851 - A stack occupies exactly one slot, regardless of quantity.
1852 - Inserting a stackable item first tries to merge into an existing compatible
1853 stack whose combined quantity would not exceed `maxStackSize`. Stacks are
1854 compatible only when `itemId` matches and `origin` matches (including both
1855 being empty). Any remainder needs an empty slot, or the whole action fails.
1856 - Moving, swapping and splitting stacks are ordinary server-validated
1857 commands. The client never asserts the resulting inventory.
1858 - Inventory, wallet and vault contents are **player-private UI state**. They
1859 are not part of 3×3 chunk replication. Other clients see ground items and
1860 pigeon entities, not another player's bags or a pigeon's cargo.
1861 - Logout and restart persist the full inventory and carried currency in
1862 `state.sqlite`.
1863
1864 ## 22.3 Paper and letters
1865
1866 Blank paper is a stackable item.
1867
1868 Writing consumes one paper and produces a **letter**: a unique-instance item
1869 whose instance data is text written by a player. A letter is not a mail
1870 record and has no inherent recipient. It is just paper with writing on it.
1871
1872 ```text
1873 LetterInstance
1874 - letterId
1875 - authorPlayerId
1876 - body
1877 - writtenAt
1878 ```
1879
1880 If the paper stack's quantity is 1, the slot may be converted in place into
1881 the letter. If quantity is greater than 1, writing requires a free inventory
1882 slot for the new letter and decrements the paper stack.
1883
1884 Reading a letter inspects its instance data. Sending a letter is the same
1885 pigeon-cargo action used for any other item stack.
1886
1887 Maximum letter length is a defined game rule and can be chosen during
1888 implementation.
1889
1890 ## 22.4 Dropping items
1891
1892 A player may drop an item stack, or part of a stack, onto their current tile.
1893
1894 ```text
1895 GroundItem
1896 - groundItemId
1897 - tileX / tileY
1898 - ItemStack
1899 - droppedAt
1900 - expiresAt // droppedAt + WorldSettings.groundItemDespawnDuration
1901 - source // player-drop | later: item-spawner
1902 - droppedByPlayerId?
1903 ```
1904
1905 Rules:
1906
1907 - Player-dropped items remain for `WorldSettings.groundItemDespawnDuration`
1908 (default **10 minutes**), then vanish forever.
1909 - Anyone may pick up a ground item. There is no owner lock and no loot-rights
1910 delay.
1911 - Ground items **do not block movement** and do not prevent a player from
1912 standing on that tile.
1913 - Pickup requires the player to **stand on that tile**. The command names the
1914 `groundItemId` when several stacks share the tile.
1915 - Pickup fails if the player's inventory cannot accept the stack (no legal
1916 merge and no empty slot). The ground item is unchanged.
1917 - Several distinct stacks may occupy one tile at once.
1918 - Later naturally spawned ground items use the same non-blocking
1919 representation, but their lifetime and respawn belong to the item spawner
1920 rather than this 10-minute player-drop timer.
1921
1922 Dropped items are not `ChunkLoader`s and do not keep a chunk simulated.
1923
1924 They **do** survive chunk unload until `expiresAt`, using timestamp expiry
1925 rather than a per-tick countdown. On unload, unexpired ground items are
1926 written to `state.sqlite`. On load or wake, items whose `expiresAt` is in
1927 the past are discarded and never replicated. Simulating chunks also remove
1928 them when the timestamp elapses.
1929
1930 If a unique-instance item that encodes a bank reservation (a filled cheque)
1931 expires on the ground or is otherwise destroyed without being redeemed, that
1932 reservation is released and the reserved goods become available in the
1933 issuer's vault again.
1934
1935 ## 22.5 Pickup and drop commands
1936
1937 ```text
1938 DROP_ITEM(slotIndex, quantity?)
1939 PICKUP_ITEM(groundItemId)
1940 ```
1941
1942 Both are intentions. The owning worker validates the actor's tile, inventory
1943 space and stack rules, then applies the result. Standing on a tile that has
1944 ground items does not pick them up automatically.
1945
1946 ## 22.6 Item inspection, origin and displayed value
1947
1948 Hovering an item — in inventory, a shop stock list, or on the ground — shows
1949 at least:
1950
1951 ```text
1952 ItemTooltip
1953 - displayName
1954 - description
1955 - originLabel // who crafted it, or the shop NPC if bought there
1956 - currentValue // undiscounted adapted value; see section 27
1957 ```
1958
1959 Origin is stored on the stack:
1960
1961 ```text
1962 ItemOrigin
1963 - kind: crafted | shop | unknown
1964 - playerId? // when crafted by a player
1965 - npcId? // when bought from a shop NPC
1966 ```
1967
1968 The origin label is the crafting player's name, or the shop NPC's name when
1969 the stack was bought from that NPC. Harvested, looted or otherwise unstamped
1970 stacks use `unknown` and omit the origin line until later content says
1971 otherwise. Buying from a shop stamps that NPC as origin. Crafting stamps the
1972 crafter. Shop-bought goods are not treated as crafted by the NPC; the NPC
1973 name simply occupies that inspection field.
1974
1975 `currentValue` uses the same last-sale lerp as shopkeepers (section 27.6) but
1976 **without** the per-shop discount. It is informational. The client must not
1977 recompute it every simulation tick. The player UI may refresh displayed
1978 values at most once per minute, from the last-sale record plus `seedValue`.
1979 The actual shop purchase price is always computed server-side at the moment
1980 of purchase.
1981
1982 # 23. Player communication and carrier pigeons
1983
1984 ## 23.1 Proximity chat is the default
1985
1986 Ordinary chat is spatial. A player speaks from a world position and only nearby
1987 players receive a useful version of the message. Legibility decreases as the
1988 recipient gets farther from the speaker.
1989
1990 Readability uses Euclidean tile distance against the 16-tile chunk size:
1991
1992 ```text
1993 distance <= 8 tiles // half a chunk: full plaintext
1994 8 < distance < 16 // linear falloff, e.g. 12 tiles → 50% readability
1995 distance >= 16 tiles // a full chunk: 0% readability, no bubble
1996 ```
1997
1998 The speaker always receives their own trimmed plaintext. Other recipients receive
1999 a server-obscured copy: letters and digits may become `.` with probability
2000 `1 - readability`; spaces and punctuation stay. At 0% readability the server
2001 sends nothing, so the client never draws a bubble.
2002
2003 Enter opens a bottom-of-screen line (max `chatMaxCharacters`, default 100).
2004 Enter again trims and sends `CHAT_SAY`. Escape cancels. The client shows
2005 `CHAT_BUBBLE` above the speaker.
2006
2007 For example:
2008
2009 ```text
2010 Near: I'm really far away
2011 Farther: I'm re...y far aw.y
2012 Very far: I'...re..ly..ar.aw.y
2013 Beyond range: no message
2014 ```
2015
2016 Crucially, degradation is performed **server-side**. The server must not send the
2017 full plaintext to a distant client and merely ask that client to obscure it,
2018 because a modified client could then recover speech it was not supposed to
2019 understand.
2020
2021 A chat message therefore conceptually contains:
2022
2023 ```text
2024 ChatSpeech
2025 - messageId
2026 - speakerEntityId
2027 - originX / originY
2028 - createdAt
2029 - text
2030 ```
2031
2032 The communication service performs a spatial recipient query and derives the
2033 recipient-specific legible representation before routing it through the gateway.
2034 Chat routing is separate from normal 3×3 chunk replication, so the eventual
2035 hearing/text range does not have to equal the visual chunk-subscription radius.
2036
2037 ## 23.2 Persistent player groups
2038
2039 Players can create permanent groups and invite other players into them. Groups
2040 are durable social entities stored in `state.sqlite`, with membership surviving
2041 logout and server restart.
2042
2043 A minimal model contains:
2044
2045 ```text
2046 PlayerGroup
2047 - groupId
2048 - name
2049 - owner / roles
2050 - createdAt
2051
2052 PlayerGroupMember
2053 - groupId
2054 - playerId
2055 - role
2056 - joinedAt
2057 ```
2058
2059 Invite, accept, leave, kick and role-management operations are authoritative
2060 server actions.
2061
2062 Group membership does **not** create magical long-distance communication. If
2063 members are close enough, they can communicate through the normal proximity
2064 rules. Communication to distant group members means sending items — including
2065 letters — by carrier pigeon, the same mechanism available to any player.
2066
2067 If group-wide letter sending is later supported, it is an addressing
2068 convenience that still consumes one paper/letter item and one pigeon dispatch
2069 per recipient. The group is not a global instant chat channel.
2070
2071 ## 23.3 Pigeons carry cargo, not messages
2072
2073 A carrier pigeon is a free physical courier. It does not send a chat packet.
2074 It carries **either**:
2075
2076 - an amount of the sender's carried currency, or
2077 - exactly one item stack (a letter, a filled cheque, blank paper, or any
2078 other stack)
2079
2080 One pigeon cannot carry both money and an item, and cannot carry two item
2081 stacks. Dispatching a pigeon is **free**, so a player who wants to move
2082 several stacks sends several pigeons one after another.
2083
2084 Cargo is removed from the sender immediately and placed into durable transit.
2085 A crash or restart cannot duplicate that cargo or silently erase it.
2086
2087 Pigeons are not inventory items. Any player may dispatch one from anywhere,
2088 provided they have valid cargo.
2089
2090 ```text
2091 SendPigeon
2092 - destination: Player(playerId) | Bank
2093 - cargo: Money(amount) | Item(slotIndex, quantity?)
2094 ```
2095
2096 ## 23.4 Destinations
2097
2098 **Player destination.** The pigeon flies toward a character addressed by
2099 **first name and last name**. The sender may type that pair, or pick a
2100 friend from their friends list to fill the same fields. On arrival:
2101
2102 - Money is added to the recipient's carried `Currency` if they are online;
2103 otherwise it is deposited into the recipient's bank.
2104 - An item stack is placed in the recipient's inventory if they are online and
2105 have space (a legal merge or an empty slot). If they are offline or cannot
2106 accept the stack, the pigeon continues to the **nearest bank** and deposits
2107 the stack into the recipient's vault.
2108
2109 This keeps offline and full-inventory delivery durable without a separate
2110 mailbox object.
2111
2112 **Bank destination.** The pigeon flies to the **nearest bank** to the dispatch
2113 tile. Travel time is that aerial journey, even though every bank shares the
2114 same vault. On arrival the cargo is deposited into the **sender's** vault,
2115 except for the filled-cheque special case in section 24.7.
2116
2117 "Nearest bank" is computed from authored Bank block positions in the pinned
2118 world revision. If additional banks are added later, a pigeon sent to `Bank`
2119 still lands at whichever bank is closest to where it was dispatched; the
2120 goods then appear in the shared vault.
2121
2122 ## 23.5 Carrier pigeon transit
2123
2124 A carrier pigeon must take time to cross the world; long-distance item and
2125 currency delivery is intentionally not instantaneous.
2126
2127 Flight speed is world-tunable in three phases (defaults chosen so a pigeon can
2128 overtake a running player):
2129
2130 | Phase | Distance | Default tiles/s | Setting |
2131 |-------|----------|-----------------|---------|
2132 | Takeoff | first `pigeonPhaseTiles` (default 5) | 3 | `pigeonTakeoffTilesPerSec` |
2133 | Cruise | middle of the route | 8 | `pigeonCruiseTilesPerSec` |
2134 | Landing | last `pigeonPhaseTiles` | 3 | `pigeonLandingTilesPerSec` |
2135
2136 At MMO scale, however, every delivery should not keep an entire trail of regions
2137 fully stimulated merely so a pigeon can advance. The recommended model is a
2138 persistent courier transit record with world position/route/progress that can
2139 advance through dormant space using coarse path segments and timestamps.
2140
2141 ```text
2142 CourierTransit
2143 - courierId
2144 - cargo // Money(amount) | ItemStack
2145 - senderPlayerId
2146 - destination // Player(playerId) | Bank
2147 - currentPosition
2148 - route
2149 - speed / timing state
2150 - status
2151 ```
2152
2153 A carrier pigeon is part of the shared physical world, not a private visual
2154 belonging only to its sender or recipient. Whenever its calculated route passes
2155 through a **simulating chunk**, the courier should materialise there as a normal
2156 ECS `Mob` entity, regardless of whether the sender or recipient is nearby. Any
2157 client whose normal 3x3 chunk subscription includes that pigeon receives it like
2158 any other visible mobile entity and can therefore see unrelated pigeons flying
2159 past in the distance.
2160
2161 The visible pigeon does **not** receive `ChunkLoader`. It exists because the chunk
2162 is already simulating for some other reason. If it leaves the last relevant
2163 simulating chunk, its exact position/progress is folded back into the durable
2164 `CourierTransit` record and the ECS instance can disappear while the journey
2165 continues abstractly. If a dormant/unloaded part of its route later becomes
2166 simulated while the pigeon should currently be inside it, the owning worker
2167 materialises the pigeon at the position implied by the transit clock and route.
2168
2169 ```text
2170 Dormant route Simulating chunk Dormant route
2171
2172 abstract transit --------> ECS pigeon visible to clients --------> abstract transit
2173 | | |
2174 Player A Player B unrelated observer
2175 ```
2176
2177 This means a player standing halfway between sender and recipient can see the
2178 pigeon fly through their area even though the cargo has nothing to do with
2179 them. Unrelated clients receive the pigeon entity, not the cargo contents. It
2180 preserves the sense that deliveries physically cross the world without
2181 requiring thousands of deliveries to become thousands of permanent
2182 `ChunkLoader`s.
2183
2184 Because pigeons fly rather than use the ground navigation grid, their coarse
2185 route can initially be represented by direct or waypoint-based aerial segments.
2186 This makes deterministic materialisation from route + elapsed time considerably
2187 simpler than it would be for a ground-based courier.
2188
2189 If future gameplay allows pigeons to be intercepted, killed or rerouted anywhere
2190 along their journey, the transit model can be made progressively more detailed;
2191 that interaction is not required by the initial courier design.
2192
2193 ## 23.6 Courier service
2194
2195 A dedicated `CourierService` should own durable cargo and delivery state.
2196 Simulation workers may own visible pigeon entities while the service owns the
2197 durable fact that a delivery exists.
2198
2199 ```text
2200 Player action -> CourierService -> durable cargo/transit
2201 |
2202 +-> visible pigeon when needed
2203 |
2204 +-> inventory, wallet or BankService deposit
2205 ```
2206
2207 This separation is also useful for marketplace settlement, which uses the same
2208 carrier-pigeon delivery infrastructure for remote counterparties.
2209
2210 ## 23.7 Character friends
2211
2212 Friendships are **character-to-character**, stored in `state.sqlite`. They
2213 are not account-wide. A hovering client shows only the nearby character's
2214 **first name**. Clicking that character opens an inspect modal with first
2215 and last name and a friend-request action.
2216
2217 A friend request must be accepted (or a reverse request counts as accept).
2218 Either character may remove the friendship; it then disappears for both.
2219 Incoming and outgoing requests and the friends list are shown in a Friends
2220 panel. Deleting a character clears its requests and friendships.
2221
2222 The friends list is an addressing book for later pigeon dispatch: pick a
2223 friend to fill first and last name, or type a name pair that the server
2224 resolves.
2225
2226 ```text
2227 FriendRequest
2228 - fromCharacterId
2229 - toCharacterId
2230 - createdAt
2231
2232 Friendship
2233 - characterIdA // min(id1, id2)
2234 - characterIdB // max(id1, id2)
2235 - createdAt
2236 ```
2237
2238 # 24. Bank, cheques and shared vaults
2239
2240 ## 24.1 Bank location and access
2241
2242 A bank exists at or near the central marketplace as an authored Bank block.
2243 Deposit, withdraw, cheque issue and in-person cheque redemption require
2244 server-validated access to a bank interaction; the bank is not a global menu
2245 usable from anywhere.
2246
2247 Pigeon dispatch to `Bank` is the exception: that command may be issued from
2248 anywhere, and the goods become available only after the pigeon arrives.
2249
2250 ## 24.2 One shared vault
2251
2252 Each **character** has a single vault in `state.sqlite`:
2253
2254 ```text
2255 CharacterVault
2256 - characterId
2257 - bankedCurrency
2258 - stacks[]
2259 - reservations[]
2260 ```
2261
2262 Capacity is unlimited: there is no slot cap. Per-stack stacking rules still
2263 apply (`maxStackSize`; unique instances never merge), so 200 blank paper is
2264 stored as 99 + 99 + 2 rather than one unbounded pile.
2265
2266 If more banks are authored later, **all banks are linked**. Withdrawing at
2267 bank B can retrieve goods deposited at bank A. The vault is not per-branch.
2268
2269 Pigeon deposits affect *when* goods become available, not *which* vault they
2270 enter. After the pigeon arrives at the nearest bank, the goods appear in the
2271 same shared vault accessible from every bank.
2272
2273 ## 24.3 Deposit and withdraw
2274
2275 While interacting with a bank, a player may:
2276
2277 - Deposit any carried currency and any inventory stacks, in whole or in part.
2278 - Withdraw currency into the carried wallet.
2279 - Withdraw an item stack, or part of a stack, into inventory, subject to the
2280 32-slot and merge rules.
2281 - Claim items or currency from the account **inheritance tab** into this
2282 character's vault (section 24.9).
2283
2284 Goods reserved by an outstanding filled cheque cannot be withdrawn by the
2285 issuer until that cheque is redeemed or voided.
2286
2287 ## 24.4 Blank cheques
2288
2289 A player at a bank may request blank cheques.
2290
2291 - Blank cheques are a stackable item with `maxStackSize` 99.
2292 - The bank counts blank cheques already in the player's **inventory** (not
2293 the vault) and issues only enough to bring that total to 99.
2294 - If the player already holds 99, the bank issues none.
2295 - Issued cheques go into inventory, merging into an existing blank-cheque
2296 stack when possible. If the player holds none and has no empty slot, the
2297 request fails.
2298
2299 The bank will not issue more than 99 blank cheques into inventory, even on
2300 repeated requests.
2301
2302 ## 24.5 Filling a cheque
2303
2304 Using a blank cheque at a bank lets the issuer pick vault goods and a
2305 **quantity**. For stackable items they choose an `itemId` and quantity; the
2306 quantity may be larger than one `maxStackSize`, and the reservation covers
2307 that many available (unreserved) items of that type in the vault. For
2308 unique-instance items they choose that exact instance and the quantity is 1.
2309
2310 ```text
2311 FilledChequeInstance
2312 - chequeId
2313 - issuerPlayerId
2314 - itemId
2315 - quantity
2316 - instance?: ItemInstance // set when the reserved goods are unique
2317 - createdAt
2318 ```
2319
2320 Filling:
2321
2322 1. Validates that the vault has at least `quantity` of that item available
2323 (not already reserved). Unique instances must still be present and unreserved.
2324 2. Reserves those goods in the issuer's vault. Reserved goods cannot be
2325 withdrawn, sold or reserved again.
2326 3. Consumes one blank cheque. If that was the last cheque in the slot, the
2327 slot becomes the filled cheque in place; otherwise a free slot is required
2328 for the filled cheque.
2329
2330 A filled cheque is a unique-instance **bearer** item. It does not stack.
2331 Whoever holds it may redeem it. Cheques specify vault items and a quantity,
2332 not carried currency. Money is moved with a pigeon, or by depositing and
2333 withdrawing at a bank.
2334
2335 ## 24.6 Redeeming a cheque in person
2336
2337 The bearer interacts with any bank and redeems the filled cheque.
2338
2339 - The server moves the reserved goods from the **issuer's** vault into the
2340 **bearer's inventory**, subject to inventory space. A quantity larger than
2341 `maxStackSize` becomes as many stacks as needed.
2342 - The cheque item is consumed.
2343 - If inventory cannot accept the resulting stacks, redemption fails and both
2344 cheque and reservation remain unchanged.
2345
2346 The bearer may then deposit those goods into their own vault if they wish.
2347
2348 ## 24.7 Redeeming a cheque by pigeon
2349
2350 If the bearer dispatches a pigeon whose cargo is a filled cheque and whose
2351 destination is `Bank`:
2352
2353 - The pigeon flies to the nearest bank from the dispatch tile.
2354 - On arrival, `BankService` transfers the reserved goods from the **issuer's**
2355 vault into the **pigeon's sender's** vault.
2356 - The cheque is consumed in transit; it is not deposited as an item.
2357
2358 The receiver of the transfer is whoever sent that pigeon, not the original
2359 cheque issuer. This is how a cheque moves goods from one vault to another
2360 without the receiver standing at a bank.
2361
2362 Sending a filled cheque to a **player** delivers the cheque item itself (or
2363 into that player's bank if they cannot hold it). It does not redeem it.
2364
2365 ## 24.8 Bank service
2366
2367 Vault mutation, cheque issue, reservation, in-person redemption and
2368 pigeon-arrival deposits are owned by a single authoritative `BankService`
2369 (or an equivalently serialised service) so two concurrent withdrawals,
2370 cheque fills or pigeon arrivals cannot double-spend the same goods.
2371
2372 ```text
2373 Bank interaction or pigeon arrival
2374 |
2375 v
2376 BankService
2377 - shared vault
2378 - reservations
2379 - cheque issue / redeem
2380 |
2381 +-> inventory / currency on the acting player when in person
2382 |
2383 +-> vault credit on pigeon arrival
2384 ```
2385
2386 Cheque identifiers are server-issued. A client cannot forge a claim against
2387 another player's vault.
2388
2389 ## 24.9 Inheritance bank tab
2390
2391 Each **account** has one inheritance tab, separate from every character
2392 vault:
2393
2394 ```text
2395 AccountInheritance
2396 - accountId
2397 - currency
2398 - stacks[]
2399 ```
2400
2401 It is written only when a character of that account is permanently deleted
2402 (section 14.6). Any of that player's living characters can move stacks and
2403 currency from this tab into their own vault at a bank. They cannot deposit
2404 into inheritance except through character deletion.
2405
2406 # 25. Central marketplace and order matching
2407
2408 ## 25.1 Marketplace location
2409
2410 A central marketplace exists at or near the centre of the game world. Creating,
2411 modifying or cancelling market orders requires server-validated access to the
2412 marketplace interaction; the marketplace is not intended to be a global menu
2413 that can be used from anywhere.
2414
2415 Orders themselves remain durable after the player leaves the marketplace or
2416 logs out.
2417
2418 ## 25.2 No public list of sell orders
2419
2420 The market is an order book, but players do not browse a list of individual
2421 items currently offered for sale.
2422
2423 A seller submits:
2424
2425 ```text
2426 SellOrder
2427 - item / item definition
2428 - quantity
2429 - minimum unit/total price
2430 ```
2431
2432 A buyer submits:
2433
2434 ```text
2435 BuyOrder
2436 - requested item / matching criteria
2437 - quantity
2438 - maximum unit/total price
2439 ```
2440
2441 The UI may know which item types exist and may eventually show historical data,
2442 but it does not expose the live asks in a way that lets a buyer simply pick a
2443 listed seller.
2444
2445 ## 25.3 Escrow
2446
2447 Market orders escrow the asset required to honour them. Escrow is taken from
2448 carried inventory and carried currency. The marketplace sits next to the bank,
2449 so a player can withdraw from the vault immediately before placing an order.
2450
2451 - Creating a sell order removes/reserves the offered item stack from the
2452 seller's inventory.
2453 - Creating a buy order removes/reserves the buyer's maximum offered currency.
2454 - Cancelling an unmatched order returns the escrowed asset through the defined
2455 settlement/delivery rules.
2456
2457 This prevents double spending, selling the same item twice, or a buyer spending
2458 currency after placing a bid.
2459
2460 ## 25.4 Matching rules
2461
2462 A buy and sell order match when:
2463
2464 ```text
2465 buyerMaximum >= sellerMinimum
2466 ```
2467
2468 Sell orders are considered cheapest first. Within the same minimum price, a
2469 stable creation sequence/FIFO rule should be used unless later game rules choose
2470 otherwise.
2471
2472 For a symmetric order book, buy orders are naturally prioritised by highest
2473 maximum bid and then oldest sequence. This means a newly submitted sell order
2474 matches the best compatible existing bid, while a newly submitted buy order
2475 matches the cheapest compatible existing ask.
2476
2477 The trade price is exactly the midpoint between the two limits:
2478
2479 ```text
2480 tradePrice = midpoint(buyerMaximum, sellerMinimum)
2481 ```
2482
2483 Example:
2484
2485 ```text
2486 Seller minimum: 80
2487 Buyer maximum: 100
2488 Trade price: 90
2489 ```
2490
2491 The exact rounding rule when integer currency produces a half-unit midpoint is a
2492 defined-but-still-open game rule and must be deterministic.
2493
2494 ## 25.5 Immediate side versus pigeon side
2495
2496 The order that is submitted last is the order that triggers the match.
2497
2498 The player who submitted that matching order receives the acquired asset
2499 immediately because they are currently present at the marketplace interaction
2500 (item stack into inventory, or currency into the carried wallet). The
2501 pre-existing counterparty receives their acquired item or currency through a
2502 carrier pigeon whose destination is `Bank`, landing at the nearest bank to the
2503 marketplace. On arrival the settlement is deposited into that counterparty's
2504 shared vault. This remains valid if they are offline.
2505
2506 ```text
2507 Existing sell + new matching buy
2508 -> new buyer receives item immediately
2509 -> existing seller receives payment by pigeon to bank
2510
2511 Existing buy + new matching sell
2512 -> new seller receives payment immediately
2513 -> existing buyer receives item by pigeon to bank
2514 ```
2515
2516 If a trade requires more than one item stack (for example a quantity that does
2517 not fit in a single `maxStackSize`), the older counterparty receives as many
2518 free sequential pigeons as needed. Each pigeon still carries only one stack or
2519 only currency.
2520
2521 Any unused part of buy-order currency escrow caused by the midpoint price is
2522 returned immediately to the triggering player when they are the buyer, and
2523 returned by the settlement pigeon into the older counterparty's vault when
2524 they were the buyer.
2525
2526 ## 25.6 Market service and atomicity
2527
2528 Marketplace matching should not live inside an arbitrary region worker. Use a
2529 single authoritative `MarketService` (or an equivalently serialised partitioned
2530 service later) so two simultaneous orders cannot both consume the same escrow.
2531
2532 Order insertion, matching, escrow movement and creation of the resulting
2533 settlement deliveries are committed atomically in `state.sqlite`.
2534
2535 Conceptually:
2536
2537 ```text
2538 Marketplace interaction
2539 |
2540 v
2541 MarketService
2542 - durable order book
2543 - escrow
2544 - deterministic matching
2545 - trade record
2546 |
2547 +-> immediate settlement to triggering player's inventory or wallet
2548 |
2549 +-> CourierService pigeon to Bank for the older counterparty
2550 |
2551 +-> last-sale index update for that itemId
2552 ```
2553
2554 The system should also retain an immutable trade record for auditing and recovery.
2555
2556 ## 25.7 Last player-market sale per item
2557
2558 Each successful player-market match updates a single durable record for that
2559 `itemId`. There is no price history series — only the latest sale:
2560
2561 ```text
2562 ItemLastMarketSale
2563 - itemId
2564 - lastTradePrice // unit price of that match (the midpoint)
2565 - lastTradeAt
2566 - priceFrom // evaluated undiscounted value at lastTradeAt
2567 ```
2568
2569 `priceFrom` is not a history log. It is the lerp origin captured at the
2570 moment of this sale so the displayed price does not jump back to seed when
2571 a new trade occurs:
2572
2573 1. Evaluate the current undiscounted value at `now` using the previous
2574 last-sale record (or `seedValue` if none exists).
2575 2. Store that value as `priceFrom`, store the new trade's unit price as
2576 `lastTradePrice`, and store `now` as `lastTradeAt`.
2577
2578 Shopkeepers and item tooltips both read this record. They do not tick it;
2579 they evaluate it from timestamps when a shop is opened, a purchase is
2580 attempted, or a tooltip refresh is requested.
2581
2582 # 26. Combat
2583
2584 ## 26.1 Every combatant can attack
2585
2586 Players, enemies, animals and any other mobile with a `Combat` component can
2587 attack. Shopkeepers and other non-fighting NPCs omit `Combat`, or never issue
2588 attack commands. Courier **pigeons** are **untargetable**: they have no `Combat`
2589 component and cannot be selected for Attack, Talk, or spells. They are not
2590 ambient wildlife; the courier/mail system spawns them for player↔player or
2591 player↔bank delivery and they fly in straight world-space lines.
2592
2593 Attacking is an intention. The client (or AI) sends `ATTACK(targetEntityId)`.
2594 The owning worker validates range, line of sight when required, the current
2595 attack profile and cooldown, then resolves hit and damage authoritatively.
2596 The client never supplies a hit result or a damage number.
2597
2598 `CANCEL_ATTACK` clears the actor's engage target. Cross-worker attacks use
2599 `REMOTE_ACTION(attack intent)` so the worker that owns the target applies the
2600 authoritative result.
2601
2602 ## 26.1b Client targeting and context menus
2603
2604 | Input | Target | Action |
2605 |-------|--------|--------|
2606 | LMB | other player | inspect (existing social UI) |
2607 | LMB | talkable friendly mob | `INTERACT` / open dialogue (shop content later) |
2608 | LMB | hostile combatant | `ATTACK` (auto-engage) |
2609 | LMB | ground / empty | `MOVE_TO` that tile (or pickup/bank as today) |
2610 | RMB | other player | Walk here · Follow · `<name> info` · Attack |
2611 | RMB | mob | Walk here · Follow · Talk (if talkable) · Attack |
2612 | Any | untargetable (pigeon) | Follow allowed; no Attack/Talk |
2613
2614 Walk here issues `MOVE_TO` for the entity's tile (or the tile under the cursor
2615 when RMB is on empty ground).
2616
2617 ## 26.1b2 Follow
2618
2619 `FOLLOW(targetEntityId)` makes the actor trail another mobile. No line of
2620 sight is required. Follow works on every mobile (players, wildlife, pigeons).
2621
2622 | Chebyshev distance | Behaviour |
2623 |--------------------|-----------|
2624 | ≤ 1 | Stay put (already in good position) |
2625 | 2–3 | Follow the target's vacated trail and remaining path; walk, or run if the target is running |
2626 | > 3 and ≤ chunk width (16) | Same route reuse, always run |
2627 | > chunk width | Break follow |
2628
2629 The follower reuses the target's path instead of independent A* once a trail
2630 exists: each time the target leaves a tile that tile is appended to the
2631 follower trail, combined with the target's remaining `path.tiles`. The
2632 follower stops one tile short of the target's current tile and waits until
2633 that tile is vacated; every step still checks walkability. If there is no
2634 shared trail yet, a one-shot catch-up path to an 8-neighbour is used.
2635
2636 `MOVE_TO` and `ATTACK` clear follow. `CANCEL_FOLLOW` clears it explicitly.
2637
2638 ## 26.1c Auto-attack and retaliation
2639
2640 Engaging sets `Combat.targetEntityId`. The weapon supplies a single
2641 `AttackProfile` that repeats until cancel, death, or the target leaves
2642 reachable range (then re-path / re-close).
2643
2644 `ATTACK` engages **only the attacker**. A fightable target **retaliates on the
2645 first resolved melee swing** against it (hit, miss, or block) — not when the
2646 player merely clicks Attack or begins pathing. Peaceful NPCs without combat
2647 (`canFight: false`) do not retaliate.
2648
2649 **Aggressive** mobs (`aggressive: true`, optional `aggroRangeTiles`, default 5)
2650 additionally auto-engage the nearest living player character within Chebyshev
2651 range when they have line of sight through enterable tiles (same occlusion
2652 rule as lighting rays: intermediate tiles must be enterable). Passive does not
2653 override an existing engage target.
2654
2655 - **Melee:** pathfind to an 8-neighbour tile, swing when Chebyshev distance is
2656 exactly 1.
2657 - **Ranged:** pathfind until Chebyshev distance ≤ `rangeTiles`, then fire.
2658 Requires line of sight through passable tiles (same obstruction rule as
2659 baked light).
2660 - **Magic:** not a default auto-attack. The player opens a spell menu, picks a
2661 known spell, then clicks a target. Utility spells cast once; attack spells
2662 repeat like weapon auto-attack. Full spell targeting (tiles, blocks, ground
2663 items) is a later batch.
2664
2665 ## 26.2 Attack profiles
2666
2667 The current attack comes from the weapon slot's `AttackProfile`, a selected
2668 spell, or a default unarmed melee profile when nothing is wielded.
2669
2670 ```text
2671 AttackProfile
2672 - mode: melee | ranged | magic
2673 - rangeTiles // melee is always 1
2674 - hitSkillId
2675 - damageSkillId
2676 - cooldownMs
2677 - baseDamage
2678 ```
2679
2680 ```text
2681 SpellDefinition (content; full cast UI later)
2682 - spellId
2683 - displayName
2684 - minSkillLevel
2685 - AttackProfile // mode = magic
2686 - castKind: utility | attack
2687 ```
2688
2689 A single **spellbook** item type carries one chosen `spellId` in its instance
2690 config (shop, drop, or spawner). If the character's Magic skill meets
2691 `minSkillLevel`, using the book teaches the spell and consumes the book.
2692
2693 Typical weapon mappings:
2694
2695 ```text
2696 Stick/club -> melee, range 1, hit Clubfighting, damage Strength
2697 Sword -> melee, range 1, hit Swordfighting, damage Strength
2698 Bow -> ranged, range from item, hit Archery, damage Dexterity
2699 Spell -> magic, range from spell, hit Magic, damage Mind
2700 Unarmed -> melee, range 1, hit Unarmed, damage Strength
2701 ```
2702
2703 ## 26.3 Melee range
2704
2705 A melee attack is legal only on one of the eight tiles surrounding the
2706 target (Chebyshev distance exactly 1). Same-tile melee is illegal.
2707
2708 ## 26.4 Ranged attacks, spells and LOS
2709
2710 Maximum Chebyshev distance is `rangeTiles`. Distance 0 is not legal unless a
2711 later exception is defined. Ranged and magic require line of sight: a ray
2712 through tile centres fails if it crosses an impassable block (same rule as
2713 baked lighting).
2714
2715 ## 26.4b Presentation: swipe, projectiles, dynamic lights
2716
2717 - **Melee:** clients draw a swipe sprite for ~0.5s between attacker and
2718 defender, rotated toward the defender, on `COMBAT_SWING`.
2719 - **Ranged / spell:** straight-line world-space projectiles (not grid steps)
2720 toward the defender tile or a miss tile beside it. Spell projectiles may
2721 use a `-bloom` companion.
2722 - **Dynamic lights (client-only):** short flashes on cast/hit; equipment with
2723 `lightRadiusTiles` (e.g. lantern) as a moving point light. Per-tile shade
2724 blends `max(bakedNightShade, dynamicContribution)`.
2725
2726 ## 26.5–26.8 Hit, damage, XP, mob stats
2727
2728 Hit chance uses the profile's hit skill (server RNG). Damage uses Strength
2729 (melee), Dexterity (ranged), or Mind (magic). Player hit XP splits equally
2730 between hit and damage skills. Mobs use archetype skill levels and do not
2731 earn XP.
2732
2733 ```text
2734 MobDefinition
2735 - hostile / talkable / untargetable / freeFlight / flying
2736 - skillLevels, defaultAttack
2737 - Combat omitted when untargetable or peaceful non-fighter
2738 ```
2739
2740 Courier **pigeons** use free-flight: straight-line world motion between
2741 delivery endpoints, no pathfinding, not bound to the navigation grid, and
2742 untargetable for all attacks and spells. They are not ambient fauna.
2743
2744 # 27. Player-driven economy and skill progression
2745
2746 ## 27.1 Item-source philosophy
2747
2748 The economy is intentionally player-driven.
2749
2750 Normal NPC shops should sell only basic ingredients. The vast majority of
2751 materials are gathered directly from the world by players. Finished goods are
2752 normally produced by player crafting/professions.
2753
2754 The only normal non-player source of finished items is enemy or boss loot.
2755
2756 This gives four broad source paths, with ground-item spawners as an additional
2757 early world source once content defines them:
2758
2759 ```text
2760 World gathering / harvesting -> ingredients
2761 Ground-item spawners --------> some world items, later specified
2762 Basic NPC shops -------------> limited basic ingredients
2763 Player production -----------> intermediate/final products
2764 Enemies and bosses ----------> loot, including possible finished items
2765 ```
2766
2767 Stacking, unique instances, letters and cheques are defined in section 22.
2768 Economy-facing fields remain on the same `ItemDefinition`:
2769
2770 ```text
2771 ItemDefinition
2772 - itemId
2773 - displayName / description / seedValue
2774 - stackable / maxStackSize / uniqueInstance
2775 - category: ingredient | intermediate | finished | document | other
2776 - npcShopAllowed
2777 - gatherSources
2778 - craftingRecipe(s)
2779 - dropTableSources
2780 - attack?: AttackProfile
2781 - equipment?: slot / overlaySpriteId / recolourableChannels / materialId
2782 ```
2783
2784 Content validation can then reject an ordinary shop inventory that accidentally
2785 contains a finished product unless explicitly permitted by a future exception.
2786
2787 ## 27.2 No player classes
2788
2789 Players do not choose a class. Capabilities and progression come from independent
2790 skills.
2791
2792 Examples include:
2793
2794 - Swordfighting, Axefighting, Archery, Magic, Unarmed
2795 - Strength, Dexterity, Mind
2796 - Defence
2797 - Lumbering
2798 - Fishing
2799 - Smithing
2800
2801 The final skill list is game content and is not limited to skills found in any
2802 particular inspiration game.
2803
2804 ## 27.3 Skill state
2805
2806 Skill progression is persistent player state.
2807
2808 ```text
2809 SkillProgress
2810 - skillId
2811 - xp
2812 ```
2813
2814 Level should preferably be derived from XP and the skill's level curve rather
2815 than stored as an independent source of truth, although it may be cached.
2816
2817 ```text
2818 SkillDefinition
2819 - skillId
2820 - displayName
2821 - levelCurve
2822 - maxLevel (if any)
2823 ```
2824
2825 ## 27.4 Actions are governed by skills
2826
2827 Every gameplay action that participates in progression is associated with a
2828 governing skill. Combat attacks are the explicit exception: they have a hit
2829 skill and a damage skill, and split XP equally between them (section 26.7).
2830
2831 ```text
2832 ActionDefinition
2833 - actionId
2834 - governingSkillId
2835 - requiredLevel
2836 - xpAward / xpFormula
2837 - other requirements
2838 ```
2839
2840 Examples:
2841
2842 ```text
2843 Cut tree -> Lumbering
2844 Catch fish -> Fishing
2845 Forge sword -> Smithing
2846 Sword hit -> Swordfighting + Strength (equal split)
2847 Bow hit -> Archery + Dexterity (equal split)
2848 Spell hit -> Magic + Mind (equal split)
2849 Defensive act -> Defence
2850 ```
2851
2852 The server validates the action, performs the authoritative outcome, and then
2853 awards XP according to the action result. A client cannot claim XP independently.
2854
2855 ## 27.5 Skills replace class restrictions
2856
2857 Equipment, recipes, actions, gathering nodes and other content may require skill
2858 levels, but there is no permanent class gate. A player can train any combination
2859 of skills over time.
2860
2861 This also fits the future scripting model: scripts issue normal actions, and
2862 successful scripted actions use exactly the same skill checks and XP rules as
2863 manual player actions.
2864
2865 ## 27.6 NPC shops and market-adapted prices
2866
2867 Named shop NPCs can sell items to players. They are not the player marketplace
2868 and they do not expose live sell orders. A shop interaction requires being at
2869 that NPC.
2870
2871 Stock remains constrained by `npcShopAllowed` and the ingredient-only rule in
2872 27.1. Each shop NPC has a hidden discount that players never see:
2873
2874 ```text
2875 ShopNpc
2876 - npcId
2877 - hiddenDiscount // multiplier, e.g. 0.9; not shown to clients
2878 - stock[] // itemIds this NPC sells
2879 ```
2880
2881 Until an `itemId` has a player-market last-sale record, the undiscounted
2882 value is `seedValue` from the item definition.
2883
2884 When a last-sale record exists, both tooltips and shops evaluate a timestamp
2885 lerp that does not require a per-tick update:
2886
2887 ```text
2888 t = min(1, (now - lastTradeAt) / WorldSettings.shopPriceLerpDuration)
2889 undiscounted = lerp(priceFrom, lastTradePrice, t)
2890 shopPrice = undiscounted * thatNpc.hiddenDiscount
2891 ```
2892
2893 `lerp(a, b, t) = a + (b - a) * t`. After the configured lerp duration
2894 (default one hour), `t` is capped at 100% and the value rests on the last
2895 player-market unit price (times discount, for shops) until another
2896 player-market sale occurs.
2897
2898 A new player-market sale captures the then-current `undiscounted` value as
2899 `priceFrom` (section 25.7), so the lerp restarts toward the new last price
2900 without jumping back to seed.
2901
2902 Integer currency must be rounded deterministically at evaluation time. Shop
2903 purchase price is computed on the server at the instant of `BuyFromShop`.
2904 Displayed tooltip value is the undiscounted figure and may be refreshed at
2905 most once per minute (section 22.6).
2906
2907 Buying from a shop removes the listed price from the player's carried
2908 currency, puts the stack in inventory subject to the 32-slot rules, and
2909 stamps `ItemOrigin.kind = shop` with that NPC. Shops in this model sell to
2910 players; they do not buy player goods unless a later iteration adds that.
2911
2912 # 28. Suggested implementation phases
2913
2914 ## Phase 1 — Single-worker playable core
2915
2916 - World coordinate helpers, 16×16 chunks and 4×4-chunk regions.
2917
2918 - Ground/block tile model and chunk spatial occupancy.
2919
2920 - Basic ECS and fixed simulation tick.
2921
2922 - ChunkLoader reference counting and sleeping/unloading.
2923
2924 - Isolated simulation workers behind a clone-on-boundary protocol
2925 (in-process default; `worker_threads` optional).
2926
2927 - world.sqlite read path and state.sqlite persistence service.
2928
2929 - Admin world editor: chunk navigation, open/closed flag, default grass for
2930 unsaved chunks, ground/block paint, light-emitting blocks, baked
2931 cross-chunk light maps, night-to-day preview slider, world settings modal
2932 with live apply and a settings edit log, per-chunk changelog, chunk save
2933 to pending revision.
2934
2935 - SpawnerSystem for at least one non-persistent mob archetype.
2936
2937 - WebSocket gateway, stub `admin-<n>` auth until auth.timfalken.com,
2938 character create/select/delete, authoritative command queue and 3×3 chunk
2939 replication.
2940
2941 - Click-to-move with server-side A\*, global walk/run cadence (default 2
2942 tiles/s walk, run every movement tick, walk every other), and `SetGait`.
2943
2944 - FrameworkV3 git submodule at `client/frameworkv3`, built first, then a
2945 game-specific client on top of it with 16×16 sprites, load-time and CI
2946 rejection of wrong-sized art (including equipment overlays and recolour
2947 masks), layered worn equipment with material recolouring, a
2948 player-centered viewport with bounded zoom, client-only lerp of
2949 tile-to-tile movement, and night shading from baked light maps.
2950
2951 - 32-slot player inventory, stack merging, drop/pickup, and 10-minute
2952 non-blocking ground items.
2953
2954 - Paper items that can be written into unique letter items.
2955
2956 - Basic proximity chat with server-side distance degradation.
2957
2958 - Persistent player skill state, including Strength, Dexterity and Mind, and
2959 at least a small initial set of skill-governed actions.
2960
2961 - Melee and ranged/spell attack validation (8-tile melee adjacency, item/spell
2962 range), server-side hit rolls, damage from the matching damage skill, and
2963 equal XP split on a successful player hit.
2964
2965 - Graceful forced-unload shutdown.
2966
2967 ## Phase 2 — Operations and live deployment
2968
2969 - RestartScheduler and player-visible scheduled restart state.
2970
2971 - origin/master change detection.
2972
2973 - `systemd` service supervision and conditional deployment hook.
2974
2975 - World-revision activation on restart.
2976
2977 - Admin immediate restart.
2978
2979 - Migration, backup and startup readiness checks.
2980
2981 ## Phase 3 — Multi-worker world
2982
2983 - Multiple isolated simulation workers and neighbour-sticky region ownership
2984 (shipped); dynamic load rebalance remains.
2985
2986 - Cross-worker entity transfers (shipped).
2987
2988 - Border ghosts for occupancy/pathfinding (shipped); remote combat actions remain.
2989
2990 - Gateway subscriptions spanning multiple workers (shipped).
2991
2992 - Load metrics and neighbour-aware region balancing remain.
2993
2994 ## Phase 4 — World depth, social systems and economy
2995
2996 - Persistent named NPCs and other persistent mob archetypes.
2997
2998 - Spawner persistent-instance index and duplicate prevention.
2999
3000 - Optional durable gameplay chunk overrides, written only on unload.
3001
3002 - Hierarchical pathfinding if long-distance autonomous travel needs it.
3003
3004 - Persistent player groups and invitations.
3005
3006 - Carrier-pigeon cargo transit: free dispatch, money or one item stack,
3007 player or nearest-bank destinations, including offline/full-inventory
3008 fallback to the recipient vault.
3009
3010 - Shared unlimited **character** bank near the marketplace, account
3011 inheritance tab on character delete, blank cheques filled to 99, reserved
3012 filled cheques, in-person redemption and pigeon-to-bank cheque transfers.
3013
3014 - Central marketplace, escrow, deterministic order matching, pigeon-to-bank
3015 settlement for the older counterparty, and a per-item last-sale record for
3016 shop/tooltip adaptation.
3017
3018 - NPC shops that sell `npcShopAllowed` stock at seed value lerped toward the
3019 last player-market price over `shopPriceLerpDuration`, with a hidden per-shop discount.
3020
3021 - Item inspection: name, description, origin (crafter or shop NPC) and
3022 undiscounted current value, refreshed at most once per minute.
3023
3024 - Player crafting/gathering economy rules and shop-content validation.
3025
3026 - Broader skill catalogue, progression curves and skill-gated content.
3027
3028 ## Phase 5 — Player scripting
3029
3030 - Custom language grammar/compiler/interpreter.
3031
3032 - ScriptController and event API.
3033
3034 - CPU/memory/query quotas and sandboxing.
3035
3036 - Online scripted control mode.
3037
3038 - Offline retained player entities with expiry and ChunkLoader
3039 behaviour.
3040
3041 - Persisted/restart-safe script state.
3042
3043 # 29. Core invariants
3044
3045 | **Invariant** | **Rule** |
3046 |------------------------|--------------------------------------------------------------------------------------------------------|
3047 | Server authority | Clients send intent; the server computes and owns outcomes. |
3048 | Region ownership | Exactly one simulation worker authoritatively owns a region. |
3049 | Entity ownership | Exactly one worker authoritatively owns an entity. |
3050 | Remote mutation | Workers never directly mutate remote authoritative state. |
3051 | Spatial separation | Region residency, chunk simulation and client visibility remain distinct. |
3052 | Persistence separation | Persistent and ChunkLoader are independent entity traits. |
3053 | Chunk persistence | Normal dirty chunk state is written on unload, not periodically. |
3054 | World authoring | Editor changes create pending authored state; the running server stays pinned to its startup revision. Each chunk save appends an admin-attributed diff changelog. |
3055 | Restart path | Planned restart force-unloads the world and reuses the ordinary unload save path. |
3056 | Control | Human and future scripted control both emit validated action commands. |
3057 | Deployment | The game exits gracefully; systemd relaunches it and only pulls/builds when an intentional deployment manifest requests it. |
3058 | Client architecture | FrameworkV3 is a git submodule under `client/frameworkv3`, built before game client code; backend ECS internals do not become the client object model. |
3059 | Sprites | World sprites may be any size. Pivot is horizontal centre and 8px from the sprite bottom, on the tile centre. Ground/block types load visual states from a per-type folder (first alphabetical PNG is default). Sheets use `frames`, `framesPerRow`, `animationSpeed`. Blocks and mobiles Y-sort north-behind-south. |
3060 | Appearance | Visible gear is layered 16×16 overlays on the mob; recolourable channels (such as metal) use material colour without duplicate art sets. Nearby clients receive appearance layers, not another player's inventory. |
3061 | Play camera | The play viewport is centered on the local player. Only the admin world editor uses a free chunk camera. |
3062 | Movement | All ground mobiles share a global walk/run cadence from world settings; the server commits integer tiles; clients lerp for presentation only. |
3063 | World time | World calendar time is server time minus 1200 years. Night darkens tiles the baked light map cannot reach. |
3064 | World settings | Tick timers and global constants (including night darkness) are authored in the editor modal, applied immediately on save, and recorded in a settings edit log. Chunk map data remains revision-pinned. |
3065 | Baked light | Static light reach is raycast through passable tiles on chunk save, may cross chunks, and is not recomputed every tick. |
3066 | Ground items | Player drops last `groundItemDespawnDuration` (default 10 minutes), block nobody, and are picked up only by a player standing on that tile. |
3067 | Shop prices | NPC shop prices lerp from the captured pre-sale value toward the last player-market unit price over `shopPriceLerpDuration` (default one hour), times a hidden per-shop discount. |
3068 | Proximity speech | Distant clients never receive unobscured plaintext that game rules say they cannot understand. |
3069 | Courier cargo | Pigeons carry money or one item stack, never a chat packet; cargo is durable in transit and remains delayed. |
3070 | Inventory | A player has 32 slots; a stack occupies one slot; the client never asserts inventory, wallet or vault results. |
3071 | Shared bank | Every bank reads the same **character** vault; pigeon deposits become available only after arrival at the nearest bank. |
3072 | Closed chunks | Closed or never-edited chunks are visible but not enterable; never-edited terrain is default grass with no blocks. |
3073 | Accounts | Login is auth.timfalken.com (or `admin-<n>` stub). Characters belong to an account; one may be in the world at a time. |
3074 | Names | Surnames are globally unique per account; first+last is unique per account; names free only after permanent delete. |
3075 | Inheritance | Deleted characters dump inventory, equipment, wallet and vault into an account inheritance tab other characters can claim. |
3076 | Cheques | Filling a cheque reserves vault goods; the bearer item is the claim; destruction without redemption releases the reservation. |
3077 | Marketplace escrow | Every open order is fully backed by escrow and matching/settlement is atomic and deterministic. |
3078 | Combat | Melee requires an 8-neighbour tile; ranged/spell range comes from the item or spell; hit uses the weapon skill; damage uses Strength, Dexterity or Mind. |
3079 | Progression | Players have no classes; non-combat actions award XP to one governing skill; a successful attack splits XP equally between hit and damage skills. |
3080
3081 # 30. Important edge cases to preserve during implementation
3082
3083 - A ChunkLoader crossing a region boundary can change
3084 residency/simulation references and worker ownership in the same tick;
3085 ordering must avoid temporary double ownership.
3086
3087 - A player at a worker boundary may receive visible chunks from multiple
3088 workers without moving ownership solely for rendering.
3089
3090 - A planned restart must ignore normal ChunkLoader retention when
3091 forcing the world to unload.
3092
3093 - A world-editor save must never cause newly loaded chunks in the
3094 current process to use the pending revision. It must append a changelog
3095 record naming the admin, timestamp and tile diffs.
3096
3097 - Pathfinding and player movement must reject tiles in closed or
3098 never-edited chunks even when those chunks are in the 3×3 view.
3099
3100 - Two accounts must not claim the same surname. One account may reuse its
3101 surname; first+last must stay unique on that account until permanent
3102 delete.
3103
3104 - Marking a character for deletion must not free the name or move items
3105 until the delay elapses. Cancelling must restore playability.
3106
3107 - Character deletion must notify the account email (or log, on stub auth).
3108 Permanent delete must void that character's issued cheques, then move
3109 inventory, equipment, wallet and vault into the account inheritance tab.
3110
3111 - Saving a chunk must rebake that chunk's light map and any neighbour
3112 chunks within max light range, using passable-tile raycasts. Light from
3113 a source in chunk A may appear in chunk B.
3114
3115 - A mob definition must not carry its own walk/run speed; gait only
3116 selects every-other vs every movement tick on the global cadence.
3117
3118 - World-settings saves must not apply to the live process; they wait for
3119 the same pending-revision restart as chunk edits.
3120
3121 - Night shading must not light a tile the baked mask marks unreachable,
3122 even if a torch is nearby through a wall.
3123
3124 - Oversized block and mob sprites must Y-sort so objects higher on the
3125 screen draw behind objects lower on the screen. Closed-chunk edges
3126 facing an open chunk must show a red border in the client.
3127
3128 - Equipping must not leave two items in the same equipment slot. Unequip
3129 into a full inventory must fail and leave the item worn.
3130
3131 - Nearby clients must not receive another player's inventory in order to
3132 draw their armour; appearance layers and material ids are sufficient.
3133
3134 - A client build without `client/frameworkv3` initialized must fail rather
3135 than silently using some other FrameworkV3 install.
3136
3137 - Client interpolation of movement must not be treated as authority. Combat
3138 range and pickup use the server tile, not the lerped draw position.
3139
3140 - The play camera must remain centered on the local player. Zoom must not
3141 expand the subscribed chunk set.
3142
3143 - A persistent mob spawned by a spawner must not be duplicated merely
3144 because it moved out of the spawner’s loaded area.
3145
3146 - A non-persistent mob disappears when its chunk is actually unloaded,
3147 not merely when it becomes dormant.
3148
3149 - If a persistent ChunkLoader or offline scripted player exists after
3150 restart, startup must discover it from an index without loading the
3151 entire world.
3152
3153 - A pending code update followed by an unrelated Node.js crash must
3154 restart the currently deployed commit rather than deploying early.
3155
3156 - Negative coordinates, daylight-saving midnight calculation, duplicate
3157 transfer messages and failed deployment migrations should all have
3158 explicit tests.
3159
3160 - Proximity chat degradation must happen before plaintext reaches an unauthorised
3161 distant client; rendering-only obfuscation is not sufficient.
3162
3163 - Carrier-pigeon deliveries must survive restarts and recipient logout without
3164 requiring every traversed chunk to remain stimulated.
3165
3166 - A pigeon carrying an item to a player whose inventory cannot accept it must
3167 not destroy the cargo; it deposits into that player's vault via the nearest
3168 bank.
3169
3170 - Two concurrent bank withdrawals, cheque fills or pigeon-arrival deposits must
3171 not spend the same vault goods twice.
3172
3173 - Filling two cheques against the same vault stack must reserve disjoint
3174 quantities or reject the second fill.
3175
3176 - A filled cheque that expires on the ground must release its reservation and
3177 must not remain redeemable.
3178
3179 - A player-dropped ground item must not block movement, must not keep its chunk
3180 loaded, and must still be present after a chunk unload/reload if `expiresAt`
3181 has not passed.
3182
3183 - Pickup of a ground item from a tile the player is not standing on must fail.
3184
3185 - Requesting blank cheques must never raise the player's carried blank-cheque
3186 count above 99.
3187
3188 - A marketplace match must atomically consume both escrows exactly once, even if
3189 two compatible orders arrive concurrently.
3190
3191 - A matching market order from an online player may settle immediately for that
3192 player while the older/offline counterparty's delivery remains durable.
3193
3194 - Skill XP is awarded only after authoritative action resolution, never directly
3195 from a client-reported result. A successful player attack splits that XP;
3196 a miss awards none.
3197
3198 - A melee attack from the target's own tile, or from Chebyshev distance greater
3199 than 1, must fail. A ranged or spell attack beyond that item or spell's
3200 `rangeTiles` must fail.
3201
3202 - A new player-market sale must capture the then-current undiscounted lerp
3203 value as `priceFrom` so shop and tooltip prices do not jump back to seed.
3204
3205 - Two shop NPCs may charge different prices for the same item at the same
3206 instant because each applies its own hidden discount to the same lerp.
3207
3208 - Item tooltip value must not be recomputed every tick; a one-minute refresh
3209 is sufficient. Purchase price is still evaluated at the moment of buy.
3210
3211 # 31. Decisions through version 0.12
3212
3213 - Chunk persistence is unload-driven rather than periodic.
3214
3215 - The authored tile model has separate visual ground and functional
3216 block layers.
3217
3218 - Mobile actors remain ECS entities and are not authored as painted tile
3219 contents.
3220
3221 - Spawner blocks are editor-placeable and configurable per instance;
3222 persistence belongs to the spawned mob type.
3223
3224 - world.sqlite is an authored, revisioned world source; state.sqlite
3225 holds runtime durable state.
3226
3227 - Editor changes are staged for activation on restart instead of
3228 hot-patching the running world.
3229
3230 - Code/world changes schedule a player-visible midnight restart; admins
3231 can trigger the same graceful pipeline immediately.
3232
3233 - Git pull/build/relaunch belongs to `systemd` supervision after the
3234 game process has safely exited.
3235
3236 - Deployment is manifest-driven: crash recovery restarts the currently
3237 checked-out commit, while only an intentional deployment restart may
3238 fast-forward `master`.
3239
3240 - Future player scripting is modelled as an alternative controller
3241 producing normal server action commands.
3242
3243 - Offline scripted players may remain in-world as ChunkLoaders until
3244 death or expiry and must survive planned restarts through persistence.
3245
3246 - The player client is built on FrameworkV3, included as the git submodule
3247 `client/frameworkv3` and built first so this game's client code can layer on
3248 top. The client does not need an ECS and consumes protocol state
3249 independently of backend ECS storage. The Node.js server does not import
3250 FrameworkV3.
3251
3252 - World sprites may be any pixel size. Each is placed with a pivot at
3253 horizontal centre and 8 pixels from the sprite bottom, on the tile
3254 centre. Blocks and mobiles are Y-sorted. The player may zoom the whole
3255 viewport within configured bounds; sprites are not scaled individually.
3256
3257 - Visible equipment is drawn as extra 16×16 layers on the mob, including
3258 players. Worn items occupy equipment slots, not the 32 inventory slots.
3259 Nearby clients replicate appearance layers only, never another player's
3260 inventory.
3261
3262 - Recolourable gear (metal armour) shares one overlay sprite and a 16×16
3263 channel mask. Material definitions supply the metal colour; luminance of
3264 the overlay is preserved. Iron and steel plate are different items with
3265 the same art and different `materialId`.
3266
3267 - The play camera is always centered on the local player. The admin world
3268 editor is the only exception, and it frames one chunk at a time.
3269
3270 - Authoritative movement is a tile-to-tile jump on a **global** cadence:
3271 default walk 2 tiles/s, run double. Walk steps every other movement tick;
3272 run steps every movement tick. Mobs do not set their own speed. Clients
3273 lerp for visuals only and never send interpolated positions.
3274
3275 - Admins edit global tick timers and constants in a world-settings modal.
3276 Saving applies those values immediately to the live process and appends
3277 a settings changelog. Chunk map saves still wait on the pending world
3278 revision.
3279
3280 - World calendar time is server time minus 1200 years, same IANA zone as
3281 midnight restarts. At night the client darkens tiles the baked light map
3282 cannot reach.
3283
3284 - Static light is baked on chunk save by raycast through passable tiles,
3285 including across chunk borders. The editor has a night-to-day slider for
3286 preview only.
3287
3288 - Each world-editor chunk save stores who edited it, when, and a bullet
3289 diff of ground changes, block placements, block replacements and block
3290 removals at world tile coordinates.
3291
3292 - Default speech is proximity-based and becomes less legible with distance.
3293 Long-distance exchange is physical: a pigeon carries money or one item stack.
3294 A letter is paper with player-written text, not a separate mail record.
3295
3296 - Permanent player groups are social/addressing structures and do not create an
3297 instant global chat channel.
3298
3299 - Carrier-pigeon transit is persistent but does not automatically keep every
3300 traversed chunk simulated. Whenever a pigeon passes through a chunk that is
3301 already simulating, it materialises as an ECS `Mob` and is visible to any
3302 nearby client whose normal chunk subscription includes it, even if that client
3303 is unrelated to the delivery. Unrelated clients do not receive cargo contents.
3304
3305 - A player has a 32-slot inventory. Stackable items occupy one slot. Currency is
3306 a numeric wallet/vault balance, not an inventory item.
3307
3308 - Player-dropped items lie on the tile for `groundItemDespawnDuration`
3309 (default 10 minutes), block nobody, and may be picked up by anyone standing
3310 on that tile. They survive unload until expiry via timestamps.
3311
3312 - The bank near the marketplace holds an unlimited **character** vault.
3313 Later banks are linked to the same vault. Pigeons may deposit money or one
3314 stack into the sender's vault after arriving at the nearest bank. An
3315 account-level inheritance tab receives a deleted character's goods.
3316
3317 - Blank cheques are issued at a bank up to a carried total of 99. Filling a
3318 cheque reserves a vault item quantity. The filled cheque is a bearer item.
3319 In-person redemption withdraws into the bearer's inventory. Sending the cheque
3320 to the bank by pigeon transfers the reserved goods into the pigeon's sender's
3321 vault.
3322
3323 - The central marketplace hides individual live sell listings and matches durable
3324 escrowed buy/sell orders at the midpoint of compatible bid/ask limits.
3325 Quantities are item stacks.
3326
3327 - The newest matching market participant receives the trade result locally; the
3328 older counterparty receives theirs by pigeon into their bank.
3329
3330 - NPC shops remain restricted to `npcShopAllowed` basic ingredients. They sell
3331 to players at
3332 `lerp(priceFrom, lastTradePrice, min(1, (now - lastTradeAt) / shopPriceLerpDuration))`
3333 times a hidden per-shop discount. With no player-market sale yet, the
3334 undiscounted value is `seedValue`. Tooltips use the same lerp without the
3335 discount and refresh at most once per minute.
3336
3337 - Hovering an item shows name, description, origin (crafter, or shop NPC name
3338 if bought there) and current undiscounted value.
3339
3340 - All combatants can attack. Melee requires standing on one of the eight
3341 neighbouring tiles. Ranged attacks and spells use the item's or spell's
3342 range. The hit roll uses the weapon skill; damage uses Strength (melee),
3343 Dexterity (ranged) or Mind (magic). Successful player-attack XP is split
3344 equally between those two skills.
3345
3346 - Player progression is skill-based rather than class-based. Non-combat
3347 actions award XP to one governing skill; combat hits split XP as above.
3348
3349 - Never-edited chunks are default grass, no blocks, and **closed**. The
3350 editor opens or closes each chunk. Closed chunks are visible but not
3351 enterable.
3352
3353 - Accounts authenticate at auth.timfalken.com. Until that service is up,
3354 each connection is stub `admin-<n>` (n = connected client count including
3355 this one) and is treated as admin.
3356
3357 - An account has unlimited characters and plays one at a time. Creation
3358 takes first name (not globally unique), last name (globally unique to the
3359 account, reusable on that account's other characters), and male/female.
3360 first+last must be unique for that account. This setup may change later.
3361
3362 - Character deletion is a 24-hour (configurable) delay with email notify
3363 and cancel. Permanent delete frees names and moves inventory, equipment,
3364 wallet and vault to the account inheritance tab, which any of that
3365 player's characters can claim into their own vault.
3366
3367 # 32. Open design decisions for later iterations
3368
3369 These do not block the initial implementation, but should eventually be
3370 specified explicitly:
3371
3372 - Whether multiple mobile entities may occupy one tile and, if so, which
3373 categories can overlap.
3374
3375 - Whether player movement is four-direction only or also supports
3376 diagonals. Combat melee adjacency already includes diagonals.
3377
3378 - Exact hit-chance and damage curves, attack intervals/cooldowns, whether
3379 Defence modifies incoming hit chance or damage, and ranged/spell
3380 line-of-sight or obstruction rules.
3381
3382 - Deterministic rounding when shop discount or lerp produces a fractional
3383 currency amount.
3384
3385 - Exact equipment slot list, per-slot draw order exceptions (cloaks,
3386 two-handed weapons), and whether worn overlays have facing frames to
3387 match the mob.
3388
3389 - Additional recolour channels beyond metal (for example cloth dyes) and
3390 the exact luminance-preserving remap function.
3391
3392 - Exact camera zoom minimum, maximum and whether zoom is restricted to
3393 integer steps.
3394
3395 - Exact night ambient curve (how dark, dusk length) and whether baked light
3396 stores a boolean reach mask or a distance/falloff value per tile.
3397
3398 - Whether opening a door at runtime should rebake or ignore static light.
3399
3400 - Exact simulation tick rate stays a world setting; lower-frequency AI and
3401 spawner cadences can still be tuned independently.
3402
3403 - Exact world/chunk binary serialisation format and schema/version
3404 migration strategy.
3405
3406 - Whether gameplay can permanently modify ground/block tiles in the
3407 initial release.
3408
3409 - Spawner timing rules, spawn-point restrictions and behaviour when
3410 persistent spawned mobs travel very far away.
3411
3412 - World-editor undo/redo and rollback UI. The per-chunk changelog is an audit
3413 log, not by itself an undo stack.
3414
3415 - Exact restart warning intervals and whether admins can
3416 cancel/reschedule a planned restart.
3417
3418 - Worker rebalance thresholds and whether regions may migrate while
3419 players are actively crossing their boundaries.
3420
3421 - Future scripting language syntax, event model and resource quotas.
3422
3423 - Group naming/roles, membership limits and whether group-wide letter sending
3424 is offered as an addressing convenience that still dispatches one pigeon and
3425 consumes one paper/letter per recipient.
3426
3427 - Whether pigeons can eventually be intercepted, killed or redirected in transit.
3428
3429 - Marketplace partial fills, cancellation rules, fees/taxes (if any),
3430 tie-breaking details and midpoint rounding for indivisible currency.
3431
3432 - Whether market price history or aggregate statistics are visible despite live
3433 order listings remaining hidden.
3434
3435 - Initial skill catalogue, XP curves, level caps, action XP formulas and the
3436 remaining interpretation of skills such as Defence.
3437
3438 - Maximum letter body length and whether writing paper requires a desk or can be
3439 done from inventory anywhere.
3440
3441 - Exact item catalogue, which items stack, per-item `maxStackSize` exceptions,
3442 harvest interactions and ground-item spawner parameters.
3443
3444 - Whether death drops inventory, and whether dropped unique items other than
3445 cheques have destruction side-effects.
3446
3447 - Whether the issuer can void a filled cheque without the bearer item being
3448 destroyed, and whether cheques can ever represent currency rather than items.
3449
3450 - Whether a short dispatch interval is needed so many pigeons cannot leave in a
3451 single tick, even though sending remains free.
3452
3453 - New-character spawn location (must be an open chunk) and name length /
3454 allowed-character rules.
3455
3456 - Later changes to character creation beyond first name, last name and sex.
3457
3458 # 33. Architectural summary
3459
3460 ECS → what an entity is and what systems can act on it
3461 Chunk → tile data, spatial lookup, simulation and client subscription
3462 Region → residency and simulation-worker ownership
3463 Coordinator→ where regions execute
3464 Gateway → stable client connections, auth, character select, and command/update routing
3465 world.sqlite→ authored versioned ground/block/spawner/light/settings world; unedited chunks are closed grass
3466 state.sqlite→ accounts, characters, friends, vaults, inheritance, and other durable live-game state
3467 systemd → process supervision and relaunch
3468 Deployment hook → conditional Git update/build only for intentional deployment restarts
3469 Controller → manual client input today; sandboxed player scripts later
3470 FrameworkV3 → git submodule at `client/frameworkv3`; built first; game client code layers on top
3471 Sprites → any size; pivot at horizontal centre, 8px from bottom; Y-sort blocks/mobs
3472 Equipment → layered 16×16 overlays on mobs; metal armour shares art and recolours by material
3473 Camera → play view centered on the local player; bounded zoom; editor is chunk-framed
3474 Movement → global walk/run cadence (default 2 tiles/s walk, run double); server tile steps; client visual lerp
3475 World time → server clock minus 1200 years; night darkens unlit tiles
3476 Light → baked passable-tile raycast on editor save; shines across chunks
3477 World settings → admin modal for tick timers and global constants; live apply
3478 Inventory → 32 slots; stacks occupy one slot; letters are written paper items
3479 Bank → per-character vault; account inheritance tab on character delete
3480 Auth → auth.timfalken.com, stub admin-<n> until live; unlimited characters, one in world
3481 Chunks → editor open/closed; default grass and closed until painted
3482 Ground items → non-blocking, 10-minute player drops, pickup only while standing on the tile
3483 Communication service → proximity speech
3484 CourierService → pigeons carrying money or one item stack through durable transit
3485 BankService → shared unlimited vaults, cheque reservations and redemption
3486 MarketService → durable escrowed order book, matching, last-sale index and pigeon-to-bank settlement
3487 Shop NPCs → sell allowed stock; price lerps toward last player-market sale over shopPriceLerpDuration, times a hidden discount
3488 Combat → melee auto-attack + retaliate; 8-neighbour melee; ranged/spell later; courier pigeon free-flight untargetable
3489 Skills → classless progression; Clubfighting/Strength on stick; attack XP split hit/damage (curves later)
3490
3491
3492 # 34. Version history
3493
3494 ## 0.19
3495
3496 - Playable item basis: 32-slot inventory, equipment overlays, carried coins,
3497 ground drops (10-minute player drops, pickup on the tile), bank vaults,
3498 and account inheritance on character delete. Spawner and bank blocks can
3499 be painted in the editor; spawners produce placeholder deer up to
3500 `maxAlive`. Missing art is temporary 16×16 PNGs under `client/assets/`
3501 so real sprites can drop in later by replacing those files.
3502
3503 ## 0.18
3504
3505 - Server ECS uses compact worker-local `EntityHandle`s (recycled free list)
3506 alongside global `EntityId`s for storage, networking and transfer. `Path`
3507 is a separate component from `Movement`; players carry `NetworkIdentity`
3508 instead of putting `sessionId` on `character`. Nearby clients get
3509 `ENTITY_SPAWN` / compact `ENTITY_MOVE` (tile + gait) / `ENTITY_DESPAWN`
3510 rather than appearance-heavy moves or extra snapshots.
3511
3512 ## 0.17
3513
3514 - Region workers own ECS worlds behind a clone-on-boundary protocol
3515 (optional `worker_threads`). ChunkLoader reference counts keep 3×3
3516 chunks simulating and 3×3 regions resident; other resident chunks stay
3517 dormant. Regions unload after the grace period and persist flagged
3518 entities. Crossing a foreign region transfers the only authoritative
3519 copy; ghosts cover border occupancy; client snapshots may span workers.
3520
3521 ## 0.16
3522
3523 - Proximity chat: Enter opens a bottom input (max `chatMaxCharacters`,
3524 default 100). Enter sends a trimmed line; the speaker always sees their
3525 own text. Other players get a server-obscured bubble (full until 8
3526 tiles, linear to silent at 16 tiles). At 0% readability no bubble is
3527 sent. Walk/run `R` is ignored while the chat line is open.
3528
3529 ## 0.15
3530
3531 - Hovering another player shows their first name. Clicking them opens an
3532 inspect modal (first + last name) to send a friend request. Requests
3533 must be accepted; removing a friend removes them on both sides. The
3534 friends list is the later pigeon address book.
3535
3536 ## 0.14
3537
3538 - Ground and block types load visual states from per-type sprite folders
3539 (first alphabetical PNG is the default). Sprite definitions include
3540 `frames`, `framesPerRow` and `animationSpeed`. The editor previews the
3541 selected tool on hover and cycles states with the mouse wheel.
3542 Gameplay may set a named visual state (for example a door).
3543
3544 ## 0.13
3545
3546 - World settings are live: an admin modal with categories, dirty-field
3547 highlighting, and a settings edit log. Save applies immediately
3548 (including `nightDarkness`) rather than waiting on a map revision.
3549
3550 ## 0.12
3551
3552 - Chunks are open or closed in the world editor. Closed chunks stay visible
3553 but cannot be entered. Never-edited chunks are default grass with no
3554 blocks and are closed.
3555 - Login uses auth.timfalken.com; until that is live, connections are stub
3556 `admin-<n>` (connected-client count including this one) and are admins.
3557 - Accounts have unlimited characters, one in the world at a time. Creation
3558 is first name, unique account-owned last name, and male/female.
3559 - Character deletion waits 24 hours with email and cancel. Permanent delete
3560 frees names and moves goods to an account inheritance bank tab.
3561
3562 ## 0.11
3563
3564 - Made walk/run a global cadence from world settings (default 2 tiles/s
3565 walk, run double): walk steps every other movement tick, run every tick.
3566 Mob definitions do not set move speed.
3567 - Added an admin world-settings modal for tick timers and global constants
3568 (shop lerp duration, drop lifetime, simulation tick, and the same class
3569 of values). Settings ride the pending world revision.
3570 - World calendar time is server time minus 1200 years.
3571 - Baked static lighting by passable-tile raycast on chunk save, including
3572 across chunk borders. Clients darken unreachable tiles at night. The
3573 editor has a night-to-day preview slider.
3574
3575 ## 0.10
3576
3577 - Drew visible equipment as 16×16 overlay layers on mobs (including players),
3578 with worn items in equipment slots rather than the 32-slot inventory.
3579 - Replicated compact appearance layers to nearby clients instead of another
3580 player's inventory.
3581 - Recolourable metal armour shares one overlay plus a 16×16 channel mask;
3582 material definitions supply the metal colour while preserving shading.
3583
3584 ## 0.9
3585
3586 - Vendored FrameworkV3 as the git submodule `client/frameworkv3`. The game
3587 client builds that library first and implements game-specific code on top
3588 of it. The Node.js server does not import the submodule.
3589
3590 ## 0.8
3591
3592 - Required all world sprites (tiles, blocks, mobs, items) to be 16×16 pixels,
3593 rejected at load, with a CI unit test that reports and fails on any other
3594 size. Sprites are not individually scaled; the player may zoom the viewport
3595 within configured bounds.
3596 - Locked the play camera to the local player. The admin world editor remains
3597 the only non-player-centered view.
3598 - Made authoritative movement integer tile-to-tile steps. Clients lerp
3599 mobiles for presentation only.
3600 - Added a per-chunk world-editor changelog: admin, timestamp, and bullet
3601 diffs for ground changes, block place/change/remove.
3602
3603 ## 0.7
3604
3605 - Added combat for all mobs including players: melee from any of the eight
3606 neighbouring tiles, ranged and spells from the item or spell range.
3607 - Hit rolls use the weapon skill (Swordfighting, Axefighting, Archery, Magic,
3608 and so on). Damage uses Strength, Dexterity or Mind according to melee,
3609 ranged or magic.
3610 - Successful player-attack XP is split equally between the hit skill and the
3611 damage skill. Ordinary mobs use archetype skill levels and do not earn XP.
3612 - Shop NPCs sell items at seed value adapted to the last player-market unit
3613 price, lerping over one hour, multiplied by a hidden per-shop discount.
3614 - Only the latest player-market sale per item is stored (price, timestamp, and
3615 lerp origin). No historical series.
3616 - Item hover shows name, description, origin (crafter or shop NPC) and the
3617 undiscounted current value, refreshed at most once per minute.
3618
3619 ## 0.6
3620
3621 - Added a 32-slot player inventory, stackable items, carried currency as a
3622 numeric wallet, and unique-instance items for letters and filled cheques.
3623 - Redefined letters as paper items with player-written text rather than a
3624 separate mail record.
3625 - Redefined carrier pigeons as free couriers that carry money or one item
3626 stack to a player or to the nearest bank.
3627 - Added a shared unlimited bank near the marketplace, blank cheques filled to
3628 99, vault reservations on fill, in-person redemption and pigeon-to-bank
3629 cheque transfers between vaults.
3630 - Added player-dropped ground items: 10-minute lifetime, non-blocking, pickup
3631 only while standing on the tile, timestamp persistence across unload.
3632 - Specified later ground-item spawners and harvesting as content that reuses
3633 this item model.
3634 - Routed offline/full-inventory pigeon delivery and older-side market
3635 settlement into the recipient's shared bank vault.
3636
3637 ## 0.5
3638
3639 - Made carrier pigeons shared world-visible entities whenever their route crosses an already-simulating chunk.
3640 - Unrelated nearby players can see pigeons in their normal 3x3 chunk view; pigeons do not keep chunks loaded themselves.
3641 - Added deterministic materialisation/dematerialisation between durable abstract transit and worker-owned ECS pigeon entities.
3642
3643 ## 0.4
3644
3645 - Added FrameworkV3 as the shared player-client foundation while keeping backend ECS internal to the server.
3646 - Added server-side proximity chat degradation, persistent player groups and durable carrier-pigeon letters.
3647 - Added scalable courier transit that can cross dormant world space without forcing normal chunk simulation.
3648 - Added the central marketplace, escrowed hidden order book, midpoint pricing and pigeon-based remote settlement.
3649 - Added the player-driven item-source philosophy and restrictions on NPC shop inventories.
3650 - Added classless, skill-based player progression and authoritative skill XP.
3651
3652 ## 0.3
3653
3654 - Converted the living design document to Markdown as the canonical format.
3655 - Defined `systemd` as the production process supervisor.
3656 - Added a conditional, manifest-driven deployment path so crashes do not deploy pending code early.
3657 - Added a concrete example systemd service shape and clarified privilege separation.
3658
3659 ## 0.2
3660
3661 - Added unload-driven chunk persistence, authored world revisions, the admin world editor, spawner blocks, graceful scheduled restarts and future player scripting hooks.
@@ -1,3661 +0,0 @@
1---
2title: Questward Server Technical Design
3version: 0.21
4status: proposed
5format: living-design-document
6---
7
8# Questward Server Technical Design
9
10**Version:** 0.21
11**Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
12**Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
13
14# 1. Design goals
15
16- Support a large tile-based MMO world without simulating unused areas.
17
18- Keep the server fully authoritative: clients send actions and
19 intentions, never authoritative state changes.
20
21- Authenticate accounts via auth.timfalken.com (with an `admin-<n>` stub
22 until that service is live). An account may have unlimited characters,
23 one in the world at a time, with delayed deletion and an inheritance
24 bank tab.
25
26- Use ECS composition for entities and systems, while using chunks and
27 regions for spatial ownership and simulation lifecycle.
28
29- Allow simulation work to scale across Node.js workers and permit
30 entities to cross worker-managed region boundaries safely.
31
32- Keep client replication small: a player receives only the current
33 16×16 chunk and the eight neighbouring chunks.
34
35- Keep authored world data separate from ephemeral simulation state.
36
37- Persist only entities that explicitly need persistence; ordinary
38 spawned mobs disappear when their chunk is unloaded.
39
40- Avoid constant chunk writes. Normal chunk persistence occurs on
41 unload; graceful shutdown is implemented as a forced unload of all
42 resident chunks.
43
44- Provide an admin-only graphical world editor for painting tiles,
45 opening or closing chunks, and placing/configuring spawners, with a
46 per-chunk changelog of who changed what and when. Unedited chunks are
47 grass-only and closed.
48
49- Automatically schedule a graceful midnight restart when live code or
50 authored world data changes, with an admin-triggered immediate restart
51 path.
52
53- Reserve a clean control abstraction for a later sandboxed player
54 scripting language without requiring the scripting system in the
55 initial release.
56
57- Build the player-facing client on the shared FrameworkV3 library, vendored
58 as a git submodule and built first so game-specific client code can layer
59 on top of it, while keeping the server-side ECS an implementation detail of
60 the backend. World sprites may be any size; each uses a centred pivot
61 8 pixels from the sprite bottom. The play viewport stays
62 centered on the local player.
63
64- Authoritative movement is tile-to-tile at a **global** walk/run cadence
65 (default walk 2 tiles/s, run double), not a per-mob speed. Admins edit
66 that cadence and other tick timers in a world-settings modal. Saving
67 those settings applies immediately to the live world. World
68 calendar time is server time minus 1200 years. At night the client
69 darkens unlit tiles (how dark is a world setting); static light reach
70 is baked by raycast when a chunk is saved.
71
72- Give every player a 32-slot inventory in which stackable items occupy a
73 single slot, and treat dropped items as temporary, non-blocking ground
74 objects rather than tile occupancy.
75
76- Make ordinary communication spatial rather than global: nearby speech is
77 progressively degraded by distance, while long-distance exchange is a
78 physical item or currency delivery by carrier pigeon. A letter is simply a
79 paper item with player-written text.
80
81- Support persistent player groups without turning them into an instant
82 long-distance chat channel.
83
84- Provide a shared, unlimited player bank near the marketplace, with later
85 banks all reading the same vault, plus bearer cheques and free pigeon
86 deposits.
87
88- Make the central marketplace an order-matching service rather than a public
89 auction list, with durable escrow and asynchronous pigeon delivery.
90
91- Keep the economy predominantly player-driven: most ingredients are gathered,
92 final goods are normally crafted by players, and finished-item drops come from
93 enemies/bosses rather than ordinary NPC shops.
94
95- Let every combatant — players and other mobs — attack. Melee requires an
96 adjacent tile including diagonals; ranged attacks and spells use the range
97 of the weapon or spell. A hit roll uses the weapon skill; damage uses
98 Strength, Dexterity or Mind. Attack XP is split equally between those two
99 skills.
100
101- Let shop NPCs sell items at a seed value that lerps toward the last
102 player-market sale price over a configurable duration (default one hour),
103 with a hidden per-shop discount.
104 Item inspection shows name, description, origin and the undiscounted
105 current value, refreshed at most once per minute.
106
107- Use skill-based progression with no player classes. Every gameplay action is
108 governed by a skill and awards XP to that skill when successfully performed.
109 Combat is the explicit dual-skill exception: hit skill and damage skill
110 share the XP.
111
112# 2. Core world model
113
114## 2.1 Spatial hierarchy
115
116World
117└── Region: 4 × 4 chunks
118└── Chunk: 16 × 16 tiles
119└── Tile
120
121One chunk contains 256 tiles. One region is 64×64 tiles and contains 16
122chunks (4,096 tiles). World tile coordinates are canonical; chunk and
123region coordinates are derived from them.
124
125chunkX = floor(tileX / 16)
126chunkY = floor(tileY / 16)
127regionX = floor(chunkX / 4)
128regionY = floor(chunkY / 4)
129
130If negative world coordinates are allowed, use true floor division
131rather than JavaScript integer truncation.
132
133## 2.2 Three independent spatial states
134
135The design deliberately separates region residency, chunk simulation,
136and client visibility.
137
138| **Concern** | **Unit** | **Meaning** |
139|-------------|----------|------------------------------------------------------------------------------------------------|
140| Residency | Region | Whether the region and its required chunk data exist in server memory and have a worker owner. |
141| Simulation | Chunk | Whether ECS systems actively simulate entities and gameplay in this chunk. |
142| Visibility | Chunk | Whether a specific client is subscribed to the chunk and receives its snapshot/deltas. |
143
144## 2.3 Region states
145
146UNLOADED
147↓ load
148RESIDENT
149↓ no residency references + grace period
150UNLOADED
151
152A resident region is assigned to exactly one simulation worker. An
153unloaded region has no active ECS representation.
154
155## 2.4 Chunk states
156
157DORMANT ⇄ SIMULATING
158
159A dormant chunk can remain resident in memory while normal gameplay
160systems ignore it. A simulating chunk participates in movement, combat,
161AI, spawners and other active systems.
162
163# 3. Tile layers and occupancy
164
165## 3.1 Ground layer
166
167Every tile has a ground type. Ground is visual only. It does not by
168itself block movement, cause collision, or create gameplay behaviour.
169
170TileGround {
171groundTypeId: GroundTypeId
172}
173
174## 3.2 Block layer
175
176A tile may also contain one block. The block is the actual world object
177standing on the tile and can determine collision and behaviour.
178
179TileBlock {
180blockTypeId: BlockTypeId \| null
181config?: BlockConfig
182}
183
184Examples include walls, doors, trees, torches and other lights, containers,
185spawners, marketplace counters and banks. Block definitions determine
186properties such as passability, interaction behaviour, whether a block
187participates in navigation, and whether it emits light (`lightRangeTiles`).
188
189## 3.3 MOBile entities
190
191A moving game entity — player, enemy, animal, NPC or any other mobile
192actor — is represented by an ECS entity rather than being painted into
193the static tile map. A mobile entity may inhabit a tile in addition to
194the tile’s ground and block layers, subject to collision rules.
195
196Tile
197├── Ground (visual layer)
198├── Block (static/world-object layer; optional)
199├── Ground item stacks (ephemeral, non-blocking)
200└── Mobile ECS entities (dynamic occupancy)
201
202The spatial chunk index maintains which mobile entity IDs currently
203occupy each tile, allowing collision, nearby queries and replication
204without scanning the global ECS. Ground item stacks are indexed per
205tile as well, but they never contribute to movement collision and never
206prevent a mobile entity from standing on that tile.
207
208# 4. ECS model
209
210## 4.1 Entity composition
211
212Entities are numeric identities plus components. Behaviour comes from
213systems querying component combinations rather than deep class
214inheritance.
215
216Player
217Position
218Movement
219Health
220Combat
221Skills
222Inventory
223Currency
224Equipment
225Player
226NetworkIdentity
227ChunkLoader
228Persistent
229
230Ordinary enemy
231Position
232Movement
233Health
234Combat
235Skills
236Creature
237AI
238
239Named NPC
240Position
241Movement
242Health
243NPC
244AI
245Persistent
246
247## 4.2 Global identity versus local ECS handle
248
249Use a globally meaningful EntityId for storage, networking and
250cross-worker transfer, and a compact worker-local EntityHandle for hot
251ECS arrays. A transferred entity keeps its EntityId but may receive a
252different local handle on the destination worker.
253
254## 4.3 Recommended initial components
255
256| **Category** | **Components** |
257|----------------|----------------------------------------------|
258| Spatial | Position, Movement, Path, Collision |
259| Living | Health, Combat, Creature, Mob, Skills |
260| Player | Player, NetworkIdentity, Inventory, Currency, Equipment |
261| AI | AI, Target, BehaviourState |
262| Lifecycle | ChunkLoader, Persistent, SpawnOrigin |
263| Presentation | Renderable / Appearance |
264| Future control | Controller / ScriptController / OfflineUntil |
265
266# 5. ChunkLoader and simulation activation
267
268## 5.1 Generic ChunkLoader component
269
270World activation is component-driven rather than player-specific. Any
271entity may carry a ChunkLoader component that says “keep the surrounding
272world resident and simulated”.
273
274ChunkLoader {
275simulationRadiusChunks: 1,
276regionLoadRadius: 1
277}
278
279A normal player can therefore stimulate a 3×3 chunk area while keeping
280the surrounding 3×3 regions resident. Bosses, travelling NPCs, machines,
281scripted actors or administrative anchors can use the same mechanism.
282
283## 5.2 Reference counting
284
285Chunk simulation and region residency should use reference counts.
286Overlapping loaders increment the same references; leaving decrements
287them. A chunk sleeps only when its simulation reference count reaches
288zero. A region becomes eligible for unload only when its residency
289references reach zero.
290
291## 5.3 Grace period
292
293After the last residency reference disappears, retain the region briefly
294before unloading. This prevents repeated SQLite reads and writes when a
295loader oscillates around a boundary. The delay should be configurable.
296
297# 6. Chunk lifecycle and persistence
298
299## 6.1 No periodic chunk saves
300
301Normal gameplay does not periodically rewrite loaded chunks. A chunk is
302saved as part of the unload path only.
303
304Resident chunk
305↓ last residency / forced shutdown unload
306Prepare unload
307↓
308Persist required chunk state once
309↓
310Persist required entities
311↓
312Remove ECS/runtime representation
313
314A graceful server restart does not introduce a second save mechanism. It
315force-unloads every resident region/chunk, so the normal unload
316persistence path remains the single source of truth.
317
318## 6.2 Persistent versus non-persistent entities
319
320Persistence is an entity property, not a property of the chunk or
321spawner. An entity with Persistent is serialised when its owning
322chunk/region unloads. A non-persistent entity is simply discarded.
323
324Non-persistent wolf
325spawn → simulate → chunk unload → disappear
326
327Persistent named NPC
328load → simulate → chunk unload → save → recreate when area loads
329
330## 6.3 Persistent is independent of ChunkLoader
331
332These traits must remain independent. A persistent entity does not
333automatically keep its area active, and a ChunkLoader does not
334automatically become persistent.
335
336# 7. Storage architecture
337
338## 7.1 Separate authored world and runtime state
339
340Use two SQLite databases with different responsibilities.
341
342| **Database** | **Responsibility** |
343|--------------|-----------------------------------------------------------------------------------------------------------------------------------------|
344| world.sqlite | Admin-authored ground tiles, block tiles, light maps, live world settings and their edit log, spawner configuration, per-chunk editor changelogs, world revisions and world metadata. |
345| state.sqlite | Accounts, characters, inventories, carried currency, character vaults, inheritance tabs, cheque reservations, skills, groups, courier cargo/transit, unexpired ground items, market orders/escrow/trades, per-item last player-market sale, persistent ECS entities, offline-script state, optional persistent runtime chunk overrides, and other durable live-game state. |
346
347This prevents editor authoring changes from becoming entangled with live
348player/entity persistence.
349
350## 7.2 Chunk writes in runtime state
351
352If initial gameplay does not allow permanent tile/block modification,
353runtime chunks require no writes at all. If permanent runtime world
354changes are later added, dirty chunk overrides are held in memory and
355written to state.sqlite only when that chunk unloads. Shutdown uses
356forced unload and therefore follows the same rule.
357
358## 7.3 Central persistence service
359
360Simulation workers should not independently compete for SQLite writes. A
361persistence service owns the write connection, batches transactions, and
362receives logical save requests from workers.
363
364Simulation workers
365│ save/unload messages
366▼
367Persistence service
368│
369▼
370SQLite (WAL)
371
372Live ECS state remains authoritative while loaded; SQLite is durable
373state, not a per-tick synchronisation mechanism.
374
375# 8. World authoring and revision model
376
377## 8.1 Admin-only world editor
378
379The server includes a separate admin-only world editor UI. It is not
380part of the normal player client.
381
382- Display a 3×3 of 16×16 chunks, with the currently selected
383 chunk in the centre and a red border around that chunk.
384 Painting, open/closed, and changelog apply only to the
385 selected chunk; neighbours are visible for alignment and
386 baked lighting context.
387
388- Provide Up, Down, Left and Right navigation buttons that move the
389 editor exactly one chunk in that direction.
390
391- Show the current chunk coordinates prominently, and whether the chunk
392 is **open** or **closed**.
393
394- Toggle the current chunk open or closed. Closed chunks remain visible
395 to nearby players but cannot be entered.
396
397- Allow painting a ground type on a tile.
398
399- Allow painting, replacing or erasing the block type on a tile.
400
401- Hovering a tile in the selected chunk previews the selected tool there:
402 existing content on that layer is hidden and the tool's sprite is shown
403 where a click would place it.
404
405- Mouse wheel cycles the **visual state** of the selected ground or block
406 type (see section 21.3). If the hovered tile already has that type, the
407 wheel also writes the new state onto it.
408
409- Render both layers together so the block appears on top of the ground.
410
411- Do not display ordinary mobile entities as editable map paint.
412
413- Allow selecting/configuring special block types such as Spawner, Bank,
414 Marketplace and light-emitting blocks (`lightRangeTiles`).
415
416- Open a **world settings** modal for global tick timers and constants
417 (movement cadence, night darkness, shop lerp duration, drop lifetime,
418 and other values listed in section 8.5). The form is categorised and
419 scrollable; a settings edit log sits beside it. Edited rows are marked
420 until Save, and only those rows are written.
421
422- Provide a **night-to-day slider** that only previews lighting; it does
423 not change live world time. Preview uses the same baked light maps as
424 play, including light that reaches this chunk from neighbouring chunks.
425
426- Later: allow configuring ground-item spawners analogously to mob
427 spawners. Exact item tables remain a later content decision.
428
429- Save changes through an authenticated admin API; the browser never
430 opens SQLite directly.
431
432- Show that chunk's changelog: a chronological list of saves, each with
433 which admin made the edit, when, and a bullet-point diff of the change.
434
435The editor camera is **not** locked to a player character. It frames the
436currently selected chunk. This is the only intended exception to the
437player-centered play viewport in section 21.4.
438
439## 8.2 World editor save behaviour
440
441Saving a **chunk** writes the authored result to world.sqlite. It does
442not live-patch the currently running simulation map. Instead, the change
443creates or updates a pending world revision and schedules a server
444restart for the next server-local midnight (or Apply now).
445
446Saving **world settings** is different: it updates the live settings
447row immediately, records a settings changelog entry, and the running
448process applies the new values without waiting for a world revision.
449
450The running game remains pinned to the **chunk** world revision selected
451at its own startup. This avoids a dangerous mixed state where some
452loaded chunks use old authored data and newly loaded chunks use newer
453editor data. Settings are not revision-pinned.
454
455## 8.3 Versioned authored chunks
456
457A practical schema is to give every editor change a monotonically
458increasing world revision. The game process pins one active revision for
459its entire lifetime. Chunk lookup selects the latest authored version
460not newer than that pinned revision.
461
462world_revisions
463revision_id
464created_at
465created_by
466status // pending / active / superseded
467
468world_chunk_versions
469chunk_x
470chunk_y
471revision_id
472open // player-enterable; default false until set
473data_blob
474
475world_meta
476active_revision
477pending_revision
478
479world_settings
480revision_id
481settings_blob // historical snapshot copied onto a map revision
482
483world_live_settings
484id // singleton row, always 1
485settings_blob // the live, immediately applied settings
486updated_at
487updated_by
488
489world_settings_edit_log
490log_id
491editor_admin_id
492edited_at
493diff_entries // which options changed, from/to
494
495world_chunk_edit_log
496log_id
497chunk_x
498chunk_y
499revision_id
500editor_admin_id
501edited_at
502diff_entries // structured bullets for this save
503
504On the next planned restart, startup promotes/selects the latest valid
505pending revision before world loading begins.
506
507## 8.4 Per-chunk changelog
508
509Every successful chunk save appends one changelog record for that chunk.
510The record is durable in `world.sqlite` and is not gameplay state.
511
512The server diffs the newly saved chunk against the previous authored
513version of that same chunk (the latest `world_chunk_versions` row for
514those coordinates that this save replaces). Unchanged tiles produce no
515bullets. Each changed tile becomes one of:
516
517```text
518- Ground at X, Y changed from Prev to New.
519- Block <type> placed at X, Y.
520- Block at X, Y changed from Prev to New.
521- Chunk opened.
522- Chunk closed.
523```
524
525`X, Y` are world tile coordinates. `Prev` / `New` / `<type>` are the
526ground or block definition display names. A block paint on an empty block
527layer is a placement. Replacing one block type (or its config, such as a
528spawner) with another is a change. Erasing a block is a removal. Ground is
529never absent; a ground paint is always a change from one type to another.
530
531The editor UI lists records newest-last or newest-first consistently, each
532headed by admin identity and timestamp, with that save's bullets underneath.
533The changelog is an audit trail, not an undo stack. Undo/redo remains an
534open editor-UX decision. Derived light maps are not changelog bullets;
535they are regenerated on save (section 8.6).
536
537## 8.5 World settings
538
539Global gameplay constants live in authored `world_live_settings`. They
540are **not** per-mob, **not** client-authored, and **not** pinned to a
541map revision. Admins edit them from a large tabbed modal in the
542world-editor UI. The modal fills most of the screen: the left pane has
543category tabs (Simulation, Graphics, World, Characters, Communication,
544Inventory, Economy) with one panel visible at a time; the right pane is
545a settings edit log (which option changed, from/to, which admin,
546date/time).
547
548Rows the admin has edited in this session are marked with a distinct
549background. Save writes **only** those dirty fields. The running
550process applies them immediately (walk cadence, tick rate, night
551darkness, bloom post-chain knobs, and other consumed timers). Chunk
552**Apply now** is not required.
553
554`nightDarkness` only darkens during dusk/night/dawn (peak hours 22–5).
555Daytime hours 8–16 stay fully bright on the client. Editing night
556darkness in the editor snaps the Night preview slider to night so the
557change is visible immediately.
558
559Minimum initial settings and defaults:
560
561```text
562WorldSettings
563- walkTilesPerSecond // default 2
564- simulationTickHz // default 20; implementation default, still a setting
565- shopPriceLerpDuration // default 1 hour
566- groundItemDespawnDuration // default 10 minutes
567- regionUnloadGracePeriod // configurable grace after last residency
568- defaultGroundTypeId // grass used for never-edited chunks
569- characterDeletionDelay // default 24 hours
570- nightDarkness // default 0.72; 0 = no extra night darkening, 1 = fully black unlit tiles
571- chatMaxCharacters // default 100; trimmed proximity-chat line length
572- bloomThreshold // default 0.35; Framework bloom bright-pass
573- bloomSoftKnee // default 0.3
574- bloomIntensity // default 1.35
575- bloomBlurSize // default 3
576- bloomSaturation // default 1.15
577- bloomColorPreserve // default 0.35
578- bloomDilate // default 2; 0 disables dilate
579- bloomScales // default 2; H/V blur scale pairs
580- bloomHalfRes // default 1; 1 = half-res blur, 0 = full-res
581```
582
583Running is always **double** walking speed. It is not a separate per-entity
584field. From `walkTilesPerSecond`:
585
586```text
587runTilesPerSecond = walkTilesPerSecond * 2 // default 4
588movementTickHz = runTilesPerSecond // default 4 Hz
589walk: commit a tile every 2 movement ticks
590run: commit a tile every 1 movement tick
591```
592
593All ground mobiles — players, enemies, NPCs — use this same cadence. A
594mob definition does not set move speed. Gait (`walk` | `run`) is the only
595per-entity choice; it selects every-other vs every movement tick.
596
597Other tick-duration constants that already exist in this document (shop
598lerp, ground-item despawn, residency grace, and later ones of the same
599kind) are edited here rather than hardcoded. Adding a new global timer
600means adding a field to `WorldSettings` and a row in this modal.
601
602## 8.6 Baked lighting
603
604Light from authored blocks is precomputed when a chunk is saved, not
605raytraced every simulation tick.
606
607A block definition may set `lightRangeTiles > 0`. That tile is a static
608light source. Light travels only through **passable** tiles (the same
609passability as walking). Ground type does not block light. Mobiles and
610ground items do not block light.
611
612For every tile within a source's range, the baker runs a simple grid
613raycast (for example Bresenham through tile centres). If the ray hits an
614impassable block before the destination, that source does not light that
615tile. A tile is lit if **any** source can reach it. Light **does** shine
616across chunk boundaries.
617
618Saving a chunk rebakes:
619
6201. that chunk's 16×16 light map, and
6212. every neighbouring chunk that could be affected (chunks within the
622 maximum `lightRangeTiles` of the saved chunk).
623
624Neighbor rebakes use light sources and walls from the pending revision,
625including the chunk just saved. Those neighbor light maps are written
626into the same pending revision so play never mixes old and new lighting.
627
628The light map is stored in the chunk `data_blob` as a 16×16 intensity
629(0 = unreachable, 1–255 = falloff by distance from the strongest
630reaching source). The client darkens tiles by that intensity at night,
631so a torch fades tile-by-tile rather than lighting a hard disc. Peak
632unlit darkness is `nightDarkness` (a live world setting). It is
633replicated to clients in `CHUNK_SNAPSHOT` / `CHUNK_DELTA`.
634
635On the client, immobile ground and ≤16×16 static blocks (plus their
636bloom companions) are composited into per-chunk atlases when a snapshot
637arrives: one ground image, one block strip per tile row (so Y-sort still
638interleaves mobiles between rows), and one bloom image for the bloom
639render layer. Blocks taller than 16×16 or with animation stay as
640individual sprites. Night shade overlays darken the baked atlases per
641tile; oversized sprites and mobiles instead receive a uniform shade from
642the darkness of the tile they stand on.
643
644Runtime door open/close does not rebake static light unless a later
645iteration adds live lighting. Baked light is authored geometry.
646
647The editor night-to-day slider interpolates preview ambient from full
648night (dark except baked-lit tiles) to full day (no ambient darkening).
649It does not persist and does not change server/world clock.
650
651## 8.7 Default chunks and open / closed
652
653A chunk the editor has never saved does not exist in `world_chunk_versions`.
654At runtime it is synthesised as:
655
656- every tile `defaultGroundTypeId` (grass),
657- no blocks,
658- **closed**,
659- no baked lights.
660
661The world is therefore an infinite grass field until admins paint it, and
662players cannot walk onto it until an admin **opens** the chunk.
663
664**Closed** chunks can still appear in a player's 3×3 view. They cannot be
665entered: `MOVE_TO`, pathfinding, spawning, and other player-entry actions
666treat every tile in a closed chunk as impassable. Visibility and lighting
667previews are unchanged. Where an **open** chunk shares an edge with a
668closed (or never-edited) chunk, the client draws a red border on that
669edge so players can see they cannot cross.
670
671**Open** chunks are the playable map. Opening or closing is an authored
672chunk flag, saved with the pending revision like paint.
673
674Spawners in a closed chunk do not spawn. Ground movement, including AI,
675does not step into a closed chunk. If a future bug or admin tool places an
676entity there, it can still be replicated to observers, but players cannot
677walk in after it.
678
679# 9. Spawner blocks
680
681## 9.1 Spawner data
682
683A Spawner is a block in the authored block layer, with per-instance
684configuration stored as part of the chunk data.
685
686SpawnerConfig {
687spawnerId: SpawnerId,
688mobTypeId: MobTypeId,
689maxAlive: number,
690spawnRangeTiles: number
691}
692
693Additional parameters such as minimum/maximum spawn delay can be added
694later without changing the core model.
695
696## 9.2 Spawner editor
697
698Selecting a Spawner tile in the world editor opens a configuration panel
699containing at minimum: mob type, maximum alive count and spawn range.
700Validation happens server-side before the pending world revision is
701written.
702
703## 9.3 Spawned entity persistence
704
705The spawner never decides whether its mob is persistent. The mob
706definition/archetype does. When the spawner creates an entity, the
707entity receives Persistent only if that mob type is defined as
708persistent.
709
710MobDefinition: deer
711persistent = false
712
713MobDefinition: named_guard_captain
714persistent = true
715
716## 9.4 SpawnOrigin
717
718Spawned mobs receive a SpawnOrigin component referencing the spawner.
719This lets maxAlive count only entities belonging to that spawner and
720avoids expensive geometric searches.
721
722SpawnOrigin {
723spawnerId: SpawnerId
724}
725
726For non-persistent mobs, disappearance on chunk unload naturally
727decreases the count. For persistent mobs, SpawnOrigin is persisted so
728the spawner can recognise an existing persistent instance even after it
729has moved or been unloaded elsewhere. A lightweight persistence index by
730spawnerId prevents duplicate persistent spawns.
731
732## 9.5 Spawner simulation
733
734SpawnerSystem runs only while the spawner’s chunk is simulating **and
735open**, and at a much lower frequency than movement. A spawn candidate
736must satisfy block collision, bounds, an open chunk, and mobile-occupancy
737rules. Ground type does not affect passability unless a later gameplay
738system explicitly introduces a separate rule for it.
739
740## 9.6 Future ground-item spawners
741
742Some items will later spawn naturally on the ground, using a world-editor
743block analogous to a mob spawner. Those spawned stacks should use the same
744non-blocking ground-item representation as player drops, but their lifetime,
745respawn and `maxOnGround` rules belong to the spawner configuration rather
746than the 10-minute player-drop timer.
747
748Exact item lists, harvest interactions and spawner parameters are later
749content decisions and do not block the inventory/bank model.
750
751# 10. Startup and loading order
752
753Loading order is explicit so authored world state exists before
754persistent entities are instantiated into it.
755
756> **1.** Start process and load configuration, including server time
757> zone and storage paths.
758>
759> **2.** Open world.sqlite and validate/migrate its schema.
760>
761> **3.** Select/promote the world revision to use for this process and
762> pin it for the lifetime of the process.
763>
764> **4.** Load static registries: ground definitions, block definitions,
765> item definitions, material definitions, spell definitions, mob archetypes and component serializers.
766>
767> **5.** Open state.sqlite and run runtime-state migrations.
768>
769> **6.** Start the persistence service, durable domain services (such as courier, bank, market and shop-price services when enabled), region coordinator and simulation workers.
770>
771> **7.** Load the index of persistent entities that themselves require
772> world activation (for example persistent ChunkLoaders or future
773> offline scripted players).
774>
775> **8.** For each required region, load authored chunk data from the
776> pinned world revision first.
777>
778> **9.** Apply any durable runtime chunk override state, if the game
779> supports such modifications.
780>
781> **10.** Instantiate persistent entities into the already-created
782> world/chunks.
783>
784> **11.** Recalculate ChunkLoader references and begin chunk simulation.
785>
786> **12.** Only after the world reports READY does the gateway accept
787> normal player logins.
788
789This ordering solves the bootstrap problem for persistent entities that
790keep their own chunks active: a compact persistence index can locate
791them without first loading the entire world.
792
793# 11. Simulation workers and region ownership
794
795## 11.1 Ownership invariant
796
797Exactly one worker authoritatively owns a region at any instant. Every
798authoritative entity belongs to the worker that owns the entity’s
799current region.
800
801## 11.2 Coordinator
802
803A central region coordinator maintains RegionId → WorkerId and
804assigns/migrates regions based on actual measured simulation effort,
805while preferring neighbouring regions on the same worker when load
806permits.
807
808## 11.3 Work measurement
809
810- Average and high-percentile tick execution time.
811
812- Number of simulating chunks.
813
814- Number of active entities and AI entities.
815
816- Pathfinding work and queued searches.
817
818- Cross-worker boundary message volume.
819
820- Backlog / tick lateness.
821
822Actual time spent simulating is more important than raw player count or
823raw region count.
824
825## 11.4 Node.js implementation
826
827Simulation workers keep mutable ECS worlds isolated and talk only through
828structured-cloneable messages. The default runtime is in-process workers
829with clone-on-boundary (so the protocol is real even without OS threads).
830`SIMULATION_WORKER_MODE=thread` runs the same `WorkerWorld` inside
831`worker_threads`. Do not share a mutable ECS in SharedArrayBuffer.
832
833A coordinator on the gateway thread owns region assignment (neighbour-sticky,
834least-loaded tie-break), global EntityIds, transfer handoff, ghost exchange,
835and SQLite. `SIMULATION_WORKERS` defaults to 2. Dynamic load rebalance is
836later.
837
838# 12. Cross-worker communication
839
840## 12.1 No remote mutation
841
842A worker may inspect a limited read-only representation of neighbouring
843entities but never directly mutates authoritative state owned by another
844worker.
845
846## 12.2 Border ghosts
847
848Neighbouring workers can exchange compact border/ghost entity data for
849nearby interaction and AI: EntityId, position, collision footprint, type
850and minimal combat metadata. Ghosts are not full ECS entities and are
851never authoritative.
852
853## 12.3 Remote actions
854
855Worker A goblin targets Player 42 (owned by Worker B)
856Worker A → REMOTE_ACTION(attack intent) → Worker B
857Worker B validates range/state and applies authoritative result
858
859## 12.4 Entity transfer
860
861When an entity crosses from a region owned by Worker A into one owned by
862Worker B, ownership is handed off at a simulation tick boundary using a
863sequence-numbered transfer protocol. There is never more than one
864authoritative copy.
865
866A: prepare transfer
867B: validate / accept
868A: freeze at handoff boundary
869B: instantiate authoritative entity at effective tick
870Coordinator: update ownership mapping
871A: remove authoritative copy
872
873# 13. Server tick and stimulation
874
875## 13.1 Fixed simulation tick
876
877Use a fixed server simulation tick. The default is 20 Hz (50 ms), stored
878as `WorldSettings.simulationTickHz`. This is not a protocol promise.
879
880Movement does **not** commit a new tile on every simulation tick. See
881section 13.4.
882
8831\. Drain validated incoming commands
8842. Apply completed worker/entity transfers
8853. Recalculate activation changes
8864. Movement / collision
8875. Combat
8886. Scheduled AI
8897. Scheduled spawners/environment, including ground-item expiry in simulating chunks
8908. Produce cross-worker messages
8919. Produce client replication deltas
89210. Queue unload/persistence work
893
894## 13.2 Different system frequencies
895
896Not every ECS system should run every tick. Ground movement commits only
897on the global movement cadence (section 13.4). AI decisions, target
898searches and spawner checks can run at lower frequencies. Sleeping chunks
899are not “slow ticked”; they are omitted from normal simulation.
900
901## 13.3 Timestamp-based inactive progression
902
903Long-lived timers such as growth, cooldowns, ground-item expiry and shop
904price lerps should store future timestamps where possible. When an area
905wakes, the system catches up from the timestamp instead of executing missed
906ticks. An expired ground item is discarded on catch-up without ever
907reappearing. Shop and tooltip prices are evaluated from last-sale timestamps
908when observed; they are not ticked. Durations such as shop lerp and
909ground-item despawn come from `WorldSettings`, not from hardcoded
910literals in systems.
911
912## 13.4 Global movement cadence
913
914All ground-moving entities share one walk speed and one run speed.
915
916- Default walk: **2 tiles per second** (`walkTilesPerSecond`).
917- Run: always **double** walk (default 4 tiles per second).
918- Movement ticks fire at `runTilesPerSecond` (default 4 Hz).
919- **Walk:** the entity may advance one path tile on every other movement
920 tick.
921- **Run:** the entity may advance one path tile on every movement tick.
922
923Mobs do not define their own move speed. `Movement.gait` is `walk` or
924`run`. Players send `SetGait`. AI may set gait; it still uses the global
925cadence. Flying pigeon transit is not this cadence; it keeps its own
926route clock.
927
928If the path is blocked on a movement tick, the entity stays on its tile
929and retries on a later legal tick. Occupancy, combat range and pickup
930always use the last committed tile.
931
932## 13.5 World calendar time
933
934World time is server time **1:1**, in the same configured IANA zone used
935for midnight restarts, with **1200 years subtracted** from the calendar
936date. A server clock of 24 Aug 2026 21:00 is world 24 Aug 826 21:00.
937Clock-of-day, including night, therefore matches the host's zone.
938
939The gateway includes current world time (or server unix time plus the
940year offset) in the status sent to clients so shading does not depend on
941the player's device clock. Lighting is presentation; combat and movement
942do not wait on the day/night overlay.
943
944# 14. Client gateway and authority
945
946## 14.1 Stable connection ownership
947
948Client WebSocket/TCP connections belong to a gateway rather than
949simulation workers. When the player crosses into a region owned by
950another worker, the socket stays connected to the same gateway; only
951internal routing changes.
952
953## 14.2 Client commands are intentions
954
955A client sends commands such as MoveTo, Interact, Attack, UseItem,
956EquipItem, UnequipItem, SelectSpell, SetGait, DropItem, PickupItem, BankDeposit,
957BankWithdraw, BuyFromShop or SendPigeon. The authenticated **account**
958determines the actor; after character select, commands apply to that
959account's **active character**. The
960client never supplies an authoritative resulting position, health
961value or inventory result.
962
963## 14.3 Input queue
964
965Socket handlers validate message shape and enqueue commands. Simulation
966workers consume commands at tick boundaries. WebSocket callbacks do not
967mutate ECS state directly.
968
969## 14.4 Authentication
970
971Live login uses **auth.timfalken.com**. The game server never stores a
972password. It receives an authenticated account identity (and email) from
973that service and maps it to a durable `accountId` in `state.sqlite`.
974
975Until auth.timfalken.com is available, the gateway uses a **stub identity**:
976each new connection is `admin-<n>`, where `n` is the number of currently
977connected clients **including this one** (the first connection is
978`admin-1`). Stub accounts are treated as admins so the world editor can be
979used during development. Stub accounts have no email; deletion “emails”
980are logged instead of sent.
981
982When real auth ships, the stub is removed. Admin rights come from that
983service, not from the `admin-` name prefix.
984
985An account may have only **one active play session** at a time (one
986character in the world).
987
988## 14.5 Characters
989
990An account has unlimited characters and plays **one** at a time. First
991login with no characters must create one before entering the world. Later
992logins show a character-selection menu: create, choose, mark for deletion,
993or cancel deletion.
994
995Initial character setup (may change later):
996
997```text
998CreateCharacter
999- firstName // not globally unique
1000- lastName // unique surname, owned by this account
1001- sex // male | female
1002```
1003
1004Rules:
1005
1006- **Last names** are globally unique. The first character to take a surname
1007 claims it for that **account**. The same player may reuse that last name
1008 on their other characters. Another account cannot use it.
1009- **First names** need not be unique globally.
1010- For a given account, `firstName` + `lastName` must be unique among
1011 characters that still exist (including those pending deletion).
1012- Uniqueness is case-insensitive; display uses the casing the player typed.
1013
1014```text
1015Account
1016- accountId
1017- authSubject // from auth.timfalken.com, or stub admin-<n>
1018- email? // from auth; absent on stub
1019- surnameClaims[]
1020
1021Character
1022- characterId
1023- accountId
1024- firstName
1025- lastName
1026- sex
1027- deletionScheduledAt? // null if not deleting
1028- inventory, equipment, currency, vault, skills, ...
1029```
1030
1031The in-world ECS player entity is a **character**, not the account.
1032
1033## 14.6 Character deletion and inheritance
1034
1035From character select, the player may mark a character for deletion.
1036
1037- The character cannot be played while deletion is pending.
1038- Permanent delete happens after `characterDeletionDelay` (default **24
1039 hours**). Until then the player may cancel.
1040- The server **always** notifies the account email when deletion is
1041 marked (and should notify again on cancel and on actual delete). Stub
1042 auth logs the message instead.
1043- On permanent delete, the name pair is freed. If this account has no
1044 remaining characters with that last name, the surname claim is released.
1045- Before the vault is moved, `BankService` voids outstanding filled
1046 cheques **issued by** this character (reservations return to the vault).
1047- All items in inventory, equipment, carried currency, and the character
1048 vault are moved to that **account's inheritance bank tab**.
1049
1050Any living character of the same account may, at a bank, **claim**
1051inheritance stacks (and currency) into that character's own vault. Claiming
1052is a move from the account tab to the character vault, not a second copy.
1053
1054# 15. Client chunk subscription and replication
1055
1056## 15.1 3×3 visibility
1057
1058A player receives the current chunk and the eight surrounding chunks, a
1059maximum viewport of 48×48 tiles. Neighbouring **closed** chunks are still
1060sent so scenery remains visible; the player simply cannot walk onto them.
1061
1062┌───┬───┬───┐
1063│ V │ V │ V │
1064├───┼───┼───┤
1065│ V │ P │ V │
1066├───┼───┼───┤
1067│ V │ V │ V │
1068└───┴───┴───┘
1069
1070## 15.2 Incremental subscription changes
1071
1072Crossing one chunk east subscribes only the three newly visible eastern
1073chunks and unsubscribes only the three old western chunks. The rest of
1074the 3×3 view remains subscribed.
1075
1076## 15.3 Snapshots and deltas
1077
1078Initial subscription sends a CHUNK_SNAPSHOT containing authored/runtime
1079tile state, currently visible entities and unexpired ground item stacks.
1080Afterwards, revisioned CHUNK_DELTA messages report tile changes, entity
1081spawn/move/change/despawn events and ground-item appear/change/despawn
1082events. Full chunks are not retransmitted every tick.
1083
1084Entity `move` events carry the new integer tile and the current gait so
1085the client can lerp over the walk or run interval. They do not carry a
1086fractional in-between position. Smooth walking is a client visual lerp
1087(section 21.5), not part of the replication payload.
1088
1089Chunk snapshots include the baked light map (section 8.6).
1090
1091Visible equipment is replicated as a compact appearance payload (body
1092sprite plus worn overlay layers and recolour parameters), not as the
1093entity's full inventory. Nearby clients can draw another player's armour
1094without receiving their bags.
1095
1096## 15.4 Visibility can span workers
1097
1098The gateway can source visible chunks from multiple workers. A player
1099may be authoritative on Worker A while one or more of the eight
1100neighbouring visible chunks are owned by Worker B. Client visibility
1101must never force simulation-region reassignment.
1102
1103# 16. Click-to-move and A\* pathfinding
1104
1105## 16.1 Command flow
1106
1107Client: MOVE_TO(tileX, tileY)
1108↓
1109Gateway validates/authenticates
1110↓
1111Owning worker validates target
1112↓
1113A\* calculates authoritative route
1114↓
1115Path component attached/updated
1116↓
1117MovementSystem advances the entity **one tile at a time** on the global
1118walk/run cadence (section 13.4)
1119
1120Authoritative `Position` is always an integer `tileX`, `tileY`. The server
1121does not store a sub-tile location for walking mobiles. When a movement
1122tick allows this gait to step, `MovementSystem` commits the next path
1123tile in a single jump. Combat, occupancy, pickup and interaction all use
1124that committed tile.
1125
1126Flying pigeons still ignore the ground navigation grid, but their
1127replicated ECS position is likewise a tile. The transit clock determines
1128which tile they occupy at a given time; the client may lerp the sprite
1129between those tiles like any other mobile.
1130
1131## 16.2 Initial A\* implementation
1132
1133For normal player clicks within the visible 3×3 chunks, the search space
1134is at most 48×48 = 2,304 tiles, so conventional A\* is a strong starting
1135point.
1136
1137- Binary heap priority queue for the open set.
1138
1139- Manhattan heuristic for four-direction movement; octile heuristic if
1140 diagonal movement is later allowed.
1141
1142- Reusable typed-array or pooled search buffers for hot paths to reduce
1143 allocation and garbage collection.
1144
1145- Rate-limit path requests per player and avoid recalculation every
1146 tick.
1147
1148- Use block passability, **open-chunk** bounds, and dynamic occupancy;
1149 ground is visual only. Tiles in closed or never-edited chunks are not
1150 legal path targets for players.
1151
1152## 16.3 Navigation revisions
1153
1154Each chunk maintains a navigation revision that increments when a
1155movement-affecting block changes. A path records the relevant revisions.
1156Static geometry changes can invalidate paths; temporary mobile occupancy
1157normally causes a short wait or small local re-path rather than
1158rebuilding every path.
1159
1160## 16.4 Long-distance extension
1161
1162If long-distance autonomous travel is added later, introduce
1163hierarchical pathfinding: region graph → chunk portals/edges → local
1164tile A\*. The client movement command interface does not need to change.
1165Server movement remains discrete tile steps; only the path length changes.
1166
1167# 17. Automatic update and restart scheduler
1168
1169## 17.1 Restart triggers
1170
1171A graceful restart is scheduled for the next midnight in configured
1172server-local time when either of these conditions occurs:
1173
1174- A new commit is detected on origin/master. The master branch is the
1175 live branch.
1176
1177- An administrator saves a world-editor change, creating/updating a
1178 pending authored world revision.
1179
1180Multiple triggers coalesce into one scheduled restart. The scheduler
1181stores all reasons so players and admins can see why a restart is
1182pending.
1183
1184## 17.2 Detecting live-code changes
1185
1186The running server periodically performs a non-destructive remote check,
1187for example git fetch origin master followed by comparison of the
1188running commit with origin/master. It does not update the checked-out
1189code while the game is live.
1190
1191## 17.3 Server-local midnight
1192
1193Midnight is calculated in a configured IANA time zone rather than by
1194adding 24 hours to the current time. This keeps behaviour correct across
1195daylight-saving transitions.
1196
1197## 17.4 Player-visible restart state
1198
1199Restart status is part of the server status sent to clients. Connected
1200players see that a restart is scheduled and the scheduled local time.
1201The server can also issue configurable countdown notices as the restart
1202approaches and includes the state immediately when a player logs in.
1203
1204RestartStatus {
1205scheduled: true,
1206scheduledAt: timestamp,
1207reasons: \["code-update", "world-update"\]
1208}
1209
1210## 17.5 Manual admin restart
1211
1212An authorised admin action can invoke the same graceful restart pipeline
1213immediately. This is not a separate “hard restart” path; it differs only
1214in scheduled time.
1215
1216## 17.6 Graceful restart sequence
1217
1218> **1.** Enter `DRAINING` / `RESTARTING` state and reject new logins.
1219>
1220> **2.** Broadcast the final restart notice.
1221>
1222> **3.** Disconnect player sessions cleanly and persist session state.
1223> Shutdown handling overrides normal offline-script retention so chunk
1224> unload cannot be blocked by a retiring process.
1225>
1226> **4.** Stop accepting new gameplay commands and finish the current
1227> safe tick boundary.
1228>
1229> **5.** Force-unload every resident region/chunk, ignoring normal
1230> `ChunkLoader` references. This invokes the ordinary chunk/entity unload
1231> persistence path exactly once.
1232>
1233> **6.** Flush the persistence service and close SQLite connections
1234> cleanly.
1235>
1236> **7.** Atomically write a restart request manifest. It records the
1237> restart reasons, whether a code deployment is requested, the target Git
1238> commit if known, and the pending world revision if one exists.
1239>
1240> **8.** Exit the Node.js game process cleanly. At this point the game
1241> process has no responsibility for updating or relaunching itself.
1242
1243## 17.7 systemd process supervisor
1244
1245The production Node.js process is owned by a `systemd` service. `systemd`
1246therefore already knows when the process has **fully exited**; no separate
1247polling process is needed. Only after the previous `ExecStart` process is
1248gone does `systemd` begin the next service start.
1249
1250The preferred lifecycle is:
1251
1252```text
1253Running Node.js server
1254 |
1255 | graceful planned restart or crash
1256 v
1257Node.js process fully exits
1258 |
1259 v
1260systemd starts the service again
1261 |
1262 +--> conditional update hook
1263 | |
1264 | +--> planned code deployment: git fetch/pull --ff-only
1265 | +--> world-only restart: no Git mutation
1266 | +--> crash/no restart manifest: no Git mutation
1267 |
1268 +--> optional dependency/build step if deployment changed code
1269 |
1270 v
1271Start Node.js server
1272 |
1273 v
1274Startup selects the new active world revision
1275 |
1276 v
1277Gateway opens when the world reports READY
1278```
1279
1280### 17.7.1 Why Git pull must be conditional
1281
1282A naive `ExecStartPre=git pull` on **every** restart is unsafe. Suppose a
1283new commit is detected at 14:00 and correctly scheduled for midnight, but
1284the game process crashes at 16:00. An unconditional pull would deploy the
1285new commit immediately during crash recovery, bypassing the scheduled
1286maintenance window.
1287
1288Therefore the restart manifest distinguishes an intentional deployment
1289restart from an ordinary process failure:
1290
1291```json
1292{
1293 "reason": ["code-update", "world-update"],
1294 "deployCode": true,
1295 "targetCommit": "<optional commit hash>",
1296 "pendingWorldRevision": 184
1297}
1298```
1299
1300The manifest should be written using a temporary file plus atomic rename
1301so the supervisor never consumes a half-written request. The supervisor
1302consumes/removes the request only after it has successfully interpreted
1303it.
1304
1305If the Node.js process dies without a valid deployment request, `systemd`
1306restarts the **currently checked-out version**. This gives fast crash
1307recovery without prematurely deploying pending code.
1308
1309### 17.7.2 Suggested systemd shape
1310
1311A production unit can conceptually look like this:
1312
1313```ini
1314[Unit]
1315Description=Questward Server
1316After=network-online.target
1317Wants=network-online.target
1318
1319[Service]
1320Type=simple
1321User=questward
1322Group=questward
1323WorkingDirectory=/srv/questward/current
1324
1325# This hook checks the restart manifest. It pulls/builds only when an
1326# intentional deployment was requested. Prefixing with '+' optionally
1327# allows the hook to run with privileges different from the game user.
1328ExecStartPre=+/usr/local/sbin/questward-update-if-requested
1329ExecStart=/usr/bin/node /srv/questward/current/dist/server.js
1330
1331Restart=always
1332RestartSec=5s
1333TimeoutStopSec=120s
1334KillSignal=SIGTERM
1335
1336[Install]
1337WantedBy=multi-user.target
1338```
1339
1340`Restart=always` is appropriate here because an explicit
1341`systemctl stop questward` does not cause systemd to restart the unit,
1342while a clean in-game restart exit and an unexpected crash both do.
1343
1344The exact paths, build command and privilege split are deployment
1345details, but the important invariant is that the **Node.js process does
1346not pull Git itself**.
1347
1348### 17.7.3 Code-update, world-update and crash behaviour
1349
1350| Situation | Restart manifest | Git pull before restart | World revision |
1351|---|---|---|---|
1352| Scheduled code update | `deployCode=true` | Yes, fast-forward only | Activate pending revision if present |
1353| World-editor-only update | `deployCode=false` | No | Activate pending revision |
1354| Manual deployment restart | Explicit admin intent | As requested | Activate pending revision if present |
1355| Unexpected Node.js crash | Missing/invalid | **No** | Continue current active revision |
1356| `systemctl stop` | Irrelevant | No automatic restart | N/A |
1357
1358This preserves the midnight deployment promise even when the game crashes
1359before the scheduled maintenance window.
1360
1361## 17.8 Failure behaviour
1362
1363Deployment should fail closed. If Git cannot fast-forward, a build or
1364migration fails, or startup validation fails, the game must not open to
1365players on a partially updated state. The update hook should log the
1366failure clearly and return non-zero; systemd may retry according to its
1367restart/start-limit policy. Databases remain intact, and backups or
1368snapshots before schema migrations are recommended.
1369
1370A failed **crash recovery** that did not request deployment must not
1371silently switch to a newer Git commit as a recovery strategy.
1372
1373# 18. Future player scripting architecture
1374
1375## 18.1 Scope
1376
1377The custom scripting language is explicitly a later feature. Version 1
1378only needs architectural hooks so adding scripts does not require
1379replacing the player-control or simulation model.
1380
1381## 18.2 Controller abstraction
1382
1383All player actions should already pass through an internal command
1384interface. Manual client input is therefore one possible controller. A
1385future script is another controller that emits the same validated action
1386intentions.
1387
1388```text
1389ClientController ─┐
1390 ├─> ActionCommand queue ─> authoritative game systems
1391ScriptController ─┘
1392```
1393
1394Scripts never mutate ECS components directly. They request actions such
1395as MoveTo, Interact or Attack and receive the same validation as a human
1396client.
1397
1398## 18.3 Online scripted mode
1399
1400A logged-in player may enable the script while remaining connected and
1401observing the game. Control mode explicitly determines whether manual
1402input or the script is currently producing gameplay commands. The server
1403remains authoritative either way.
1404
1405## 18.4 Logout with active script
1406
1407If a player has configured offline script execution, logout removes the
1408network/controller connection but keeps the player entity alive. The
1409entity changes to an offline script-controlled state and continues
1410acting until it dies or its configured offline duration expires.
1411
1412Player online
1413Player + NetworkIdentity + ChunkLoader + Controller
1414↓ logout with offline scripting
1415Player + ScriptController + ChunkLoader + OfflineUntil
1416↓ death OR expiry
1417persist player state → remove runtime entity
1418
1419## 18.5 Offline scripted players and loading
1420
1421An offline scripted player must continue to stimulate the world it
1422traverses, so it retains a ChunkLoader. This is powerful but potentially
1423expensive: thousands of offline scripts could keep large parts of the
1424world active. Offline duration, script CPU budget and concurrent
1425offline-script limits therefore become explicit resource policy, not
1426implementation accidents.
1427
1428## 18.6 Restart continuity
1429
1430A planned restart persists the offline-script state and expiry time,
1431force-unloads the old process, and rehydrates still-valid offline
1432scripted players during startup. This is why the startup index for
1433persistent ChunkLoaders is part of the base architecture.
1434
1435## 18.7 Scripting language safety requirements
1436
1437When the language is implemented, it should be interpreted/compiled into
1438a purpose-built sandbox rather than evaluated as JavaScript. At minimum
1439it should enforce:
1440
1441- No file-system, operating-system, database or arbitrary network
1442 access.
1443
1444- No eval or escape into Node.js objects.
1445
1446- Per-tick/per-event instruction budgets and bounded memory.
1447
1448- Rate-limited expensive operations such as path requests and world
1449 queries.
1450
1451- Capability-based read APIs for nearby visible/known world state.
1452
1453- Action output only through the normal server command pipeline.
1454
1455- Persistable script variables/state if offline execution must survive
1456 restarts.
1457
1458- Deterministic or tightly controlled timing semantics where practical.
1459
1460An event-driven language is preferable to running every player script
1461continuously at full simulation frequency. Events such as arrival,
1462attack, nearby entity changes or timer expiration can wake scripts only
1463when useful.
1464
1465# 19. Security and administration
1466
1467- World-editor endpoints require an explicit admin role and separate
1468 server-side authorisation checks.
1469
1470- Client-supplied entity/player IDs are never trusted as authority;
1471 authenticated connection/session context identifies the actor.
1472
1473- World-editor data is validated against known ground, block, item and mob
1474 definitions before database write.
1475
1476- Admin restart and deployment controls use the same authenticated
1477 administration layer.
1478
1479- The Node.js game process should run as a dedicated unprivileged user.
1480 Where practical, source-update permission belongs only to the systemd
1481 update hook (for example a privileged `ExecStartPre` helper), leaving
1482 the running Node.js process unable to modify its own checkout.
1483
1484- SQLite writes are parameterised and centralised through
1485 persistence/editor services.
1486
1487- Inventory, vault, cheque and courier mutations are server-authoritative.
1488 Clients cannot invent cheque IDs, forge cargo, or credit a vault.
1489
1490- Attack hit/miss and damage are server-authoritative. Clients cannot supply
1491 a roll or a damage result. Shop purchase prices are computed at buy time
1492 on the server.
1493
1494# 20. Recommended process topology
1495
1496```text
1497Clients
1498 |
1499 v
1500WebSocket/API Gateway
1501 |
1502 +-- Region Coordinator ----> Simulation Worker A
1503 | <--> Simulation Worker B
1504 |
1505 +-- Communication Service --> proximity speech
1506 |
1507 +-- CourierService ---------> pigeon cargo / transit
1508 |
1509 +-- BankService ------------> shared vaults / cheques / reservations
1510 |
1511 +-- MarketService ----------> order book / escrow / trades / last-sale index
1512 |
1513 +-- Persistence Service ----> state.sqlite
1514 |
1515 +-- Admin / World Editor ---> world.sqlite
1516
1517External process supervision:
1518systemd ---> conditional deployment hook ---> Node.js relaunch
1519```
1520
1521# 21. Player client architecture
1522
1523## 21.1 FrameworkV3 as a git submodule
1524
1525The player-facing client is built on the shared FrameworkV3 library:
1526
1527<https://gitlab.com/Timfa/frameworkv3>
1528
1529FrameworkV3 contains generic reusable client-side code. Game-specific rendering,
1530UI, input, assets and protocol handling live in this repository, on top of
1531that library. They are not patched into FrameworkV3 unless they are genuinely
1532reusable across games.
1533
1534This repository vendors FrameworkV3 as a **git submodule** rather than
1535copying its source or depending on an unpublished global install.
1536
1537```text
1538mmo/
1539 client/
1540 frameworkv3/ # git submodule → gitlab.com/Timfa/frameworkv3
1541 src/ # this game's client: protocol, UI, world view, assets
1542 server/ # Node.js ECS backend; does not import FrameworkV3
1543```
1544
1545The submodule path is `client/frameworkv3`. A clone of this repo is not
1546client-buildable until submodules are present:
1547
1548```text
1549git clone --recurse-submodules <this-repo>
1550# or, in an existing checkout:
1551git submodule update --init --recursive
1552```
1553
1554The submodule records a **pinned commit**. Bumping FrameworkV3 is an explicit
1555commit in this repository (new submodule SHA). Game code must not rely on an
1556uncommitted dirty checkout of the submodule.
1557
1558Build order:
1559
1560```text
15611. Build FrameworkV3 from client/frameworkv3
15622. Build this game's client against that output
15633. The Node.js server is a separate build and does not link FrameworkV3
1564```
1565
1566The exact FrameworkV3 build command follows that project's own instructions.
1567This game's client build must consume the framework's public/build artefacts,
1568not fork its internals.
1569
1570CI and developer machines check out submodules before the client job. A
1571missing or uninitialized submodule is a failed client build, not a fallback
1572to a system copy of FrameworkV3.
1573
1574If this repo's `master` also ships the built web/desktop client from the
1575same process that deploys the game server, a submodule bump is just another
1576commit and follows the normal midnight restart/deploy path. The running
1577Node.js game process still does not compile or import FrameworkV3.
1578
1579The backend remains the authoritative Node.js ECS simulation described in this
1580document. The client does **not** need to use ECS. It receives only a small
15813×3-chunk view plus player/UI state, so a conventional object/view-model model is
1582simpler and entirely appropriate.
1583
1584## 21.2 Server/client model separation
1585
1586Backend ECS components are not treated as a shared client object model. Network
1587messages form the contract between the two sides.
1588
1589```text
1590Authoritative Node.js ECS
1591 |
1592 | snapshots / deltas / UI state
1593 v
1594Network protocol DTOs
1595 |
1596 v
1597Built FrameworkV3 (from client/frameworkv3 submodule)
1598 |
1599 v
1600This game's client code (client/src)
1601```
1602
1603The two projects may share protocol schemas, enums or generated message types,
1604but the client must not depend on the internal layout of ECS component storage.
1605That allows server internals to be optimised without forcing corresponding
1606client rewrites.
1607
1608## 21.3 Sprite size, pivot and Y-sort
1609
1610World sprites may be any pixel size. The gameplay tile remains 16×16.
1611Each sprite is placed with an automatic pivot: **horizontally centred**,
1612and **8 pixels up from the bottom** of the sprite. That pivot sits on the
1613tile centre, so a 16×16 sprite still fills the tile and a taller sprite
1614stands on the same feet line and extends upward.
1615
1616Each sprite kind — **grounds**, **blocks**, **items**, **mobs**, and
1617**characters** — uses its own per-type asset folder
1618(`client/assets/<kind>/<key>/`). Every base PNG in that folder is a
1619**visual state**. Filenames ending in `-bloom`, `-equip`, or combinations
1620such as `-equip-bloom` are **companions**, not states: `torch-bloom.png`
1621is the bloom overlay for state `torch`, `{state}-equip.png` is the worn
1622equipment overlay for that state, and `{state}-equip-bloom.png` is the
1623bloom overlay for that equip sprite. Companions always live in the same
1624folder as their base state and are never listed as placeable editor
1625states. Image names follow `layer:key:state` (plus `:equip` / `:bloom`
1626suffixes). States are not listed in the type definition: the first base
1627filename in alphabetical (numeric) order is the default. A later gameplay
1628system may set a named state on a placed tile (for example a door
1629`closed` / `open`); unknown names fall back to the default. The editor
1630mouse wheel cycles these states.
1631
1632Bloom companions are drawn on a separate Framework **bloom** render
1633layer that uses `Shader.getBloomPostChain(...)`. Bloom post-chain
1634parameters are live world settings under the Graphics tab.
1635
1636Each type definition may set sprite-sheet playback for every state PNG:
1637
1638```text
1639frames // sub-images in the sheet; default 1
1640framesPerRow // columns in the sheet; default 1
1641animationSpeed // seconds per frame; 0 means still
1642```
1643
1644Blocks and mobiles with oversized sprites are **Y-sorted**: sprites
1645higher on the screen draw behind sprites lower on the screen, using the
1646pivot's world Y (the occupied tile, or the interpolated foot position
1647while walking). Ground tiles and the night overlay stay behind and in
1648front of that pass respectively.
1649
1650Nearest-neighbour sampling still applies so pixels stay sharp under
1651viewport zoom. Zoom scales the whole view uniformly; it is not a
1652per-sprite size override.
1653
1654## 21.4 Viewport, camera and zoom
1655
1656In normal play the viewport is **always centered on the local player's
1657character**. The camera does not free-pan. Scrolling the world happens
1658only because the player moved.
1659
1660The player may zoom in and out within configured minimum and maximum
1661bounds (for example 1× to 4×; the exact numbers are a game setting). Zoom
1662does not move the camera off the player and does not change server
1663visibility: the client still receives only the 3×3 chunk window.
1664
1665The admin world editor is the exception: it frames the selected 16×16
1666chunk and navigates by chunk, as in section 8.1.
1667
1668## 21.5 Client movement interpolation
1669
1670The server jumps mobiles from tile to tile. The client draws a visual
1671lerp between the previous replicated tile and the new one over the
1672interval implied by gait and `WorldSettings` (walk: `1 / walkTilesPerSecond`,
1673run: half of that). If a delta arrives late, clamp the remaining lerp.
1674That lerp is presentation only:
1675
1676- Hit tests, range, pickup and occupancy use the authoritative tile.
1677- A corrected server position snaps the interpolation target; the client
1678 does not accumulate drift.
1679- Interpolation does not entitle the client to send fractional positions.
1680
1681## 21.6 Equipment layers and recolouring
1682
1683A mob (including a player character) is drawn as a **stack of sprites**
1684on the same tile: the body sprite (male or female from character
1685sex, or the mob archetype body), then each piece of visible equipment.
1686Overlays are not baked into the body art.
1687
1688```text
1689draw order (back → front, default)
1690 1. body / mob base
1691 2. boots
1692 3. chest
1693 4. weapon
1694 5. legs
1695 6. hair (if visible; inserted before headgear)
1696 7. head
1697 8. off-hand
1698```
1699
1700Slot draw order is data (`EQUIPMENT_DRAW_ORDER`) so a cloak or a two-handed sprite can be inserted
1701without a renderer rewrite. Weapon sits above chest and under legs so bows/weapons
1702read between shirt and trousers; clothing art should avoid bad waist overlap.
1703Overlay sprites use the same automatic pivot
1704as other world art (horizontal centre, 8 pixels from the bottom).
1705
1706Equipment items stay in dedicated **equipment slots**, not in the 32
1707inventory slots, while worn. `EquipItem(slotIndex)` moves a legal item
1708from inventory into the matching equipment slot, returning any previously
1709worn item to inventory if there is space. `UnequipItem(equipSlot)` does
1710the reverse. The weapon equipment slot is what combat uses; it replaces
1711the older “wielded flag on an inventory slot” idea.
1712
1713Non-player mobs may carry an `Equipment` component or a simpler appearance
1714list on the mob definition so a guard can show armour without a player
1715inventory.
1716
1717```text
1718Equipment
1719- slots: { head?, chest?, legs?, boots?, weapon?, offhand?, ... }
1720
1721ItemDefinition.equipment?
1722- slot
1723- overlaySpriteId
1724- recolourableChannels?: ["metal"] // omitted if the art is not recoloured
1725- materialId? // e.g. iron, steel; used with "metal"
1726```
1727
1728Inventory icons and worn overlays may be different 16×16 files. Both are
1729world sprites and both go through the size check.
1730
1731### Recolourable equipment
1732
1733Some gear shares one overlay and is tinted per material. Metal armour is
1734the initial case: iron, steel and later metals are not separate full-size
1735art sets.
1736
1737```text
1738MaterialDefinition
1739- materialId // iron, steel, ...
1740- displayName
1741- channel // metal for armour; later channels may include cloth
1742- colour // destination RGB for that channel
1743```
1744
1745A recolourable overlay is authored as:
1746
1747- the 16×16 overlay sprite, with shading in the channel regions, and
1748- an optional 16×16 **channel mask** of the same dimensions, whose pixels
1749 name which recolour channel they belong to (for example a reserved mask
1750 colour meaning `metal`). Unmasked pixels are drawn unchanged.
1751
1752At draw time, masked pixels keep the overlay’s relative brightness
1753(highlights and shadows) and replace the hue/saturation with the
1754item’s `MaterialDefinition.colour`. The client must not invent a colour;
1755the server sends the material id (or the already-resolved colour) on the
1756appearance layer.
1757
1758Iron plate and steel plate therefore share `overlaySpriteId = platebody`
1759and differ only by `materialId`. Non-metal unique art omits
1760`recolourableChannels` and is blitted as authored.
1761
1762Recolour happens on the client as a presentation step. It does not change
1763item identity, combat stats or inventory. Nearby observers receive enough
1764appearance data to apply the same layers and tints.
1765
1766## 21.7 World time and night shading
1767
1768The client treats **world time** as server time minus 1200 years (section
176913.5). It uses that clock-of-day to shade the 3×3 view.
1770
1771At night, tiles that the baked light map says are unreachable from any
1772static light are drawn darker. Tiles a light can reach stay brighter.
1773Light does not bleed through walls: the mask was raycast through passable
1774tiles at editor save, including across chunk borders, so a torch on the
1775edge of one chunk can light tiles in the next.
1776
1777By day, ambient light is full and the baked mask does not darken the
1778ground. The day/night curve (how dark “night” is, dusk length) can stay a
1779world setting or a later tuning value; the invariant is that night uses
1780baked reachability, not a per-frame raycast.
1781
1782The world-editor night-to-day slider is the same shading function, driven
1783by the slider instead of the clock, so an admin can preview a chunk at
1784any light level without changing live world time.
1785
1786# 22. Items, inventory and ground drops
1787
1788## 22.1 Item definitions
1789
1790Every obtainable object is an `ItemDefinition`. Stacking, uniqueness and
1791later economy rules are data on that definition, not special cases in UI
1792code.
1793
1794```text
1795ItemDefinition
1796- itemId
1797- displayName
1798- description
1799- seedValue // base price before player-market adaptation
1800- stackable
1801- maxStackSize // default 99 for stackable items
1802- uniqueInstance // true for letters, filled cheques, and similar
1803- category: ingredient | intermediate | finished | document | other
1804- npcShopAllowed
1805- gatherSources
1806- craftingRecipe(s)
1807- dropTableSources
1808- attack?: AttackProfile // weapons; omitted for non-weapons
1809- equipment?: // worn/wielded visuals; see 21.6
1810 slot
1811 overlaySpriteId
1812 recolourableChannels?
1813 materialId?
1814```
1815
1816A stackable item with no instance data merges with an identical `itemId` in
1817the same container up to `maxStackSize`. Unique-instance items never merge;
1818each occupies its own slot at quantity 1.
1819
1820**Currency is not an inventory item.** Carried money is a numeric `Currency`
1821balance on the player. Banked money is a numeric balance on that player's
1822vault. Coins do not occupy inventory slots and cannot be dropped on the
1823ground in this model.
1824
1825How most items are obtained is specified later. Two source families already
1826fit this model without changing it:
1827
1828- Ground-item spawners in the world editor, analogous to mob spawners.
1829- Later harvesting from the environment by players.
1830
1831Paper, blank cheques and letters are specified now because communication,
1832banking and pigeons depend on them.
1833
1834## 22.2 Player inventory
1835
1836A player inventory has exactly **32 slots**.
1837
1838```text
1839Inventory
1840- slots[32]: empty | ItemStack
1841
1842ItemStack
1843- itemId
1844- quantity // 1 for unique-instance items
1845- instance?: ItemInstance // present only when uniqueInstance is true
1846- origin?: ItemOrigin // crafter or shop NPC; see 22.6
1847```
1848
1849Rules:
1850
1851- A stack occupies exactly one slot, regardless of quantity.
1852- Inserting a stackable item first tries to merge into an existing compatible
1853 stack whose combined quantity would not exceed `maxStackSize`. Stacks are
1854 compatible only when `itemId` matches and `origin` matches (including both
1855 being empty). Any remainder needs an empty slot, or the whole action fails.
1856- Moving, swapping and splitting stacks are ordinary server-validated
1857 commands. The client never asserts the resulting inventory.
1858- Inventory, wallet and vault contents are **player-private UI state**. They
1859 are not part of 3×3 chunk replication. Other clients see ground items and
1860 pigeon entities, not another player's bags or a pigeon's cargo.
1861- Logout and restart persist the full inventory and carried currency in
1862 `state.sqlite`.
1863
1864## 22.3 Paper and letters
1865
1866Blank paper is a stackable item.
1867
1868Writing consumes one paper and produces a **letter**: a unique-instance item
1869whose instance data is text written by a player. A letter is not a mail
1870record and has no inherent recipient. It is just paper with writing on it.
1871
1872```text
1873LetterInstance
1874- letterId
1875- authorPlayerId
1876- body
1877- writtenAt
1878```
1879
1880If the paper stack's quantity is 1, the slot may be converted in place into
1881the letter. If quantity is greater than 1, writing requires a free inventory
1882slot for the new letter and decrements the paper stack.
1883
1884Reading a letter inspects its instance data. Sending a letter is the same
1885pigeon-cargo action used for any other item stack.
1886
1887Maximum letter length is a defined game rule and can be chosen during
1888implementation.
1889
1890## 22.4 Dropping items
1891
1892A player may drop an item stack, or part of a stack, onto their current tile.
1893
1894```text
1895GroundItem
1896- groundItemId
1897- tileX / tileY
1898- ItemStack
1899- droppedAt
1900- expiresAt // droppedAt + WorldSettings.groundItemDespawnDuration
1901- source // player-drop | later: item-spawner
1902- droppedByPlayerId?
1903```
1904
1905Rules:
1906
1907- Player-dropped items remain for `WorldSettings.groundItemDespawnDuration`
1908 (default **10 minutes**), then vanish forever.
1909- Anyone may pick up a ground item. There is no owner lock and no loot-rights
1910 delay.
1911- Ground items **do not block movement** and do not prevent a player from
1912 standing on that tile.
1913- Pickup requires the player to **stand on that tile**. The command names the
1914 `groundItemId` when several stacks share the tile.
1915- Pickup fails if the player's inventory cannot accept the stack (no legal
1916 merge and no empty slot). The ground item is unchanged.
1917- Several distinct stacks may occupy one tile at once.
1918- Later naturally spawned ground items use the same non-blocking
1919 representation, but their lifetime and respawn belong to the item spawner
1920 rather than this 10-minute player-drop timer.
1921
1922Dropped items are not `ChunkLoader`s and do not keep a chunk simulated.
1923
1924They **do** survive chunk unload until `expiresAt`, using timestamp expiry
1925rather than a per-tick countdown. On unload, unexpired ground items are
1926written to `state.sqlite`. On load or wake, items whose `expiresAt` is in
1927the past are discarded and never replicated. Simulating chunks also remove
1928them when the timestamp elapses.
1929
1930If a unique-instance item that encodes a bank reservation (a filled cheque)
1931expires on the ground or is otherwise destroyed without being redeemed, that
1932reservation is released and the reserved goods become available in the
1933issuer's vault again.
1934
1935## 22.5 Pickup and drop commands
1936
1937```text
1938DROP_ITEM(slotIndex, quantity?)
1939PICKUP_ITEM(groundItemId)
1940```
1941
1942Both are intentions. The owning worker validates the actor's tile, inventory
1943space and stack rules, then applies the result. Standing on a tile that has
1944ground items does not pick them up automatically.
1945
1946## 22.6 Item inspection, origin and displayed value
1947
1948Hovering an item — in inventory, a shop stock list, or on the ground — shows
1949at least:
1950
1951```text
1952ItemTooltip
1953- displayName
1954- description
1955- originLabel // who crafted it, or the shop NPC if bought there
1956- currentValue // undiscounted adapted value; see section 27
1957```
1958
1959Origin is stored on the stack:
1960
1961```text
1962ItemOrigin
1963- kind: crafted | shop | unknown
1964- playerId? // when crafted by a player
1965- npcId? // when bought from a shop NPC
1966```
1967
1968The origin label is the crafting player's name, or the shop NPC's name when
1969the stack was bought from that NPC. Harvested, looted or otherwise unstamped
1970stacks use `unknown` and omit the origin line until later content says
1971otherwise. Buying from a shop stamps that NPC as origin. Crafting stamps the
1972crafter. Shop-bought goods are not treated as crafted by the NPC; the NPC
1973name simply occupies that inspection field.
1974
1975`currentValue` uses the same last-sale lerp as shopkeepers (section 27.6) but
1976**without** the per-shop discount. It is informational. The client must not
1977recompute it every simulation tick. The player UI may refresh displayed
1978values at most once per minute, from the last-sale record plus `seedValue`.
1979The actual shop purchase price is always computed server-side at the moment
1980of purchase.
1981
1982# 23. Player communication and carrier pigeons
1983
1984## 23.1 Proximity chat is the default
1985
1986Ordinary chat is spatial. A player speaks from a world position and only nearby
1987players receive a useful version of the message. Legibility decreases as the
1988recipient gets farther from the speaker.
1989
1990Readability uses Euclidean tile distance against the 16-tile chunk size:
1991
1992```text
1993distance <= 8 tiles // half a chunk: full plaintext
19948 < distance < 16 // linear falloff, e.g. 12 tiles → 50% readability
1995distance >= 16 tiles // a full chunk: 0% readability, no bubble
1996```
1997
1998The speaker always receives their own trimmed plaintext. Other recipients receive
1999a server-obscured copy: letters and digits may become `.` with probability
2000`1 - readability`; spaces and punctuation stay. At 0% readability the server
2001sends nothing, so the client never draws a bubble.
2002
2003Enter opens a bottom-of-screen line (max `chatMaxCharacters`, default 100).
2004Enter again trims and sends `CHAT_SAY`. Escape cancels. The client shows
2005`CHAT_BUBBLE` above the speaker.
2006
2007For example:
2008
2009```text
2010Near: I'm really far away
2011Farther: I'm re...y far aw.y
2012Very far: I'...re..ly..ar.aw.y
2013Beyond range: no message
2014```
2015
2016Crucially, degradation is performed **server-side**. The server must not send the
2017full plaintext to a distant client and merely ask that client to obscure it,
2018because a modified client could then recover speech it was not supposed to
2019understand.
2020
2021A chat message therefore conceptually contains:
2022
2023```text
2024ChatSpeech
2025- messageId
2026- speakerEntityId
2027- originX / originY
2028- createdAt
2029- text
2030```
2031
2032The communication service performs a spatial recipient query and derives the
2033recipient-specific legible representation before routing it through the gateway.
2034Chat routing is separate from normal 3×3 chunk replication, so the eventual
2035hearing/text range does not have to equal the visual chunk-subscription radius.
2036
2037## 23.2 Persistent player groups
2038
2039Players can create permanent groups and invite other players into them. Groups
2040are durable social entities stored in `state.sqlite`, with membership surviving
2041logout and server restart.
2042
2043A minimal model contains:
2044
2045```text
2046PlayerGroup
2047- groupId
2048- name
2049- owner / roles
2050- createdAt
2051
2052PlayerGroupMember
2053- groupId
2054- playerId
2055- role
2056- joinedAt
2057```
2058
2059Invite, accept, leave, kick and role-management operations are authoritative
2060server actions.
2061
2062Group membership does **not** create magical long-distance communication. If
2063members are close enough, they can communicate through the normal proximity
2064rules. Communication to distant group members means sending items — including
2065letters — by carrier pigeon, the same mechanism available to any player.
2066
2067If group-wide letter sending is later supported, it is an addressing
2068convenience that still consumes one paper/letter item and one pigeon dispatch
2069per recipient. The group is not a global instant chat channel.
2070
2071## 23.3 Pigeons carry cargo, not messages
2072
2073A carrier pigeon is a free physical courier. It does not send a chat packet.
2074It carries **either**:
2075
2076- an amount of the sender's carried currency, or
2077- exactly one item stack (a letter, a filled cheque, blank paper, or any
2078 other stack)
2079
2080One pigeon cannot carry both money and an item, and cannot carry two item
2081stacks. Dispatching a pigeon is **free**, so a player who wants to move
2082several stacks sends several pigeons one after another.
2083
2084Cargo is removed from the sender immediately and placed into durable transit.
2085A crash or restart cannot duplicate that cargo or silently erase it.
2086
2087Pigeons are not inventory items. Any player may dispatch one from anywhere,
2088provided they have valid cargo.
2089
2090```text
2091SendPigeon
2092- destination: Player(playerId) | Bank
2093- cargo: Money(amount) | Item(slotIndex, quantity?)
2094```
2095
2096## 23.4 Destinations
2097
2098**Player destination.** The pigeon flies toward a character addressed by
2099**first name and last name**. The sender may type that pair, or pick a
2100friend from their friends list to fill the same fields. On arrival:
2101
2102- Money is added to the recipient's carried `Currency` if they are online;
2103 otherwise it is deposited into the recipient's bank.
2104- An item stack is placed in the recipient's inventory if they are online and
2105 have space (a legal merge or an empty slot). If they are offline or cannot
2106 accept the stack, the pigeon continues to the **nearest bank** and deposits
2107 the stack into the recipient's vault.
2108
2109This keeps offline and full-inventory delivery durable without a separate
2110mailbox object.
2111
2112**Bank destination.** The pigeon flies to the **nearest bank** to the dispatch
2113tile. Travel time is that aerial journey, even though every bank shares the
2114same vault. On arrival the cargo is deposited into the **sender's** vault,
2115except for the filled-cheque special case in section 24.7.
2116
2117"Nearest bank" is computed from authored Bank block positions in the pinned
2118world revision. If additional banks are added later, a pigeon sent to `Bank`
2119still lands at whichever bank is closest to where it was dispatched; the
2120goods then appear in the shared vault.
2121
2122## 23.5 Carrier pigeon transit
2123
2124A carrier pigeon must take time to cross the world; long-distance item and
2125currency delivery is intentionally not instantaneous.
2126
2127Flight speed is world-tunable in three phases (defaults chosen so a pigeon can
2128overtake a running player):
2129
2130| Phase | Distance | Default tiles/s | Setting |
2131|-------|----------|-----------------|---------|
2132| Takeoff | first `pigeonPhaseTiles` (default 5) | 3 | `pigeonTakeoffTilesPerSec` |
2133| Cruise | middle of the route | 8 | `pigeonCruiseTilesPerSec` |
2134| Landing | last `pigeonPhaseTiles` | 3 | `pigeonLandingTilesPerSec` |
2135
2136At MMO scale, however, every delivery should not keep an entire trail of regions
2137fully stimulated merely so a pigeon can advance. The recommended model is a
2138persistent courier transit record with world position/route/progress that can
2139advance through dormant space using coarse path segments and timestamps.
2140
2141```text
2142CourierTransit
2143- courierId
2144- cargo // Money(amount) | ItemStack
2145- senderPlayerId
2146- destination // Player(playerId) | Bank
2147- currentPosition
2148- route
2149- speed / timing state
2150- status
2151```
2152
2153A carrier pigeon is part of the shared physical world, not a private visual
2154belonging only to its sender or recipient. Whenever its calculated route passes
2155through a **simulating chunk**, the courier should materialise there as a normal
2156ECS `Mob` entity, regardless of whether the sender or recipient is nearby. Any
2157client whose normal 3x3 chunk subscription includes that pigeon receives it like
2158any other visible mobile entity and can therefore see unrelated pigeons flying
2159past in the distance.
2160
2161The visible pigeon does **not** receive `ChunkLoader`. It exists because the chunk
2162is already simulating for some other reason. If it leaves the last relevant
2163simulating chunk, its exact position/progress is folded back into the durable
2164`CourierTransit` record and the ECS instance can disappear while the journey
2165continues abstractly. If a dormant/unloaded part of its route later becomes
2166simulated while the pigeon should currently be inside it, the owning worker
2167materialises the pigeon at the position implied by the transit clock and route.
2168
2169```text
2170Dormant route Simulating chunk Dormant route
2171
2172abstract transit --------> ECS pigeon visible to clients --------> abstract transit
2173 | | |
2174 Player A Player B unrelated observer
2175```
2176
2177This means a player standing halfway between sender and recipient can see the
2178pigeon fly through their area even though the cargo has nothing to do with
2179them. Unrelated clients receive the pigeon entity, not the cargo contents. It
2180preserves the sense that deliveries physically cross the world without
2181requiring thousands of deliveries to become thousands of permanent
2182`ChunkLoader`s.
2183
2184Because pigeons fly rather than use the ground navigation grid, their coarse
2185route can initially be represented by direct or waypoint-based aerial segments.
2186This makes deterministic materialisation from route + elapsed time considerably
2187simpler than it would be for a ground-based courier.
2188
2189If future gameplay allows pigeons to be intercepted, killed or rerouted anywhere
2190along their journey, the transit model can be made progressively more detailed;
2191that interaction is not required by the initial courier design.
2192
2193## 23.6 Courier service
2194
2195A dedicated `CourierService` should own durable cargo and delivery state.
2196Simulation workers may own visible pigeon entities while the service owns the
2197durable fact that a delivery exists.
2198
2199```text
2200Player action -> CourierService -> durable cargo/transit
2201 |
2202 +-> visible pigeon when needed
2203 |
2204 +-> inventory, wallet or BankService deposit
2205```
2206
2207This separation is also useful for marketplace settlement, which uses the same
2208carrier-pigeon delivery infrastructure for remote counterparties.
2209
2210## 23.7 Character friends
2211
2212Friendships are **character-to-character**, stored in `state.sqlite`. They
2213are not account-wide. A hovering client shows only the nearby character's
2214**first name**. Clicking that character opens an inspect modal with first
2215and last name and a friend-request action.
2216
2217A friend request must be accepted (or a reverse request counts as accept).
2218Either character may remove the friendship; it then disappears for both.
2219Incoming and outgoing requests and the friends list are shown in a Friends
2220panel. Deleting a character clears its requests and friendships.
2221
2222The friends list is an addressing book for later pigeon dispatch: pick a
2223friend to fill first and last name, or type a name pair that the server
2224resolves.
2225
2226```text
2227FriendRequest
2228- fromCharacterId
2229- toCharacterId
2230- createdAt
2231
2232Friendship
2233- characterIdA // min(id1, id2)
2234- characterIdB // max(id1, id2)
2235- createdAt
2236```
2237
2238# 24. Bank, cheques and shared vaults
2239
2240## 24.1 Bank location and access
2241
2242A bank exists at or near the central marketplace as an authored Bank block.
2243Deposit, withdraw, cheque issue and in-person cheque redemption require
2244server-validated access to a bank interaction; the bank is not a global menu
2245usable from anywhere.
2246
2247Pigeon dispatch to `Bank` is the exception: that command may be issued from
2248anywhere, and the goods become available only after the pigeon arrives.
2249
2250## 24.2 One shared vault
2251
2252Each **character** has a single vault in `state.sqlite`:
2253
2254```text
2255CharacterVault
2256- characterId
2257- bankedCurrency
2258- stacks[]
2259- reservations[]
2260```
2261
2262Capacity is unlimited: there is no slot cap. Per-stack stacking rules still
2263apply (`maxStackSize`; unique instances never merge), so 200 blank paper is
2264stored as 99 + 99 + 2 rather than one unbounded pile.
2265
2266If more banks are authored later, **all banks are linked**. Withdrawing at
2267bank B can retrieve goods deposited at bank A. The vault is not per-branch.
2268
2269Pigeon deposits affect *when* goods become available, not *which* vault they
2270enter. After the pigeon arrives at the nearest bank, the goods appear in the
2271same shared vault accessible from every bank.
2272
2273## 24.3 Deposit and withdraw
2274
2275While interacting with a bank, a player may:
2276
2277- Deposit any carried currency and any inventory stacks, in whole or in part.
2278- Withdraw currency into the carried wallet.
2279- Withdraw an item stack, or part of a stack, into inventory, subject to the
2280 32-slot and merge rules.
2281- Claim items or currency from the account **inheritance tab** into this
2282 character's vault (section 24.9).
2283
2284Goods reserved by an outstanding filled cheque cannot be withdrawn by the
2285issuer until that cheque is redeemed or voided.
2286
2287## 24.4 Blank cheques
2288
2289A player at a bank may request blank cheques.
2290
2291- Blank cheques are a stackable item with `maxStackSize` 99.
2292- The bank counts blank cheques already in the player's **inventory** (not
2293 the vault) and issues only enough to bring that total to 99.
2294- If the player already holds 99, the bank issues none.
2295- Issued cheques go into inventory, merging into an existing blank-cheque
2296 stack when possible. If the player holds none and has no empty slot, the
2297 request fails.
2298
2299The bank will not issue more than 99 blank cheques into inventory, even on
2300repeated requests.
2301
2302## 24.5 Filling a cheque
2303
2304Using a blank cheque at a bank lets the issuer pick vault goods and a
2305**quantity**. For stackable items they choose an `itemId` and quantity; the
2306quantity may be larger than one `maxStackSize`, and the reservation covers
2307that many available (unreserved) items of that type in the vault. For
2308unique-instance items they choose that exact instance and the quantity is 1.
2309
2310```text
2311FilledChequeInstance
2312- chequeId
2313- issuerPlayerId
2314- itemId
2315- quantity
2316- instance?: ItemInstance // set when the reserved goods are unique
2317- createdAt
2318```
2319
2320Filling:
2321
23221. Validates that the vault has at least `quantity` of that item available
2323 (not already reserved). Unique instances must still be present and unreserved.
23242. Reserves those goods in the issuer's vault. Reserved goods cannot be
2325 withdrawn, sold or reserved again.
23263. Consumes one blank cheque. If that was the last cheque in the slot, the
2327 slot becomes the filled cheque in place; otherwise a free slot is required
2328 for the filled cheque.
2329
2330A filled cheque is a unique-instance **bearer** item. It does not stack.
2331Whoever holds it may redeem it. Cheques specify vault items and a quantity,
2332not carried currency. Money is moved with a pigeon, or by depositing and
2333withdrawing at a bank.
2334
2335## 24.6 Redeeming a cheque in person
2336
2337The bearer interacts with any bank and redeems the filled cheque.
2338
2339- The server moves the reserved goods from the **issuer's** vault into the
2340 **bearer's inventory**, subject to inventory space. A quantity larger than
2341 `maxStackSize` becomes as many stacks as needed.
2342- The cheque item is consumed.
2343- If inventory cannot accept the resulting stacks, redemption fails and both
2344 cheque and reservation remain unchanged.
2345
2346The bearer may then deposit those goods into their own vault if they wish.
2347
2348## 24.7 Redeeming a cheque by pigeon
2349
2350If the bearer dispatches a pigeon whose cargo is a filled cheque and whose
2351destination is `Bank`:
2352
2353- The pigeon flies to the nearest bank from the dispatch tile.
2354- On arrival, `BankService` transfers the reserved goods from the **issuer's**
2355 vault into the **pigeon's sender's** vault.
2356- The cheque is consumed in transit; it is not deposited as an item.
2357
2358The receiver of the transfer is whoever sent that pigeon, not the original
2359cheque issuer. This is how a cheque moves goods from one vault to another
2360without the receiver standing at a bank.
2361
2362Sending a filled cheque to a **player** delivers the cheque item itself (or
2363into that player's bank if they cannot hold it). It does not redeem it.
2364
2365## 24.8 Bank service
2366
2367Vault mutation, cheque issue, reservation, in-person redemption and
2368pigeon-arrival deposits are owned by a single authoritative `BankService`
2369(or an equivalently serialised service) so two concurrent withdrawals,
2370cheque fills or pigeon arrivals cannot double-spend the same goods.
2371
2372```text
2373Bank interaction or pigeon arrival
2374 |
2375 v
2376BankService
2377 - shared vault
2378 - reservations
2379 - cheque issue / redeem
2380 |
2381 +-> inventory / currency on the acting player when in person
2382 |
2383 +-> vault credit on pigeon arrival
2384```
2385
2386Cheque identifiers are server-issued. A client cannot forge a claim against
2387another player's vault.
2388
2389## 24.9 Inheritance bank tab
2390
2391Each **account** has one inheritance tab, separate from every character
2392vault:
2393
2394```text
2395AccountInheritance
2396- accountId
2397- currency
2398- stacks[]
2399```
2400
2401It is written only when a character of that account is permanently deleted
2402(section 14.6). Any of that player's living characters can move stacks and
2403currency from this tab into their own vault at a bank. They cannot deposit
2404into inheritance except through character deletion.
2405
2406# 25. Central marketplace and order matching
2407
2408## 25.1 Marketplace location
2409
2410A central marketplace exists at or near the centre of the game world. Creating,
2411modifying or cancelling market orders requires server-validated access to the
2412marketplace interaction; the marketplace is not intended to be a global menu
2413that can be used from anywhere.
2414
2415Orders themselves remain durable after the player leaves the marketplace or
2416logs out.
2417
2418## 25.2 No public list of sell orders
2419
2420The market is an order book, but players do not browse a list of individual
2421items currently offered for sale.
2422
2423A seller submits:
2424
2425```text
2426SellOrder
2427- item / item definition
2428- quantity
2429- minimum unit/total price
2430```
2431
2432A buyer submits:
2433
2434```text
2435BuyOrder
2436- requested item / matching criteria
2437- quantity
2438- maximum unit/total price
2439```
2440
2441The UI may know which item types exist and may eventually show historical data,
2442but it does not expose the live asks in a way that lets a buyer simply pick a
2443listed seller.
2444
2445## 25.3 Escrow
2446
2447Market orders escrow the asset required to honour them. Escrow is taken from
2448carried inventory and carried currency. The marketplace sits next to the bank,
2449so a player can withdraw from the vault immediately before placing an order.
2450
2451- Creating a sell order removes/reserves the offered item stack from the
2452 seller's inventory.
2453- Creating a buy order removes/reserves the buyer's maximum offered currency.
2454- Cancelling an unmatched order returns the escrowed asset through the defined
2455 settlement/delivery rules.
2456
2457This prevents double spending, selling the same item twice, or a buyer spending
2458currency after placing a bid.
2459
2460## 25.4 Matching rules
2461
2462A buy and sell order match when:
2463
2464```text
2465buyerMaximum >= sellerMinimum
2466```
2467
2468Sell orders are considered cheapest first. Within the same minimum price, a
2469stable creation sequence/FIFO rule should be used unless later game rules choose
2470otherwise.
2471
2472For a symmetric order book, buy orders are naturally prioritised by highest
2473maximum bid and then oldest sequence. This means a newly submitted sell order
2474matches the best compatible existing bid, while a newly submitted buy order
2475matches the cheapest compatible existing ask.
2476
2477The trade price is exactly the midpoint between the two limits:
2478
2479```text
2480tradePrice = midpoint(buyerMaximum, sellerMinimum)
2481```
2482
2483Example:
2484
2485```text
2486Seller minimum: 80
2487Buyer maximum: 100
2488Trade price: 90
2489```
2490
2491The exact rounding rule when integer currency produces a half-unit midpoint is a
2492defined-but-still-open game rule and must be deterministic.
2493
2494## 25.5 Immediate side versus pigeon side
2495
2496The order that is submitted last is the order that triggers the match.
2497
2498The player who submitted that matching order receives the acquired asset
2499immediately because they are currently present at the marketplace interaction
2500(item stack into inventory, or currency into the carried wallet). The
2501pre-existing counterparty receives their acquired item or currency through a
2502carrier pigeon whose destination is `Bank`, landing at the nearest bank to the
2503marketplace. On arrival the settlement is deposited into that counterparty's
2504shared vault. This remains valid if they are offline.
2505
2506```text
2507Existing sell + new matching buy
2508-> new buyer receives item immediately
2509-> existing seller receives payment by pigeon to bank
2510
2511Existing buy + new matching sell
2512-> new seller receives payment immediately
2513-> existing buyer receives item by pigeon to bank
2514```
2515
2516If a trade requires more than one item stack (for example a quantity that does
2517not fit in a single `maxStackSize`), the older counterparty receives as many
2518free sequential pigeons as needed. Each pigeon still carries only one stack or
2519only currency.
2520
2521Any unused part of buy-order currency escrow caused by the midpoint price is
2522returned immediately to the triggering player when they are the buyer, and
2523returned by the settlement pigeon into the older counterparty's vault when
2524they were the buyer.
2525
2526## 25.6 Market service and atomicity
2527
2528Marketplace matching should not live inside an arbitrary region worker. Use a
2529single authoritative `MarketService` (or an equivalently serialised partitioned
2530service later) so two simultaneous orders cannot both consume the same escrow.
2531
2532Order insertion, matching, escrow movement and creation of the resulting
2533settlement deliveries are committed atomically in `state.sqlite`.
2534
2535Conceptually:
2536
2537```text
2538Marketplace interaction
2539 |
2540 v
2541MarketService
2542 - durable order book
2543 - escrow
2544 - deterministic matching
2545 - trade record
2546 |
2547 +-> immediate settlement to triggering player's inventory or wallet
2548 |
2549 +-> CourierService pigeon to Bank for the older counterparty
2550 |
2551 +-> last-sale index update for that itemId
2552```
2553
2554The system should also retain an immutable trade record for auditing and recovery.
2555
2556## 25.7 Last player-market sale per item
2557
2558Each successful player-market match updates a single durable record for that
2559`itemId`. There is no price history series — only the latest sale:
2560
2561```text
2562ItemLastMarketSale
2563- itemId
2564- lastTradePrice // unit price of that match (the midpoint)
2565- lastTradeAt
2566- priceFrom // evaluated undiscounted value at lastTradeAt
2567```
2568
2569`priceFrom` is not a history log. It is the lerp origin captured at the
2570moment of this sale so the displayed price does not jump back to seed when
2571a new trade occurs:
2572
25731. Evaluate the current undiscounted value at `now` using the previous
2574 last-sale record (or `seedValue` if none exists).
25752. Store that value as `priceFrom`, store the new trade's unit price as
2576 `lastTradePrice`, and store `now` as `lastTradeAt`.
2577
2578Shopkeepers and item tooltips both read this record. They do not tick it;
2579they evaluate it from timestamps when a shop is opened, a purchase is
2580attempted, or a tooltip refresh is requested.
2581
2582# 26. Combat
2583
2584## 26.1 Every combatant can attack
2585
2586Players, enemies, animals and any other mobile with a `Combat` component can
2587attack. Shopkeepers and other non-fighting NPCs omit `Combat`, or never issue
2588attack commands. Courier **pigeons** are **untargetable**: they have no `Combat`
2589component and cannot be selected for Attack, Talk, or spells. They are not
2590ambient wildlife; the courier/mail system spawns them for player↔player or
2591player↔bank delivery and they fly in straight world-space lines.
2592
2593Attacking is an intention. The client (or AI) sends `ATTACK(targetEntityId)`.
2594The owning worker validates range, line of sight when required, the current
2595attack profile and cooldown, then resolves hit and damage authoritatively.
2596The client never supplies a hit result or a damage number.
2597
2598`CANCEL_ATTACK` clears the actor's engage target. Cross-worker attacks use
2599`REMOTE_ACTION(attack intent)` so the worker that owns the target applies the
2600authoritative result.
2601
2602## 26.1b Client targeting and context menus
2603
2604| Input | Target | Action |
2605|-------|--------|--------|
2606| LMB | other player | inspect (existing social UI) |
2607| LMB | talkable friendly mob | `INTERACT` / open dialogue (shop content later) |
2608| LMB | hostile combatant | `ATTACK` (auto-engage) |
2609| LMB | ground / empty | `MOVE_TO` that tile (or pickup/bank as today) |
2610| RMB | other player | Walk here · Follow · `<name> info` · Attack |
2611| RMB | mob | Walk here · Follow · Talk (if talkable) · Attack |
2612| Any | untargetable (pigeon) | Follow allowed; no Attack/Talk |
2613
2614Walk here issues `MOVE_TO` for the entity's tile (or the tile under the cursor
2615when RMB is on empty ground).
2616
2617## 26.1b2 Follow
2618
2619`FOLLOW(targetEntityId)` makes the actor trail another mobile. No line of
2620sight is required. Follow works on every mobile (players, wildlife, pigeons).
2621
2622| Chebyshev distance | Behaviour |
2623|--------------------|-----------|
2624| ≤ 1 | Stay put (already in good position) |
2625| 2–3 | Follow the target's vacated trail and remaining path; walk, or run if the target is running |
2626| > 3 and ≤ chunk width (16) | Same route reuse, always run |
2627| > chunk width | Break follow |
2628
2629The follower reuses the target's path instead of independent A* once a trail
2630exists: each time the target leaves a tile that tile is appended to the
2631follower trail, combined with the target's remaining `path.tiles`. The
2632follower stops one tile short of the target's current tile and waits until
2633that tile is vacated; every step still checks walkability. If there is no
2634shared trail yet, a one-shot catch-up path to an 8-neighbour is used.
2635
2636`MOVE_TO` and `ATTACK` clear follow. `CANCEL_FOLLOW` clears it explicitly.
2637
2638## 26.1c Auto-attack and retaliation
2639
2640Engaging sets `Combat.targetEntityId`. The weapon supplies a single
2641`AttackProfile` that repeats until cancel, death, or the target leaves
2642reachable range (then re-path / re-close).
2643
2644`ATTACK` engages **only the attacker**. A fightable target **retaliates on the
2645first resolved melee swing** against it (hit, miss, or block) — not when the
2646player merely clicks Attack or begins pathing. Peaceful NPCs without combat
2647(`canFight: false`) do not retaliate.
2648
2649**Aggressive** mobs (`aggressive: true`, optional `aggroRangeTiles`, default 5)
2650additionally auto-engage the nearest living player character within Chebyshev
2651range when they have line of sight through enterable tiles (same occlusion
2652rule as lighting rays: intermediate tiles must be enterable). Passive does not
2653override an existing engage target.
2654
2655- **Melee:** pathfind to an 8-neighbour tile, swing when Chebyshev distance is
2656 exactly 1.
2657- **Ranged:** pathfind until Chebyshev distance ≤ `rangeTiles`, then fire.
2658 Requires line of sight through passable tiles (same obstruction rule as
2659 baked light).
2660- **Magic:** not a default auto-attack. The player opens a spell menu, picks a
2661 known spell, then clicks a target. Utility spells cast once; attack spells
2662 repeat like weapon auto-attack. Full spell targeting (tiles, blocks, ground
2663 items) is a later batch.
2664
2665## 26.2 Attack profiles
2666
2667The current attack comes from the weapon slot's `AttackProfile`, a selected
2668spell, or a default unarmed melee profile when nothing is wielded.
2669
2670```text
2671AttackProfile
2672- mode: melee | ranged | magic
2673- rangeTiles // melee is always 1
2674- hitSkillId
2675- damageSkillId
2676- cooldownMs
2677- baseDamage
2678```
2679
2680```text
2681SpellDefinition (content; full cast UI later)
2682- spellId
2683- displayName
2684- minSkillLevel
2685- AttackProfile // mode = magic
2686- castKind: utility | attack
2687```
2688
2689A single **spellbook** item type carries one chosen `spellId` in its instance
2690config (shop, drop, or spawner). If the character's Magic skill meets
2691`minSkillLevel`, using the book teaches the spell and consumes the book.
2692
2693Typical weapon mappings:
2694
2695```text
2696Stick/club -> melee, range 1, hit Clubfighting, damage Strength
2697Sword -> melee, range 1, hit Swordfighting, damage Strength
2698Bow -> ranged, range from item, hit Archery, damage Dexterity
2699Spell -> magic, range from spell, hit Magic, damage Mind
2700Unarmed -> melee, range 1, hit Unarmed, damage Strength
2701```
2702
2703## 26.3 Melee range
2704
2705A melee attack is legal only on one of the eight tiles surrounding the
2706target (Chebyshev distance exactly 1). Same-tile melee is illegal.
2707
2708## 26.4 Ranged attacks, spells and LOS
2709
2710Maximum Chebyshev distance is `rangeTiles`. Distance 0 is not legal unless a
2711later exception is defined. Ranged and magic require line of sight: a ray
2712through tile centres fails if it crosses an impassable block (same rule as
2713baked lighting).
2714
2715## 26.4b Presentation: swipe, projectiles, dynamic lights
2716
2717- **Melee:** clients draw a swipe sprite for ~0.5s between attacker and
2718 defender, rotated toward the defender, on `COMBAT_SWING`.
2719- **Ranged / spell:** straight-line world-space projectiles (not grid steps)
2720 toward the defender tile or a miss tile beside it. Spell projectiles may
2721 use a `-bloom` companion.
2722- **Dynamic lights (client-only):** short flashes on cast/hit; equipment with
2723 `lightRadiusTiles` (e.g. lantern) as a moving point light. Per-tile shade
2724 blends `max(bakedNightShade, dynamicContribution)`.
2725
2726## 26.5–26.8 Hit, damage, XP, mob stats
2727
2728Hit chance uses the profile's hit skill (server RNG). Damage uses Strength
2729(melee), Dexterity (ranged), or Mind (magic). Player hit XP splits equally
2730between hit and damage skills. Mobs use archetype skill levels and do not
2731earn XP.
2732
2733```text
2734MobDefinition
2735- hostile / talkable / untargetable / freeFlight / flying
2736- skillLevels, defaultAttack
2737- Combat omitted when untargetable or peaceful non-fighter
2738```
2739
2740Courier **pigeons** use free-flight: straight-line world motion between
2741delivery endpoints, no pathfinding, not bound to the navigation grid, and
2742untargetable for all attacks and spells. They are not ambient fauna.
2743
2744# 27. Player-driven economy and skill progression
2745
2746## 27.1 Item-source philosophy
2747
2748The economy is intentionally player-driven.
2749
2750Normal NPC shops should sell only basic ingredients. The vast majority of
2751materials are gathered directly from the world by players. Finished goods are
2752normally produced by player crafting/professions.
2753
2754The only normal non-player source of finished items is enemy or boss loot.
2755
2756This gives four broad source paths, with ground-item spawners as an additional
2757early world source once content defines them:
2758
2759```text
2760World gathering / harvesting -> ingredients
2761Ground-item spawners --------> some world items, later specified
2762Basic NPC shops -------------> limited basic ingredients
2763Player production -----------> intermediate/final products
2764Enemies and bosses ----------> loot, including possible finished items
2765```
2766
2767Stacking, unique instances, letters and cheques are defined in section 22.
2768Economy-facing fields remain on the same `ItemDefinition`:
2769
2770```text
2771ItemDefinition
2772- itemId
2773- displayName / description / seedValue
2774- stackable / maxStackSize / uniqueInstance
2775- category: ingredient | intermediate | finished | document | other
2776- npcShopAllowed
2777- gatherSources
2778- craftingRecipe(s)
2779- dropTableSources
2780- attack?: AttackProfile
2781- equipment?: slot / overlaySpriteId / recolourableChannels / materialId
2782```
2783
2784Content validation can then reject an ordinary shop inventory that accidentally
2785contains a finished product unless explicitly permitted by a future exception.
2786
2787## 27.2 No player classes
2788
2789Players do not choose a class. Capabilities and progression come from independent
2790skills.
2791
2792Examples include:
2793
2794- Swordfighting, Axefighting, Archery, Magic, Unarmed
2795- Strength, Dexterity, Mind
2796- Defence
2797- Lumbering
2798- Fishing
2799- Smithing
2800
2801The final skill list is game content and is not limited to skills found in any
2802particular inspiration game.
2803
2804## 27.3 Skill state
2805
2806Skill progression is persistent player state.
2807
2808```text
2809SkillProgress
2810- skillId
2811- xp
2812```
2813
2814Level should preferably be derived from XP and the skill's level curve rather
2815than stored as an independent source of truth, although it may be cached.
2816
2817```text
2818SkillDefinition
2819- skillId
2820- displayName
2821- levelCurve
2822- maxLevel (if any)
2823```
2824
2825## 27.4 Actions are governed by skills
2826
2827Every gameplay action that participates in progression is associated with a
2828governing skill. Combat attacks are the explicit exception: they have a hit
2829skill and a damage skill, and split XP equally between them (section 26.7).
2830
2831```text
2832ActionDefinition
2833- actionId
2834- governingSkillId
2835- requiredLevel
2836- xpAward / xpFormula
2837- other requirements
2838```
2839
2840Examples:
2841
2842```text
2843Cut tree -> Lumbering
2844Catch fish -> Fishing
2845Forge sword -> Smithing
2846Sword hit -> Swordfighting + Strength (equal split)
2847Bow hit -> Archery + Dexterity (equal split)
2848Spell hit -> Magic + Mind (equal split)
2849Defensive act -> Defence
2850```
2851
2852The server validates the action, performs the authoritative outcome, and then
2853awards XP according to the action result. A client cannot claim XP independently.
2854
2855## 27.5 Skills replace class restrictions
2856
2857Equipment, recipes, actions, gathering nodes and other content may require skill
2858levels, but there is no permanent class gate. A player can train any combination
2859of skills over time.
2860
2861This also fits the future scripting model: scripts issue normal actions, and
2862successful scripted actions use exactly the same skill checks and XP rules as
2863manual player actions.
2864
2865## 27.6 NPC shops and market-adapted prices
2866
2867Named shop NPCs can sell items to players. They are not the player marketplace
2868and they do not expose live sell orders. A shop interaction requires being at
2869that NPC.
2870
2871Stock remains constrained by `npcShopAllowed` and the ingredient-only rule in
287227.1. Each shop NPC has a hidden discount that players never see:
2873
2874```text
2875ShopNpc
2876- npcId
2877- hiddenDiscount // multiplier, e.g. 0.9; not shown to clients
2878- stock[] // itemIds this NPC sells
2879```
2880
2881Until an `itemId` has a player-market last-sale record, the undiscounted
2882value is `seedValue` from the item definition.
2883
2884When a last-sale record exists, both tooltips and shops evaluate a timestamp
2885lerp that does not require a per-tick update:
2886
2887```text
2888t = min(1, (now - lastTradeAt) / WorldSettings.shopPriceLerpDuration)
2889undiscounted = lerp(priceFrom, lastTradePrice, t)
2890shopPrice = undiscounted * thatNpc.hiddenDiscount
2891```
2892
2893`lerp(a, b, t) = a + (b - a) * t`. After the configured lerp duration
2894(default one hour), `t` is capped at 100% and the value rests on the last
2895player-market unit price (times discount, for shops) until another
2896player-market sale occurs.
2897
2898A new player-market sale captures the then-current `undiscounted` value as
2899`priceFrom` (section 25.7), so the lerp restarts toward the new last price
2900without jumping back to seed.
2901
2902Integer currency must be rounded deterministically at evaluation time. Shop
2903purchase price is computed on the server at the instant of `BuyFromShop`.
2904Displayed tooltip value is the undiscounted figure and may be refreshed at
2905most once per minute (section 22.6).
2906
2907Buying from a shop removes the listed price from the player's carried
2908currency, puts the stack in inventory subject to the 32-slot rules, and
2909stamps `ItemOrigin.kind = shop` with that NPC. Shops in this model sell to
2910players; they do not buy player goods unless a later iteration adds that.
2911
2912# 28. Suggested implementation phases
2913
2914## Phase 1 — Single-worker playable core
2915
2916- World coordinate helpers, 16×16 chunks and 4×4-chunk regions.
2917
2918- Ground/block tile model and chunk spatial occupancy.
2919
2920- Basic ECS and fixed simulation tick.
2921
2922- ChunkLoader reference counting and sleeping/unloading.
2923
2924- Isolated simulation workers behind a clone-on-boundary protocol
2925 (in-process default; `worker_threads` optional).
2926
2927- world.sqlite read path and state.sqlite persistence service.
2928
2929- Admin world editor: chunk navigation, open/closed flag, default grass for
2930 unsaved chunks, ground/block paint, light-emitting blocks, baked
2931 cross-chunk light maps, night-to-day preview slider, world settings modal
2932 with live apply and a settings edit log, per-chunk changelog, chunk save
2933 to pending revision.
2934
2935- SpawnerSystem for at least one non-persistent mob archetype.
2936
2937- WebSocket gateway, stub `admin-<n>` auth until auth.timfalken.com,
2938 character create/select/delete, authoritative command queue and 3×3 chunk
2939 replication.
2940
2941- Click-to-move with server-side A\*, global walk/run cadence (default 2
2942 tiles/s walk, run every movement tick, walk every other), and `SetGait`.
2943
2944- FrameworkV3 git submodule at `client/frameworkv3`, built first, then a
2945 game-specific client on top of it with 16×16 sprites, load-time and CI
2946 rejection of wrong-sized art (including equipment overlays and recolour
2947 masks), layered worn equipment with material recolouring, a
2948 player-centered viewport with bounded zoom, client-only lerp of
2949 tile-to-tile movement, and night shading from baked light maps.
2950
2951- 32-slot player inventory, stack merging, drop/pickup, and 10-minute
2952 non-blocking ground items.
2953
2954- Paper items that can be written into unique letter items.
2955
2956- Basic proximity chat with server-side distance degradation.
2957
2958- Persistent player skill state, including Strength, Dexterity and Mind, and
2959 at least a small initial set of skill-governed actions.
2960
2961- Melee and ranged/spell attack validation (8-tile melee adjacency, item/spell
2962 range), server-side hit rolls, damage from the matching damage skill, and
2963 equal XP split on a successful player hit.
2964
2965- Graceful forced-unload shutdown.
2966
2967## Phase 2 — Operations and live deployment
2968
2969- RestartScheduler and player-visible scheduled restart state.
2970
2971- origin/master change detection.
2972
2973- `systemd` service supervision and conditional deployment hook.
2974
2975- World-revision activation on restart.
2976
2977- Admin immediate restart.
2978
2979- Migration, backup and startup readiness checks.
2980
2981## Phase 3 — Multi-worker world
2982
2983- Multiple isolated simulation workers and neighbour-sticky region ownership
2984 (shipped); dynamic load rebalance remains.
2985
2986- Cross-worker entity transfers (shipped).
2987
2988- Border ghosts for occupancy/pathfinding (shipped); remote combat actions remain.
2989
2990- Gateway subscriptions spanning multiple workers (shipped).
2991
2992- Load metrics and neighbour-aware region balancing remain.
2993
2994## Phase 4 — World depth, social systems and economy
2995
2996- Persistent named NPCs and other persistent mob archetypes.
2997
2998- Spawner persistent-instance index and duplicate prevention.
2999
3000- Optional durable gameplay chunk overrides, written only on unload.
3001
3002- Hierarchical pathfinding if long-distance autonomous travel needs it.
3003
3004- Persistent player groups and invitations.
3005
3006- Carrier-pigeon cargo transit: free dispatch, money or one item stack,
3007 player or nearest-bank destinations, including offline/full-inventory
3008 fallback to the recipient vault.
3009
3010- Shared unlimited **character** bank near the marketplace, account
3011 inheritance tab on character delete, blank cheques filled to 99, reserved
3012 filled cheques, in-person redemption and pigeon-to-bank cheque transfers.
3013
3014- Central marketplace, escrow, deterministic order matching, pigeon-to-bank
3015 settlement for the older counterparty, and a per-item last-sale record for
3016 shop/tooltip adaptation.
3017
3018- NPC shops that sell `npcShopAllowed` stock at seed value lerped toward the
3019 last player-market price over `shopPriceLerpDuration`, with a hidden per-shop discount.
3020
3021- Item inspection: name, description, origin (crafter or shop NPC) and
3022 undiscounted current value, refreshed at most once per minute.
3023
3024- Player crafting/gathering economy rules and shop-content validation.
3025
3026- Broader skill catalogue, progression curves and skill-gated content.
3027
3028## Phase 5 — Player scripting
3029
3030- Custom language grammar/compiler/interpreter.
3031
3032- ScriptController and event API.
3033
3034- CPU/memory/query quotas and sandboxing.
3035
3036- Online scripted control mode.
3037
3038- Offline retained player entities with expiry and ChunkLoader
3039 behaviour.
3040
3041- Persisted/restart-safe script state.
3042
3043# 29. Core invariants
3044
3045| **Invariant** | **Rule** |
3046|------------------------|--------------------------------------------------------------------------------------------------------|
3047| Server authority | Clients send intent; the server computes and owns outcomes. |
3048| Region ownership | Exactly one simulation worker authoritatively owns a region. |
3049| Entity ownership | Exactly one worker authoritatively owns an entity. |
3050| Remote mutation | Workers never directly mutate remote authoritative state. |
3051| Spatial separation | Region residency, chunk simulation and client visibility remain distinct. |
3052| Persistence separation | Persistent and ChunkLoader are independent entity traits. |
3053| Chunk persistence | Normal dirty chunk state is written on unload, not periodically. |
3054| World authoring | Editor changes create pending authored state; the running server stays pinned to its startup revision. Each chunk save appends an admin-attributed diff changelog. |
3055| Restart path | Planned restart force-unloads the world and reuses the ordinary unload save path. |
3056| Control | Human and future scripted control both emit validated action commands. |
3057| Deployment | The game exits gracefully; systemd relaunches it and only pulls/builds when an intentional deployment manifest requests it. |
3058| Client architecture | FrameworkV3 is a git submodule under `client/frameworkv3`, built before game client code; backend ECS internals do not become the client object model. |
3059| Sprites | World sprites may be any size. Pivot is horizontal centre and 8px from the sprite bottom, on the tile centre. Ground/block types load visual states from a per-type folder (first alphabetical PNG is default). Sheets use `frames`, `framesPerRow`, `animationSpeed`. Blocks and mobiles Y-sort north-behind-south. |
3060| Appearance | Visible gear is layered 16×16 overlays on the mob; recolourable channels (such as metal) use material colour without duplicate art sets. Nearby clients receive appearance layers, not another player's inventory. |
3061| Play camera | The play viewport is centered on the local player. Only the admin world editor uses a free chunk camera. |
3062| Movement | All ground mobiles share a global walk/run cadence from world settings; the server commits integer tiles; clients lerp for presentation only. |
3063| World time | World calendar time is server time minus 1200 years. Night darkens tiles the baked light map cannot reach. |
3064| World settings | Tick timers and global constants (including night darkness) are authored in the editor modal, applied immediately on save, and recorded in a settings edit log. Chunk map data remains revision-pinned. |
3065| Baked light | Static light reach is raycast through passable tiles on chunk save, may cross chunks, and is not recomputed every tick. |
3066| Ground items | Player drops last `groundItemDespawnDuration` (default 10 minutes), block nobody, and are picked up only by a player standing on that tile. |
3067| Shop prices | NPC shop prices lerp from the captured pre-sale value toward the last player-market unit price over `shopPriceLerpDuration` (default one hour), times a hidden per-shop discount. |
3068| Proximity speech | Distant clients never receive unobscured plaintext that game rules say they cannot understand. |
3069| Courier cargo | Pigeons carry money or one item stack, never a chat packet; cargo is durable in transit and remains delayed. |
3070| Inventory | A player has 32 slots; a stack occupies one slot; the client never asserts inventory, wallet or vault results. |
3071| Shared bank | Every bank reads the same **character** vault; pigeon deposits become available only after arrival at the nearest bank. |
3072| Closed chunks | Closed or never-edited chunks are visible but not enterable; never-edited terrain is default grass with no blocks. |
3073| Accounts | Login is auth.timfalken.com (or `admin-<n>` stub). Characters belong to an account; one may be in the world at a time. |
3074| Names | Surnames are globally unique per account; first+last is unique per account; names free only after permanent delete. |
3075| Inheritance | Deleted characters dump inventory, equipment, wallet and vault into an account inheritance tab other characters can claim. |
3076| Cheques | Filling a cheque reserves vault goods; the bearer item is the claim; destruction without redemption releases the reservation. |
3077| Marketplace escrow | Every open order is fully backed by escrow and matching/settlement is atomic and deterministic. |
3078| Combat | Melee requires an 8-neighbour tile; ranged/spell range comes from the item or spell; hit uses the weapon skill; damage uses Strength, Dexterity or Mind. |
3079| Progression | Players have no classes; non-combat actions award XP to one governing skill; a successful attack splits XP equally between hit and damage skills. |
3080
3081# 30. Important edge cases to preserve during implementation
3082
3083- A ChunkLoader crossing a region boundary can change
3084 residency/simulation references and worker ownership in the same tick;
3085 ordering must avoid temporary double ownership.
3086
3087- A player at a worker boundary may receive visible chunks from multiple
3088 workers without moving ownership solely for rendering.
3089
3090- A planned restart must ignore normal ChunkLoader retention when
3091 forcing the world to unload.
3092
3093- A world-editor save must never cause newly loaded chunks in the
3094 current process to use the pending revision. It must append a changelog
3095 record naming the admin, timestamp and tile diffs.
3096
3097- Pathfinding and player movement must reject tiles in closed or
3098 never-edited chunks even when those chunks are in the 3×3 view.
3099
3100- Two accounts must not claim the same surname. One account may reuse its
3101 surname; first+last must stay unique on that account until permanent
3102 delete.
3103
3104- Marking a character for deletion must not free the name or move items
3105 until the delay elapses. Cancelling must restore playability.
3106
3107- Character deletion must notify the account email (or log, on stub auth).
3108 Permanent delete must void that character's issued cheques, then move
3109 inventory, equipment, wallet and vault into the account inheritance tab.
3110
3111- Saving a chunk must rebake that chunk's light map and any neighbour
3112 chunks within max light range, using passable-tile raycasts. Light from
3113 a source in chunk A may appear in chunk B.
3114
3115- A mob definition must not carry its own walk/run speed; gait only
3116 selects every-other vs every movement tick on the global cadence.
3117
3118- World-settings saves must not apply to the live process; they wait for
3119 the same pending-revision restart as chunk edits.
3120
3121- Night shading must not light a tile the baked mask marks unreachable,
3122 even if a torch is nearby through a wall.
3123
3124- Oversized block and mob sprites must Y-sort so objects higher on the
3125 screen draw behind objects lower on the screen. Closed-chunk edges
3126 facing an open chunk must show a red border in the client.
3127
3128- Equipping must not leave two items in the same equipment slot. Unequip
3129 into a full inventory must fail and leave the item worn.
3130
3131- Nearby clients must not receive another player's inventory in order to
3132 draw their armour; appearance layers and material ids are sufficient.
3133
3134- A client build without `client/frameworkv3` initialized must fail rather
3135 than silently using some other FrameworkV3 install.
3136
3137- Client interpolation of movement must not be treated as authority. Combat
3138 range and pickup use the server tile, not the lerped draw position.
3139
3140- The play camera must remain centered on the local player. Zoom must not
3141 expand the subscribed chunk set.
3142
3143- A persistent mob spawned by a spawner must not be duplicated merely
3144 because it moved out of the spawner’s loaded area.
3145
3146- A non-persistent mob disappears when its chunk is actually unloaded,
3147 not merely when it becomes dormant.
3148
3149- If a persistent ChunkLoader or offline scripted player exists after
3150 restart, startup must discover it from an index without loading the
3151 entire world.
3152
3153- A pending code update followed by an unrelated Node.js crash must
3154 restart the currently deployed commit rather than deploying early.
3155
3156- Negative coordinates, daylight-saving midnight calculation, duplicate
3157 transfer messages and failed deployment migrations should all have
3158 explicit tests.
3159
3160- Proximity chat degradation must happen before plaintext reaches an unauthorised
3161 distant client; rendering-only obfuscation is not sufficient.
3162
3163- Carrier-pigeon deliveries must survive restarts and recipient logout without
3164 requiring every traversed chunk to remain stimulated.
3165
3166- A pigeon carrying an item to a player whose inventory cannot accept it must
3167 not destroy the cargo; it deposits into that player's vault via the nearest
3168 bank.
3169
3170- Two concurrent bank withdrawals, cheque fills or pigeon-arrival deposits must
3171 not spend the same vault goods twice.
3172
3173- Filling two cheques against the same vault stack must reserve disjoint
3174 quantities or reject the second fill.
3175
3176- A filled cheque that expires on the ground must release its reservation and
3177 must not remain redeemable.
3178
3179- A player-dropped ground item must not block movement, must not keep its chunk
3180 loaded, and must still be present after a chunk unload/reload if `expiresAt`
3181 has not passed.
3182
3183- Pickup of a ground item from a tile the player is not standing on must fail.
3184
3185- Requesting blank cheques must never raise the player's carried blank-cheque
3186 count above 99.
3187
3188- A marketplace match must atomically consume both escrows exactly once, even if
3189 two compatible orders arrive concurrently.
3190
3191- A matching market order from an online player may settle immediately for that
3192 player while the older/offline counterparty's delivery remains durable.
3193
3194- Skill XP is awarded only after authoritative action resolution, never directly
3195 from a client-reported result. A successful player attack splits that XP;
3196 a miss awards none.
3197
3198- A melee attack from the target's own tile, or from Chebyshev distance greater
3199 than 1, must fail. A ranged or spell attack beyond that item or spell's
3200 `rangeTiles` must fail.
3201
3202- A new player-market sale must capture the then-current undiscounted lerp
3203 value as `priceFrom` so shop and tooltip prices do not jump back to seed.
3204
3205- Two shop NPCs may charge different prices for the same item at the same
3206 instant because each applies its own hidden discount to the same lerp.
3207
3208- Item tooltip value must not be recomputed every tick; a one-minute refresh
3209 is sufficient. Purchase price is still evaluated at the moment of buy.
3210
3211# 31. Decisions through version 0.12
3212
3213- Chunk persistence is unload-driven rather than periodic.
3214
3215- The authored tile model has separate visual ground and functional
3216 block layers.
3217
3218- Mobile actors remain ECS entities and are not authored as painted tile
3219 contents.
3220
3221- Spawner blocks are editor-placeable and configurable per instance;
3222 persistence belongs to the spawned mob type.
3223
3224- world.sqlite is an authored, revisioned world source; state.sqlite
3225 holds runtime durable state.
3226
3227- Editor changes are staged for activation on restart instead of
3228 hot-patching the running world.
3229
3230- Code/world changes schedule a player-visible midnight restart; admins
3231 can trigger the same graceful pipeline immediately.
3232
3233- Git pull/build/relaunch belongs to `systemd` supervision after the
3234 game process has safely exited.
3235
3236- Deployment is manifest-driven: crash recovery restarts the currently
3237 checked-out commit, while only an intentional deployment restart may
3238 fast-forward `master`.
3239
3240- Future player scripting is modelled as an alternative controller
3241 producing normal server action commands.
3242
3243- Offline scripted players may remain in-world as ChunkLoaders until
3244 death or expiry and must survive planned restarts through persistence.
3245
3246- The player client is built on FrameworkV3, included as the git submodule
3247 `client/frameworkv3` and built first so this game's client code can layer on
3248 top. The client does not need an ECS and consumes protocol state
3249 independently of backend ECS storage. The Node.js server does not import
3250 FrameworkV3.
3251
3252- World sprites may be any pixel size. Each is placed with a pivot at
3253 horizontal centre and 8 pixels from the sprite bottom, on the tile
3254 centre. Blocks and mobiles are Y-sorted. The player may zoom the whole
3255 viewport within configured bounds; sprites are not scaled individually.
3256
3257- Visible equipment is drawn as extra 16×16 layers on the mob, including
3258 players. Worn items occupy equipment slots, not the 32 inventory slots.
3259 Nearby clients replicate appearance layers only, never another player's
3260 inventory.
3261
3262- Recolourable gear (metal armour) shares one overlay sprite and a 16×16
3263 channel mask. Material definitions supply the metal colour; luminance of
3264 the overlay is preserved. Iron and steel plate are different items with
3265 the same art and different `materialId`.
3266
3267- The play camera is always centered on the local player. The admin world
3268 editor is the only exception, and it frames one chunk at a time.
3269
3270- Authoritative movement is a tile-to-tile jump on a **global** cadence:
3271 default walk 2 tiles/s, run double. Walk steps every other movement tick;
3272 run steps every movement tick. Mobs do not set their own speed. Clients
3273 lerp for visuals only and never send interpolated positions.
3274
3275- Admins edit global tick timers and constants in a world-settings modal.
3276 Saving applies those values immediately to the live process and appends
3277 a settings changelog. Chunk map saves still wait on the pending world
3278 revision.
3279
3280- World calendar time is server time minus 1200 years, same IANA zone as
3281 midnight restarts. At night the client darkens tiles the baked light map
3282 cannot reach.
3283
3284- Static light is baked on chunk save by raycast through passable tiles,
3285 including across chunk borders. The editor has a night-to-day slider for
3286 preview only.
3287
3288- Each world-editor chunk save stores who edited it, when, and a bullet
3289 diff of ground changes, block placements, block replacements and block
3290 removals at world tile coordinates.
3291
3292- Default speech is proximity-based and becomes less legible with distance.
3293 Long-distance exchange is physical: a pigeon carries money or one item stack.
3294 A letter is paper with player-written text, not a separate mail record.
3295
3296- Permanent player groups are social/addressing structures and do not create an
3297 instant global chat channel.
3298
3299- Carrier-pigeon transit is persistent but does not automatically keep every
3300 traversed chunk simulated. Whenever a pigeon passes through a chunk that is
3301 already simulating, it materialises as an ECS `Mob` and is visible to any
3302 nearby client whose normal chunk subscription includes it, even if that client
3303 is unrelated to the delivery. Unrelated clients do not receive cargo contents.
3304
3305- A player has a 32-slot inventory. Stackable items occupy one slot. Currency is
3306 a numeric wallet/vault balance, not an inventory item.
3307
3308- Player-dropped items lie on the tile for `groundItemDespawnDuration`
3309 (default 10 minutes), block nobody, and may be picked up by anyone standing
3310 on that tile. They survive unload until expiry via timestamps.
3311
3312- The bank near the marketplace holds an unlimited **character** vault.
3313 Later banks are linked to the same vault. Pigeons may deposit money or one
3314 stack into the sender's vault after arriving at the nearest bank. An
3315 account-level inheritance tab receives a deleted character's goods.
3316
3317- Blank cheques are issued at a bank up to a carried total of 99. Filling a
3318 cheque reserves a vault item quantity. The filled cheque is a bearer item.
3319 In-person redemption withdraws into the bearer's inventory. Sending the cheque
3320 to the bank by pigeon transfers the reserved goods into the pigeon's sender's
3321 vault.
3322
3323- The central marketplace hides individual live sell listings and matches durable
3324 escrowed buy/sell orders at the midpoint of compatible bid/ask limits.
3325 Quantities are item stacks.
3326
3327- The newest matching market participant receives the trade result locally; the
3328 older counterparty receives theirs by pigeon into their bank.
3329
3330- NPC shops remain restricted to `npcShopAllowed` basic ingredients. They sell
3331 to players at
3332 `lerp(priceFrom, lastTradePrice, min(1, (now - lastTradeAt) / shopPriceLerpDuration))`
3333 times a hidden per-shop discount. With no player-market sale yet, the
3334 undiscounted value is `seedValue`. Tooltips use the same lerp without the
3335 discount and refresh at most once per minute.
3336
3337- Hovering an item shows name, description, origin (crafter, or shop NPC name
3338 if bought there) and current undiscounted value.
3339
3340- All combatants can attack. Melee requires standing on one of the eight
3341 neighbouring tiles. Ranged attacks and spells use the item's or spell's
3342 range. The hit roll uses the weapon skill; damage uses Strength (melee),
3343 Dexterity (ranged) or Mind (magic). Successful player-attack XP is split
3344 equally between those two skills.
3345
3346- Player progression is skill-based rather than class-based. Non-combat
3347 actions award XP to one governing skill; combat hits split XP as above.
3348
3349- Never-edited chunks are default grass, no blocks, and **closed**. The
3350 editor opens or closes each chunk. Closed chunks are visible but not
3351 enterable.
3352
3353- Accounts authenticate at auth.timfalken.com. Until that service is up,
3354 each connection is stub `admin-<n>` (n = connected client count including
3355 this one) and is treated as admin.
3356
3357- An account has unlimited characters and plays one at a time. Creation
3358 takes first name (not globally unique), last name (globally unique to the
3359 account, reusable on that account's other characters), and male/female.
3360 first+last must be unique for that account. This setup may change later.
3361
3362- Character deletion is a 24-hour (configurable) delay with email notify
3363 and cancel. Permanent delete frees names and moves inventory, equipment,
3364 wallet and vault to the account inheritance tab, which any of that
3365 player's characters can claim into their own vault.
3366
3367# 32. Open design decisions for later iterations
3368
3369These do not block the initial implementation, but should eventually be
3370specified explicitly:
3371
3372- Whether multiple mobile entities may occupy one tile and, if so, which
3373 categories can overlap.
3374
3375- Whether player movement is four-direction only or also supports
3376 diagonals. Combat melee adjacency already includes diagonals.
3377
3378- Exact hit-chance and damage curves, attack intervals/cooldowns, whether
3379 Defence modifies incoming hit chance or damage, and ranged/spell
3380 line-of-sight or obstruction rules.
3381
3382- Deterministic rounding when shop discount or lerp produces a fractional
3383 currency amount.
3384
3385- Exact equipment slot list, per-slot draw order exceptions (cloaks,
3386 two-handed weapons), and whether worn overlays have facing frames to
3387 match the mob.
3388
3389- Additional recolour channels beyond metal (for example cloth dyes) and
3390 the exact luminance-preserving remap function.
3391
3392- Exact camera zoom minimum, maximum and whether zoom is restricted to
3393 integer steps.
3394
3395- Exact night ambient curve (how dark, dusk length) and whether baked light
3396 stores a boolean reach mask or a distance/falloff value per tile.
3397
3398- Whether opening a door at runtime should rebake or ignore static light.
3399
3400- Exact simulation tick rate stays a world setting; lower-frequency AI and
3401 spawner cadences can still be tuned independently.
3402
3403- Exact world/chunk binary serialisation format and schema/version
3404 migration strategy.
3405
3406- Whether gameplay can permanently modify ground/block tiles in the
3407 initial release.
3408
3409- Spawner timing rules, spawn-point restrictions and behaviour when
3410 persistent spawned mobs travel very far away.
3411
3412- World-editor undo/redo and rollback UI. The per-chunk changelog is an audit
3413 log, not by itself an undo stack.
3414
3415- Exact restart warning intervals and whether admins can
3416 cancel/reschedule a planned restart.
3417
3418- Worker rebalance thresholds and whether regions may migrate while
3419 players are actively crossing their boundaries.
3420
3421- Future scripting language syntax, event model and resource quotas.
3422
3423- Group naming/roles, membership limits and whether group-wide letter sending
3424 is offered as an addressing convenience that still dispatches one pigeon and
3425 consumes one paper/letter per recipient.
3426
3427- Whether pigeons can eventually be intercepted, killed or redirected in transit.
3428
3429- Marketplace partial fills, cancellation rules, fees/taxes (if any),
3430 tie-breaking details and midpoint rounding for indivisible currency.
3431
3432- Whether market price history or aggregate statistics are visible despite live
3433 order listings remaining hidden.
3434
3435- Initial skill catalogue, XP curves, level caps, action XP formulas and the
3436 remaining interpretation of skills such as Defence.
3437
3438- Maximum letter body length and whether writing paper requires a desk or can be
3439 done from inventory anywhere.
3440
3441- Exact item catalogue, which items stack, per-item `maxStackSize` exceptions,
3442 harvest interactions and ground-item spawner parameters.
3443
3444- Whether death drops inventory, and whether dropped unique items other than
3445 cheques have destruction side-effects.
3446
3447- Whether the issuer can void a filled cheque without the bearer item being
3448 destroyed, and whether cheques can ever represent currency rather than items.
3449
3450- Whether a short dispatch interval is needed so many pigeons cannot leave in a
3451 single tick, even though sending remains free.
3452
3453- New-character spawn location (must be an open chunk) and name length /
3454 allowed-character rules.
3455
3456- Later changes to character creation beyond first name, last name and sex.
3457
3458# 33. Architectural summary
3459
3460ECS → what an entity is and what systems can act on it
3461Chunk → tile data, spatial lookup, simulation and client subscription
3462Region → residency and simulation-worker ownership
3463Coordinator→ where regions execute
3464Gateway → stable client connections, auth, character select, and command/update routing
3465world.sqlite→ authored versioned ground/block/spawner/light/settings world; unedited chunks are closed grass
3466state.sqlite→ accounts, characters, friends, vaults, inheritance, and other durable live-game state
3467systemd → process supervision and relaunch
3468Deployment hook → conditional Git update/build only for intentional deployment restarts
3469Controller → manual client input today; sandboxed player scripts later
3470FrameworkV3 → git submodule at `client/frameworkv3`; built first; game client code layers on top
3471Sprites → any size; pivot at horizontal centre, 8px from bottom; Y-sort blocks/mobs
3472Equipment → layered 16×16 overlays on mobs; metal armour shares art and recolours by material
3473Camera → play view centered on the local player; bounded zoom; editor is chunk-framed
3474Movement → global walk/run cadence (default 2 tiles/s walk, run double); server tile steps; client visual lerp
3475World time → server clock minus 1200 years; night darkens unlit tiles
3476Light → baked passable-tile raycast on editor save; shines across chunks
3477World settings → admin modal for tick timers and global constants; live apply
3478Inventory → 32 slots; stacks occupy one slot; letters are written paper items
3479Bank → per-character vault; account inheritance tab on character delete
3480Auth → auth.timfalken.com, stub admin-<n> until live; unlimited characters, one in world
3481Chunks → editor open/closed; default grass and closed until painted
3482Ground items → non-blocking, 10-minute player drops, pickup only while standing on the tile
3483Communication service → proximity speech
3484CourierService → pigeons carrying money or one item stack through durable transit
3485BankService → shared unlimited vaults, cheque reservations and redemption
3486MarketService → durable escrowed order book, matching, last-sale index and pigeon-to-bank settlement
3487Shop NPCs → sell allowed stock; price lerps toward last player-market sale over shopPriceLerpDuration, times a hidden discount
3488Combat → melee auto-attack + retaliate; 8-neighbour melee; ranged/spell later; courier pigeon free-flight untargetable
3489Skills → classless progression; Clubfighting/Strength on stick; attack XP split hit/damage (curves later)
3490
3491
3492# 34. Version history
3493
3494## 0.19
3495
3496- Playable item basis: 32-slot inventory, equipment overlays, carried coins,
3497 ground drops (10-minute player drops, pickup on the tile), bank vaults,
3498 and account inheritance on character delete. Spawner and bank blocks can
3499 be painted in the editor; spawners produce placeholder deer up to
3500 `maxAlive`. Missing art is temporary 16×16 PNGs under `client/assets/`
3501 so real sprites can drop in later by replacing those files.
3502
3503## 0.18
3504
3505- Server ECS uses compact worker-local `EntityHandle`s (recycled free list)
3506 alongside global `EntityId`s for storage, networking and transfer. `Path`
3507 is a separate component from `Movement`; players carry `NetworkIdentity`
3508 instead of putting `sessionId` on `character`. Nearby clients get
3509 `ENTITY_SPAWN` / compact `ENTITY_MOVE` (tile + gait) / `ENTITY_DESPAWN`
3510 rather than appearance-heavy moves or extra snapshots.
3511
3512## 0.17
3513
3514- Region workers own ECS worlds behind a clone-on-boundary protocol
3515 (optional `worker_threads`). ChunkLoader reference counts keep 3×3
3516 chunks simulating and 3×3 regions resident; other resident chunks stay
3517 dormant. Regions unload after the grace period and persist flagged
3518 entities. Crossing a foreign region transfers the only authoritative
3519 copy; ghosts cover border occupancy; client snapshots may span workers.
3520
3521## 0.16
3522
3523- Proximity chat: Enter opens a bottom input (max `chatMaxCharacters`,
3524 default 100). Enter sends a trimmed line; the speaker always sees their
3525 own text. Other players get a server-obscured bubble (full until 8
3526 tiles, linear to silent at 16 tiles). At 0% readability no bubble is
3527 sent. Walk/run `R` is ignored while the chat line is open.
3528
3529## 0.15
3530
3531- Hovering another player shows their first name. Clicking them opens an
3532 inspect modal (first + last name) to send a friend request. Requests
3533 must be accepted; removing a friend removes them on both sides. The
3534 friends list is the later pigeon address book.
3535
3536## 0.14
3537
3538- Ground and block types load visual states from per-type sprite folders
3539 (first alphabetical PNG is the default). Sprite definitions include
3540 `frames`, `framesPerRow` and `animationSpeed`. The editor previews the
3541 selected tool on hover and cycles states with the mouse wheel.
3542 Gameplay may set a named visual state (for example a door).
3543
3544## 0.13
3545
3546- World settings are live: an admin modal with categories, dirty-field
3547 highlighting, and a settings edit log. Save applies immediately
3548 (including `nightDarkness`) rather than waiting on a map revision.
3549
3550## 0.12
3551
3552- Chunks are open or closed in the world editor. Closed chunks stay visible
3553 but cannot be entered. Never-edited chunks are default grass with no
3554 blocks and are closed.
3555- Login uses auth.timfalken.com; until that is live, connections are stub
3556 `admin-<n>` (connected-client count including this one) and are admins.
3557- Accounts have unlimited characters, one in the world at a time. Creation
3558 is first name, unique account-owned last name, and male/female.
3559- Character deletion waits 24 hours with email and cancel. Permanent delete
3560 frees names and moves goods to an account inheritance bank tab.
3561
3562## 0.11
3563
3564- Made walk/run a global cadence from world settings (default 2 tiles/s
3565 walk, run double): walk steps every other movement tick, run every tick.
3566 Mob definitions do not set move speed.
3567- Added an admin world-settings modal for tick timers and global constants
3568 (shop lerp duration, drop lifetime, simulation tick, and the same class
3569 of values). Settings ride the pending world revision.
3570- World calendar time is server time minus 1200 years.
3571- Baked static lighting by passable-tile raycast on chunk save, including
3572 across chunk borders. Clients darken unreachable tiles at night. The
3573 editor has a night-to-day preview slider.
3574
3575## 0.10
3576
3577- Drew visible equipment as 16×16 overlay layers on mobs (including players),
3578 with worn items in equipment slots rather than the 32-slot inventory.
3579- Replicated compact appearance layers to nearby clients instead of another
3580 player's inventory.
3581- Recolourable metal armour shares one overlay plus a 16×16 channel mask;
3582 material definitions supply the metal colour while preserving shading.
3583
3584## 0.9
3585
3586- Vendored FrameworkV3 as the git submodule `client/frameworkv3`. The game
3587 client builds that library first and implements game-specific code on top
3588 of it. The Node.js server does not import the submodule.
3589
3590## 0.8
3591
3592- Required all world sprites (tiles, blocks, mobs, items) to be 16×16 pixels,
3593 rejected at load, with a CI unit test that reports and fails on any other
3594 size. Sprites are not individually scaled; the player may zoom the viewport
3595 within configured bounds.
3596- Locked the play camera to the local player. The admin world editor remains
3597 the only non-player-centered view.
3598- Made authoritative movement integer tile-to-tile steps. Clients lerp
3599 mobiles for presentation only.
3600- Added a per-chunk world-editor changelog: admin, timestamp, and bullet
3601 diffs for ground changes, block place/change/remove.
3602
3603## 0.7
3604
3605- Added combat for all mobs including players: melee from any of the eight
3606 neighbouring tiles, ranged and spells from the item or spell range.
3607- Hit rolls use the weapon skill (Swordfighting, Axefighting, Archery, Magic,
3608 and so on). Damage uses Strength, Dexterity or Mind according to melee,
3609 ranged or magic.
3610- Successful player-attack XP is split equally between the hit skill and the
3611 damage skill. Ordinary mobs use archetype skill levels and do not earn XP.
3612- Shop NPCs sell items at seed value adapted to the last player-market unit
3613 price, lerping over one hour, multiplied by a hidden per-shop discount.
3614- Only the latest player-market sale per item is stored (price, timestamp, and
3615 lerp origin). No historical series.
3616- Item hover shows name, description, origin (crafter or shop NPC) and the
3617 undiscounted current value, refreshed at most once per minute.
3618
3619## 0.6
3620
3621- Added a 32-slot player inventory, stackable items, carried currency as a
3622 numeric wallet, and unique-instance items for letters and filled cheques.
3623- Redefined letters as paper items with player-written text rather than a
3624 separate mail record.
3625- Redefined carrier pigeons as free couriers that carry money or one item
3626 stack to a player or to the nearest bank.
3627- Added a shared unlimited bank near the marketplace, blank cheques filled to
3628 99, vault reservations on fill, in-person redemption and pigeon-to-bank
3629 cheque transfers between vaults.
3630- Added player-dropped ground items: 10-minute lifetime, non-blocking, pickup
3631 only while standing on the tile, timestamp persistence across unload.
3632- Specified later ground-item spawners and harvesting as content that reuses
3633 this item model.
3634- Routed offline/full-inventory pigeon delivery and older-side market
3635 settlement into the recipient's shared bank vault.
3636
3637## 0.5
3638
3639- Made carrier pigeons shared world-visible entities whenever their route crosses an already-simulating chunk.
3640- Unrelated nearby players can see pigeons in their normal 3x3 chunk view; pigeons do not keep chunks loaded themselves.
3641- Added deterministic materialisation/dematerialisation between durable abstract transit and worker-owned ECS pigeon entities.
3642
3643## 0.4
3644
3645- Added FrameworkV3 as the shared player-client foundation while keeping backend ECS internal to the server.
3646- Added server-side proximity chat degradation, persistent player groups and durable carrier-pigeon letters.
3647- Added scalable courier transit that can cross dormant world space without forcing normal chunk simulation.
3648- Added the central marketplace, escrowed hidden order book, midpoint pricing and pigeon-based remote settlement.
3649- Added the player-driven item-source philosophy and restrictions on NPC shop inventories.
3650- Added classless, skill-based player progression and authoritative skill XP.
3651
3652## 0.3
3653
3654- Converted the living design document to Markdown as the canonical format.
3655- Defined `systemd` as the production process supervisor.
3656- Added a conditional, manifest-driven deployment path so crashes do not deploy pending code early.
3657- Added a concrete example systemd service shape and clarified privilege separation.
3658
3659## 0.2
3660
3661- Added unload-driven chunk persistence, authored world revisions, the admin world editor, spawner blocks, graceful scheduled restarts and future player scripting hooks.