Block letter CE sales and recipe NPC buyback; add spring visuals and seasonal regrow.
Letters stay off the Central Exchange but remain NPC-sellable (destroyed); recipe paper cannot be sold to NPCs while CE listing stays allowed. Market/shop prices ceil fractional lerps. Calendar spring drives grass art and tree/plant regrow multipliers.
The contents of this binary file are not shown.
@@ -67,7 +67,8 @@
67
67
<label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>
68
68
<label>Season preview
69
69
<select id="season">
70
<option value="summer">Summer / spring</option>
70
<option value="spring">Spring</option>
71
<option value="summer">Summer</option>
71
72
<option value="fall">Fall</option>
72
73
<option value="winter">Winter</option>
73
74
</select>
@@ -75,7 +76,7 @@
75
76
<button id="open-settings" type="button">World settings</button>
76
77
<button id="open-quests" type="button">Quests</button>
77
78
<button id="open-dialogues" type="button">Dialogues</button>
78
<p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states (seasonal outdoor tiles cycle summer/fall/winter and update Season preview).</p>
79
<p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states (seasonal outdoor tiles cycle spring/summer/fall/winter and update Season preview).</p>
79
80
</aside>
80
81
<section id="changelog-wrap">
81
82
<h2>Changelog</h2>
@@ -67,7 +67,8 @@67
<label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>67
<label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>68
<label>Season preview68
<label>Season preview69
<select id="season">69
<select id="season">70
<option value="summer">Summer / spring</option>70
<option value="spring">Spring</option>71
<option value="summer">Summer</option>71
<option value="fall">Fall</option>72
<option value="fall">Fall</option>72
<option value="winter">Winter</option>73
<option value="winter">Winter</option>73
</select>74
</select>@@ -75,7 +76,7 @@75
<button id="open-settings" type="button">World settings</button>76
<button id="open-settings" type="button">World settings</button>76
<button id="open-quests" type="button">Quests</button>77
<button id="open-quests" type="button">Quests</button>77
<button id="open-dialogues" type="button">Dialogues</button>78
<button id="open-dialogues" type="button">Dialogues</button>78
<p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states (seasonal outdoor tiles cycle summer/fall/winter and update Season preview).</p>79
<p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states (seasonal outdoor tiles cycle spring/summer/fall/winter and update Season preview).</p>79
</aside>80
</aside>80
<section id="changelog-wrap">81
<section id="changelog-wrap">81
<h2>Changelog</h2>82
<h2>Changelog</h2>@@ -1163,7 +1163,10 @@ $("season").addEventListener("change", () =>
1163
1163
1164
1164
function syncSeasonControls (season)
1165
1165
{
1166
const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
1166
const next = season === SeasonId.spring
1167
|| season === SeasonId.fall
1168
|| season === SeasonId.winter
1169
|| season === SeasonId.summer
1167
1170
? season
1168
1171
: seasonIdAt();
1169
1172
$("season").value = next;
@@ -1163,7 +1163,10 @@ $("season").addEventListener("change", () =>1163
1163
1164
function syncSeasonControls (season)1164
function syncSeasonControls (season)1165
{1165
{1166
const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer1166
const next = season === SeasonId.spring1167
|| season === SeasonId.fall1168
|| season === SeasonId.winter1169
|| season === SeasonId.summer1167
? season1170
? season1168
: seasonIdAt();1171
: seasonIdAt();1169
$("season").value = next;1172
$("season").value = next;@@ -853,6 +853,10 @@ export function initInventory ({
853
853
{
854
854
localCharacterId = characterId;
855
855
},
856
getLocalCharacterId ()
857
{
858
return localCharacterId;
859
},
856
860
getInventorySlots ()
857
861
{
858
862
return bag.inventory ?? [];
@@ -853,6 +853,10 @@ export function initInventory ({853
{853
{854
localCharacterId = characterId;854
localCharacterId = characterId;855
},855
},856
getLocalCharacterId ()857
{858
return localCharacterId;859
},856
getInventorySlots ()860
getInventorySlots ()857
{861
{858
return bag.inventory ?? [];862
return bag.inventory ?? [];@@ -1100,6 +1100,10 @@ async function main ()
1100
1100
getInventorySlots ()
1101
1101
{
1102
1102
return inventory?.getInventorySlots?.() ?? [];
1103
},
1104
getLocalCharacterId ()
1105
{
1106
return inventory?.getLocalCharacterId?.() ?? null;
1103
1107
}
1104
1108
});
1105
1109
bounty = initBounty({
@@ -1100,6 +1100,10 @@ async function main ()1100
getInventorySlots ()1100
getInventorySlots ()1101
{1101
{1102
return inventory?.getInventorySlots?.() ?? [];1102
return inventory?.getInventorySlots?.() ?? [];1103
},1104
getLocalCharacterId ()1105
{1106
return inventory?.getLocalCharacterId?.() ?? null;1103
}1107
}1104
});1108
});1105
bounty = initBounty({1109
bounty = initBounty({@@ -7,6 +7,7 @@ import {
7
7
import { INVENTORY_SLOTS } from "/shared/items/inventory.js";
8
8
import { marketOrderListingFee } from "/shared/market/exchange.js";
9
9
import { countMarketFunds, resolveMarketSellListing } from "/shared/market/funds.js";
10
import { canSellOnMarketplace } from "/shared/items/marketplace.js";
10
11
import { applyItemIcon } from "../render/potionIcon.js";
11
12
12
13
export function initMarket ({
@@ -14,6 +15,7 @@ export function initMarket ({
14
15
MessageType,
15
16
getInventorySlots,
16
17
getCoinCount,
18
getLocalCharacterId,
17
19
onSuppressWorldClick
18
20
})
19
21
{
@@ -204,7 +206,7 @@ export function initMarket ({
204
206
const price = entry?.hintPrice;
205
207
if (price == null || !(Number(price) > 0))
206
208
{ return null; }
207
return Math.max(1, Math.round(Number(price)));
209
return Math.max(1, Math.ceil(Number(price)));
208
210
}
209
211
210
212
function updateSellSuggest (itemId = null)
@@ -333,7 +335,7 @@ export function initMarket ({
333
335
const button = document.createElement("button");
334
336
button.type = "button";
335
337
const listing = slot ? resolveMarketSellListing(slot) : null;
336
const sellable = !!listing && itemDefinition(slot.itemId)?.marketplaceSellable !== false;
338
const sellable = !!listing && canSellOnMarketplace(slot, getLocalCharacterId?.() ?? null);
337
339
button.className = `item-slot${selectedSellSlot === slotIndex ? " selected" : ""}`;
338
340
if (slot && !sellable)
339
341
{ button.classList.add("disabled"); }
@@ -7,6 +7,7 @@ import {7
import { INVENTORY_SLOTS } from "/shared/items/inventory.js";7
import { INVENTORY_SLOTS } from "/shared/items/inventory.js";8
import { marketOrderListingFee } from "/shared/market/exchange.js";8
import { marketOrderListingFee } from "/shared/market/exchange.js";9
import { countMarketFunds, resolveMarketSellListing } from "/shared/market/funds.js";9
import { countMarketFunds, resolveMarketSellListing } from "/shared/market/funds.js";10
import { canSellOnMarketplace } from "/shared/items/marketplace.js";10
import { applyItemIcon } from "../render/potionIcon.js";11
import { applyItemIcon } from "../render/potionIcon.js";11
12
12
export function initMarket ({13
export function initMarket ({@@ -14,6 +15,7 @@ export function initMarket ({14
MessageType,15
MessageType,15
getInventorySlots,16
getInventorySlots,16
getCoinCount,17
getCoinCount,18
getLocalCharacterId,17
onSuppressWorldClick19
onSuppressWorldClick18
})20
})19
{21
{@@ -204,7 +206,7 @@ export function initMarket ({204
const price = entry?.hintPrice;206
const price = entry?.hintPrice;205
if (price == null || !(Number(price) > 0))207
if (price == null || !(Number(price) > 0))206
{ return null; }208
{ return null; }207
return Math.max(1, Math.round(Number(price)));209
return Math.max(1, Math.ceil(Number(price)));208
}210
}209
211
210
function updateSellSuggest (itemId = null)212
function updateSellSuggest (itemId = null)@@ -333,7 +335,7 @@ export function initMarket ({333
const button = document.createElement("button");335
const button = document.createElement("button");334
button.type = "button";336
button.type = "button";335
const listing = slot ? resolveMarketSellListing(slot) : null;337
const listing = slot ? resolveMarketSellListing(slot) : null;336
const sellable = !!listing && itemDefinition(slot.itemId)?.marketplaceSellable !== false;338
const sellable = !!listing && canSellOnMarketplace(slot, getLocalCharacterId?.() ?? null);337
button.className = `item-slot${selectedSellSlot === slotIndex ? " selected" : ""}`;339
button.className = `item-slot${selectedSellSlot === slotIndex ? " selected" : ""}`;338
if (slot && !sellable)340
if (slot && !sellable)339
{ button.classList.add("disabled"); }341
{ button.classList.add("disabled"); }@@ -394,7 +394,7 @@ export class WorldView
394
394
this.bloomEnabled = true;
395
395
this.settings = { ...DEFAULT_WORLD_SETTINGS };
396
396
this.worldHour = 12;
397
/** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */
397
/** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */
398
398
this.worldSeason = seasonIdAt();
399
399
this.nightPreview = null;
400
400
this.followPlayer = true;
@@ -443,7 +443,10 @@ export class WorldView
443
443
/** Apply server (or local) calendar season; rebakes chunks when it changes. */
444
444
setWorldSeason (season)
445
445
{
446
const calendar = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
446
const calendar = season === SeasonId.spring
447
|| season === SeasonId.fall
448
|| season === SeasonId.winter
449
|| season === SeasonId.summer
447
450
? season
448
451
: seasonIdAt();
449
452
this.calendarSeason = calendar;
@@ -394,7 +394,7 @@ export class WorldView394
this.bloomEnabled = true;394
this.bloomEnabled = true;395
this.settings = { ...DEFAULT_WORLD_SETTINGS };395
this.settings = { ...DEFAULT_WORLD_SETTINGS };396
this.worldHour = 12;396
this.worldHour = 12;397
/** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */397
/** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */398
this.worldSeason = seasonIdAt();398
this.worldSeason = seasonIdAt();399
this.nightPreview = null;399
this.nightPreview = null;400
this.followPlayer = true;400
this.followPlayer = true;@@ -443,7 +443,10 @@ export class WorldView443
/** Apply server (or local) calendar season; rebakes chunks when it changes. */443
/** Apply server (or local) calendar season; rebakes chunks when it changes. */444
setWorldSeason (season)444
setWorldSeason (season)445
{445
{446
const calendar = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer446
const calendar = season === SeasonId.spring447
|| season === SeasonId.fall448
|| season === SeasonId.winter449
|| season === SeasonId.summer447
? season450
? season448
: seasonIdAt();451
: seasonIdAt();449
this.calendarSeason = calendar;452
this.calendarSeason = calendar;@@ -16,7 +16,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16
16
## Interior dimensions
17
17
18
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`; spring→summer art, autumn→fall). 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.
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
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
21
22
22
## Ground and block tile layers
@@ -76,7 +76,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
76
76
## World editor (client)
77
77
78
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: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, **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.
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, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, **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
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
81
82
82
## Per-chunk changelog
@@ -148,7 +148,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
148
148
## Night shading
149
149
150
150
**Status:** full
151
**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** (`summer` / `fall` / `winter`) for seasonal tile visuals.
151
**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).
152
152
**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
153
153
154
154
## FrameworkV3 client bootstrap
@@ -166,7 +166,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
166
166
## Visual tile states
167
167
168
168
**Status:** full
169
**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, calendar season overrides authored state in play; 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.
169
**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.
170
170
**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`
171
171
172
172
## Region workers and cross-worker transfer
@@ -248,8 +248,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
248
248
## Gathering, crafting, and production skills
249
249
250
250
**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower/herb herbalism live)
251
**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. **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). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
252
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
251
**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). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
252
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `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/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`, `server/tests/season.test.js`
253
253
254
254
## Cloth, dyes, and tailoring
255
255
@@ -16,7 +16,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi16
## Interior dimensions
16
## Interior dimensions
17
17
18
**Status:** partial
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`; spring→summer art, autumn→fall). 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.
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`
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
21
22
## Ground and block tile layers
22
## Ground and block tile layers
@@ -76,7 +76,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi76
## World editor (client)
76
## World editor (client)
77
77
78
**Status:** full
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: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, **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.
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, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, **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`
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
81
82
## Per-chunk changelog
82
## Per-chunk changelog
@@ -148,7 +148,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi148
## Night shading
148
## Night shading
149
149
150
**Status:** full
150
**Status:** full
151
**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** (`summer` / `fall` / `winter`) for seasonal tile visuals.
151
**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).
152
**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
152
**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
153
153
154
## FrameworkV3 client bootstrap
154
## FrameworkV3 client bootstrap
@@ -166,7 +166,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi166
## Visual tile states
166
## Visual tile states
167
167
168
**Status:** full
168
**Status:** full
169
**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, calendar season overrides authored state in play; 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.
169
**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.
170
**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`
170
**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`
171
171
172
## Region workers and cross-worker transfer
172
## Region workers and cross-worker transfer
@@ -248,8 +248,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi248
## Gathering, crafting, and production skills
248
## Gathering, crafting, and production skills
249
249
250
**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower/herb herbalism live)
250
**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower/herb herbalism live)
251
**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. **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). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
251
**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). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
252
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
252
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `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/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`, `server/tests/season.test.js`
253
253
254
## Cloth, dyes, and tailoring
254
## Cloth, dyes, and tailoring
255
255
@@ -2,6 +2,7 @@ import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2
2
import { BlockType } from "../../../shared/definitions/tiles.js";
3
3
import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4
4
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5
import { isLetterWrittenBy } from "../../../shared/items/letters.js";
5
6
import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
6
7
import { attachOrigins, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
7
8
import { advanceCourierFlight } from "../../../shared/courier/flight.js";
@@ -130,14 +131,11 @@ export class CourierService
130
131
error.userFacing = true;
131
132
throw error;
132
133
}
133
if (slot?.itemId === ItemId.letter)
134
if (slot?.itemId === ItemId.letter && !isLetterWrittenBy(slot, characterId))
134
135
{
135
if (Number(slot.instance?.authorCharacterId) !== Number(characterId))
136
{
137
const error = new Error("You can only send letters you wrote.");
138
error.userFacing = true;
139
throw error;
140
}
136
const error = new Error("You can only send letters you wrote.");
137
error.userFacing = true;
138
throw error;
141
139
}
142
140
const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null);
143
141
if (!taken.ok || !taken.taken)
@@ -2,6 +2,7 @@ import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";3
import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";3
import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";4
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";4
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";5
import { isLetterWrittenBy } from "../../../shared/items/letters.js";5
import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";6
import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";6
import { attachOrigins, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";7
import { attachOrigins, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";7
import { advanceCourierFlight } from "../../../shared/courier/flight.js";8
import { advanceCourierFlight } from "../../../shared/courier/flight.js";@@ -130,14 +131,11 @@ export class CourierService130
error.userFacing = true;131
error.userFacing = true;131
throw error;132
throw error;132
}133
}133
if (slot?.itemId === ItemId.letter)134
if (slot?.itemId === ItemId.letter && !isLetterWrittenBy(slot, characterId))134
{135
{135
if (Number(slot.instance?.authorCharacterId) !== Number(characterId))136
const error = new Error("You can only send letters you wrote.");136
{137
error.userFacing = true;137
const error = new Error("You can only send letters you wrote.");138
throw error;138
error.userFacing = true;139
throw error;140
}141
}139
}142
const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null);140
const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null);143
if (!taken.ok || !taken.taken)141
if (!taken.ok || !taken.taken)@@ -7,6 +7,7 @@ import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
7
7
import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
8
8
import { publicSkillsView } from "../../../shared/skills/state.js";
9
9
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
10
import { canCharacterSeeGroundItem } from "../../../shared/items/letters.js";
10
11
11
12
let nextSessionId = 1;
12
13
@@ -1052,7 +1053,10 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1052
1053
const entityChanged = entityNext.has(key) !== session.entitySubscribed.has(key);
1053
1054
if (forceSnapshots || !session.staticSubscribed.has(key) || entityChanged)
1054
1055
{
1055
send(session, { type: MessageType.chunkSnapshot, ...snapshot });
1056
const groundItems = (snapshot.groundItems ?? []).filter((item) =>
1057
canCharacterSeeGroundItem(item, session.characterId)
1058
);
1059
send(session, { type: MessageType.chunkSnapshot, ...snapshot, groundItems });
1056
1060
}
1057
1061
}
1058
1062
session.entitySubscribed = entityNext;
@@ -1653,6 +1657,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1653
1657
{
1654
1658
if (!seesTo)
1655
1659
{ continue; }
1660
if (!canCharacterSeeGroundItem(event, session.characterId))
1661
{ continue; }
1656
1662
send(session, { type: MessageType.groundItemAppear, ...event, type: MessageType.groundItemAppear });
1657
1663
continue;
1658
1664
}
@@ -1660,6 +1666,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1660
1666
{
1661
1667
if (!seesTo)
1662
1668
{ continue; }
1669
if (!canCharacterSeeGroundItem(event, session.characterId))
1670
{ continue; }
1663
1671
send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });
1664
1672
continue;
1665
1673
}
@@ -7,6 +7,7 @@ import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";7
import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";7
import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";8
import { publicSkillsView } from "../../../shared/skills/state.js";8
import { publicSkillsView } from "../../../shared/skills/state.js";9
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";9
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";10
import { canCharacterSeeGroundItem } from "../../../shared/items/letters.js";10
11
11
let nextSessionId = 1;12
let nextSessionId = 1;12
13
@@ -1052,7 +1053,10 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1052
const entityChanged = entityNext.has(key) !== session.entitySubscribed.has(key);1053
const entityChanged = entityNext.has(key) !== session.entitySubscribed.has(key);1053
if (forceSnapshots || !session.staticSubscribed.has(key) || entityChanged)1054
if (forceSnapshots || !session.staticSubscribed.has(key) || entityChanged)1054
{1055
{1055
send(session, { type: MessageType.chunkSnapshot, ...snapshot });1056
const groundItems = (snapshot.groundItems ?? []).filter((item) =>1057
canCharacterSeeGroundItem(item, session.characterId)1058
);1059
send(session, { type: MessageType.chunkSnapshot, ...snapshot, groundItems });1056
}1060
}1057
}1061
}1058
session.entitySubscribed = entityNext;1062
session.entitySubscribed = entityNext;@@ -1653,6 +1657,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1653
{1657
{1654
if (!seesTo)1658
if (!seesTo)1655
{ continue; }1659
{ continue; }1660
if (!canCharacterSeeGroundItem(event, session.characterId))1661
{ continue; }1656
send(session, { type: MessageType.groundItemAppear, ...event, type: MessageType.groundItemAppear });1662
send(session, { type: MessageType.groundItemAppear, ...event, type: MessageType.groundItemAppear });1657
continue;1663
continue;1658
}1664
}@@ -1660,6 +1666,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1660
{1666
{1661
if (!seesTo)1667
if (!seesTo)1662
{ continue; }1668
{ continue; }1669
if (!canCharacterSeeGroundItem(event, session.characterId))1670
{ continue; }1663
send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });1671
send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });1664
continue;1672
continue;1665
}1673
}@@ -35,7 +35,12 @@ import { herbDefinition, isHerbId } from "../../../shared/definitions/herbs.js";
35
35
import { insertStack } from "../../../shared/items/inventory.js";
36
36
import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
37
37
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
38
import { seasonIdAt, treeStumpStateForSeason, SeasonId } from "../../../shared/world/season.js";
38
import {
39
seasonIdAt,
40
treeStumpStateForSeason,
41
SeasonId,
42
scaleRegrowDurationMs
43
} from "../../../shared/world/season.js";
39
44
import { bagView } from "../items/bags.js";
40
45
import { chebyshev, clearEngage } from "../combat/service.js";
41
46
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
@@ -667,7 +672,7 @@ function completeWoodcutting (world, handle, entityId, character, gather, events
667
672
tileY: gather.tileY,
668
673
typeId: gather.typeId,
669
674
woodTier: gather.woodTier,
670
respawnsAt: now + treeExhaustDurationMs(gather.woodTier)
675
respawnsAt: now + scaleRegrowDurationMs(treeExhaustDurationMs(gather.woodTier), now)
671
676
});
672
677
}
673
678
@@ -769,7 +774,7 @@ function completePlant (world, handle, entityId, character, gather, events, priv
769
774
: (gather.plantKind === "herb" && isHerbId(gather.herbId)
770
775
? gather.herbId
771
776
: defaultPlantState(gather.typeId)),
772
respawnsAt: now + PLANT_EXHAUST_MS
777
respawnsAt: now + scaleRegrowDurationMs(PLANT_EXHAUST_MS, now)
773
778
});
774
779
775
780
clearGather(world.ecs, handle);
@@ -35,7 +35,12 @@ import { herbDefinition, isHerbId } from "../../../shared/definitions/herbs.js";35
import { insertStack } from "../../../shared/items/inventory.js";35
import { insertStack } from "../../../shared/items/inventory.js";36
import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";36
import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";37
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";37
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";38
import { seasonIdAt, treeStumpStateForSeason, SeasonId } from "../../../shared/world/season.js";38
import {39
seasonIdAt,40
treeStumpStateForSeason,41
SeasonId,42
scaleRegrowDurationMs43
} from "../../../shared/world/season.js";39
import { bagView } from "../items/bags.js";44
import { bagView } from "../items/bags.js";40
import { chebyshev, clearEngage } from "../combat/service.js";45
import { chebyshev, clearEngage } from "../combat/service.js";41
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";46
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";@@ -667,7 +672,7 @@ function completeWoodcutting (world, handle, entityId, character, gather, events667
tileY: gather.tileY,672
tileY: gather.tileY,668
typeId: gather.typeId,673
typeId: gather.typeId,669
woodTier: gather.woodTier,674
woodTier: gather.woodTier,670
respawnsAt: now + treeExhaustDurationMs(gather.woodTier)675
respawnsAt: now + scaleRegrowDurationMs(treeExhaustDurationMs(gather.woodTier), now)671
});676
});672
}677
}673
678
@@ -769,7 +774,7 @@ function completePlant (world, handle, entityId, character, gather, events, priv769
: (gather.plantKind === "herb" && isHerbId(gather.herbId)774
: (gather.plantKind === "herb" && isHerbId(gather.herbId)770
? gather.herbId775
? gather.herbId771
: defaultPlantState(gather.typeId)),776
: defaultPlantState(gather.typeId)),772
respawnsAt: now + PLANT_EXHAUST_MS777
respawnsAt: now + scaleRegrowDurationMs(PLANT_EXHAUST_MS, now)773
});778
});774
779
775
clearGather(world.ecs, handle);780
clearGather(world.ecs, handle);@@ -39,6 +39,7 @@ import {
39
39
normalizeOrigins
40
40
} from "../../../shared/items/origin.js";
41
41
import { BANK_LETTER_AUTHOR } from "../../../shared/courier/systemLetters.js";
42
import { canCharacterPickupGroundItem } from "../../../shared/items/letters.js";
42
43
43
44
export function publicGroundItem (item)
44
45
{
@@ -54,7 +55,8 @@ export function publicGroundItem (item)
54
55
instance: instance && (instance.kind === "potion" || instance.kind === "letter" || instance.kind === "recipe-paper")
55
56
? instance
56
57
: null,
57
expiresAt: item.expiresAt
58
expiresAt: item.expiresAt,
59
droppedByCharacterId: item.droppedByCharacterId ?? null
58
60
};
59
61
}
60
62
@@ -228,6 +230,8 @@ function pickupItem (world, sessionId, command)
228
230
const item = world.groundItems.get(command.groundItemId);
229
231
if (!item)
230
232
{ throw userError("That item is no longer on the ground."); }
233
if (!canCharacterPickupGroundItem(item, command.characterId))
234
{ throw userError("That item is no longer on the ground."); }
231
235
const position = world.ecs.get(handle, Component.position);
232
236
if (position.tileX !== item.tileX || position.tileY !== item.tileY)
233
237
{ throw userError("Stand on the item to pick it up."); }
@@ -39,6 +39,7 @@ import {39
normalizeOrigins39
normalizeOrigins40
} from "../../../shared/items/origin.js";40
} from "../../../shared/items/origin.js";41
import { BANK_LETTER_AUTHOR } from "../../../shared/courier/systemLetters.js";41
import { BANK_LETTER_AUTHOR } from "../../../shared/courier/systemLetters.js";42
import { canCharacterPickupGroundItem } from "../../../shared/items/letters.js";42
43
43
export function publicGroundItem (item)44
export function publicGroundItem (item)44
{45
{@@ -54,7 +55,8 @@ export function publicGroundItem (item)54
instance: instance && (instance.kind === "potion" || instance.kind === "letter" || instance.kind === "recipe-paper")55
instance: instance && (instance.kind === "potion" || instance.kind === "letter" || instance.kind === "recipe-paper")55
? instance56
? instance56
: null,57
: null,57
expiresAt: item.expiresAt58
expiresAt: item.expiresAt,59
droppedByCharacterId: item.droppedByCharacterId ?? null58
};60
};59
}61
}60
62
@@ -228,6 +230,8 @@ function pickupItem (world, sessionId, command)228
const item = world.groundItems.get(command.groundItemId);230
const item = world.groundItems.get(command.groundItemId);229
if (!item)231
if (!item)230
{ throw userError("That item is no longer on the ground."); }232
{ throw userError("That item is no longer on the ground."); }233
if (!canCharacterPickupGroundItem(item, command.characterId))234
{ throw userError("That item is no longer on the ground."); }231
const position = world.ecs.get(handle, Component.position);235
const position = world.ecs.get(handle, Component.position);232
if (position.tileX !== item.tileX || position.tileY !== item.tileY)236
if (position.tileX !== item.tileX || position.tileY !== item.tileY)233
{ throw userError("Stand on the item to pick it up."); }237
{ throw userError("Stand on the item to pick it up."); }@@ -12,7 +12,7 @@ import {
12
12
} from "../../../shared/items/inventory.js";
13
13
import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js";
14
14
import { attachOrigins, normalizeOrigins, splitOrigins, writtenOrigin } from "../../../shared/items/origin.js";
15
import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";
15
import { undiscountedMarketValue, undiscountedMarketCoins } from "../../../shared/shop/pricing.js";
16
16
import { CENTRAL_EXCHANGE_ORG } from "../../../shared/courier/systemLetters.js";
17
17
import {
18
18
MARKET_ORDER_MAX_AGE_MS,
@@ -214,7 +214,7 @@ export class MarketService
214
214
const slot = bag.inventory?.[slotIndex];
215
215
if (!slot)
216
216
{ throw userError("That slot is empty."); }
217
assertMarketplaceSellable(slot);
217
assertMarketplaceSellable(slot, characterId);
218
218
if ((slot.itemId | 0) === ItemId.coins)
219
219
{ throw userError("Coins cannot be listed on the marketplace."); }
220
220
@@ -900,7 +900,7 @@ export class MarketService
900
900
catalog.push({
901
901
itemId: def.itemId,
902
902
displayName: def.displayName,
903
hintPrice: undiscountedMarketValue(
903
hintPrice: undiscountedMarketCoins(
904
904
def.itemId,
905
905
this.lastSaleFor(def.itemId),
906
906
now,
@@ -12,7 +12,7 @@ import {12
} from "../../../shared/items/inventory.js";12
} from "../../../shared/items/inventory.js";13
import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js";13
import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js";14
import { attachOrigins, normalizeOrigins, splitOrigins, writtenOrigin } from "../../../shared/items/origin.js";14
import { attachOrigins, normalizeOrigins, splitOrigins, writtenOrigin } from "../../../shared/items/origin.js";15
import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";15
import { undiscountedMarketValue, undiscountedMarketCoins } from "../../../shared/shop/pricing.js";16
import { CENTRAL_EXCHANGE_ORG } from "../../../shared/courier/systemLetters.js";16
import { CENTRAL_EXCHANGE_ORG } from "../../../shared/courier/systemLetters.js";17
import {17
import {18
MARKET_ORDER_MAX_AGE_MS,18
MARKET_ORDER_MAX_AGE_MS,@@ -214,7 +214,7 @@ export class MarketService214
const slot = bag.inventory?.[slotIndex];214
const slot = bag.inventory?.[slotIndex];215
if (!slot)215
if (!slot)216
{ throw userError("That slot is empty."); }216
{ throw userError("That slot is empty."); }217
assertMarketplaceSellable(slot);217
assertMarketplaceSellable(slot, characterId);218
if ((slot.itemId | 0) === ItemId.coins)218
if ((slot.itemId | 0) === ItemId.coins)219
{ throw userError("Coins cannot be listed on the marketplace."); }219
{ throw userError("Coins cannot be listed on the marketplace."); }220
220
@@ -900,7 +900,7 @@ export class MarketService900
catalog.push({900
catalog.push({901
itemId: def.itemId,901
itemId: def.itemId,902
displayName: def.displayName,902
displayName: def.displayName,903
hintPrice: undiscountedMarketValue(903
hintPrice: undiscountedMarketCoins(904
def.itemId,904
def.itemId,905
this.lastSaleFor(def.itemId),905
this.lastSaleFor(def.itemId),906
now,906
now,@@ -9,6 +9,7 @@ import {
9
9
splitOrigins,
10
10
shopOrigin
11
11
} from "../../../shared/items/origin.js";
12
import { isLetterStack } from "../../../shared/items/letters.js";
12
13
import {
13
14
addCoinsToSlots,
14
15
cloneStack,
@@ -534,6 +535,7 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
534
535
* Filled cheques sell as their reserved goods with a 5% admin fee.
535
536
* Limited catalog lines refill first; remainder goes into boughtStock
536
537
* (cleared at midnight). Infinite catalog lines absorb goods without resale stock.
538
* Letters pay out but are destroyed — never restocked or put in boughtStock.
537
539
*/
538
540
export function sellToShop (world, sessionId, characterId, npcEntityId, slotIndex, quantity = 1, now = Date.now())
539
541
{
@@ -552,6 +554,7 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde
552
554
{ throw userError("They will not buy that."); }
553
555
554
556
const isCheque = (slot.itemId | 0) === ItemId.filledCheque;
557
const isLetter = isLetterStack(slot);
555
558
const quote = resolveShopSellQuote(slot, {
556
559
lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),
557
560
now,
@@ -567,7 +570,13 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde
567
570
const line = catalogLine(shop, goodsItemId);
568
571
let refill = 0;
569
572
let leftover = qty;
570
if (line)
573
if (isLetter)
574
{
575
// Destroyed on sale — never enter shop stock.
576
refill = 0;
577
leftover = 0;
578
}
579
else if (line)
571
580
{
572
581
if ((line.quantity | 0) <= 0)
573
582
{
@@ -9,6 +9,7 @@ import {9
splitOrigins,9
splitOrigins,10
shopOrigin10
shopOrigin11
} from "../../../shared/items/origin.js";11
} from "../../../shared/items/origin.js";12
import { isLetterStack } from "../../../shared/items/letters.js";12
import {13
import {13
addCoinsToSlots,14
addCoinsToSlots,14
cloneStack,15
cloneStack,@@ -534,6 +535,7 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,534
* Filled cheques sell as their reserved goods with a 5% admin fee.535
* Filled cheques sell as their reserved goods with a 5% admin fee.535
* Limited catalog lines refill first; remainder goes into boughtStock536
* Limited catalog lines refill first; remainder goes into boughtStock536
* (cleared at midnight). Infinite catalog lines absorb goods without resale stock.537
* (cleared at midnight). Infinite catalog lines absorb goods without resale stock.538
* Letters pay out but are destroyed — never restocked or put in boughtStock.537
*/539
*/538
export function sellToShop (world, sessionId, characterId, npcEntityId, slotIndex, quantity = 1, now = Date.now())540
export function sellToShop (world, sessionId, characterId, npcEntityId, slotIndex, quantity = 1, now = Date.now())539
{541
{@@ -552,6 +554,7 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde552
{ throw userError("They will not buy that."); }554
{ throw userError("They will not buy that."); }553
555
554
const isCheque = (slot.itemId | 0) === ItemId.filledCheque;556
const isCheque = (slot.itemId | 0) === ItemId.filledCheque;557
const isLetter = isLetterStack(slot);555
const quote = resolveShopSellQuote(slot, {558
const quote = resolveShopSellQuote(slot, {556
lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),559
lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),557
now,560
now,@@ -567,7 +570,13 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde567
const line = catalogLine(shop, goodsItemId);570
const line = catalogLine(shop, goodsItemId);568
let refill = 0;571
let refill = 0;569
let leftover = qty;572
let leftover = qty;570
if (line)573
if (isLetter)574
{575
// Destroyed on sale — never enter shop stock.576
refill = 0;577
leftover = 0;578
}579
else if (line)571
{580
{572
if ((line.quantity | 0) <= 0)581
if ((line.quantity | 0) <= 0)573
{582
{@@ -37,7 +37,8 @@ test("lighting and season resolve helpers", () =>
37
37
assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.alwaysDark, 0.1), 1);
38
38
assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.dayNight, 0.55), 0.55);
39
39
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.auto), null);
40
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.spring), "summer");
40
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.spring), "spring");
41
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.summer), "summer");
41
42
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.autumn), "fall");
42
43
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.winter), "winter");
43
44
});
@@ -37,7 +37,8 @@ test("lighting and season resolve helpers", () =>37
assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.alwaysDark, 0.1), 1);37
assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.alwaysDark, 0.1), 1);38
assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.dayNight, 0.55), 0.55);38
assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.dayNight, 0.55), 0.55);39
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.auto), null);39
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.auto), null);40
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.spring), "summer");40
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.spring), "spring");41
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.summer), "summer");41
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.autumn), "fall");42
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.autumn), "fall");42
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.winter), "winter");43
assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.winter), "winter");43
});44
});@@ -150,3 +150,68 @@ test("reading a closed letter opens it", () =>
150
150
finally
151
151
{ harness.close(); }
152
152
});
153
154
test("dropped received letters are only pickable by the dropper", () =>
155
{
156
const harness = makeSimulation({ workerCount: 1 });
157
try
158
{
159
const owner = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ada", lastName: "Owner" });
160
const stranger = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Bob", lastName: "Stranger" });
161
const ownerId = harness.simulation.spawnCharacter(1, owner);
162
const strangerId = harness.simulation.spawnCharacter(2, stranger);
163
const bag = harness.simulation.bagOf(ownerId);
164
const free = bag.inventory.findIndex((slot) => !slot);
165
bag.inventory[free] = {
166
itemId: ItemId.letter,
167
quantity: 1,
168
instance: {
169
kind: "letter",
170
letterId: "priv-1",
171
authorCharacterId: 999,
172
authorDisplayName: "Other Writer",
173
body: "Secret",
174
opened: true,
175
writtenAt: Date.now()
176
}
177
};
178
harness.simulation.applyBag(ownerId, bag);
179
180
harness.simulation.enqueue(1, {
181
type: "drop-item",
182
characterId: owner.character_id,
183
slotIndex: free
184
});
185
const dropped = harness.simulation.step();
186
const appear = dropped.events.find((event) => event.type === "ground-item-appear");
187
assert.ok(appear, JSON.stringify(dropped.events));
188
assert.equal(appear.droppedByCharacterId, owner.character_id);
189
assert.equal(appear.itemId, ItemId.letter);
190
191
harness.simulation.enqueue(2, {
192
type: "pickup-item",
193
characterId: stranger.character_id,
194
groundItemId: appear.groundItemId
195
});
196
const stolen = harness.simulation.step();
197
assert.ok(
198
stolen.events.some((event) => event.type === "command-error"),
199
JSON.stringify(stolen.events)
200
);
201
assert.equal(
202
harness.simulation.bagOf(strangerId).inventory.some((slot) => slot?.itemId === ItemId.letter),
203
false
204
);
205
206
harness.simulation.enqueue(1, {
207
type: "pickup-item",
208
characterId: owner.character_id,
209
groundItemId: appear.groundItemId
210
});
211
const reclaim = harness.simulation.step();
212
assert.equal(reclaim.events.some((event) => event.type === "command-error"), false, JSON.stringify(reclaim.events));
213
assert.ok(harness.simulation.bagOf(ownerId).inventory.some((slot) => slot?.itemId === ItemId.letter));
214
}
215
finally
216
{ harness.close(); }
217
});
@@ -150,3 +150,68 @@ test("reading a closed letter opens it", () =>150
finally150
finally151
{ harness.close(); }151
{ harness.close(); }152
});152
});153
154
test("dropped received letters are only pickable by the dropper", () =>155
{156
const harness = makeSimulation({ workerCount: 1 });157
try158
{159
const owner = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ada", lastName: "Owner" });160
const stranger = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Bob", lastName: "Stranger" });161
const ownerId = harness.simulation.spawnCharacter(1, owner);162
const strangerId = harness.simulation.spawnCharacter(2, stranger);163
const bag = harness.simulation.bagOf(ownerId);164
const free = bag.inventory.findIndex((slot) => !slot);165
bag.inventory[free] = {166
itemId: ItemId.letter,167
quantity: 1,168
instance: {169
kind: "letter",170
letterId: "priv-1",171
authorCharacterId: 999,172
authorDisplayName: "Other Writer",173
body: "Secret",174
opened: true,175
writtenAt: Date.now()176
}177
};178
harness.simulation.applyBag(ownerId, bag);179
180
harness.simulation.enqueue(1, {181
type: "drop-item",182
characterId: owner.character_id,183
slotIndex: free184
});185
const dropped = harness.simulation.step();186
const appear = dropped.events.find((event) => event.type === "ground-item-appear");187
assert.ok(appear, JSON.stringify(dropped.events));188
assert.equal(appear.droppedByCharacterId, owner.character_id);189
assert.equal(appear.itemId, ItemId.letter);190
191
harness.simulation.enqueue(2, {192
type: "pickup-item",193
characterId: stranger.character_id,194
groundItemId: appear.groundItemId195
});196
const stolen = harness.simulation.step();197
assert.ok(198
stolen.events.some((event) => event.type === "command-error"),199
JSON.stringify(stolen.events)200
);201
assert.equal(202
harness.simulation.bagOf(strangerId).inventory.some((slot) => slot?.itemId === ItemId.letter),203
false204
);205
206
harness.simulation.enqueue(1, {207
type: "pickup-item",208
characterId: owner.character_id,209
groundItemId: appear.groundItemId210
});211
const reclaim = harness.simulation.step();212
assert.equal(reclaim.events.some((event) => event.type === "command-error"), false, JSON.stringify(reclaim.events));213
assert.ok(harness.simulation.bagOf(ownerId).inventory.some((slot) => slot?.itemId === ItemId.letter));214
}215
finally216
{ harness.close(); }217
});@@ -38,6 +38,32 @@ test("normal items are marketplace sellable by default", () =>
38
38
assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);
39
39
});
40
40
41
test("letters cannot be listed on the marketplace", () =>
42
{
43
const own = {
44
itemId: ItemId.letter,
45
quantity: 1,
46
instance: {
47
kind: "letter",
48
letterId: "x",
49
authorCharacterId: 1,
50
authorDisplayName: "Ada",
51
body: "Hi",
52
opened: true
53
}
54
};
55
const received = {
56
...own,
57
instance: { ...own.instance, authorCharacterId: 2, authorDisplayName: "Bob" }
58
};
59
assert.equal(canSellOnMarketplace(own, 1), false);
60
assert.equal(canSellOnMarketplace(received, 1), false);
61
assert.throws(
62
() => assertMarketplaceSellable(own, 1),
63
(err) => /letters cannot be sold on the marketplace/i.test(err.message)
64
);
65
});
66
41
67
test("midpoint trade price rounds half units deterministically", () =>
42
68
{
43
69
assert.equal(midpointTradePrice(100, 80), 90);
@@ -38,6 +38,32 @@ test("normal items are marketplace sellable by default", () =>38
assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);38
assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);39
});39
});40
40
41
test("letters cannot be listed on the marketplace", () =>42
{43
const own = {44
itemId: ItemId.letter,45
quantity: 1,46
instance: {47
kind: "letter",48
letterId: "x",49
authorCharacterId: 1,50
authorDisplayName: "Ada",51
body: "Hi",52
opened: true53
}54
};55
const received = {56
...own,57
instance: { ...own.instance, authorCharacterId: 2, authorDisplayName: "Bob" }58
};59
assert.equal(canSellOnMarketplace(own, 1), false);60
assert.equal(canSellOnMarketplace(received, 1), false);61
assert.throws(62
() => assertMarketplaceSellable(own, 1),63
(err) => /letters cannot be sold on the marketplace/i.test(err.message)64
);65
});66
41
test("midpoint trade price rounds half units deterministically", () =>67
test("midpoint trade price rounds half units deterministically", () =>42
{68
{43
assert.equal(midpointTradePrice(100, 80), 90);69
assert.equal(midpointTradePrice(100, 80), 90);@@ -4,7 +4,11 @@ import { fileURLToPath } from "node:url";
4
4
import { join } from "node:path";
5
5
import {
6
6
SeasonId,
7
GrowthSeasonId,
7
8
seasonIdAt,
9
growthSeasonIdAt,
10
regrowDurationMultiplier,
11
scaleRegrowDurationMs,
8
12
resolveSeasonalVisualState,
9
13
preferredSeasonalDefaultState,
10
14
typeHasSeasonalStates,
@@ -16,9 +20,11 @@ import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
16
20
17
21
const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));
18
22
19
test("seasonIdAt maps local months to summer/fall/winter", () =>
23
test("seasonIdAt maps local months to spring/summer/fall/winter", () =>
20
24
{
21
assert.equal(seasonIdAt(new Date(2026, 2, 1).getTime()), SeasonId.summer);
25
assert.equal(seasonIdAt(new Date(2026, 2, 1).getTime()), SeasonId.spring);
26
assert.equal(seasonIdAt(new Date(2026, 4, 31).getTime()), SeasonId.spring);
27
assert.equal(seasonIdAt(new Date(2026, 5, 1).getTime()), SeasonId.summer);
22
28
assert.equal(seasonIdAt(new Date(2026, 7, 15).getTime()), SeasonId.summer);
23
29
assert.equal(seasonIdAt(new Date(2026, 8, 1).getTime()), SeasonId.fall);
24
30
assert.equal(seasonIdAt(new Date(2026, 10, 30).getTime()), SeasonId.fall);
@@ -26,6 +32,29 @@ test("seasonIdAt maps local months to summer/fall/winter", () =>
26
32
assert.equal(seasonIdAt(new Date(2026, 0, 15).getTime()), SeasonId.winter);
27
33
});
28
34
35
test("growthSeasonIdAt matches seasonIdAt", () =>
36
{
37
assert.equal(growthSeasonIdAt(new Date(2026, 2, 1).getTime()), GrowthSeasonId.spring);
38
assert.equal(growthSeasonIdAt(new Date(2026, 4, 31).getTime()), GrowthSeasonId.spring);
39
assert.equal(growthSeasonIdAt(new Date(2026, 5, 1).getTime()), GrowthSeasonId.summer);
40
assert.equal(growthSeasonIdAt(new Date(2026, 7, 15).getTime()), GrowthSeasonId.summer);
41
assert.equal(growthSeasonIdAt(new Date(2026, 8, 1).getTime()), GrowthSeasonId.fall);
42
assert.equal(growthSeasonIdAt(new Date(2026, 11, 1).getTime()), GrowthSeasonId.winter);
43
});
44
45
test("regrow duration: summer/fall 1×, winter 2×, spring 0.75×", () =>
46
{
47
assert.equal(regrowDurationMultiplier(GrowthSeasonId.summer), 1);
48
assert.equal(regrowDurationMultiplier(GrowthSeasonId.fall), 1);
49
assert.equal(regrowDurationMultiplier(GrowthSeasonId.winter), 2);
50
assert.equal(regrowDurationMultiplier(GrowthSeasonId.spring), 0.75);
51
assert.equal(scaleRegrowDurationMs(10_000, GrowthSeasonId.summer), 10_000);
52
assert.equal(scaleRegrowDurationMs(10_000, GrowthSeasonId.fall), 10_000);
53
assert.equal(scaleRegrowDurationMs(10_000, GrowthSeasonId.winter), 20_000);
54
assert.equal(scaleRegrowDurationMs(10_000, GrowthSeasonId.spring), 7_500);
55
assert.equal(scaleRegrowDurationMs(15_000, GrowthSeasonId.spring), 11_250);
56
});
57
29
58
test("seasonal visual state follows calendar, not authored state", () =>
30
59
{
31
60
const states = ["fall", "grass", "summer", "winter"];
@@ -53,18 +82,32 @@ test("seasonal overlay uses *-winter when present, else the base state", () =>
53
82
assert.equal(resolveSeasonalVisualState(states, "copper-ore", SeasonId.summer), "copper-ore");
54
83
});
55
84
56
test("seasonalCycleStates lists summer/fall/winter for editor cycling", () =>
85
test("spring uses spring art when present, else summer", () =>
86
{
87
const grass = ["fall", "grass", "spring", "summer", "winter"];
88
assert.equal(resolveSeasonalVisualState(grass, "summer", SeasonId.spring), SeasonId.spring);
89
assert.equal(resolveSeasonalVisualState(grass, "winter", SeasonId.summer), SeasonId.summer);
90
const pine = ["fall", "summer", "winter"];
91
assert.equal(resolveSeasonalVisualState(pine, "winter", SeasonId.spring), SeasonId.summer);
92
});
93
94
test("seasonalCycleStates lists spring/summer/fall/winter for editor cycling", () =>
57
95
{
58
96
assert.deepEqual(
59
97
seasonalCycleStates(["fall", "grass", "summer", "winter"]),
60
98
["summer", "fall", "winter"]
61
99
);
100
assert.deepEqual(
101
seasonalCycleStates(["fall", "grass", "spring", "summer", "winter"]),
102
["spring", "summer", "fall", "winter"]
103
);
62
104
assert.deepEqual(
63
105
seasonalCycleStates(["fall", "grass", "winter"]),
64
106
["grass", "fall", "winter"]
65
107
);
66
108
assert.equal(seasonalCycleStates(["1", "2"]), null);
67
109
assert.equal(seasonIdFromVisualState("grass"), SeasonId.summer);
110
assert.equal(seasonIdFromVisualState("spring"), SeasonId.spring);
68
111
assert.equal(seasonIdFromVisualState("fall"), SeasonId.fall);
69
112
});
70
113
@@ -79,7 +122,7 @@ test("shopRestockDayKey uses server-local calendar date", () =>
79
122
test("catalog exposes seasonal grass and pine-tree states", () =>
80
123
{
81
124
const catalog = buildSpriteCatalog(ASSET_ROOT);
82
assert.deepEqual(catalog.grounds.grass.states, ["fall", "grass", "summer", "winter"]);
125
assert.deepEqual(catalog.grounds.grass.states, ["fall", "grass", "spring", "summer", "winter"]);
83
126
assert.equal(catalog.grounds.grass.defaultState, "summer");
84
127
assert.equal(catalog.grounds.grass.outdoor, true);
85
128
assert.equal(catalog.grounds.grass.seasonal, true);
@@ -4,7 +4,11 @@ import { fileURLToPath } from "node:url";4
import { join } from "node:path";4
import { join } from "node:path";5
import {5
import {6
SeasonId,6
SeasonId,7
GrowthSeasonId,7
seasonIdAt,8
seasonIdAt,9
growthSeasonIdAt,10
regrowDurationMultiplier,11
scaleRegrowDurationMs,8
resolveSeasonalVisualState,12
resolveSeasonalVisualState,9
preferredSeasonalDefaultState,13
preferredSeasonalDefaultState,10
typeHasSeasonalStates,14
typeHasSeasonalStates,@@ -16,9 +20,11 @@ import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";16
20
17
const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));21
const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));18
22
19
test("seasonIdAt maps local months to summer/fall/winter", () =>23
test("seasonIdAt maps local months to spring/summer/fall/winter", () =>20
{24
{21
assert.equal(seasonIdAt(new Date(2026, 2, 1).getTime()), SeasonId.summer);25
assert.equal(seasonIdAt(new Date(2026, 2, 1).getTime()), SeasonId.spring);26
assert.equal(seasonIdAt(new Date(2026, 4, 31).getTime()), SeasonId.spring);27
assert.equal(seasonIdAt(new Date(2026, 5, 1).getTime()), SeasonId.summer);22
assert.equal(seasonIdAt(new Date(2026, 7, 15).getTime()), SeasonId.summer);28
assert.equal(seasonIdAt(new Date(2026, 7, 15).getTime()), SeasonId.summer);23
assert.equal(seasonIdAt(new Date(2026, 8, 1).getTime()), SeasonId.fall);29
assert.equal(seasonIdAt(new Date(2026, 8, 1).getTime()), SeasonId.fall);24
assert.equal(seasonIdAt(new Date(2026, 10, 30).getTime()), SeasonId.fall);30
assert.equal(seasonIdAt(new Date(2026, 10, 30).getTime()), SeasonId.fall);@@ -26,6 +32,29 @@ test("seasonIdAt maps local months to summer/fall/winter", () =>26
assert.equal(seasonIdAt(new Date(2026, 0, 15).getTime()), SeasonId.winter);32
assert.equal(seasonIdAt(new Date(2026, 0, 15).getTime()), SeasonId.winter);27
});33
});28
34
35
test("growthSeasonIdAt matches seasonIdAt", () =>36
{37
assert.equal(growthSeasonIdAt(new Date(2026, 2, 1).getTime()), GrowthSeasonId.spring);38
assert.equal(growthSeasonIdAt(new Date(2026, 4, 31).getTime()), GrowthSeasonId.spring);39
assert.equal(growthSeasonIdAt(new Date(2026, 5, 1).getTime()), GrowthSeasonId.summer);40
assert.equal(growthSeasonIdAt(new Date(2026, 7, 15).getTime()), GrowthSeasonId.summer);41
assert.equal(growthSeasonIdAt(new Date(2026, 8, 1).getTime()), GrowthSeasonId.fall);42
assert.equal(growthSeasonIdAt(new Date(2026, 11, 1).getTime()), GrowthSeasonId.winter);43
});44
45
test("regrow duration: summer/fall 1×, winter 2×, spring 0.75×", () =>46
{47
assert.equal(regrowDurationMultiplier(GrowthSeasonId.summer), 1);48
assert.equal(regrowDurationMultiplier(GrowthSeasonId.fall), 1);49
assert.equal(regrowDurationMultiplier(GrowthSeasonId.winter), 2);50
assert.equal(regrowDurationMultiplier(GrowthSeasonId.spring), 0.75);51
assert.equal(scaleRegrowDurationMs(10_000, GrowthSeasonId.summer), 10_000);52
assert.equal(scaleRegrowDurationMs(10_000, GrowthSeasonId.fall), 10_000);53
assert.equal(scaleRegrowDurationMs(10_000, GrowthSeasonId.winter), 20_000);54
assert.equal(scaleRegrowDurationMs(10_000, GrowthSeasonId.spring), 7_500);55
assert.equal(scaleRegrowDurationMs(15_000, GrowthSeasonId.spring), 11_250);56
});57
29
test("seasonal visual state follows calendar, not authored state", () =>58
test("seasonal visual state follows calendar, not authored state", () =>30
{59
{31
const states = ["fall", "grass", "summer", "winter"];60
const states = ["fall", "grass", "summer", "winter"];@@ -53,18 +82,32 @@ test("seasonal overlay uses *-winter when present, else the base state", () =>53
assert.equal(resolveSeasonalVisualState(states, "copper-ore", SeasonId.summer), "copper-ore");82
assert.equal(resolveSeasonalVisualState(states, "copper-ore", SeasonId.summer), "copper-ore");54
});83
});55
84
56
test("seasonalCycleStates lists summer/fall/winter for editor cycling", () =>85
test("spring uses spring art when present, else summer", () =>86
{87
const grass = ["fall", "grass", "spring", "summer", "winter"];88
assert.equal(resolveSeasonalVisualState(grass, "summer", SeasonId.spring), SeasonId.spring);89
assert.equal(resolveSeasonalVisualState(grass, "winter", SeasonId.summer), SeasonId.summer);90
const pine = ["fall", "summer", "winter"];91
assert.equal(resolveSeasonalVisualState(pine, "winter", SeasonId.spring), SeasonId.summer);92
});93
94
test("seasonalCycleStates lists spring/summer/fall/winter for editor cycling", () =>57
{95
{58
assert.deepEqual(96
assert.deepEqual(59
seasonalCycleStates(["fall", "grass", "summer", "winter"]),97
seasonalCycleStates(["fall", "grass", "summer", "winter"]),60
["summer", "fall", "winter"]98
["summer", "fall", "winter"]61
);99
);100
assert.deepEqual(101
seasonalCycleStates(["fall", "grass", "spring", "summer", "winter"]),102
["spring", "summer", "fall", "winter"]103
);62
assert.deepEqual(104
assert.deepEqual(63
seasonalCycleStates(["fall", "grass", "winter"]),105
seasonalCycleStates(["fall", "grass", "winter"]),64
["grass", "fall", "winter"]106
["grass", "fall", "winter"]65
);107
);66
assert.equal(seasonalCycleStates(["1", "2"]), null);108
assert.equal(seasonalCycleStates(["1", "2"]), null);67
assert.equal(seasonIdFromVisualState("grass"), SeasonId.summer);109
assert.equal(seasonIdFromVisualState("grass"), SeasonId.summer);110
assert.equal(seasonIdFromVisualState("spring"), SeasonId.spring);68
assert.equal(seasonIdFromVisualState("fall"), SeasonId.fall);111
assert.equal(seasonIdFromVisualState("fall"), SeasonId.fall);69
});112
});70
113
@@ -79,7 +122,7 @@ test("shopRestockDayKey uses server-local calendar date", () =>79
test("catalog exposes seasonal grass and pine-tree states", () =>122
test("catalog exposes seasonal grass and pine-tree states", () =>80
{123
{81
const catalog = buildSpriteCatalog(ASSET_ROOT);124
const catalog = buildSpriteCatalog(ASSET_ROOT);82
assert.deepEqual(catalog.grounds.grass.states, ["fall", "grass", "summer", "winter"]);125
assert.deepEqual(catalog.grounds.grass.states, ["fall", "grass", "spring", "summer", "winter"]);83
assert.equal(catalog.grounds.grass.defaultState, "summer");126
assert.equal(catalog.grounds.grass.defaultState, "summer");84
assert.equal(catalog.grounds.grass.outdoor, true);127
assert.equal(catalog.grounds.grass.outdoor, true);85
assert.equal(catalog.grounds.grass.seasonal, true);128
assert.equal(catalog.grounds.grass.seasonal, true);@@ -3,6 +3,8 @@ import assert from "node:assert/strict";
3
3
import {
4
4
shopUnitPrice,
5
5
undiscountedMarketValue,
6
undiscountedMarketCoins,
7
marketValueAsCoins,
6
8
canSellInNpcShop,
7
9
canPlayerSellToNpc,
8
10
shopBuyFromPlayerPrice,
@@ -50,6 +52,11 @@ test("shop prices fall back to seedValue and apply hidden discount", () =>
50
52
assert.equal(canPlayerSellToNpc({ itemId: ItemId.stick, quantity: 1 }), true);
51
53
assert.equal(canPlayerSellToNpc({ itemId: ItemId.blankCheque, quantity: 1 }), false);
52
54
assert.equal(canPlayerSellToNpc({ itemId: ItemId.coins, quantity: 10 }), false);
55
assert.equal(canPlayerSellToNpc({
56
itemId: ItemId.recipePaper,
57
quantity: 1,
58
instance: { kind: "recipe-paper", recipeId: "lesser-health-tonic" }
59
}), false);
53
60
assert.equal(canPlayerSellToNpc({
54
61
itemId: ItemId.filledCheque,
55
62
quantity: 1,
@@ -68,6 +75,29 @@ test("shop prices fall back to seedValue and apply hidden discount", () =>
68
75
assert.equal(chequeQuote.payout, chequeQuote.baseTotal - chequeQuote.adminFee);
69
76
});
70
77
78
test("market value display and shop use ceil fractional lerps", () =>
79
{
80
const now = 1_000_000;
81
const lastSale = {
82
lastTradePrice: 10,
83
lastTradeAt: now - 500,
84
priceFrom: 5
85
};
86
// Halfway from 5 → 10 over 1000ms → 7.5 internally.
87
const raw = undiscountedMarketValue(ItemId.copperOre, lastSale, now, 1000);
88
assert.equal(raw, 7.5);
89
assert.equal(marketValueAsCoins(raw), 8);
90
assert.equal(undiscountedMarketCoins(ItemId.copperOre, lastSale, now, 1000), 8);
91
assert.equal(shopBuyFromPlayerPrice(ItemId.copperOre, { lastSale, now, lerpDurationMs: 1000 }), 6);
92
assert.equal(shopBoughtResalePrice(ItemId.copperOre, { lastSale, now, lerpDurationMs: 1000 }), 9);
93
assert.equal(shopUnitPrice(ItemId.copperOre, {
94
lastSale,
95
now,
96
lerpDurationMs: 1000,
97
hiddenDiscount: 1
98
}), 8);
99
});
100
71
101
test("humanoid spawner config keeps sex equipment sells quantities and buysItems", () =>
72
102
{
73
103
assert.equal(isHumanoidMob(MobId.humanoid), true);
@@ -837,3 +867,101 @@ test("resale stock keeps the seller origin instead of Bought from NPC", () =>
837
867
finally
838
868
{ harness.close(); }
839
869
});
870
871
test("NPC letter sales pay out and destroy the letter without stock", () =>
872
{
873
const harness = makeSimulation({ workerCount: 1 });
874
try
875
{
876
const data = createEmptyChunkData();
877
data.open = true;
878
data.spawners = [{
879
localX: 9,
880
localY: 8,
881
config: {
882
mobTypeId: MobId.humanoid,
883
maxAlive: 1,
884
spawnRangeTiles: 0,
885
maxWanderRangeTiles: 0,
886
displayName: "Fence",
887
sells: [],
888
buysItems: true,
889
hiddenDiscount: 1
890
}
891
}];
892
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
893
harness.simulation.reloadWorld();
894
895
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
896
const funded = addCoinsToSlots(emptySlots(), 10);
897
assert.equal(funded.ok, true);
898
funded.slots[1] = {
899
itemId: ItemId.letter,
900
quantity: 1,
901
instance: {
902
kind: "letter",
903
letterId: "sell-me",
904
authorCharacterId: character.character_id,
905
authorDisplayName: "Ada",
906
body: "For sale",
907
opened: true,
908
writtenAt: Date.now()
909
}
910
};
911
harness.stateDb.saveBag(character.character_id, {
912
inventory: funded.slots,
913
equipment: emptyEquipment(),
914
vault: [],
915
vaultReserved: []
916
});
917
const playerId = harness.simulation.spawnCharacter(1, character);
918
harness.simulation.step();
919
harness.advance(50);
920
harness.simulation.step();
921
922
const record = harness.simulation.entityRecord(playerId);
923
const worker = harness.simulation.workers[record.workerId];
924
let npcId = null;
925
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
926
{
927
if (entity.creature.mobTypeId === MobId.humanoid)
928
{
929
npcId = entity.entityId;
930
break;
931
}
932
}
933
assert.ok(npcId);
934
const npcHandle = worker.world.ecs.handleOf(npcId);
935
const shop = worker.world.ecs.get(npcHandle, Component.shop);
936
const npcPos = worker.world.ecs.get(npcHandle, Component.position);
937
const playerHandle = worker.world.ecs.handleOf(playerId);
938
const playerPos = worker.world.ecs.get(playerHandle, Component.position);
939
playerPos.tileX = npcPos.tileX;
940
playerPos.tileY = npcPos.tileY;
941
942
const letterSlot = harness.simulation.bagOf(playerId).inventory
943
.findIndex((slot) => slot?.itemId === ItemId.letter);
944
assert.ok(letterSlot >= 0);
945
const quote = resolveShopSellQuote(harness.simulation.bagOf(playerId).inventory[letterSlot]);
946
assert.ok(quote);
947
const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
948
949
harness.simulation.enqueue(1, {
950
type: "sell-to-shop",
951
characterId: character.character_id,
952
npcEntityId: npcId,
953
slotIndex: letterSlot,
954
quantity: 1
955
});
956
const sold = harness.simulation.step();
957
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
958
const bag = harness.simulation.bagOf(playerId);
959
assert.equal(bag.inventory.some((slot) => slot?.itemId === ItemId.letter), false);
960
assert.equal(boughtQty(shop, ItemId.letter), 0);
961
assert.equal(shop.boughtStock?.[ItemId.letter], undefined);
962
const afterCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
963
assert.equal(afterCoins - beforeCoins, quote.payout);
964
}
965
finally
966
{ harness.close(); }
967
});
@@ -3,6 +3,8 @@ import assert from "node:assert/strict";3
import {3
import {4
shopUnitPrice,4
shopUnitPrice,5
undiscountedMarketValue,5
undiscountedMarketValue,6
undiscountedMarketCoins,7
marketValueAsCoins,6
canSellInNpcShop,8
canSellInNpcShop,7
canPlayerSellToNpc,9
canPlayerSellToNpc,8
shopBuyFromPlayerPrice,10
shopBuyFromPlayerPrice,@@ -50,6 +52,11 @@ test("shop prices fall back to seedValue and apply hidden discount", () =>50
assert.equal(canPlayerSellToNpc({ itemId: ItemId.stick, quantity: 1 }), true);52
assert.equal(canPlayerSellToNpc({ itemId: ItemId.stick, quantity: 1 }), true);51
assert.equal(canPlayerSellToNpc({ itemId: ItemId.blankCheque, quantity: 1 }), false);53
assert.equal(canPlayerSellToNpc({ itemId: ItemId.blankCheque, quantity: 1 }), false);52
assert.equal(canPlayerSellToNpc({ itemId: ItemId.coins, quantity: 10 }), false);54
assert.equal(canPlayerSellToNpc({ itemId: ItemId.coins, quantity: 10 }), false);55
assert.equal(canPlayerSellToNpc({56
itemId: ItemId.recipePaper,57
quantity: 1,58
instance: { kind: "recipe-paper", recipeId: "lesser-health-tonic" }59
}), false);53
assert.equal(canPlayerSellToNpc({60
assert.equal(canPlayerSellToNpc({54
itemId: ItemId.filledCheque,61
itemId: ItemId.filledCheque,55
quantity: 1,62
quantity: 1,@@ -68,6 +75,29 @@ test("shop prices fall back to seedValue and apply hidden discount", () =>68
assert.equal(chequeQuote.payout, chequeQuote.baseTotal - chequeQuote.adminFee);75
assert.equal(chequeQuote.payout, chequeQuote.baseTotal - chequeQuote.adminFee);69
});76
});70
77
78
test("market value display and shop use ceil fractional lerps", () =>79
{80
const now = 1_000_000;81
const lastSale = {82
lastTradePrice: 10,83
lastTradeAt: now - 500,84
priceFrom: 585
};86
// Halfway from 5 → 10 over 1000ms → 7.5 internally.87
const raw = undiscountedMarketValue(ItemId.copperOre, lastSale, now, 1000);88
assert.equal(raw, 7.5);89
assert.equal(marketValueAsCoins(raw), 8);90
assert.equal(undiscountedMarketCoins(ItemId.copperOre, lastSale, now, 1000), 8);91
assert.equal(shopBuyFromPlayerPrice(ItemId.copperOre, { lastSale, now, lerpDurationMs: 1000 }), 6);92
assert.equal(shopBoughtResalePrice(ItemId.copperOre, { lastSale, now, lerpDurationMs: 1000 }), 9);93
assert.equal(shopUnitPrice(ItemId.copperOre, {94
lastSale,95
now,96
lerpDurationMs: 1000,97
hiddenDiscount: 198
}), 8);99
});100
71
test("humanoid spawner config keeps sex equipment sells quantities and buysItems", () =>101
test("humanoid spawner config keeps sex equipment sells quantities and buysItems", () =>72
{102
{73
assert.equal(isHumanoidMob(MobId.humanoid), true);103
assert.equal(isHumanoidMob(MobId.humanoid), true);@@ -837,3 +867,101 @@ test("resale stock keeps the seller origin instead of Bought from NPC", () =>837
finally867
finally838
{ harness.close(); }868
{ harness.close(); }839
});869
});870
871
test("NPC letter sales pay out and destroy the letter without stock", () =>872
{873
const harness = makeSimulation({ workerCount: 1 });874
try875
{876
const data = createEmptyChunkData();877
data.open = true;878
data.spawners = [{879
localX: 9,880
localY: 8,881
config: {882
mobTypeId: MobId.humanoid,883
maxAlive: 1,884
spawnRangeTiles: 0,885
maxWanderRangeTiles: 0,886
displayName: "Fence",887
sells: [],888
buysItems: true,889
hiddenDiscount: 1890
}891
}];892
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));893
harness.simulation.reloadWorld();894
895
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });896
const funded = addCoinsToSlots(emptySlots(), 10);897
assert.equal(funded.ok, true);898
funded.slots[1] = {899
itemId: ItemId.letter,900
quantity: 1,901
instance: {902
kind: "letter",903
letterId: "sell-me",904
authorCharacterId: character.character_id,905
authorDisplayName: "Ada",906
body: "For sale",907
opened: true,908
writtenAt: Date.now()909
}910
};911
harness.stateDb.saveBag(character.character_id, {912
inventory: funded.slots,913
equipment: emptyEquipment(),914
vault: [],915
vaultReserved: []916
});917
const playerId = harness.simulation.spawnCharacter(1, character);918
harness.simulation.step();919
harness.advance(50);920
harness.simulation.step();921
922
const record = harness.simulation.entityRecord(playerId);923
const worker = harness.simulation.workers[record.workerId];924
let npcId = null;925
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))926
{927
if (entity.creature.mobTypeId === MobId.humanoid)928
{929
npcId = entity.entityId;930
break;931
}932
}933
assert.ok(npcId);934
const npcHandle = worker.world.ecs.handleOf(npcId);935
const shop = worker.world.ecs.get(npcHandle, Component.shop);936
const npcPos = worker.world.ecs.get(npcHandle, Component.position);937
const playerHandle = worker.world.ecs.handleOf(playerId);938
const playerPos = worker.world.ecs.get(playerHandle, Component.position);939
playerPos.tileX = npcPos.tileX;940
playerPos.tileY = npcPos.tileY;941
942
const letterSlot = harness.simulation.bagOf(playerId).inventory943
.findIndex((slot) => slot?.itemId === ItemId.letter);944
assert.ok(letterSlot >= 0);945
const quote = resolveShopSellQuote(harness.simulation.bagOf(playerId).inventory[letterSlot]);946
assert.ok(quote);947
const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);948
949
harness.simulation.enqueue(1, {950
type: "sell-to-shop",951
characterId: character.character_id,952
npcEntityId: npcId,953
slotIndex: letterSlot,954
quantity: 1955
});956
const sold = harness.simulation.step();957
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));958
const bag = harness.simulation.bagOf(playerId);959
assert.equal(bag.inventory.some((slot) => slot?.itemId === ItemId.letter), false);960
assert.equal(boughtQty(shop, ItemId.letter), 0);961
assert.equal(shop.boughtStock?.[ItemId.letter], undefined);962
const afterCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);963
assert.equal(afterCoins - beforeCoins, quote.payout);964
}965
finally966
{ harness.close(); }967
});@@ -10,7 +10,7 @@ import {
10
10
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
11
11
import { SkillId } from "../../shared/definitions/skills.js";
12
12
import { BlockType, isChopableTreeBlock, woodTierForTreeBlock } from "../../shared/definitions/tiles.js";
13
import { SeasonId, resolveSeasonalVisualState, treeStumpStateForSeason } from "../../shared/world/season.js";
13
import { SeasonId, resolveSeasonalVisualState, treeStumpStateForSeason, scaleRegrowDurationMs } from "../../shared/world/season.js";
14
14
import { ItemOriginKind, GatherOriginVerb } from "../../shared/items/origin.js";
15
15
import { totalXpForLevel } from "../../shared/skills/progression.js";
16
16
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
@@ -181,7 +181,8 @@ test("tree stump respawns after exhaust duration", () =>
181
181
advanceMs(harness, woodcuttingDurationMs(WoodTier.pine, WoodTier.pine) + 200);
182
182
assert.ok(String(worker.world.chunkData(0, 0).blocks[8 * 16 + 9].state).endsWith("-stump"));
183
183
184
advanceMs(harness, treeExhaustDurationMs(WoodTier.pine) + 200);
184
const exhaustMs = scaleRegrowDurationMs(treeExhaustDurationMs(WoodTier.pine), harness.now());
185
advanceMs(harness, exhaustMs + 200);
185
186
const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
186
187
assert.equal(isChopableTreeBlock(block), true);
187
188
assert.equal(tierRank(WoodTier.pine), 1);
@@ -10,7 +10,7 @@ import {10
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";10
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";11
import { SkillId } from "../../shared/definitions/skills.js";11
import { SkillId } from "../../shared/definitions/skills.js";12
import { BlockType, isChopableTreeBlock, woodTierForTreeBlock } from "../../shared/definitions/tiles.js";12
import { BlockType, isChopableTreeBlock, woodTierForTreeBlock } from "../../shared/definitions/tiles.js";13
import { SeasonId, resolveSeasonalVisualState, treeStumpStateForSeason } from "../../shared/world/season.js";13
import { SeasonId, resolveSeasonalVisualState, treeStumpStateForSeason, scaleRegrowDurationMs } from "../../shared/world/season.js";14
import { ItemOriginKind, GatherOriginVerb } from "../../shared/items/origin.js";14
import { ItemOriginKind, GatherOriginVerb } from "../../shared/items/origin.js";15
import { totalXpForLevel } from "../../shared/skills/progression.js";15
import { totalXpForLevel } from "../../shared/skills/progression.js";16
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";16
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";@@ -181,7 +181,8 @@ test("tree stump respawns after exhaust duration", () =>181
advanceMs(harness, woodcuttingDurationMs(WoodTier.pine, WoodTier.pine) + 200);181
advanceMs(harness, woodcuttingDurationMs(WoodTier.pine, WoodTier.pine) + 200);182
assert.ok(String(worker.world.chunkData(0, 0).blocks[8 * 16 + 9].state).endsWith("-stump"));182
assert.ok(String(worker.world.chunkData(0, 0).blocks[8 * 16 + 9].state).endsWith("-stump"));183
183
184
advanceMs(harness, treeExhaustDurationMs(WoodTier.pine) + 200);184
const exhaustMs = scaleRegrowDurationMs(treeExhaustDurationMs(WoodTier.pine), harness.now());185
advanceMs(harness, exhaustMs + 200);185
const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];186
const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];186
assert.equal(isChopableTreeBlock(block), true);187
assert.equal(isChopableTreeBlock(block), true);187
assert.equal(tierRank(WoodTier.pine), 1);188
assert.equal(tierRank(WoodTier.pine), 1);