BlueGit

timfa questward

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.

timfa Tim Falken · pushed by timfa

Authored 2026-08-27 · 2 months ago

Hash
be79265f202fd87641befaa4175b75f515a63c7b
Parent
d28051ec
27 files changed +545 −62
client/assets/grounds/grass/spring.png added Binary file +0 −0

The contents of this binary file are not shown.

client/editor.html +3 −2
@@ -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 preview
68 <label>Season preview
69 <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>
client/src/editor/main.js +4 −1
@@ -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
1164function syncSeasonControls (season)
1164function 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 ? season
1170 ? season
1168 : seasonIdAt();
1171 : seasonIdAt();
1169 $("season").value = next;
1172 $("season").value = next;
client/src/play/inventory.js +4 −0
@@ -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 ?? [];
client/src/play/main.js +4 −0
@@ -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({
client/src/play/market.js +4 −2
@@ -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 {
7import { INVENTORY_SLOTS } from "/shared/items/inventory.js";
7import { INVENTORY_SLOTS } from "/shared/items/inventory.js";
8import { marketOrderListingFee } from "/shared/market/exchange.js";
8import { marketOrderListingFee } from "/shared/market/exchange.js";
9import { countMarketFunds, resolveMarketSellListing } from "/shared/market/funds.js";
9import { countMarketFunds, resolveMarketSellListing } from "/shared/market/funds.js";
10import { canSellOnMarketplace } from "/shared/items/marketplace.js";
10import { applyItemIcon } from "../render/potionIcon.js";
11import { applyItemIcon } from "../render/potionIcon.js";
11
12
12export function initMarket ({
13export function initMarket ({
@@ -14,6 +15,7 @@ export function initMarket ({
14 MessageType,
15 MessageType,
15 getInventorySlots,
16 getInventorySlots,
16 getCoinCount,
17 getCoinCount,
18 getLocalCharacterId,
17 onSuppressWorldClick
19 onSuppressWorldClick
18})
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"); }
client/src/render/worldView.js +5 −2
@@ -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 WorldView
394 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 WorldView
443 /** 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.summer
446 const calendar = season === SeasonId.spring
447 || season === SeasonId.fall
448 || season === SeasonId.winter
449 || season === SeasonId.summer
447 ? season
450 ? season
448 : seasonIdAt();
451 : seasonIdAt();
449 this.calendarSeason = calendar;
452 this.calendarSeason = calendar;
docs/FEATURES.md +6 −6
@@ -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 fi
16## 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 fi
76## 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 fi
148## 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 fi
166## 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 fi
248## 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
server/src/courier/service.js +5 −7
@@ -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";
2import { BlockType } from "../../../shared/definitions/tiles.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
3import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { isLetterWrittenBy } from "../../../shared/items/letters.js";
5import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
6import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
6import { attachOrigins, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
7import { attachOrigins, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
7import { advanceCourierFlight } from "../../../shared/courier/flight.js";
8import { advanceCourierFlight } from "../../../shared/courier/flight.js";
@@ -130,14 +131,11 @@ export class CourierService
130 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)
server/src/gateway/websocket.js +9 −1
@@ -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";
7import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
8import { publicSkillsView } from "../../../shared/skills/state.js";
8import { publicSkillsView } from "../../../shared/skills/state.js";
9import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
9import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
10import { canCharacterSeeGroundItem } from "../../../shared/items/letters.js";
10
11
11let nextSessionId = 1;
12let 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 }
server/src/gathering/service.js +8 −3
@@ -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";
35import { insertStack } from "../../../shared/items/inventory.js";
35import { insertStack } from "../../../shared/items/inventory.js";
36import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
36import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
37import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
37import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
38import { seasonIdAt, treeStumpStateForSeason, SeasonId } from "../../../shared/world/season.js";
38import {
39 seasonIdAt,
40 treeStumpStateForSeason,
41 SeasonId,
42 scaleRegrowDurationMs
43} from "../../../shared/world/season.js";
39import { bagView } from "../items/bags.js";
44import { bagView } from "../items/bags.js";
40import { chebyshev, clearEngage } from "../combat/service.js";
45import { chebyshev, clearEngage } from "../combat/service.js";
41import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
46import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
@@ -667,7 +672,7 @@ function completeWoodcutting (world, handle, entityId, character, gather, events
667 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, priv
769 : (gather.plantKind === "herb" && isHerbId(gather.herbId)
774 : (gather.plantKind === "herb" && isHerbId(gather.herbId)
770 ? gather.herbId
775 ? gather.herbId
771 : defaultPlantState(gather.typeId)),
776 : defaultPlantState(gather.typeId)),
772 respawnsAt: now + PLANT_EXHAUST_MS
777 respawnsAt: now + scaleRegrowDurationMs(PLANT_EXHAUST_MS, now)
773 });
778 });
774
779
775 clearGather(world.ecs, handle);
780 clearGather(world.ecs, handle);
server/src/items/bags.js +5 −1
@@ -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 normalizeOrigins
39 normalizeOrigins
40} from "../../../shared/items/origin.js";
40} from "../../../shared/items/origin.js";
41import { BANK_LETTER_AUTHOR } from "../../../shared/courier/systemLetters.js";
41import { BANK_LETTER_AUTHOR } from "../../../shared/courier/systemLetters.js";
42import { canCharacterPickupGroundItem } from "../../../shared/items/letters.js";
42
43
43export function publicGroundItem (item)
44export 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 ? instance
56 ? instance
56 : null,
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 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."); }
server/src/market/service.js +3 −3
@@ -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";
13import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js";
13import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js";
14import { attachOrigins, normalizeOrigins, splitOrigins, writtenOrigin } from "../../../shared/items/origin.js";
14import { attachOrigins, normalizeOrigins, splitOrigins, writtenOrigin } from "../../../shared/items/origin.js";
15import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";
15import { undiscountedMarketValue, undiscountedMarketCoins } from "../../../shared/shop/pricing.js";
16import { CENTRAL_EXCHANGE_ORG } from "../../../shared/courier/systemLetters.js";
16import { CENTRAL_EXCHANGE_ORG } from "../../../shared/courier/systemLetters.js";
17import {
17import {
18 MARKET_ORDER_MAX_AGE_MS,
18 MARKET_ORDER_MAX_AGE_MS,
@@ -214,7 +214,7 @@ export class MarketService
214 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 MarketService
900 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,
server/src/shop/service.js +10 −1
@@ -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 shopOrigin
10 shopOrigin
11} from "../../../shared/items/origin.js";
11} from "../../../shared/items/origin.js";
12import { isLetterStack } from "../../../shared/items/letters.js";
12import {
13import {
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 boughtStock
536 * Limited catalog lines refill first; remainder goes into boughtStock
536 * (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 */
538export function sellToShop (world, sessionId, characterId, npcEntityId, slotIndex, quantity = 1, now = Date.now())
540export 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 { 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, slotInde
567 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 {
server/tests/dimensions.test.js +2 −1
@@ -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});
server/tests/letters.test.js +65 −0
@@ -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 finally
150 finally
151 { harness.close(); }
151 { harness.close(); }
152});
152});
153
154test("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});
server/tests/marketplace.test.js +26 −0
@@ -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
41test("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
41test("midpoint trade price rounds half units deterministically", () =>
67test("midpoint trade price rounds half units deterministically", () =>
42{
68{
43 assert.equal(midpointTradePrice(100, 80), 90);
69 assert.equal(midpointTradePrice(100, 80), 90);
server/tests/season.test.js +47 −4
@@ -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";
4import { join } from "node:path";
4import { join } from "node:path";
5import {
5import {
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
17const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));
21const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));
18
22
19test("seasonIdAt maps local months to summer/fall/winter", () =>
23test("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
35test("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
45test("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
29test("seasonal visual state follows calendar, not authored state", () =>
58test("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
56test("seasonalCycleStates lists summer/fall/winter for editor cycling", () =>
85test("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
94test("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", () =>
79test("catalog exposes seasonal grass and pine-tree states", () =>
122test("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);
server/tests/shop.test.js +128 −0
@@ -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";
3import {
3import {
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
78test("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
71test("humanoid spawner config keeps sex equipment sells quantities and buysItems", () =>
101test("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 finally
867 finally
838 { harness.close(); }
868 { harness.close(); }
839});
869});
870
871test("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});
server/tests/woodcutting.test.js +3 −2
@@ -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 {
10import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
10import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
11import { SkillId } from "../../shared/definitions/skills.js";
11import { SkillId } from "../../shared/definitions/skills.js";
12import { BlockType, isChopableTreeBlock, woodTierForTreeBlock } from "../../shared/definitions/tiles.js";
12import { BlockType, isChopableTreeBlock, woodTierForTreeBlock } from "../../shared/definitions/tiles.js";
13import { SeasonId, resolveSeasonalVisualState, treeStumpStateForSeason } from "../../shared/world/season.js";
13import { SeasonId, resolveSeasonalVisualState, treeStumpStateForSeason, scaleRegrowDurationMs } from "../../shared/world/season.js";
14import { ItemOriginKind, GatherOriginVerb } from "../../shared/items/origin.js";
14import { ItemOriginKind, GatherOriginVerb } from "../../shared/items/origin.js";
15import { totalXpForLevel } from "../../shared/skills/progression.js";
15import { totalXpForLevel } from "../../shared/skills/progression.js";
16import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
16import { 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);
shared/definitions/gathering.js +2 −2
@@ -45,7 +45,7 @@ export {
45 45 /** Same curve as mining: (rank×8s) − (toolRank×3s), min 0.5s. */
46 46 export const woodcuttingDurationMs = miningDurationMs;
47 47
48 /** Same curve as ore: 10s × wood tier rank. */
48 /** Same curve as ore: 10s × wood tier rank (before seasonal regrow scaling). */
49 49 export const treeExhaustDurationMs = oreExhaustDurationMs;
50 50
51 51 /** Ore item produced when mining a material node. */
@@ -278,7 +278,7 @@ export function herbalismXpForPick (kind, herbTier = null)
278 278 return 3;
279 279 }
280 280
281 /** Plant node exhaust then respawn (ms). */
281 /** Plant node exhaust then respawn (ms), before seasonal regrow scaling. */
282 282 export const PLANT_EXHAUST_MS = 15_000;
283 283
284 284 /** Craft duration: furnace recipes scale by bar tier; others use the fixed craft duration. */
@@ -45,7 +45,7 @@ export {
45/** Same curve as mining: (rank×8s) − (toolRank×3s), min 0.5s. */
45/** Same curve as mining: (rank×8s) − (toolRank×3s), min 0.5s. */
46export const woodcuttingDurationMs = miningDurationMs;
46export const woodcuttingDurationMs = miningDurationMs;
47
47
48/** Same curve as ore: 10s × wood tier rank. */
48/** Same curve as ore: 10s × wood tier rank (before seasonal regrow scaling). */
49export const treeExhaustDurationMs = oreExhaustDurationMs;
49export const treeExhaustDurationMs = oreExhaustDurationMs;
50
50
51/** Ore item produced when mining a material node. */
51/** Ore item produced when mining a material node. */
@@ -278,7 +278,7 @@ export function herbalismXpForPick (kind, herbTier = null)
278 return 3;
278 return 3;
279}
279}
280
280
281/** Plant node exhaust then respawn (ms). */
281/** Plant node exhaust then respawn (ms), before seasonal regrow scaling. */
282export const PLANT_EXHAUST_MS = 15_000;
282export const PLANT_EXHAUST_MS = 15_000;
283
283
284/** Craft duration: furnace recipes scale by bar tier; others use the fixed craft duration. */
284/** Craft duration: furnace recipes scale by bar tier; others use the fixed craft duration. */
shared/definitions/items.js +3 −1
@@ -97,7 +97,9 @@ export const ITEM_DEFINITIONS = Object.freeze({
97 97 maxStackSize: 1,
98 98 uniqueInstance: true,
99 99 category: "document",
100 defaultState: "letter-opened"
100 defaultState: "letter-opened",
101 marketplaceSellable: false,
102 marketplaceSellBlockedReason: "Letters cannot be sold on the marketplace."
101 103 }),
102 104 [ItemId.apple]: Object.freeze({
103 105 itemId: ItemId.apple,
@@ -97,7 +97,9 @@ export const ITEM_DEFINITIONS = Object.freeze({
97 maxStackSize: 1,
97 maxStackSize: 1,
98 uniqueInstance: true,
98 uniqueInstance: true,
99 category: "document",
99 category: "document",
100 defaultState: "letter-opened"
100 defaultState: "letter-opened",
101 marketplaceSellable: false,
102 marketplaceSellBlockedReason: "Letters cannot be sold on the marketplace."
101 }),
103 }),
102 [ItemId.apple]: Object.freeze({
104 [ItemId.apple]: Object.freeze({
103 itemId: ItemId.apple,
105 itemId: ItemId.apple,
shared/items/letters.js added +65 −0
@@ -0,0 +1,65 @@
1 import { ItemId } from "../definitions/items.js";
2
3 /** @param {object|null|undefined} stack */
4 export function isLetterStack (stack)
5 {
6 return (stack?.itemId | 0) === ItemId.letter && stack?.instance?.kind === "letter";
7 }
8
9 /**
10 * True when this character authored the letter (system letters use authorCharacterId 0).
11 * @param {object|null|undefined} stack
12 * @param {number} characterId
13 */
14 export function isLetterWrittenBy (stack, characterId)
15 {
16 if (!isLetterStack(stack))
17 { return false; }
18 const authorId = Number(stack.instance?.authorCharacterId);
19 return authorId > 0 && authorId === Number(characterId);
20 }
21
22 /**
23 * Letters you did not write cannot be pigeon'd or CE-listed to reach another player.
24 * Inheritance is handled separately outside these checks.
25 * @param {object|null|undefined} stack
26 * @param {number} characterId
27 */
28 export function canTransferLetterToOtherPlayers (stack, characterId)
29 {
30 if (!isLetterStack(stack))
31 { return true; }
32 return isLetterWrittenBy(stack, characterId);
33 }
34
35 /**
36 * A ground letter dropped by someone who did not write it is private to that dropper.
37 * Accepts a full ground item (`stack` + `droppedByCharacterId`) or a public payload
38 * (`itemId`/`instance` + `droppedByCharacterId`).
39 */
40 export function isPrivateGroundLetter (item)
41 {
42 if (!item)
43 { return false; }
44 const stack = item.stack ?? { itemId: item.itemId, instance: item.instance };
45 if (!isLetterStack(stack))
46 { return false; }
47 const dropperId = Number(item.droppedByCharacterId);
48 if (!(dropperId > 0))
49 { return false; }
50 return !isLetterWrittenBy(stack, dropperId);
51 }
52
53 /** @param {object} item @param {number} characterId */
54 export function canCharacterSeeGroundItem (item, characterId)
55 {
56 if (!isPrivateGroundLetter(item))
57 { return true; }
58 return Number(item.droppedByCharacterId) === Number(characterId);
59 }
60
61 /** @param {object} item @param {number} characterId */
62 export function canCharacterPickupGroundItem (item, characterId)
63 {
64 return canCharacterSeeGroundItem(item, characterId);
65 }
@@ -0,0 +1,65 @@
1import { ItemId } from "../definitions/items.js";
2
3/** @param {object|null|undefined} stack */
4export function isLetterStack (stack)
5{
6 return (stack?.itemId | 0) === ItemId.letter && stack?.instance?.kind === "letter";
7}
8
9/**
10 * True when this character authored the letter (system letters use authorCharacterId 0).
11 * @param {object|null|undefined} stack
12 * @param {number} characterId
13 */
14export function isLetterWrittenBy (stack, characterId)
15{
16 if (!isLetterStack(stack))
17 { return false; }
18 const authorId = Number(stack.instance?.authorCharacterId);
19 return authorId > 0 && authorId === Number(characterId);
20}
21
22/**
23 * Letters you did not write cannot be pigeon'd or CE-listed to reach another player.
24 * Inheritance is handled separately outside these checks.
25 * @param {object|null|undefined} stack
26 * @param {number} characterId
27 */
28export function canTransferLetterToOtherPlayers (stack, characterId)
29{
30 if (!isLetterStack(stack))
31 { return true; }
32 return isLetterWrittenBy(stack, characterId);
33}
34
35/**
36 * A ground letter dropped by someone who did not write it is private to that dropper.
37 * Accepts a full ground item (`stack` + `droppedByCharacterId`) or a public payload
38 * (`itemId`/`instance` + `droppedByCharacterId`).
39 */
40export function isPrivateGroundLetter (item)
41{
42 if (!item)
43 { return false; }
44 const stack = item.stack ?? { itemId: item.itemId, instance: item.instance };
45 if (!isLetterStack(stack))
46 { return false; }
47 const dropperId = Number(item.droppedByCharacterId);
48 if (!(dropperId > 0))
49 { return false; }
50 return !isLetterWrittenBy(stack, dropperId);
51}
52
53/** @param {object} item @param {number} characterId */
54export function canCharacterSeeGroundItem (item, characterId)
55{
56 if (!isPrivateGroundLetter(item))
57 { return true; }
58 return Number(item.droppedByCharacterId) === Number(characterId);
59}
60
61/** @param {object} item @param {number} characterId */
62export function canCharacterPickupGroundItem (item, characterId)
63{
64 return canCharacterSeeGroundItem(item, characterId);
65}
shared/items/marketplace.js +14 −5
@@ -1,23 +1,32 @@
1 1 import { itemDefinition } from "../definitions/items.js";
2 import { isLetterStack } from "./letters.js";
2 3
3 4 /** Whether this stack may be listed as a marketplace sell order. */
4 export function canSellOnMarketplace (stack)
5 export function canSellOnMarketplace (stack, characterId = null)
5 6 {
7 void characterId;
6 8 const def = itemDefinition(stack?.itemId);
7 9 if (!def || !stack)
8 10 { return false; }
9 return def.marketplaceSellable !== false;
11 if (def.marketplaceSellable === false)
12 { return false; }
13 // Belt-and-suspenders: letters never list, even if a def flag is missing.
14 if (isLetterStack(stack))
15 { return false; }
16 return true;
10 17 }
11 18
12 19 /** @throws {Error & { userFacing?: boolean }} */
13 export function assertMarketplaceSellable (stack)
20 export function assertMarketplaceSellable (stack, characterId = null)
14 21 {
15 if (canSellOnMarketplace(stack))
22 if (canSellOnMarketplace(stack, characterId))
16 23 { return; }
17 24 const def = itemDefinition(stack?.itemId);
18 25 const error = new Error(
19 26 def?.marketplaceSellBlockedReason
20 ?? "That item cannot be sold on the marketplace."
27 ?? (isLetterStack(stack)
28 ? "Letters cannot be sold on the marketplace."
29 : "That item cannot be sold on the marketplace.")
21 30 );
22 31 error.userFacing = true;
23 32 throw error;
@@ -1,23 +1,32 @@
1import { itemDefinition } from "../definitions/items.js";
1import { itemDefinition } from "../definitions/items.js";
2import { isLetterStack } from "./letters.js";
2
3
3/** Whether this stack may be listed as a marketplace sell order. */
4/** Whether this stack may be listed as a marketplace sell order. */
4export function canSellOnMarketplace (stack)
5export function canSellOnMarketplace (stack, characterId = null)
5{
6{
7 void characterId;
6 const def = itemDefinition(stack?.itemId);
8 const def = itemDefinition(stack?.itemId);
7 if (!def || !stack)
9 if (!def || !stack)
8 { return false; }
10 { return false; }
9 return def.marketplaceSellable !== false;
11 if (def.marketplaceSellable === false)
12 { return false; }
13 // Belt-and-suspenders: letters never list, even if a def flag is missing.
14 if (isLetterStack(stack))
15 { return false; }
16 return true;
10}
17}
11
18
12/** @throws {Error & { userFacing?: boolean }} */
19/** @throws {Error & { userFacing?: boolean }} */
13export function assertMarketplaceSellable (stack)
20export function assertMarketplaceSellable (stack, characterId = null)
14{
21{
15 if (canSellOnMarketplace(stack))
22 if (canSellOnMarketplace(stack, characterId))
16 { return; }
23 { return; }
17 const def = itemDefinition(stack?.itemId);
24 const def = itemDefinition(stack?.itemId);
18 const error = new Error(
25 const error = new Error(
19 def?.marketplaceSellBlockedReason
26 def?.marketplaceSellBlockedReason
20 ?? "That item cannot be sold on the marketplace."
27 ?? (isLetterStack(stack)
28 ? "Letters cannot be sold on the marketplace."
29 : "That item cannot be sold on the marketplace.")
21 );
30 );
22 error.userFacing = true;
31 error.userFacing = true;
23 throw error;
32 throw error;
shared/shop/pricing.js +39 −5
@@ -57,6 +57,7 @@ export function effectiveSeedValue (itemId, settings = null)
57 57 /**
58 58 * @param {object|null} lastSale `{ lastTradePrice, lastTradeAt, priceFrom }`
59 59 * @param {object|null} settings world settings (reads itemSeedValues + lerp duration)
60 * @returns {number} Internal market value — may be fractional while lerping.
60 61 */
61 62 export function undiscountedMarketValue (
62 63 itemId,
@@ -83,6 +84,32 @@ export function undiscountedMarketValue (
83 84 return lerp(from, to, t);
84 85 }
85 86
87 /** Integer coins for display and transactions (ceil of a market-derived float). */
88 export function marketValueAsCoins (value)
89 {
90 const n = Number(value);
91 if (!Number.isFinite(n) || n <= 0)
92 { return 1; }
93 return Math.max(1, Math.ceil(n));
94 }
95
96 /**
97 * Player-facing / transactional market value (integer coins).
98 * Internal lerp in {@link undiscountedMarketValue} may still be fractional.
99 */
100 export function undiscountedMarketCoins (
101 itemId,
102 lastSale = null,
103 now = Date.now(),
104 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
105 settings = null
106 )
107 {
108 return marketValueAsCoins(
109 undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings)
110 );
111 }
112
86 113 /** Integer shop purchase price (player buying catalog stock). */
87 114 export function shopUnitPrice (itemId, {
88 115 lastSale = null,
@@ -94,7 +121,7 @@ export function shopUnitPrice (itemId, {
94 121 {
95 122 const undiscounted = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings);
96 123 const discount = Math.min(1, Math.max(0.01, Number(hiddenDiscount) || 1));
97 return Math.max(1, Math.round(undiscounted * discount));
124 return marketValueAsCoins(undiscounted * discount);
98 125 }
99 126
100 127 /** NPC pays the player this much when buying (80% of market). */
@@ -105,7 +132,9 @@ export function shopBuyFromPlayerPrice (itemId, {
105 132 settings = null
106 133 } = {})
107 134 {
108 return Math.max(1, Math.round(undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 0.8));
135 return marketValueAsCoins(
136 undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 0.8
137 );
109 138 }
110 139
111 140 /** Resale price for goods the NPC bought from players today (120% of market). */
@@ -116,7 +145,9 @@ export function shopBoughtResalePrice (itemId, {
116 145 settings = null
117 146 } = {})
118 147 {
119 return Math.max(1, Math.round(undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 1.2));
148 return marketValueAsCoins(
149 undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 1.2
150 );
120 151 }
121 152
122 153 /**
@@ -137,7 +168,7 @@ export function itemPriceSnapshot (itemId, {
137 168 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
138 169 const seedValue = effectiveSeedValue(itemId, settings);
139 170 const marketKnown = !!(lastSale?.lastTradeAt && lastSale.lastTradePrice != null);
140 const marketValue = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings);
171 const marketValue = undiscountedMarketCoins(itemId, lastSale, now, lerpDurationMs, settings);
141 172 const shopPrice = shopUnitPrice(itemId, {
142 173 lastSale,
143 174 now,
@@ -151,7 +182,7 @@ export function itemPriceSnapshot (itemId, {
151 182 key: def.key ?? String(def.itemId),
152 183 definitionSeedValue: Math.max(1, Number(def.seedValue) || 1),
153 184 seedValue,
154 marketValue: Math.max(1, Math.round(marketValue)),
185 marketValue,
155 186 marketKnown,
156 187 shopPrice
157 188 };
@@ -196,6 +227,9 @@ export function canPlayerSellToNpc (stack)
196 227 const itemId = stack.itemId | 0;
197 228 if (itemId === ItemId.blankCheque || itemId === ItemId.coins)
198 229 { return false; }
230 // Recipes are nearly free to scribe; NPC buyback would mint free coins.
231 if (itemId === ItemId.recipePaper)
232 { return false; }
199 233 if (itemId === ItemId.filledCheque)
200 234 {
201 235 const instance = stack.instance;
@@ -57,6 +57,7 @@ export function effectiveSeedValue (itemId, settings = null)
57/**
57/**
58 * @param {object|null} lastSale `{ lastTradePrice, lastTradeAt, priceFrom }`
58 * @param {object|null} lastSale `{ lastTradePrice, lastTradeAt, priceFrom }`
59 * @param {object|null} settings world settings (reads itemSeedValues + lerp duration)
59 * @param {object|null} settings world settings (reads itemSeedValues + lerp duration)
60 * @returns {number} Internal market value — may be fractional while lerping.
60 */
61 */
61export function undiscountedMarketValue (
62export function undiscountedMarketValue (
62 itemId,
63 itemId,
@@ -83,6 +84,32 @@ export function undiscountedMarketValue (
83 return lerp(from, to, t);
84 return lerp(from, to, t);
84}
85}
85
86
87/** Integer coins for display and transactions (ceil of a market-derived float). */
88export function marketValueAsCoins (value)
89{
90 const n = Number(value);
91 if (!Number.isFinite(n) || n <= 0)
92 { return 1; }
93 return Math.max(1, Math.ceil(n));
94}
95
96/**
97 * Player-facing / transactional market value (integer coins).
98 * Internal lerp in {@link undiscountedMarketValue} may still be fractional.
99 */
100export function undiscountedMarketCoins (
101 itemId,
102 lastSale = null,
103 now = Date.now(),
104 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
105 settings = null
106)
107{
108 return marketValueAsCoins(
109 undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings)
110 );
111}
112
86/** Integer shop purchase price (player buying catalog stock). */
113/** Integer shop purchase price (player buying catalog stock). */
87export function shopUnitPrice (itemId, {
114export function shopUnitPrice (itemId, {
88 lastSale = null,
115 lastSale = null,
@@ -94,7 +121,7 @@ export function shopUnitPrice (itemId, {
94{
121{
95 const undiscounted = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings);
122 const undiscounted = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings);
96 const discount = Math.min(1, Math.max(0.01, Number(hiddenDiscount) || 1));
123 const discount = Math.min(1, Math.max(0.01, Number(hiddenDiscount) || 1));
97 return Math.max(1, Math.round(undiscounted * discount));
124 return marketValueAsCoins(undiscounted * discount);
98}
125}
99
126
100/** NPC pays the player this much when buying (80% of market). */
127/** NPC pays the player this much when buying (80% of market). */
@@ -105,7 +132,9 @@ export function shopBuyFromPlayerPrice (itemId, {
105 settings = null
132 settings = null
106} = {})
133} = {})
107{
134{
108 return Math.max(1, Math.round(undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 0.8));
135 return marketValueAsCoins(
136 undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 0.8
137 );
109}
138}
110
139
111/** Resale price for goods the NPC bought from players today (120% of market). */
140/** Resale price for goods the NPC bought from players today (120% of market). */
@@ -116,7 +145,9 @@ export function shopBoughtResalePrice (itemId, {
116 settings = null
145 settings = null
117} = {})
146} = {})
118{
147{
119 return Math.max(1, Math.round(undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 1.2));
148 return marketValueAsCoins(
149 undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 1.2
150 );
120}
151}
121
152
122/**
153/**
@@ -137,7 +168,7 @@ export function itemPriceSnapshot (itemId, {
137 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
168 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
138 const seedValue = effectiveSeedValue(itemId, settings);
169 const seedValue = effectiveSeedValue(itemId, settings);
139 const marketKnown = !!(lastSale?.lastTradeAt && lastSale.lastTradePrice != null);
170 const marketKnown = !!(lastSale?.lastTradeAt && lastSale.lastTradePrice != null);
140 const marketValue = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings);
171 const marketValue = undiscountedMarketCoins(itemId, lastSale, now, lerpDurationMs, settings);
141 const shopPrice = shopUnitPrice(itemId, {
172 const shopPrice = shopUnitPrice(itemId, {
142 lastSale,
173 lastSale,
143 now,
174 now,
@@ -151,7 +182,7 @@ export function itemPriceSnapshot (itemId, {
151 key: def.key ?? String(def.itemId),
182 key: def.key ?? String(def.itemId),
152 definitionSeedValue: Math.max(1, Number(def.seedValue) || 1),
183 definitionSeedValue: Math.max(1, Number(def.seedValue) || 1),
153 seedValue,
184 seedValue,
154 marketValue: Math.max(1, Math.round(marketValue)),
185 marketValue,
155 marketKnown,
186 marketKnown,
156 shopPrice
187 shopPrice
157 };
188 };
@@ -196,6 +227,9 @@ export function canPlayerSellToNpc (stack)
196 const itemId = stack.itemId | 0;
227 const itemId = stack.itemId | 0;
197 if (itemId === ItemId.blankCheque || itemId === ItemId.coins)
228 if (itemId === ItemId.blankCheque || itemId === ItemId.coins)
198 { return false; }
229 { return false; }
230 // Recipes are nearly free to scribe; NPC buyback would mint free coins.
231 if (itemId === ItemId.recipePaper)
232 { return false; }
199 if (itemId === ItemId.filledCheque)
233 if (itemId === ItemId.filledCheque)
200 {
234 {
201 const instance = stack.instance;
235 const instance = stack.instance;
shared/world/dimensions.js +5 −3
@@ -11,7 +11,7 @@ export const DimensionLightingMode = Object.freeze({
11 11 alwaysDark: "alwaysDark"
12 12 });
13 13
14 /** Authoring values; render resolves spring→summer, autumn→fall. */
14 /** Authoring values; autumn→fall for SeasonId; spring keeps its own art when present. */
15 15 export const DimensionSeasonMode = Object.freeze({
16 16 auto: "auto",
17 17 summer: "summer",
@@ -60,7 +60,7 @@ export function normalizeSeasonMode (raw)
60 60
61 61 /**
62 62 * Map dimension season mode to a SeasonId for sprite bake, or null for calendar auto.
63 * @returns {null | "summer" | "fall" | "winter"}
63 * @returns {null | "spring" | "summer" | "fall" | "winter"}
64 64 */
65 65 export function resolveDimensionSeasonId (seasonMode)
66 66 {
@@ -69,7 +69,9 @@ export function resolveDimensionSeasonId (seasonMode)
69 69 { return null; }
70 70 if (mode === DimensionSeasonMode.autumn)
71 71 { return "fall"; }
72 if (mode === DimensionSeasonMode.spring || mode === DimensionSeasonMode.summer)
72 if (mode === DimensionSeasonMode.spring)
73 { return "spring"; }
74 if (mode === DimensionSeasonMode.summer)
73 75 { return "summer"; }
74 76 return "winter";
75 77 }
@@ -11,7 +11,7 @@ export const DimensionLightingMode = Object.freeze({
11 alwaysDark: "alwaysDark"
11 alwaysDark: "alwaysDark"
12});
12});
13
13
14/** Authoring values; render resolves spring→summer, autumn→fall. */
14/** Authoring values; autumn→fall for SeasonId; spring keeps its own art when present. */
15export const DimensionSeasonMode = Object.freeze({
15export const DimensionSeasonMode = Object.freeze({
16 auto: "auto",
16 auto: "auto",
17 summer: "summer",
17 summer: "summer",
@@ -60,7 +60,7 @@ export function normalizeSeasonMode (raw)
60
60
61/**
61/**
62 * Map dimension season mode to a SeasonId for sprite bake, or null for calendar auto.
62 * Map dimension season mode to a SeasonId for sprite bake, or null for calendar auto.
63 * @returns {null | "summer" | "fall" | "winter"}
63 * @returns {null | "spring" | "summer" | "fall" | "winter"}
64 */
64 */
65export function resolveDimensionSeasonId (seasonMode)
65export function resolveDimensionSeasonId (seasonMode)
66{
66{
@@ -69,7 +69,9 @@ export function resolveDimensionSeasonId (seasonMode)
69 { return null; }
69 { return null; }
70 if (mode === DimensionSeasonMode.autumn)
70 if (mode === DimensionSeasonMode.autumn)
71 { return "fall"; }
71 { return "fall"; }
72 if (mode === DimensionSeasonMode.spring || mode === DimensionSeasonMode.summer)
72 if (mode === DimensionSeasonMode.spring)
73 { return "spring"; }
74 if (mode === DimensionSeasonMode.summer)
73 { return "summer"; }
75 { return "summer"; }
74 return "winter";
76 return "winter";
75}
77}
shared/world/season.js +76 −10
@@ -2,12 +2,17 @@ import { resolveState, statesForType } from "../definitions/tileSprites.js";
2 2
3 3 /** Calendar seasons for outdoor ground/block visuals (server local clock). */
4 4 export const SeasonId = Object.freeze({
5 spring: "spring",
5 6 summer: "summer",
6 7 fall: "fall",
7 8 winter: "winter"
8 9 });
9 10
11 /** @deprecated Prefer {@link SeasonId}; same four-way calendar for regrow rates. */
12 export const GrowthSeasonId = SeasonId;
13
10 14 export const SEASON_STATE_ORDER = Object.freeze([
15 SeasonId.spring,
11 16 SeasonId.summer,
12 17 SeasonId.fall,
13 18 SeasonId.winter
@@ -15,20 +20,48 @@ export const SEASON_STATE_ORDER = Object.freeze([
15 20
16 21 /**
17 22 * Season from a local Date / unix ms.
18 * Spring+summer share `summer` (Mar–Aug); fall Sep–Nov; winter Dec–Feb.
23 * Spring Mar–May; summer Jun–Aug; fall Sep–Nov; winter Dec–Feb.
19 24 */
20 25 export function seasonIdAt (now = Date.now())
21 26 {
22 27 const month = new Date(now).getMonth();
23 if (month >= 2 && month <= 7)
28 if (month >= 2 && month <= 4)
29 { return SeasonId.spring; }
30 if (month >= 5 && month <= 7)
24 31 { return SeasonId.summer; }
25 32 if (month >= 8 && month <= 10)
26 33 { return SeasonId.fall; }
27 34 return SeasonId.winter;
28 35 }
29 36
37 /** Alias of {@link seasonIdAt} (regrow rates use the same four seasons). */
38 export const growthSeasonIdAt = seasonIdAt;
39
40 /**
41 * Tree / flower / herb exhaust→respawn duration multiplier by growth season.
42 * Summer & fall: 1×; winter: 2×; spring: 0.75× (25% faster).
43 */
44 export function regrowDurationMultiplier (growthSeasonId)
45 {
46 if (growthSeasonId === SeasonId.winter)
47 { return 2; }
48 if (growthSeasonId === SeasonId.spring)
49 { return 0.75; }
50 return 1;
51 }
52
53 /** Scale a base exhaust duration (ms) for the current growth season. */
54 export function scaleRegrowDurationMs (baseMs, nowOrGrowthSeason = Date.now())
55 {
56 const growth = typeof nowOrGrowthSeason === "string"
57 ? nowOrGrowthSeason
58 : growthSeasonIdAt(nowOrGrowthSeason);
59 return Math.max(1, Math.round((baseMs | 0 || 0) * regrowDurationMultiplier(growth)));
60 }
61
30 62 /**
31 63 * True when this type has full summer/fall/winter visual states.
64 * Optional `spring` is allowed; types without it fall back to summer in spring.
32 65 * Only outdoor types should ship these; indoor types never need them.
33 66 */
34 67 export function typeHasSeasonalStates (states)
@@ -73,15 +106,31 @@ export function seasonalOverlayState (baseState, seasonId)
73 106 if (!baseState || isSeasonalOverlayVariant(baseState) || isSeasonalStumpState(baseState))
74 107 { return null; }
75 108 const season = seasonId ?? SeasonId.summer;
76 if (season === SeasonId.summer || season === SeasonId.fall || season === SeasonId.winter)
109 if (
110 season === SeasonId.spring
111 || season === SeasonId.summer
112 || season === SeasonId.fall
113 || season === SeasonId.winter
114 )
77 115 { return `${baseState}-${season}`; }
78 116 return null;
79 117 }
80 118
119 /** Summer (or legacy grass) look when spring art is absent. */
120 function resolveSummerVisualState (states)
121 {
122 if (states.includes(SeasonId.summer))
123 { return SeasonId.summer; }
124 if (states.includes("grass"))
125 { return "grass"; }
126 return null;
127 }
128
81 129 /**
82 130 * Pick the visual state for the current season when the type supports seasons.
83 131 * Authored stump states stay exhausted visuals (seasonal stump sprite).
84 132 * Full seasonal outdoor types ignore authored live state (calendar drives the look).
133 * Spring uses `spring` when present, otherwise the summer look.
85 134 * Types with only some overlays (e.g. `*-winter`) use the overlay when present, else the base.
86 135 */
87 136 export function resolveSeasonalVisualState (states, authoredState, seasonId)
@@ -98,12 +147,19 @@ export function resolveSeasonalVisualState (states, authoredState, seasonId)
98 147 }
99 148 if (typeHasSeasonalStates(states))
100 149 {
150 if (season === SeasonId.spring)
151 {
152 if (states.includes(SeasonId.spring))
153 { return SeasonId.spring; }
154 const summer = resolveSummerVisualState(states);
155 if (summer)
156 { return summer; }
157 }
101 158 if (season === SeasonId.summer)
102 159 {
103 if (states.includes(SeasonId.summer))
104 { return SeasonId.summer; }
105 if (states.includes("grass"))
106 { return "grass"; }
160 const summer = resolveSummerVisualState(states);
161 if (summer)
162 { return summer; }
107 163 }
108 164 if (states.includes(season))
109 165 { return season; }
@@ -114,6 +170,9 @@ export function resolveSeasonalVisualState (states, authoredState, seasonId)
114 170 const overlay = seasonalOverlayState(base, season);
115 171 if (overlay && states.includes(overlay))
116 172 { return overlay; }
173 // Spring overlays are optional; fall back to the unseasoned base.
174 if (season === SeasonId.spring && base && states.includes(base))
175 { return base; }
117 176 if (base && states.includes(base))
118 177 { return base; }
119 178 return resolved;
@@ -125,7 +184,7 @@ export function isSeasonalStumpState (state)
125 184 return typeof state === "string" && (state === "stump" || state.endsWith("-stump"));
126 185 }
127 186
128 /** Exhausted tree visual for a calendar season. */
187 /** Exhausted tree visual for a calendar season (spring shares summer stump art). */
129 188 export function treeStumpStateForSeason (seasonId)
130 189 {
131 190 const season = seasonId === SeasonId.fall || seasonId === SeasonId.winter
@@ -147,7 +206,7 @@ export function preferredSeasonalDefaultState (states)
147 206 }
148 207
149 208 /**
150 * Ordered seasonal visual states to cycle in the editor (summer/fall/winter).
209 * Ordered seasonal visual states to cycle in the editor (spring/summer/fall/winter).
151 210 * Legacy `grass` stands in for summer when `summer` is absent.
152 211 * Returns null when the type is not fully seasonal.
153 212 */
@@ -156,6 +215,8 @@ export function seasonalCycleStates (states)
156 215 if (!typeHasSeasonalStates(states))
157 216 { return null; }
158 217 const out = [];
218 if (states.includes(SeasonId.spring))
219 { out.push(SeasonId.spring); }
159 220 if (states.includes(SeasonId.summer))
160 221 { out.push(SeasonId.summer); }
161 222 else if (states.includes("grass"))
@@ -170,7 +231,12 @@ export function seasonalCycleStates (states)
170 231 /** Map a seasonal visual state name to a SeasonId (legacy `grass` → summer). */
171 232 export function seasonIdFromVisualState (state)
172 233 {
173 if (state === SeasonId.fall || state === SeasonId.winter || state === SeasonId.summer)
234 if (
235 state === SeasonId.spring
236 || state === SeasonId.fall
237 || state === SeasonId.winter
238 || state === SeasonId.summer
239 )
174 240 { return state; }
175 241 if (state === "grass")
176 242 { return SeasonId.summer; }
@@ -2,12 +2,17 @@ import { resolveState, statesForType } from "../definitions/tileSprites.js";
2
2
3/** Calendar seasons for outdoor ground/block visuals (server local clock). */
3/** Calendar seasons for outdoor ground/block visuals (server local clock). */
4export const SeasonId = Object.freeze({
4export const SeasonId = Object.freeze({
5 spring: "spring",
5 summer: "summer",
6 summer: "summer",
6 fall: "fall",
7 fall: "fall",
7 winter: "winter"
8 winter: "winter"
8});
9});
9
10
11/** @deprecated Prefer {@link SeasonId}; same four-way calendar for regrow rates. */
12export const GrowthSeasonId = SeasonId;
13
10export const SEASON_STATE_ORDER = Object.freeze([
14export const SEASON_STATE_ORDER = Object.freeze([
15 SeasonId.spring,
11 SeasonId.summer,
16 SeasonId.summer,
12 SeasonId.fall,
17 SeasonId.fall,
13 SeasonId.winter
18 SeasonId.winter
@@ -15,20 +20,48 @@ export const SEASON_STATE_ORDER = Object.freeze([
15
20
16/**
21/**
17 * Season from a local Date / unix ms.
22 * Season from a local Date / unix ms.
18 * Spring+summer share `summer` (Mar–Aug); fall Sep–Nov; winter Dec–Feb.
23 * Spring Mar–May; summer Jun–Aug; fall Sep–Nov; winter Dec–Feb.
19 */
24 */
20export function seasonIdAt (now = Date.now())
25export function seasonIdAt (now = Date.now())
21{
26{
22 const month = new Date(now).getMonth();
27 const month = new Date(now).getMonth();
23 if (month >= 2 && month <= 7)
28 if (month >= 2 && month <= 4)
29 { return SeasonId.spring; }
30 if (month >= 5 && month <= 7)
24 { return SeasonId.summer; }
31 { return SeasonId.summer; }
25 if (month >= 8 && month <= 10)
32 if (month >= 8 && month <= 10)
26 { return SeasonId.fall; }
33 { return SeasonId.fall; }
27 return SeasonId.winter;
34 return SeasonId.winter;
28}
35}
29
36
37/** Alias of {@link seasonIdAt} (regrow rates use the same four seasons). */
38export const growthSeasonIdAt = seasonIdAt;
39
40/**
41 * Tree / flower / herb exhaust→respawn duration multiplier by growth season.
42 * Summer & fall: 1×; winter: 2×; spring: 0.75× (25% faster).
43 */
44export function regrowDurationMultiplier (growthSeasonId)
45{
46 if (growthSeasonId === SeasonId.winter)
47 { return 2; }
48 if (growthSeasonId === SeasonId.spring)
49 { return 0.75; }
50 return 1;
51}
52
53/** Scale a base exhaust duration (ms) for the current growth season. */
54export function scaleRegrowDurationMs (baseMs, nowOrGrowthSeason = Date.now())
55{
56 const growth = typeof nowOrGrowthSeason === "string"
57 ? nowOrGrowthSeason
58 : growthSeasonIdAt(nowOrGrowthSeason);
59 return Math.max(1, Math.round((baseMs | 0 || 0) * regrowDurationMultiplier(growth)));
60}
61
30/**
62/**
31 * True when this type has full summer/fall/winter visual states.
63 * True when this type has full summer/fall/winter visual states.
64 * Optional `spring` is allowed; types without it fall back to summer in spring.
32 * Only outdoor types should ship these; indoor types never need them.
65 * Only outdoor types should ship these; indoor types never need them.
33 */
66 */
34export function typeHasSeasonalStates (states)
67export function typeHasSeasonalStates (states)
@@ -73,15 +106,31 @@ export function seasonalOverlayState (baseState, seasonId)
73 if (!baseState || isSeasonalOverlayVariant(baseState) || isSeasonalStumpState(baseState))
106 if (!baseState || isSeasonalOverlayVariant(baseState) || isSeasonalStumpState(baseState))
74 { return null; }
107 { return null; }
75 const season = seasonId ?? SeasonId.summer;
108 const season = seasonId ?? SeasonId.summer;
76 if (season === SeasonId.summer || season === SeasonId.fall || season === SeasonId.winter)
109 if (
110 season === SeasonId.spring
111 || season === SeasonId.summer
112 || season === SeasonId.fall
113 || season === SeasonId.winter
114 )
77 { return `${baseState}-${season}`; }
115 { return `${baseState}-${season}`; }
78 return null;
116 return null;
79}
117}
80
118
119/** Summer (or legacy grass) look when spring art is absent. */
120function resolveSummerVisualState (states)
121{
122 if (states.includes(SeasonId.summer))
123 { return SeasonId.summer; }
124 if (states.includes("grass"))
125 { return "grass"; }
126 return null;
127}
128
81/**
129/**
82 * Pick the visual state for the current season when the type supports seasons.
130 * Pick the visual state for the current season when the type supports seasons.
83 * Authored stump states stay exhausted visuals (seasonal stump sprite).
131 * Authored stump states stay exhausted visuals (seasonal stump sprite).
84 * Full seasonal outdoor types ignore authored live state (calendar drives the look).
132 * Full seasonal outdoor types ignore authored live state (calendar drives the look).
133 * Spring uses `spring` when present, otherwise the summer look.
85 * Types with only some overlays (e.g. `*-winter`) use the overlay when present, else the base.
134 * Types with only some overlays (e.g. `*-winter`) use the overlay when present, else the base.
86 */
135 */
87export function resolveSeasonalVisualState (states, authoredState, seasonId)
136export function resolveSeasonalVisualState (states, authoredState, seasonId)
@@ -98,12 +147,19 @@ export function resolveSeasonalVisualState (states, authoredState, seasonId)
98 }
147 }
99 if (typeHasSeasonalStates(states))
148 if (typeHasSeasonalStates(states))
100 {
149 {
150 if (season === SeasonId.spring)
151 {
152 if (states.includes(SeasonId.spring))
153 { return SeasonId.spring; }
154 const summer = resolveSummerVisualState(states);
155 if (summer)
156 { return summer; }
157 }
101 if (season === SeasonId.summer)
158 if (season === SeasonId.summer)
102 {
159 {
103 if (states.includes(SeasonId.summer))
160 const summer = resolveSummerVisualState(states);
104 { return SeasonId.summer; }
161 if (summer)
105 if (states.includes("grass"))
162 { return summer; }
106 { return "grass"; }
107 }
163 }
108 if (states.includes(season))
164 if (states.includes(season))
109 { return season; }
165 { return season; }
@@ -114,6 +170,9 @@ export function resolveSeasonalVisualState (states, authoredState, seasonId)
114 const overlay = seasonalOverlayState(base, season);
170 const overlay = seasonalOverlayState(base, season);
115 if (overlay && states.includes(overlay))
171 if (overlay && states.includes(overlay))
116 { return overlay; }
172 { return overlay; }
173 // Spring overlays are optional; fall back to the unseasoned base.
174 if (season === SeasonId.spring && base && states.includes(base))
175 { return base; }
117 if (base && states.includes(base))
176 if (base && states.includes(base))
118 { return base; }
177 { return base; }
119 return resolved;
178 return resolved;
@@ -125,7 +184,7 @@ export function isSeasonalStumpState (state)
125 return typeof state === "string" && (state === "stump" || state.endsWith("-stump"));
184 return typeof state === "string" && (state === "stump" || state.endsWith("-stump"));
126}
185}
127
186
128/** Exhausted tree visual for a calendar season. */
187/** Exhausted tree visual for a calendar season (spring shares summer stump art). */
129export function treeStumpStateForSeason (seasonId)
188export function treeStumpStateForSeason (seasonId)
130{
189{
131 const season = seasonId === SeasonId.fall || seasonId === SeasonId.winter
190 const season = seasonId === SeasonId.fall || seasonId === SeasonId.winter
@@ -147,7 +206,7 @@ export function preferredSeasonalDefaultState (states)
147}
206}
148
207
149/**
208/**
150 * Ordered seasonal visual states to cycle in the editor (summer/fall/winter).
209 * Ordered seasonal visual states to cycle in the editor (spring/summer/fall/winter).
151 * Legacy `grass` stands in for summer when `summer` is absent.
210 * Legacy `grass` stands in for summer when `summer` is absent.
152 * Returns null when the type is not fully seasonal.
211 * Returns null when the type is not fully seasonal.
153 */
212 */
@@ -156,6 +215,8 @@ export function seasonalCycleStates (states)
156 if (!typeHasSeasonalStates(states))
215 if (!typeHasSeasonalStates(states))
157 { return null; }
216 { return null; }
158 const out = [];
217 const out = [];
218 if (states.includes(SeasonId.spring))
219 { out.push(SeasonId.spring); }
159 if (states.includes(SeasonId.summer))
220 if (states.includes(SeasonId.summer))
160 { out.push(SeasonId.summer); }
221 { out.push(SeasonId.summer); }
161 else if (states.includes("grass"))
222 else if (states.includes("grass"))
@@ -170,7 +231,12 @@ export function seasonalCycleStates (states)
170/** Map a seasonal visual state name to a SeasonId (legacy `grass` → summer). */
231/** Map a seasonal visual state name to a SeasonId (legacy `grass` → summer). */
171export function seasonIdFromVisualState (state)
232export function seasonIdFromVisualState (state)
172{
233{
173 if (state === SeasonId.fall || state === SeasonId.winter || state === SeasonId.summer)
234 if (
235 state === SeasonId.spring
236 || state === SeasonId.fall
237 || state === SeasonId.winter
238 || state === SeasonId.summer
239 )
174 { return state; }
240 { return state; }
175 if (state === "grass")
241 if (state === "grass")
176 { return SeasonId.summer; }
242 { return SeasonId.summer; }