Add Central Exchange marketplace with escrow matching and seasonal world polish.
Ship the hidden order book (midpoint trades, pigeon+staff letters, 30-day expiry), craft/shop origin stamps, and outdoor seasonal tiles including winter ice.
@@ -24,4 +24,4 @@ Open [http://localhost:8080](http://localhost:8080) to play and [http://localhos
24
24
25
25
Until auth.timfalken.com exists, each browser connection is a stub admin (`admin-1`, `admin-2`, …). A fresh world is infinite closed grass: open chunk `0,0` in the editor, save, then **Apply now** before a character can walk.
26
26
27
The player-driven marketplace is not in this slice. Bank and spawner blocks can be placed in the editor (placeholder sprites until real art exists). Open **Bag** in play to drop, pick up, and equip starter items.
27
The player-driven **Central Exchange** marketplace is live (hidden order book, escrow, midpoint matching, pigeon settlement). Place a Central Exchange counter in the editor next to a bank.
@@ -24,4 +24,4 @@ Open [http://localhost:8080](http://localhost:8080) to play and [http://localhos24
24
25
Until auth.timfalken.com exists, each browser connection is a stub admin (`admin-1`, `admin-2`, …). A fresh world is infinite closed grass: open chunk `0,0` in the editor, save, then **Apply now** before a character can walk.
25
Until auth.timfalken.com exists, each browser connection is a stub admin (`admin-1`, `admin-2`, …). A fresh world is infinite closed grass: open chunk `0,0` in the editor, save, then **Apply now** before a character can walk.
26
26
27
The player-driven marketplace is not in this slice. Bank and spawner blocks can be placed in the editor (placeholder sprites until real art exists). Open **Bag** in play to drop, pick up, and equip starter items.
27
The player-driven **Central Exchange** marketplace is live (hidden order book, escrow, midpoint matching, pigeon settlement). Place a Central Exchange counter in the editor next to a bank.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -33,8 +33,15 @@
33
33
<button id="apply" type="button" disabled title="Save a chunk first to create a pending revision">Apply now</button>
34
34
<p id="apply-status" class="hint" aria-live="polite"></p>
35
35
<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>
36
<label>Season preview
37
<select id="season">
38
<option value="summer">Summer / spring</option>
39
<option value="fall">Fall</option>
40
<option value="winter">Winter</option>
41
</select>
42
</label>
36
43
<button id="open-settings" type="button">World settings</button>
37
<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.</p>
44
<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>
38
45
</aside>
39
46
<section id="changelog-wrap">
40
47
<h2>Changelog</h2>
@@ -33,8 +33,15 @@33
<button id="apply" type="button" disabled title="Save a chunk first to create a pending revision">Apply now</button>33
<button id="apply" type="button" disabled title="Save a chunk first to create a pending revision">Apply now</button>34
<p id="apply-status" class="hint" aria-live="polite"></p>34
<p id="apply-status" class="hint" aria-live="polite"></p>35
<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>35
<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>36
<label>Season preview37
<select id="season">38
<option value="summer">Summer / spring</option>39
<option value="fall">Fall</option>40
<option value="winter">Winter</option>41
</select>42
</label>36
<button id="open-settings" type="button">World settings</button>43
<button id="open-settings" type="button">World settings</button>37
<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.</p>44
<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>38
</aside>45
</aside>39
<section id="changelog-wrap">46
<section id="changelog-wrap">40
<h2>Changelog</h2>47
<h2>Changelog</h2>@@ -220,6 +220,45 @@
220
220
<button id="shop-qty-confirm" type="button">Buy</button>
221
221
</aside>
222
222
223
<div id="market-backdrop" class="modal-backdrop" hidden></div>
224
<aside id="market-panel" hidden>
225
<header>
226
<h2 id="market-title">Central Exchange</h2>
227
<button id="market-close" type="button">Close</button>
228
</header>
229
<p id="market-hint" class="hint"></p>
230
<p id="market-coins" class="shop-coins">Coins: 0</p>
231
<section class="market-section">
232
<h3>Your orders</h3>
233
<div id="market-orders"></div>
234
</section>
235
<section class="market-section market-columns">
236
<div>
237
<h3>Buy order</h3>
238
<div id="market-catalog" class="market-catalog"></div>
239
<p id="market-buy-item" class="hint">Select an item</p>
240
<label class="send-row">Quantity
241
<input id="market-buy-qty" type="number" min="1" step="1" value="1">
242
</label>
243
<label class="send-row">Max unit price
244
<input id="market-buy-max" type="number" min="1" step="1" value="1">
245
</label>
246
<button id="market-buy-confirm" type="button">Place buy order</button>
247
</div>
248
<div>
249
<h3>Sell order</h3>
250
<div id="market-sell-list" class="market-sell-list"></div>
251
<label class="send-row">Quantity
252
<input id="market-sell-qty" type="number" min="1" step="1" value="1">
253
</label>
254
<label class="send-row">Min unit price
255
<input id="market-sell-min" type="number" min="1" step="1" value="1">
256
</label>
257
<button id="market-sell-confirm" type="button">Place sell order</button>
258
</div>
259
</section>
260
</aside>
261
223
262
<div id="cauldron-backdrop" class="modal-backdrop" hidden></div>
224
263
<aside id="cauldron-panel" hidden>
225
264
<header>
@@ -220,6 +220,45 @@220
<button id="shop-qty-confirm" type="button">Buy</button>220
<button id="shop-qty-confirm" type="button">Buy</button>221
</aside>221
</aside>222
222
223
<div id="market-backdrop" class="modal-backdrop" hidden></div>224
<aside id="market-panel" hidden>225
<header>226
<h2 id="market-title">Central Exchange</h2>227
<button id="market-close" type="button">Close</button>228
</header>229
<p id="market-hint" class="hint"></p>230
<p id="market-coins" class="shop-coins">Coins: 0</p>231
<section class="market-section">232
<h3>Your orders</h3>233
<div id="market-orders"></div>234
</section>235
<section class="market-section market-columns">236
<div>237
<h3>Buy order</h3>238
<div id="market-catalog" class="market-catalog"></div>239
<p id="market-buy-item" class="hint">Select an item</p>240
<label class="send-row">Quantity241
<input id="market-buy-qty" type="number" min="1" step="1" value="1">242
</label>243
<label class="send-row">Max unit price244
<input id="market-buy-max" type="number" min="1" step="1" value="1">245
</label>246
<button id="market-buy-confirm" type="button">Place buy order</button>247
</div>248
<div>249
<h3>Sell order</h3>250
<div id="market-sell-list" class="market-sell-list"></div>251
<label class="send-row">Quantity252
<input id="market-sell-qty" type="number" min="1" step="1" value="1">253
</label>254
<label class="send-row">Min unit price255
<input id="market-sell-min" type="number" min="1" step="1" value="1">256
</label>257
<button id="market-sell-confirm" type="button">Place sell order</button>258
</div>259
</section>260
</aside>261
223
<div id="cauldron-backdrop" class="modal-backdrop" hidden></div>262
<div id="cauldron-backdrop" class="modal-backdrop" hidden></div>224
<aside id="cauldron-panel" hidden>263
<aside id="cauldron-panel" hidden>225
<header>264
<header>@@ -9,6 +9,13 @@ import {
9
9
listPlaceableBlockPaletteEntries
10
10
} from "/shared/definitions/tiles.js";
11
11
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
12
import {
13
SeasonId,
14
seasonIdAt,
15
seasonalCycleStates,
16
seasonIdFromVisualState,
17
placeableStatesForType
18
} from "/shared/world/season.js";
12
19
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
13
20
import { GameSocket, defaultSocketUrl } from "../net/socket.js";
14
21
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
@@ -422,6 +429,7 @@ async function main ()
422
429
useNearestNeighbour(scene, game.images);
423
430
view = new WorldView(game, scene, catalog);
424
431
view.followPlayer = false;
432
syncSeasonControls(view.worldSeason ?? seasonIdAt());
425
433
layoutScene();
426
434
selectTool(tool);
427
435
$("tool").textContent = selectedToolLabel();
@@ -626,6 +634,24 @@ $("night").addEventListener("input", () =>
626
634
view.nightPreview = Number($("night").value);
627
635
$("night-label").textContent = view.nightPreview.toFixed(1);
628
636
});
637
$("season").addEventListener("change", () =>
638
{
639
applySeasonPreview($("season").value);
640
});
641
642
function syncSeasonControls (season)
643
{
644
const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
645
? season
646
: seasonIdAt();
647
$("season").value = next;
648
view?.setWorldSeason(next);
649
}
650
651
function applySeasonPreview (season)
652
{
653
syncSeasonControls(season);
654
}
629
655
630
656
function cycleToolState (direction)
631
657
{
@@ -633,11 +659,16 @@ function cycleToolState (direction)
633
659
{ return; }
634
660
const layer = tool.kind === "ground" ? "ground" : "block";
635
661
const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
636
const states = statesForType(catalog, layer, def.key);
662
const allStates = statesForType(catalog, layer, def.key);
663
const seasonal = seasonalCycleStates(allStates);
664
const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
637
665
if (states.length < 2)
638
666
{ return; }
639
667
tool.state = cycleState(states, tool.state, direction);
640
668
$("tool").textContent = selectedToolLabel();
669
const season = seasonIdFromVisualState(tool.state);
670
if (season)
671
{ applySeasonPreview(season); }
641
672
if (!draft || !hoverLocal)
642
673
{ return; }
643
674
const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
@@ -9,6 +9,13 @@ import {9
listPlaceableBlockPaletteEntries9
listPlaceableBlockPaletteEntries10
} from "/shared/definitions/tiles.js";10
} from "/shared/definitions/tiles.js";11
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";11
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";12
import {13
SeasonId,14
seasonIdAt,15
seasonalCycleStates,16
seasonIdFromVisualState,17
placeableStatesForType18
} from "/shared/world/season.js";12
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";19
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";13
import { GameSocket, defaultSocketUrl } from "../net/socket.js";20
import { GameSocket, defaultSocketUrl } from "../net/socket.js";14
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";21
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";@@ -422,6 +429,7 @@ async function main ()422
useNearestNeighbour(scene, game.images);429
useNearestNeighbour(scene, game.images);423
view = new WorldView(game, scene, catalog);430
view = new WorldView(game, scene, catalog);424
view.followPlayer = false;431
view.followPlayer = false;432
syncSeasonControls(view.worldSeason ?? seasonIdAt());425
layoutScene();433
layoutScene();426
selectTool(tool);434
selectTool(tool);427
$("tool").textContent = selectedToolLabel();435
$("tool").textContent = selectedToolLabel();@@ -626,6 +634,24 @@ $("night").addEventListener("input", () =>626
view.nightPreview = Number($("night").value);634
view.nightPreview = Number($("night").value);627
$("night-label").textContent = view.nightPreview.toFixed(1);635
$("night-label").textContent = view.nightPreview.toFixed(1);628
});636
});637
$("season").addEventListener("change", () =>638
{639
applySeasonPreview($("season").value);640
});641
642
function syncSeasonControls (season)643
{644
const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer645
? season646
: seasonIdAt();647
$("season").value = next;648
view?.setWorldSeason(next);649
}650
651
function applySeasonPreview (season)652
{653
syncSeasonControls(season);654
}629
655
630
function cycleToolState (direction)656
function cycleToolState (direction)631
{657
{@@ -633,11 +659,16 @@ function cycleToolState (direction)633
{ return; }659
{ return; }634
const layer = tool.kind === "ground" ? "ground" : "block";660
const layer = tool.kind === "ground" ? "ground" : "block";635
const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];661
const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];636
const states = statesForType(catalog, layer, def.key);662
const allStates = statesForType(catalog, layer, def.key);663
const seasonal = seasonalCycleStates(allStates);664
const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);637
if (states.length < 2)665
if (states.length < 2)638
{ return; }666
{ return; }639
tool.state = cycleState(states, tool.state, direction);667
tool.state = cycleState(states, tool.state, direction);640
$("tool").textContent = selectedToolLabel();668
$("tool").textContent = selectedToolLabel();669
const season = seasonIdFromVisualState(tool.state);670
if (season)671
{ applySeasonPreview(season); }641
if (!draft || !hoverLocal)672
if (!draft || !hoverLocal)642
{ return; }673
{ return; }643
const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;674
const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;@@ -129,7 +129,7 @@ export function initTileConfigModal ({ onSave, onRemove })
129
129
qty.min = "0";
130
130
qty.step = "1";
131
131
qty.value = String(line.quantity | 0);
132
qty.title = "0 = infinite; otherwise restocks this many at 00:00 UTC";
132
qty.title = "0 = infinite; otherwise restocks this many at 00:00 server time";
133
133
qty.addEventListener("input", () =>
134
134
{
135
135
sellsDraft[index].quantity = Math.max(0, Number(qty.value) || 0) | 0;
@@ -193,7 +193,7 @@ export function initTileConfigModal ({ onSave, onRemove })
193
193
194
194
const hint = document.createElement("p");
195
195
hint.className = "hint";
196
hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 UTC. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock.";
196
hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 server time. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock.";
197
197
wrap.append(hint);
198
198
199
199
sellsDraft = (config.sells ?? []).map((line) =>
@@ -129,7 +129,7 @@ export function initTileConfigModal ({ onSave, onRemove })129
qty.min = "0";129
qty.min = "0";130
qty.step = "1";130
qty.step = "1";131
qty.value = String(line.quantity | 0);131
qty.value = String(line.quantity | 0);132
qty.title = "0 = infinite; otherwise restocks this many at 00:00 UTC";132
qty.title = "0 = infinite; otherwise restocks this many at 00:00 server time";133
qty.addEventListener("input", () =>133
qty.addEventListener("input", () =>134
{134
{135
sellsDraft[index].quantity = Math.max(0, Number(qty.value) || 0) | 0;135
sellsDraft[index].quantity = Math.max(0, Number(qty.value) || 0) | 0;@@ -193,7 +193,7 @@ export function initTileConfigModal ({ onSave, onRemove })193
193
194
const hint = document.createElement("p");194
const hint = document.createElement("p");195
hint.className = "hint";195
hint.className = "hint";196
hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 UTC. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock.";196
hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 server time. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock.";197
wrap.append(hint);197
wrap.append(hint);198
198
199
sellsDraft = (config.sells ?? []).map((line) =>199
sellsDraft = (config.sells ?? []).map((line) =>@@ -1,5 +1,5 @@
1
1
import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName } from "/shared/definitions/tiles.js";
2
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock } from "/shared/definitions/tiles.js";
3
3
import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4
4
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
5
5
import { WorldView } from "../render/worldView.js";
@@ -14,6 +14,7 @@ import { initContextMenu } from "./contextMenu.js";
14
14
import { initDeath } from "./death.js";
15
15
import { initToasts } from "./toasts.js";
16
16
import { initShop } from "./shop.js";
17
import { initMarket } from "./market.js";
17
18
import { CraftingStationId } from "/shared/definitions/craftingStations.js";
18
19
import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
19
20
import { formatQuantity } from "/shared/items/formatQuantity.js";
@@ -46,8 +47,9 @@ let contextMenu;
46
47
let death;
47
48
let toasts;
48
49
let shop;
50
let market;
49
51
let pendingPickup = null;
50
/** @type {{ kind: "bank" | "cauldron" | "station" | "mine", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
52
/** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
51
53
let pendingInteract = null;
52
54
/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
53
55
let approachMove = null;
@@ -184,6 +186,17 @@ function requestOpenBank (tileX, tileY, { getCheques = false } = {})
184
186
{ approachAdjacentTile(tileX, tileY); }
185
187
}
186
188
189
function requestOpenMarket (tileX, tileY)
190
{
191
clearAllPendingActions();
192
pendingInteract = { kind: "market", tileX, tileY };
193
const local = view?.entities.get(view.localEntityId);
194
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
195
{ flushPendingInteract(); }
196
else
197
{ approachAdjacentTile(tileX, tileY); }
198
}
199
187
200
function requestOpenCauldron (tileX, tileY)
188
201
{
189
202
clearAllPendingActions();
@@ -222,6 +235,17 @@ function requestMine (tileX, tileY)
222
235
{ approachAdjacentTile(tileX, tileY); }
223
236
}
224
237
238
function requestChop (tileX, tileY)
239
{
240
clearAllPendingActions();
241
pendingInteract = { kind: "chop", tileX, tileY };
242
const local = view?.entities.get(view.localEntityId);
243
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
244
{ flushPendingInteract(); }
245
else
246
{ approachAdjacentTile(tileX, tileY); }
247
}
248
225
249
function requestTalk (targetEntityId)
226
250
{
227
251
clearAllPendingActions();
@@ -256,6 +280,15 @@ function flushPendingInteract ()
256
280
return;
257
281
}
258
282
283
if (pendingInteract.kind === "market")
284
{
285
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
286
{ return; }
287
socket.send({ type: MessageType.openMarket });
288
clearPendingInteract();
289
return;
290
}
291
259
292
if (pendingInteract.kind === "cauldron")
260
293
{
261
294
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
@@ -290,6 +323,19 @@ function flushPendingInteract ()
290
323
return;
291
324
}
292
325
326
if (pendingInteract.kind === "chop")
327
{
328
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
329
{ return; }
330
socket.send({
331
type: MessageType.chop,
332
tileX: pendingInteract.tileX,
333
tileY: pendingInteract.tileY
334
});
335
clearPendingInteract();
336
return;
337
}
338
293
339
if (pendingInteract.kind === "talk")
294
340
{
295
341
const target = view.entities.get(pendingInteract.targetEntityId);
@@ -395,6 +441,8 @@ function handleLeftClick (mouseX, mouseY)
395
441
{ requestPickup(ground); }
396
442
else if (isBankTile(view, tile.tileX, tile.tileY))
397
443
{ requestOpenBank(tile.tileX, tile.tileY); }
444
else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
445
{ requestOpenMarket(tile.tileX, tile.tileY); }
398
446
else if (isCauldronTile(view, tile.tileX, tile.tileY))
399
447
{ requestOpenCauldron(tile.tileX, tile.tileY); }
400
448
else if (isFurnaceTile(view, tile.tileX, tile.tileY))
@@ -407,6 +455,8 @@ function handleLeftClick (mouseX, mouseY)
407
455
{ requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
408
456
else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
409
457
{ requestMine(tile.tileX, tile.tileY); }
458
else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
459
{ requestChop(tile.tileX, tile.tileY); }
410
460
else
411
461
{
412
462
clearAllPendingActions();
@@ -498,6 +548,14 @@ function handleRightClick (event, mouseX, mouseY)
498
548
});
499
549
}
500
550
551
if (isMarketplaceTile(view, tile.tileX, tile.tileY))
552
{
553
items.push({
554
label: "Central Exchange",
555
onSelect: () => requestOpenMarket(tile.tileX, tile.tileY)
556
});
557
}
558
501
559
if (isCauldronTile(view, tile.tileX, tile.tileY))
502
560
{
503
561
items.push({
@@ -546,6 +604,14 @@ function handleRightClick (event, mouseX, mouseY)
546
604
});
547
605
}
548
606
607
if (isChopableTreeTile(view, tile.tileX, tile.tileY))
608
{
609
items.push({
610
label: "Chop",
611
onSelect: () => requestChop(tile.tileX, tile.tileY)
612
});
613
}
614
549
615
contextMenu.show(event.clientX, event.clientY, items);
550
616
}
551
617
@@ -651,6 +717,7 @@ function startPlay (payload)
651
717
view.setSettings(payload.settings ?? view.settings);
652
718
chat?.syncSettings();
653
719
view.worldHour = payload.worldTime?.hour ?? 12;
720
view.setWorldSeason(payload.worldTime?.season);
654
721
view.setLocalEntity(
655
722
payload.entityId,
656
723
payload.tileX,
@@ -728,6 +795,19 @@ async function main ()
728
795
return inventory?.getInventorySlots?.() ?? [];
729
796
}
730
797
});
798
market = initMarket({
799
socket: { send (payload) { socket.send(payload); } },
800
MessageType,
801
onSuppressWorldClick: consumeWorldClick,
802
getCoinCount ()
803
{
804
return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
805
},
806
getInventorySlots ()
807
{
808
return inventory?.getInventorySlots?.() ?? [];
809
}
810
});
731
811
chat = initChat({
732
812
socket: { send (payload) { socket.send(payload); } },
733
813
MessageType,
@@ -803,6 +883,7 @@ async function main ()
803
883
crafting?.refresh();
804
884
alchemy?.refresh();
805
885
shop?.refresh();
886
market?.refresh();
806
887
break;
807
888
case MessageType.skills:
808
889
skills?.render(message.skills);
@@ -839,6 +920,7 @@ async function main ()
839
920
{
840
921
view.setSettings(message.settings ?? view.settings);
841
922
view.worldHour = message.worldTime?.hour ?? view.worldHour;
923
view.setWorldSeason(message.worldTime?.season);
842
924
chat?.syncSettings();
843
925
}
844
926
break;
@@ -865,6 +947,16 @@ async function main ()
865
947
case MessageType.shopClosed:
866
948
shop?.handleShopClosed(message);
867
949
break;
950
case MessageType.marketOpen:
951
market?.handleOpen(message);
952
break;
953
case MessageType.marketClosed:
954
market?.handleClosed(message);
955
break;
956
case MessageType.marketTrade:
957
market?.handleTrade(message);
958
toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
959
break;
868
960
case MessageType.itemBubble:
869
961
chat?.showItemBubble(message);
870
962
break;
@@ -978,6 +1070,11 @@ function isBankTile (view, tileX, tileY)
978
1070
return blockTypeAt(view, tileX, tileY) === BlockType.bank;
979
1071
}
980
1072
1073
function isMarketplaceTile (view, tileX, tileY)
1074
{
1075
return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
1076
}
1077
981
1078
function isCauldronTile (view, tileX, tileY)
982
1079
{
983
1080
return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
@@ -1009,6 +1106,11 @@ function isOreBoulderTile (view, tileX, tileY)
1009
1106
return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
1010
1107
}
1011
1108
1109
function isChopableTreeTile (view, tileX, tileY)
1110
{
1111
return isChopableTreeBlock(blockAt(view, tileX, tileY));
1112
}
1113
1012
1114
function hideWorldTooltip ()
1013
1115
{
1014
1116
if (worldTooltip)
@@ -1,5 +1,5 @@1
import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";1
import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";2
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName } from "/shared/definitions/tiles.js";2
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock } from "/shared/definitions/tiles.js";3
import { GameSocket, defaultSocketUrl } from "../net/socket.js";3
import { GameSocket, defaultSocketUrl } from "../net/socket.js";4
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";4
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";5
import { WorldView } from "../render/worldView.js";5
import { WorldView } from "../render/worldView.js";@@ -14,6 +14,7 @@ import { initContextMenu } from "./contextMenu.js";14
import { initDeath } from "./death.js";14
import { initDeath } from "./death.js";15
import { initToasts } from "./toasts.js";15
import { initToasts } from "./toasts.js";16
import { initShop } from "./shop.js";16
import { initShop } from "./shop.js";17
import { initMarket } from "./market.js";17
import { CraftingStationId } from "/shared/definitions/craftingStations.js";18
import { CraftingStationId } from "/shared/definitions/craftingStations.js";18
import { isOreBoulderState } from "/shared/definitions/materialTiers.js";19
import { isOreBoulderState } from "/shared/definitions/materialTiers.js";19
import { formatQuantity } from "/shared/items/formatQuantity.js";20
import { formatQuantity } from "/shared/items/formatQuantity.js";@@ -46,8 +47,9 @@ let contextMenu;46
let death;47
let death;47
let toasts;48
let toasts;48
let shop;49
let shop;50
let market;49
let pendingPickup = null;51
let pendingPickup = null;50
/** @type {{ kind: "bank" | "cauldron" | "station" | "mine", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */52
/** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */51
let pendingInteract = null;53
let pendingInteract = null;52
/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */54
/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */53
let approachMove = null;55
let approachMove = null;@@ -184,6 +186,17 @@ function requestOpenBank (tileX, tileY, { getCheques = false } = {})184
{ approachAdjacentTile(tileX, tileY); }186
{ approachAdjacentTile(tileX, tileY); }185
}187
}186
188
189
function requestOpenMarket (tileX, tileY)190
{191
clearAllPendingActions();192
pendingInteract = { kind: "market", tileX, tileY };193
const local = view?.entities.get(view.localEntityId);194
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)195
{ flushPendingInteract(); }196
else197
{ approachAdjacentTile(tileX, tileY); }198
}199
187
function requestOpenCauldron (tileX, tileY)200
function requestOpenCauldron (tileX, tileY)188
{201
{189
clearAllPendingActions();202
clearAllPendingActions();@@ -222,6 +235,17 @@ function requestMine (tileX, tileY)222
{ approachAdjacentTile(tileX, tileY); }235
{ approachAdjacentTile(tileX, tileY); }223
}236
}224
237
238
function requestChop (tileX, tileY)239
{240
clearAllPendingActions();241
pendingInteract = { kind: "chop", tileX, tileY };242
const local = view?.entities.get(view.localEntityId);243
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)244
{ flushPendingInteract(); }245
else246
{ approachAdjacentTile(tileX, tileY); }247
}248
225
function requestTalk (targetEntityId)249
function requestTalk (targetEntityId)226
{250
{227
clearAllPendingActions();251
clearAllPendingActions();@@ -256,6 +280,15 @@ function flushPendingInteract ()256
return;280
return;257
}281
}258
282
283
if (pendingInteract.kind === "market")284
{285
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)286
{ return; }287
socket.send({ type: MessageType.openMarket });288
clearPendingInteract();289
return;290
}291
259
if (pendingInteract.kind === "cauldron")292
if (pendingInteract.kind === "cauldron")260
{293
{261
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)294
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)@@ -290,6 +323,19 @@ function flushPendingInteract ()290
return;323
return;291
}324
}292
325
326
if (pendingInteract.kind === "chop")327
{328
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)329
{ return; }330
socket.send({331
type: MessageType.chop,332
tileX: pendingInteract.tileX,333
tileY: pendingInteract.tileY334
});335
clearPendingInteract();336
return;337
}338
293
if (pendingInteract.kind === "talk")339
if (pendingInteract.kind === "talk")294
{340
{295
const target = view.entities.get(pendingInteract.targetEntityId);341
const target = view.entities.get(pendingInteract.targetEntityId);@@ -395,6 +441,8 @@ function handleLeftClick (mouseX, mouseY)395
{ requestPickup(ground); }441
{ requestPickup(ground); }396
else if (isBankTile(view, tile.tileX, tile.tileY))442
else if (isBankTile(view, tile.tileX, tile.tileY))397
{ requestOpenBank(tile.tileX, tile.tileY); }443
{ requestOpenBank(tile.tileX, tile.tileY); }444
else if (isMarketplaceTile(view, tile.tileX, tile.tileY))445
{ requestOpenMarket(tile.tileX, tile.tileY); }398
else if (isCauldronTile(view, tile.tileX, tile.tileY))446
else if (isCauldronTile(view, tile.tileX, tile.tileY))399
{ requestOpenCauldron(tile.tileX, tile.tileY); }447
{ requestOpenCauldron(tile.tileX, tile.tileY); }400
else if (isFurnaceTile(view, tile.tileX, tile.tileY))448
else if (isFurnaceTile(view, tile.tileX, tile.tileY))@@ -407,6 +455,8 @@ function handleLeftClick (mouseX, mouseY)407
{ requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }455
{ requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }408
else if (isOreBoulderTile(view, tile.tileX, tile.tileY))456
else if (isOreBoulderTile(view, tile.tileX, tile.tileY))409
{ requestMine(tile.tileX, tile.tileY); }457
{ requestMine(tile.tileX, tile.tileY); }458
else if (isChopableTreeTile(view, tile.tileX, tile.tileY))459
{ requestChop(tile.tileX, tile.tileY); }410
else460
else411
{461
{412
clearAllPendingActions();462
clearAllPendingActions();@@ -498,6 +548,14 @@ function handleRightClick (event, mouseX, mouseY)498
});548
});499
}549
}500
550
551
if (isMarketplaceTile(view, tile.tileX, tile.tileY))552
{553
items.push({554
label: "Central Exchange",555
onSelect: () => requestOpenMarket(tile.tileX, tile.tileY)556
});557
}558
501
if (isCauldronTile(view, tile.tileX, tile.tileY))559
if (isCauldronTile(view, tile.tileX, tile.tileY))502
{560
{503
items.push({561
items.push({@@ -546,6 +604,14 @@ function handleRightClick (event, mouseX, mouseY)546
});604
});547
}605
}548
606
607
if (isChopableTreeTile(view, tile.tileX, tile.tileY))608
{609
items.push({610
label: "Chop",611
onSelect: () => requestChop(tile.tileX, tile.tileY)612
});613
}614
549
contextMenu.show(event.clientX, event.clientY, items);615
contextMenu.show(event.clientX, event.clientY, items);550
}616
}551
617
@@ -651,6 +717,7 @@ function startPlay (payload)651
view.setSettings(payload.settings ?? view.settings);717
view.setSettings(payload.settings ?? view.settings);652
chat?.syncSettings();718
chat?.syncSettings();653
view.worldHour = payload.worldTime?.hour ?? 12;719
view.worldHour = payload.worldTime?.hour ?? 12;720
view.setWorldSeason(payload.worldTime?.season);654
view.setLocalEntity(721
view.setLocalEntity(655
payload.entityId,722
payload.entityId,656
payload.tileX,723
payload.tileX,@@ -728,6 +795,19 @@ async function main ()728
return inventory?.getInventorySlots?.() ?? [];795
return inventory?.getInventorySlots?.() ?? [];729
}796
}730
});797
});798
market = initMarket({799
socket: { send (payload) { socket.send(payload); } },800
MessageType,801
onSuppressWorldClick: consumeWorldClick,802
getCoinCount ()803
{804
return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);805
},806
getInventorySlots ()807
{808
return inventory?.getInventorySlots?.() ?? [];809
}810
});731
chat = initChat({811
chat = initChat({732
socket: { send (payload) { socket.send(payload); } },812
socket: { send (payload) { socket.send(payload); } },733
MessageType,813
MessageType,@@ -803,6 +883,7 @@ async function main ()803
crafting?.refresh();883
crafting?.refresh();804
alchemy?.refresh();884
alchemy?.refresh();805
shop?.refresh();885
shop?.refresh();886
market?.refresh();806
break;887
break;807
case MessageType.skills:888
case MessageType.skills:808
skills?.render(message.skills);889
skills?.render(message.skills);@@ -839,6 +920,7 @@ async function main ()839
{920
{840
view.setSettings(message.settings ?? view.settings);921
view.setSettings(message.settings ?? view.settings);841
view.worldHour = message.worldTime?.hour ?? view.worldHour;922
view.worldHour = message.worldTime?.hour ?? view.worldHour;923
view.setWorldSeason(message.worldTime?.season);842
chat?.syncSettings();924
chat?.syncSettings();843
}925
}844
break;926
break;@@ -865,6 +947,16 @@ async function main ()865
case MessageType.shopClosed:947
case MessageType.shopClosed:866
shop?.handleShopClosed(message);948
shop?.handleShopClosed(message);867
break;949
break;950
case MessageType.marketOpen:951
market?.handleOpen(message);952
break;953
case MessageType.marketClosed:954
market?.handleClosed(message);955
break;956
case MessageType.marketTrade:957
market?.handleTrade(message);958
toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);959
break;868
case MessageType.itemBubble:960
case MessageType.itemBubble:869
chat?.showItemBubble(message);961
chat?.showItemBubble(message);870
break;962
break;@@ -978,6 +1070,11 @@ function isBankTile (view, tileX, tileY)978
return blockTypeAt(view, tileX, tileY) === BlockType.bank;1070
return blockTypeAt(view, tileX, tileY) === BlockType.bank;979
}1071
}980
1072
1073
function isMarketplaceTile (view, tileX, tileY)1074
{1075
return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;1076
}1077
981
function isCauldronTile (view, tileX, tileY)1078
function isCauldronTile (view, tileX, tileY)982
{1079
{983
return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;1080
return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;@@ -1009,6 +1106,11 @@ function isOreBoulderTile (view, tileX, tileY)1009
return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);1106
return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);1010
}1107
}1011
1108
1109
function isChopableTreeTile (view, tileX, tileY)1110
{1111
return isChopableTreeBlock(blockAt(view, tileX, tileY));1112
}1113
1012
function hideWorldTooltip ()1114
function hideWorldTooltip ()1013
{1115
{1014
if (worldTooltip)1116
if (worldTooltip)@@ -0,0 +1,231 @@
1
import {
2
itemDefinition,
3
itemDisplayName,
4
itemAssetPathForStack,
5
formatQuantity
6
} from "/shared/definitions/items.js";
7
import { applyItemIcon } from "../render/potionIcon.js";
8
9
export function initMarket ({
10
socket,
11
MessageType,
12
getInventorySlots,
13
getCoinCount,
14
onSuppressWorldClick
15
})
16
{
17
const backdrop = document.getElementById("market-backdrop");
18
const panel = document.getElementById("market-panel");
19
const title = document.getElementById("market-title");
20
const ordersEl = document.getElementById("market-orders");
21
const catalogEl = document.getElementById("market-catalog");
22
const sellList = document.getElementById("market-sell-list");
23
const buyItem = document.getElementById("market-buy-item");
24
const buyQty = document.getElementById("market-buy-qty");
25
const buyMax = document.getElementById("market-buy-max");
26
const sellQty = document.getElementById("market-sell-qty");
27
const sellMin = document.getElementById("market-sell-min");
28
const coinsEl = document.getElementById("market-coins");
29
const hintEl = document.getElementById("market-hint");
30
31
let open = false;
32
let catalog = [];
33
let orders = [];
34
let selectedSellSlot = null;
35
let selectedBuyItemId = null;
36
37
function suppressWorldClick ()
38
{
39
onSuppressWorldClick?.();
40
}
41
42
document.getElementById("market-close")?.addEventListener("click", () => close());
43
backdrop?.addEventListener("mousedown", (event) =>
44
{
45
event.preventDefault();
46
suppressWorldClick();
47
});
48
backdrop?.addEventListener("click", () => close());
49
panel?.addEventListener("mousedown", (event) =>
50
{
51
event.stopPropagation();
52
suppressWorldClick();
53
});
54
55
document.getElementById("market-buy-confirm")?.addEventListener("click", () =>
56
{
57
if (selectedBuyItemId == null)
58
{ return; }
59
socket.send({
60
type: MessageType.placeMarketBuy,
61
itemId: selectedBuyItemId,
62
quantity: Math.max(1, buyQty?.valueAsNumber || 1),
63
maxUnitPrice: Math.max(1, buyMax?.valueAsNumber || 1)
64
});
65
});
66
67
document.getElementById("market-sell-confirm")?.addEventListener("click", () =>
68
{
69
if (selectedSellSlot == null)
70
{ return; }
71
socket.send({
72
type: MessageType.placeMarketSell,
73
slotIndex: selectedSellSlot,
74
quantity: Math.max(1, sellQty?.valueAsNumber || 1),
75
minUnitPrice: Math.max(1, sellMin?.valueAsNumber || 1)
76
});
77
});
78
79
function close ()
80
{
81
if (!open)
82
{ return; }
83
open = false;
84
if (backdrop)
85
{ backdrop.hidden = true; }
86
if (panel)
87
{ panel.hidden = true; }
88
socket.send({ type: MessageType.closeMarket });
89
}
90
91
function renderOrders ()
92
{
93
ordersEl.replaceChildren();
94
if (!orders.length)
95
{
96
const empty = document.createElement("p");
97
empty.className = "hint";
98
empty.textContent = "No open orders.";
99
ordersEl.append(empty);
100
return;
101
}
102
for (const order of orders)
103
{
104
const row = document.createElement("div");
105
row.className = "market-order-row";
106
const label = document.createElement("span");
107
label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${order.limitUnitPrice}`;
108
const cancel = document.createElement("button");
109
cancel.type = "button";
110
cancel.textContent = "Cancel";
111
cancel.addEventListener("click", () =>
112
{
113
socket.send({
114
type: MessageType.cancelMarketOrder,
115
orderId: order.orderId
116
});
117
});
118
row.append(label, cancel);
119
ordersEl.append(row);
120
}
121
}
122
123
function renderCatalog ()
124
{
125
catalogEl.replaceChildren();
126
for (const entry of catalog)
127
{
128
const row = document.createElement("button");
129
row.type = "button";
130
row.className = "market-catalog-row";
131
if (selectedBuyItemId === entry.itemId)
132
{ row.classList.add("selected"); }
133
row.textContent = `${entry.displayName} (~${entry.hintPrice})`;
134
row.addEventListener("click", () =>
135
{
136
selectedBuyItemId = entry.itemId;
137
if (buyItem)
138
{ buyItem.textContent = entry.displayName; }
139
if (buyMax && !(buyMax.valueAsNumber > 0))
140
{ buyMax.value = String(entry.hintPrice); }
141
renderCatalog();
142
});
143
catalogEl.append(row);
144
}
145
}
146
147
function renderSellables ()
148
{
149
sellList.replaceChildren();
150
const slots = getInventorySlots?.() ?? [];
151
slots.forEach((slot, slotIndex) =>
152
{
153
if (!slot || slot.itemId == null)
154
{ return; }
155
const def = itemDefinition(slot.itemId);
156
if (!def || def.marketplaceSellable === false)
157
{ return; }
158
const row = document.createElement("button");
159
row.type = "button";
160
row.className = "market-sell-row";
161
if (selectedSellSlot === slotIndex)
162
{ row.classList.add("selected"); }
163
const icon = document.createElement("img");
164
icon.alt = "";
165
applyItemIcon(icon, itemAssetPathForStack(slot));
166
const label = document.createElement("span");
167
label.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;
168
row.append(icon, label);
169
row.addEventListener("click", () =>
170
{
171
selectedSellSlot = slotIndex;
172
if (sellQty)
173
{ sellQty.value = "1"; }
174
renderSellables();
175
});
176
sellList.append(row);
177
});
178
}
179
180
function refreshChrome ()
181
{
182
if (coinsEl)
183
{ coinsEl.textContent = `Coins: ${formatQuantity(getCoinCount?.() ?? 0)}`; }
184
renderSellables();
185
}
186
187
return {
188
handleOpen (payload)
189
{
190
open = true;
191
orders = payload.orders ?? [];
192
catalog = payload.catalog ?? [];
193
if (title)
194
{ title.textContent = payload.displayName || "Central Exchange"; }
195
if (hintEl)
196
{
197
hintEl.textContent = "Orders are matched privately. Live asks are not listed. Unfilled orders expire after one month.";
198
}
199
if (backdrop)
200
{ backdrop.hidden = false; }
201
if (panel)
202
{ panel.hidden = false; }
203
renderOrders();
204
renderCatalog();
205
refreshChrome();
206
},
207
handleClosed ()
208
{
209
open = false;
210
if (backdrop)
211
{ backdrop.hidden = true; }
212
if (panel)
213
{ panel.hidden = true; }
214
},
215
handleTrade ()
216
{
217
if (open)
218
{ refreshChrome(); }
219
},
220
refresh ()
221
{
222
if (open)
223
{ refreshChrome(); }
224
},
225
isOpen ()
226
{
227
return open;
228
},
229
close
230
};
231
}
@@ -0,0 +1,231 @@1
import {2
itemDefinition,3
itemDisplayName,4
itemAssetPathForStack,5
formatQuantity6
} from "/shared/definitions/items.js";7
import { applyItemIcon } from "../render/potionIcon.js";8
9
export function initMarket ({10
socket,11
MessageType,12
getInventorySlots,13
getCoinCount,14
onSuppressWorldClick15
})16
{17
const backdrop = document.getElementById("market-backdrop");18
const panel = document.getElementById("market-panel");19
const title = document.getElementById("market-title");20
const ordersEl = document.getElementById("market-orders");21
const catalogEl = document.getElementById("market-catalog");22
const sellList = document.getElementById("market-sell-list");23
const buyItem = document.getElementById("market-buy-item");24
const buyQty = document.getElementById("market-buy-qty");25
const buyMax = document.getElementById("market-buy-max");26
const sellQty = document.getElementById("market-sell-qty");27
const sellMin = document.getElementById("market-sell-min");28
const coinsEl = document.getElementById("market-coins");29
const hintEl = document.getElementById("market-hint");30
31
let open = false;32
let catalog = [];33
let orders = [];34
let selectedSellSlot = null;35
let selectedBuyItemId = null;36
37
function suppressWorldClick ()38
{39
onSuppressWorldClick?.();40
}41
42
document.getElementById("market-close")?.addEventListener("click", () => close());43
backdrop?.addEventListener("mousedown", (event) =>44
{45
event.preventDefault();46
suppressWorldClick();47
});48
backdrop?.addEventListener("click", () => close());49
panel?.addEventListener("mousedown", (event) =>50
{51
event.stopPropagation();52
suppressWorldClick();53
});54
55
document.getElementById("market-buy-confirm")?.addEventListener("click", () =>56
{57
if (selectedBuyItemId == null)58
{ return; }59
socket.send({60
type: MessageType.placeMarketBuy,61
itemId: selectedBuyItemId,62
quantity: Math.max(1, buyQty?.valueAsNumber || 1),63
maxUnitPrice: Math.max(1, buyMax?.valueAsNumber || 1)64
});65
});66
67
document.getElementById("market-sell-confirm")?.addEventListener("click", () =>68
{69
if (selectedSellSlot == null)70
{ return; }71
socket.send({72
type: MessageType.placeMarketSell,73
slotIndex: selectedSellSlot,74
quantity: Math.max(1, sellQty?.valueAsNumber || 1),75
minUnitPrice: Math.max(1, sellMin?.valueAsNumber || 1)76
});77
});78
79
function close ()80
{81
if (!open)82
{ return; }83
open = false;84
if (backdrop)85
{ backdrop.hidden = true; }86
if (panel)87
{ panel.hidden = true; }88
socket.send({ type: MessageType.closeMarket });89
}90
91
function renderOrders ()92
{93
ordersEl.replaceChildren();94
if (!orders.length)95
{96
const empty = document.createElement("p");97
empty.className = "hint";98
empty.textContent = "No open orders.";99
ordersEl.append(empty);100
return;101
}102
for (const order of orders)103
{104
const row = document.createElement("div");105
row.className = "market-order-row";106
const label = document.createElement("span");107
label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${order.limitUnitPrice}`;108
const cancel = document.createElement("button");109
cancel.type = "button";110
cancel.textContent = "Cancel";111
cancel.addEventListener("click", () =>112
{113
socket.send({114
type: MessageType.cancelMarketOrder,115
orderId: order.orderId116
});117
});118
row.append(label, cancel);119
ordersEl.append(row);120
}121
}122
123
function renderCatalog ()124
{125
catalogEl.replaceChildren();126
for (const entry of catalog)127
{128
const row = document.createElement("button");129
row.type = "button";130
row.className = "market-catalog-row";131
if (selectedBuyItemId === entry.itemId)132
{ row.classList.add("selected"); }133
row.textContent = `${entry.displayName} (~${entry.hintPrice})`;134
row.addEventListener("click", () =>135
{136
selectedBuyItemId = entry.itemId;137
if (buyItem)138
{ buyItem.textContent = entry.displayName; }139
if (buyMax && !(buyMax.valueAsNumber > 0))140
{ buyMax.value = String(entry.hintPrice); }141
renderCatalog();142
});143
catalogEl.append(row);144
}145
}146
147
function renderSellables ()148
{149
sellList.replaceChildren();150
const slots = getInventorySlots?.() ?? [];151
slots.forEach((slot, slotIndex) =>152
{153
if (!slot || slot.itemId == null)154
{ return; }155
const def = itemDefinition(slot.itemId);156
if (!def || def.marketplaceSellable === false)157
{ return; }158
const row = document.createElement("button");159
row.type = "button";160
row.className = "market-sell-row";161
if (selectedSellSlot === slotIndex)162
{ row.classList.add("selected"); }163
const icon = document.createElement("img");164
icon.alt = "";165
applyItemIcon(icon, itemAssetPathForStack(slot));166
const label = document.createElement("span");167
label.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;168
row.append(icon, label);169
row.addEventListener("click", () =>170
{171
selectedSellSlot = slotIndex;172
if (sellQty)173
{ sellQty.value = "1"; }174
renderSellables();175
});176
sellList.append(row);177
});178
}179
180
function refreshChrome ()181
{182
if (coinsEl)183
{ coinsEl.textContent = `Coins: ${formatQuantity(getCoinCount?.() ?? 0)}`; }184
renderSellables();185
}186
187
return {188
handleOpen (payload)189
{190
open = true;191
orders = payload.orders ?? [];192
catalog = payload.catalog ?? [];193
if (title)194
{ title.textContent = payload.displayName || "Central Exchange"; }195
if (hintEl)196
{197
hintEl.textContent = "Orders are matched privately. Live asks are not listed. Unfilled orders expire after one month.";198
}199
if (backdrop)200
{ backdrop.hidden = false; }201
if (panel)202
{ panel.hidden = false; }203
renderOrders();204
renderCatalog();205
refreshChrome();206
},207
handleClosed ()208
{209
open = false;210
if (backdrop)211
{ backdrop.hidden = true; }212
if (panel)213
{ panel.hidden = true; }214
},215
handleTrade ()216
{217
if (open)218
{ refreshChrome(); }219
},220
refresh ()221
{222
if (open)223
{ refreshChrome(); }224
},225
isOpen ()226
{227
return open;228
},229
close230
};231
}@@ -1,12 +1,13 @@
1
1
import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2
2
import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3
import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
3
import { bloomImageName, spriteImageName } from "/shared/definitions/tileSprites.js";
4
import { resolveSeasonalVisualState, SeasonId } from "/shared/world/season.js";
4
5
5
6
/**
6
7
* Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
7
8
* Oversized or animated blocks/grounds are returned for individual sprites.
8
9
*/
9
export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
10
export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null, season = SeasonId.summer })
10
11
{
11
12
const width = CHUNK_SIZE * SPRITE_SIZE_PX;
12
13
const height = CHUNK_SIZE * SPRITE_SIZE_PX;
@@ -49,12 +50,12 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
49
50
50
51
const dx = localX * SPRITE_SIZE_PX;
51
52
const dy = localY * SPRITE_SIZE_PX;
52
const groundName = groundSpriteName(catalog, groundEntry);
53
const groundName = groundSpriteName(catalog, groundEntry, season);
53
54
const groundMeta = groundCatalogMeta(catalog, groundEntry);
54
55
if (isBakeable(images[groundName], groundMeta))
55
56
{
56
57
blit(groundCtx, images[groundName], dx, dy);
57
const groundBloom = groundBloomName(catalog, groundEntry);
58
const groundBloom = groundBloomName(catalog, groundEntry, season);
58
59
if (groundBloom)
59
60
{ blit(bloomCtx, images[groundBloom], dx, dy); }
60
61
}
@@ -65,18 +66,18 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
65
66
tileY,
66
67
sprite: groundName,
67
68
typeId: normalizeGround(groundEntry).typeId,
68
bloom: groundBloomName(catalog, groundEntry)
69
bloom: groundBloomName(catalog, groundEntry, season)
69
70
});
70
71
}
71
72
72
const blockName = blockSpriteName(catalog, blockEntry);
73
const blockName = blockSpriteName(catalog, blockEntry, season);
73
74
if (!blockName)
74
75
{ continue; }
75
76
const blockMeta = blockCatalogMeta(catalog, blockEntry);
76
77
if (isBakeable(images[blockName], blockMeta))
77
78
{
78
79
blit(blockCtxs[localY], images[blockName], dx, 0);
79
const blockBloom = blockBloomName(catalog, blockEntry);
80
const blockBloom = blockBloomName(catalog, blockEntry, season);
80
81
if (blockBloom)
81
82
{ blit(bloomCtx, images[blockBloom], dx, dy); }
82
83
}
@@ -86,7 +87,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
86
87
tileX,
87
88
tileY,
88
89
sprite: blockName,
89
bloom: blockBloomName(catalog, blockEntry)
90
bloom: blockBloomName(catalog, blockEntry, season)
90
91
});
91
92
}
92
93
}
@@ -101,9 +102,11 @@ export function isBakeable (sprite, meta = null)
101
102
{ return false; }
102
103
if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX)
103
104
{ return false; }
104
if ((meta?.frames ?? 1) > 1)
105
const frames = Number(sprite.subImages) || Number(sprite.subImgTotal) || (meta?.frames ?? 1);
106
const speed = sprite._animationSpeed ?? meta?.animationSpeed ?? 0;
107
if (frames > 1)
105
108
{ return false; }
106
if ((meta?.animationSpeed ?? 0) > 0)
109
if (speed > 0)
107
110
{ return false; }
108
111
return true;
109
112
}
@@ -134,16 +137,16 @@ function blit (ctx, sprite, dx, dy)
134
137
);
135
138
}
136
139
137
function groundSpriteName (catalog, ground)
140
function groundSpriteName (catalog, ground, season = SeasonId.summer)
138
141
{
139
142
const entry = normalizeGround(ground);
140
143
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
141
144
const states = catalog.grounds?.[def.key]?.states ?? [];
142
const state = resolveState(states, entry.state);
145
const state = resolveSeasonalVisualState(states, entry.state, season);
143
146
return spriteImageName("ground", def.key, state);
144
147
}
145
148
146
function blockSpriteName (catalog, block)
149
function blockSpriteName (catalog, block, season = SeasonId.summer)
147
150
{
148
151
const entry = normalizeBlock(block);
149
152
if (!entry)
@@ -152,22 +155,22 @@ function blockSpriteName (catalog, block)
152
155
if (!def || def.editorHidden)
153
156
{ return null; }
154
157
const states = catalog.blocks?.[def.key]?.states ?? [];
155
const state = resolveState(states, entry.state);
158
const state = resolveSeasonalVisualState(states, entry.state, season);
156
159
return spriteImageName("block", def.key, state);
157
160
}
158
161
159
function groundBloomName (catalog, ground)
162
function groundBloomName (catalog, ground, season = SeasonId.summer)
160
163
{
161
164
const entry = normalizeGround(ground);
162
165
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
163
166
const type = catalog.grounds?.[def.key];
164
const state = resolveState(type?.states ?? [], entry.state);
167
const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);
165
168
if (!state || !type?.blooms?.[state])
166
169
{ return null; }
167
170
return bloomImageName("ground", def.key, state);
168
171
}
169
172
170
function blockBloomName (catalog, block)
173
function blockBloomName (catalog, block, season = SeasonId.summer)
171
174
{
172
175
const entry = normalizeBlock(block);
173
176
if (!entry)
@@ -176,7 +179,7 @@ function blockBloomName (catalog, block)
176
179
if (!def)
177
180
{ return null; }
178
181
const type = catalog.blocks?.[def.key];
179
const state = resolveState(type?.states ?? [], entry.state);
182
const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);
180
183
if (!state || !type?.blooms?.[state])
181
184
{ return null; }
182
185
return bloomImageName("block", def.key, state);
@@ -1,12 +1,13 @@1
import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";1
import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";2
import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";2
import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";3
import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";3
import { bloomImageName, spriteImageName } from "/shared/definitions/tileSprites.js";4
import { resolveSeasonalVisualState, SeasonId } from "/shared/world/season.js";4
5
5
/**6
/**6
* Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.7
* Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.7
* Oversized or animated blocks/grounds are returned for individual sprites.8
* Oversized or animated blocks/grounds are returned for individual sprites.8
*/9
*/9
export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })10
export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null, season = SeasonId.summer })10
{11
{11
const width = CHUNK_SIZE * SPRITE_SIZE_PX;12
const width = CHUNK_SIZE * SPRITE_SIZE_PX;12
const height = CHUNK_SIZE * SPRITE_SIZE_PX;13
const height = CHUNK_SIZE * SPRITE_SIZE_PX;@@ -49,12 +50,12 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })49
50
50
const dx = localX * SPRITE_SIZE_PX;51
const dx = localX * SPRITE_SIZE_PX;51
const dy = localY * SPRITE_SIZE_PX;52
const dy = localY * SPRITE_SIZE_PX;52
const groundName = groundSpriteName(catalog, groundEntry);53
const groundName = groundSpriteName(catalog, groundEntry, season);53
const groundMeta = groundCatalogMeta(catalog, groundEntry);54
const groundMeta = groundCatalogMeta(catalog, groundEntry);54
if (isBakeable(images[groundName], groundMeta))55
if (isBakeable(images[groundName], groundMeta))55
{56
{56
blit(groundCtx, images[groundName], dx, dy);57
blit(groundCtx, images[groundName], dx, dy);57
const groundBloom = groundBloomName(catalog, groundEntry);58
const groundBloom = groundBloomName(catalog, groundEntry, season);58
if (groundBloom)59
if (groundBloom)59
{ blit(bloomCtx, images[groundBloom], dx, dy); }60
{ blit(bloomCtx, images[groundBloom], dx, dy); }60
}61
}@@ -65,18 +66,18 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })65
tileY,66
tileY,66
sprite: groundName,67
sprite: groundName,67
typeId: normalizeGround(groundEntry).typeId,68
typeId: normalizeGround(groundEntry).typeId,68
bloom: groundBloomName(catalog, groundEntry)69
bloom: groundBloomName(catalog, groundEntry, season)69
});70
});70
}71
}71
72
72
const blockName = blockSpriteName(catalog, blockEntry);73
const blockName = blockSpriteName(catalog, blockEntry, season);73
if (!blockName)74
if (!blockName)74
{ continue; }75
{ continue; }75
const blockMeta = blockCatalogMeta(catalog, blockEntry);76
const blockMeta = blockCatalogMeta(catalog, blockEntry);76
if (isBakeable(images[blockName], blockMeta))77
if (isBakeable(images[blockName], blockMeta))77
{78
{78
blit(blockCtxs[localY], images[blockName], dx, 0);79
blit(blockCtxs[localY], images[blockName], dx, 0);79
const blockBloom = blockBloomName(catalog, blockEntry);80
const blockBloom = blockBloomName(catalog, blockEntry, season);80
if (blockBloom)81
if (blockBloom)81
{ blit(bloomCtx, images[blockBloom], dx, dy); }82
{ blit(bloomCtx, images[blockBloom], dx, dy); }82
}83
}@@ -86,7 +87,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })86
tileX,87
tileX,87
tileY,88
tileY,88
sprite: blockName,89
sprite: blockName,89
bloom: blockBloomName(catalog, blockEntry)90
bloom: blockBloomName(catalog, blockEntry, season)90
});91
});91
}92
}92
}93
}@@ -101,9 +102,11 @@ export function isBakeable (sprite, meta = null)101
{ return false; }102
{ return false; }102
if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX)103
if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX)103
{ return false; }104
{ return false; }104
if ((meta?.frames ?? 1) > 1)105
const frames = Number(sprite.subImages) || Number(sprite.subImgTotal) || (meta?.frames ?? 1);106
const speed = sprite._animationSpeed ?? meta?.animationSpeed ?? 0;107
if (frames > 1)105
{ return false; }108
{ return false; }106
if ((meta?.animationSpeed ?? 0) > 0)109
if (speed > 0)107
{ return false; }110
{ return false; }108
return true;111
return true;109
}112
}@@ -134,16 +137,16 @@ function blit (ctx, sprite, dx, dy)134
);137
);135
}138
}136
139
137
function groundSpriteName (catalog, ground)140
function groundSpriteName (catalog, ground, season = SeasonId.summer)138
{141
{139
const entry = normalizeGround(ground);142
const entry = normalizeGround(ground);140
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];143
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];141
const states = catalog.grounds?.[def.key]?.states ?? [];144
const states = catalog.grounds?.[def.key]?.states ?? [];142
const state = resolveState(states, entry.state);145
const state = resolveSeasonalVisualState(states, entry.state, season);143
return spriteImageName("ground", def.key, state);146
return spriteImageName("ground", def.key, state);144
}147
}145
148
146
function blockSpriteName (catalog, block)149
function blockSpriteName (catalog, block, season = SeasonId.summer)147
{150
{148
const entry = normalizeBlock(block);151
const entry = normalizeBlock(block);149
if (!entry)152
if (!entry)@@ -152,22 +155,22 @@ function blockSpriteName (catalog, block)152
if (!def || def.editorHidden)155
if (!def || def.editorHidden)153
{ return null; }156
{ return null; }154
const states = catalog.blocks?.[def.key]?.states ?? [];157
const states = catalog.blocks?.[def.key]?.states ?? [];155
const state = resolveState(states, entry.state);158
const state = resolveSeasonalVisualState(states, entry.state, season);156
return spriteImageName("block", def.key, state);159
return spriteImageName("block", def.key, state);157
}160
}158
161
159
function groundBloomName (catalog, ground)162
function groundBloomName (catalog, ground, season = SeasonId.summer)160
{163
{161
const entry = normalizeGround(ground);164
const entry = normalizeGround(ground);162
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];165
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];163
const type = catalog.grounds?.[def.key];166
const type = catalog.grounds?.[def.key];164
const state = resolveState(type?.states ?? [], entry.state);167
const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);165
if (!state || !type?.blooms?.[state])168
if (!state || !type?.blooms?.[state])166
{ return null; }169
{ return null; }167
return bloomImageName("ground", def.key, state);170
return bloomImageName("ground", def.key, state);168
}171
}169
172
170
function blockBloomName (catalog, block)173
function blockBloomName (catalog, block, season = SeasonId.summer)171
{174
{172
const entry = normalizeBlock(block);175
const entry = normalizeBlock(block);173
if (!entry)176
if (!entry)@@ -176,7 +179,7 @@ function blockBloomName (catalog, block)176
if (!def)179
if (!def)177
{ return null; }180
{ return null; }178
const type = catalog.blocks?.[def.key];181
const type = catalog.blocks?.[def.key];179
const state = resolveState(type?.states ?? [], entry.state);182
const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);180
if (!state || !type?.blooms?.[state])183
if (!state || !type?.blooms?.[state])181
{ return null; }184
{ return null; }182
return bloomImageName("block", def.key, state);185
return bloomImageName("block", def.key, state);@@ -1,27 +1,28 @@
1
1
import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
2
import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
2
import { bloomImageName, spriteImageName } from "/shared/definitions/tileSprites.js";
3
import { resolveSeasonalVisualState, SeasonId } from "/shared/world/season.js";
3
4
4
5
/** Resolve ground/block/bloom image names for one tile. */
5
export function resolveTileSprites ({ catalog, ground, block })
6
export function resolveTileSprites ({ catalog, ground, block, season = SeasonId.summer })
6
7
{
7
8
return {
8
ground: groundSpriteName(catalog, ground),
9
groundBloom: groundBloomName(catalog, ground),
10
block: blockSpriteName(catalog, block),
11
blockBloom: blockBloomName(catalog, block)
9
ground: groundSpriteName(catalog, ground, season),
10
groundBloom: groundBloomName(catalog, ground, season),
11
block: blockSpriteName(catalog, block, season),
12
blockBloom: blockBloomName(catalog, block, season)
12
13
};
13
14
}
14
15
15
function groundSpriteName (catalog, ground)
16
function groundSpriteName (catalog, ground, season = SeasonId.summer)
16
17
{
17
18
const entry = normalizeGround(ground);
18
19
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
19
20
const states = catalog.grounds?.[def.key]?.states ?? [];
20
const state = resolveState(states, entry.state);
21
const state = resolveSeasonalVisualState(states, entry.state, season);
21
22
return spriteImageName("ground", def.key, state);
22
23
}
23
24
24
function blockSpriteName (catalog, block)
25
function blockSpriteName (catalog, block, season = SeasonId.summer)
25
26
{
26
27
const entry = normalizeBlock(block);
27
28
if (!entry)
@@ -30,22 +31,22 @@ function blockSpriteName (catalog, block)
30
31
if (!def)
31
32
{ return null; }
32
33
const states = catalog.blocks?.[def.key]?.states ?? [];
33
const state = resolveState(states, entry.state);
34
const state = resolveSeasonalVisualState(states, entry.state, season);
34
35
return spriteImageName("block", def.key, state);
35
36
}
36
37
37
function groundBloomName (catalog, ground)
38
function groundBloomName (catalog, ground, season = SeasonId.summer)
38
39
{
39
40
const entry = normalizeGround(ground);
40
41
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
41
42
const type = catalog.grounds?.[def.key];
42
const state = resolveState(type?.states ?? [], entry.state);
43
const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);
43
44
if (!state || !type?.blooms?.[state])
44
45
{ return null; }
45
46
return bloomImageName("ground", def.key, state);
46
47
}
47
48
48
function blockBloomName (catalog, block)
49
function blockBloomName (catalog, block, season = SeasonId.summer)
49
50
{
50
51
const entry = normalizeBlock(block);
51
52
if (!entry)
@@ -54,7 +55,7 @@ function blockBloomName (catalog, block)
54
55
if (!def)
55
56
{ return null; }
56
57
const type = catalog.blocks?.[def.key];
57
const state = resolveState(type?.states ?? [], entry.state);
58
const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);
58
59
if (!state || !type?.blooms?.[state])
59
60
{ return null; }
60
61
return bloomImageName("block", def.key, state);
@@ -1,27 +1,28 @@1
import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";1
import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";2
import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";2
import { bloomImageName, spriteImageName } from "/shared/definitions/tileSprites.js";3
import { resolveSeasonalVisualState, SeasonId } from "/shared/world/season.js";3
4
4
/** Resolve ground/block/bloom image names for one tile. */5
/** Resolve ground/block/bloom image names for one tile. */5
export function resolveTileSprites ({ catalog, ground, block })6
export function resolveTileSprites ({ catalog, ground, block, season = SeasonId.summer })6
{7
{7
return {8
return {8
ground: groundSpriteName(catalog, ground),9
ground: groundSpriteName(catalog, ground, season),9
groundBloom: groundBloomName(catalog, ground),10
groundBloom: groundBloomName(catalog, ground, season),10
block: blockSpriteName(catalog, block),11
block: blockSpriteName(catalog, block, season),11
blockBloom: blockBloomName(catalog, block)12
blockBloom: blockBloomName(catalog, block, season)12
};13
};13
}14
}14
15
15
function groundSpriteName (catalog, ground)16
function groundSpriteName (catalog, ground, season = SeasonId.summer)16
{17
{17
const entry = normalizeGround(ground);18
const entry = normalizeGround(ground);18
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];19
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];19
const states = catalog.grounds?.[def.key]?.states ?? [];20
const states = catalog.grounds?.[def.key]?.states ?? [];20
const state = resolveState(states, entry.state);21
const state = resolveSeasonalVisualState(states, entry.state, season);21
return spriteImageName("ground", def.key, state);22
return spriteImageName("ground", def.key, state);22
}23
}23
24
24
function blockSpriteName (catalog, block)25
function blockSpriteName (catalog, block, season = SeasonId.summer)25
{26
{26
const entry = normalizeBlock(block);27
const entry = normalizeBlock(block);27
if (!entry)28
if (!entry)@@ -30,22 +31,22 @@ function blockSpriteName (catalog, block)30
if (!def)31
if (!def)31
{ return null; }32
{ return null; }32
const states = catalog.blocks?.[def.key]?.states ?? [];33
const states = catalog.blocks?.[def.key]?.states ?? [];33
const state = resolveState(states, entry.state);34
const state = resolveSeasonalVisualState(states, entry.state, season);34
return spriteImageName("block", def.key, state);35
return spriteImageName("block", def.key, state);35
}36
}36
37
37
function groundBloomName (catalog, ground)38
function groundBloomName (catalog, ground, season = SeasonId.summer)38
{39
{39
const entry = normalizeGround(ground);40
const entry = normalizeGround(ground);40
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];41
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];41
const type = catalog.grounds?.[def.key];42
const type = catalog.grounds?.[def.key];42
const state = resolveState(type?.states ?? [], entry.state);43
const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);43
if (!state || !type?.blooms?.[state])44
if (!state || !type?.blooms?.[state])44
{ return null; }45
{ return null; }45
return bloomImageName("ground", def.key, state);46
return bloomImageName("ground", def.key, state);46
}47
}47
48
48
function blockBloomName (catalog, block)49
function blockBloomName (catalog, block, season = SeasonId.summer)49
{50
{50
const entry = normalizeBlock(block);51
const entry = normalizeBlock(block);51
if (!entry)52
if (!entry)@@ -54,7 +55,7 @@ function blockBloomName (catalog, block)54
if (!def)55
if (!def)55
{ return null; }56
{ return null; }56
const type = catalog.blocks?.[def.key];57
const type = catalog.blocks?.[def.key];57
const state = resolveState(type?.states ?? [], entry.state);58
const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);58
if (!state || !type?.blooms?.[state])59
if (!state || !type?.blooms?.[state])59
{ return null; }60
{ return null; }60
return bloomImageName("block", def.key, state);61
return bloomImageName("block", def.key, state);@@ -4,7 +4,7 @@ import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
4
4
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5
5
import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
6
6
import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";
7
import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";
7
import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround } from "/shared/definitions/tiles.js";
8
8
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
9
9
import { bakeChunkAtlases } from "./chunkBake.js";
10
10
import {
@@ -12,6 +12,7 @@ import {
12
12
invalidateCanvasTexture
13
13
} from "./canvasSprite.js";
14
14
import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";
15
import { SeasonId, seasonIdAt } from "/shared/world/season.js";
15
16
16
17
const LAYER_GROUND = 0;
17
18
const LAYER_EDGE = 900000;
@@ -195,6 +196,8 @@ export class WorldView
195
196
this.localEntityId = null;
196
197
this.settings = { ...DEFAULT_WORLD_SETTINGS };
197
198
this.worldHour = 12;
199
/** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */
200
this.worldSeason = seasonIdAt();
198
201
this.nightPreview = null;
199
202
this.followPlayer = true;
200
203
this.dynamicLights = [];
@@ -214,6 +217,18 @@ export class WorldView
214
217
this.#syncBloomLayer();
215
218
}
216
219
220
/** Apply server (or local) calendar season; rebakes chunks when it changes. */
221
setWorldSeason (season)
222
{
223
const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
224
? season
225
: seasonIdAt();
226
if (next === this.worldSeason)
227
{ return; }
228
this.worldSeason = next;
229
this.#rebakeAllChunks();
230
}
231
217
232
setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)
218
233
{
219
234
this.localEntityId = entityId;
@@ -966,6 +981,7 @@ export class WorldView
966
981
entity.gatherToolItemId = toolItemId;
967
982
entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
968
983
this.#rebuildOverlays(entity);
984
this.#placeEntity(entity, performance.now());
969
985
}
970
986
971
987
#expireGatherToolOverlay (entity, now)
@@ -979,7 +995,7 @@ export class WorldView
979
995
this.#rebuildOverlays(entity);
980
996
}
981
997
982
/** Prefer the gather tool's equip sprite over the worn weapon while harvesting. */
998
/** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
983
999
#layersForDisplay (entity)
984
1000
{
985
1001
const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
@@ -987,9 +1003,13 @@ export class WorldView
987
1003
if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
988
1004
{ return layers; }
989
1005
const equip = itemEquipSprite(toolId);
990
if (!equip)
1006
if (!equip || !this.game.images[equip])
991
1007
{ return layers; }
992
const replacement = { sprite: equip, itemId: toolId };
1008
const replacement = {
1009
sprite: equip,
1010
itemId: toolId,
1011
tint: resolveEquipTint(toolId)
1012
};
993
1013
for (let index = layers.length - 1; index >= 1; index--)
994
1014
{
995
1015
const def = itemDefinition(layers[index].itemId);
@@ -1064,7 +1084,7 @@ export class WorldView
1064
1084
? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
1065
1085
: 0;
1066
1086
const tileShade = this.#entityShadeAlpha(entity, now);
1067
const wade = isWadeGround(this.#groundTypeAt(entity.tileX, entity.tileY));
1087
const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
1068
1088
1069
1089
entity.object.transform.rotation = walkTilt;
1070
1090
this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
@@ -1150,11 +1170,12 @@ export class WorldView
1150
1170
1151
1171
#waterCoastEdges (tileX, tileY)
1152
1172
{
1173
const season = this.worldSeason;
1153
1174
return {
1154
n: !isWaterGround(this.#groundTypeAt(tileX, tileY - 1)) ? 1 : 0,
1155
e: !isWaterGround(this.#groundTypeAt(tileX + 1, tileY)) ? 1 : 0,
1156
s: !isWaterGround(this.#groundTypeAt(tileX, tileY + 1)) ? 1 : 0,
1157
w: !isWaterGround(this.#groundTypeAt(tileX - 1, tileY)) ? 1 : 0
1175
n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
1176
e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
1177
s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
1178
w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
1158
1179
};
1159
1180
}
1160
1181
@@ -1175,6 +1196,21 @@ export class WorldView
1175
1196
};
1176
1197
}
1177
1198
1199
/** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
1200
#syncGroundWaterFx (objects, darkness, timeSec)
1201
{
1202
if (!objects?.ground)
1203
{ return; }
1204
if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
1205
{
1206
objects.waterEdges = null;
1207
this.#syncLitSprite(objects.ground, darkness);
1208
return;
1209
}
1210
objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1211
this.#syncWaterGroundSprite(objects.ground, darkness, objects.waterEdges, timeSec);
1212
}
1213
1178
1214
#applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
1179
1215
{
1180
1216
const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
@@ -1250,6 +1286,12 @@ export class WorldView
1250
1286
}
1251
1287
}
1252
1288
1289
#rebakeAllChunks ()
1290
{
1291
for (const snapshot of this.chunks.values())
1292
{ this.#rebuildChunk(snapshot); }
1293
}
1294
1253
1295
#bakeAndPlaceChunk (snapshot)
1254
1296
{
1255
1297
const key = `${snapshot.chunkX},${snapshot.chunkY}`;
@@ -1257,7 +1299,8 @@ export class WorldView
1257
1299
snapshot,
1258
1300
catalog: this.catalog,
1259
1301
images: this.game.images,
1260
preview: this.preview
1302
preview: this.preview,
1303
season: this.worldSeason
1261
1304
});
1262
1305
const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
1263
1306
let baked = this.bakedChunks.get(key);
@@ -1400,8 +1443,7 @@ export class WorldView
1400
1443
{ continue; }
1401
1444
if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
1402
1445
{ continue; }
1403
objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1404
this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, objects.waterEdges, timeSec);
1446
this.#syncGroundWaterFx(objects, objects.shadeAlpha ?? 0, timeSec);
1405
1447
}
1406
1448
}
1407
1449
@@ -1441,11 +1483,7 @@ export class WorldView
1441
1483
objects.ground.transform.size = new vector(size, size);
1442
1484
objects.ground.layer = LAYER_GROUND;
1443
1485
objects.groundTypeId = animatedGround.typeId;
1444
const edges = isWaterGround(animatedGround.typeId)
1445
? this.#waterCoastEdges(tileX, tileY)
1446
: { n: 0, e: 0, s: 0, w: 0 };
1447
objects.waterEdges = edges;
1448
this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, edges, performance.now() / 1000);
1486
this.#syncGroundWaterFx(objects, objects.shadeAlpha ?? 0, performance.now() / 1000);
1449
1487
this.#markSortDirty();
1450
1488
}
1451
1489
if (animatedGround.bloom)
@@ -1679,10 +1717,9 @@ export class WorldView
1679
1717
{ this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1680
1718
if (objects.ground && isWaterGround(objects.groundTypeId))
1681
1719
{
1682
this.#syncWaterGroundSprite(
1683
objects.ground,
1720
this.#syncGroundWaterFx(
1721
objects,
1684
1722
objects.shadeAlpha,
1685
objects.waterEdges ?? this.#waterCoastEdges(objects.tileX, objects.tileY),
1686
1723
now / 1000
1687
1724
);
1688
1725
}
@@ -4,7 +4,7 @@ import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";4
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";4
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";5
import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";5
import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";6
import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";6
import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";7
import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";7
import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround } from "/shared/definitions/tiles.js";8
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";8
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";9
import { bakeChunkAtlases } from "./chunkBake.js";9
import { bakeChunkAtlases } from "./chunkBake.js";10
import {10
import {@@ -12,6 +12,7 @@ import {12
invalidateCanvasTexture12
invalidateCanvasTexture13
} from "./canvasSprite.js";13
} from "./canvasSprite.js";14
import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";14
import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";15
import { SeasonId, seasonIdAt } from "/shared/world/season.js";15
16
16
const LAYER_GROUND = 0;17
const LAYER_GROUND = 0;17
const LAYER_EDGE = 900000;18
const LAYER_EDGE = 900000;@@ -195,6 +196,8 @@ export class WorldView195
this.localEntityId = null;196
this.localEntityId = null;196
this.settings = { ...DEFAULT_WORLD_SETTINGS };197
this.settings = { ...DEFAULT_WORLD_SETTINGS };197
this.worldHour = 12;198
this.worldHour = 12;199
/** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */200
this.worldSeason = seasonIdAt();198
this.nightPreview = null;201
this.nightPreview = null;199
this.followPlayer = true;202
this.followPlayer = true;200
this.dynamicLights = [];203
this.dynamicLights = [];@@ -214,6 +217,18 @@ export class WorldView214
this.#syncBloomLayer();217
this.#syncBloomLayer();215
}218
}216
219
220
/** Apply server (or local) calendar season; rebakes chunks when it changes. */221
setWorldSeason (season)222
{223
const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer224
? season225
: seasonIdAt();226
if (next === this.worldSeason)227
{ return; }228
this.worldSeason = next;229
this.#rebakeAllChunks();230
}231
217
setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)232
setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)218
{233
{219
this.localEntityId = entityId;234
this.localEntityId = entityId;@@ -966,6 +981,7 @@ export class WorldView966
entity.gatherToolItemId = toolItemId;981
entity.gatherToolItemId = toolItemId;967
entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;982
entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;968
this.#rebuildOverlays(entity);983
this.#rebuildOverlays(entity);984
this.#placeEntity(entity, performance.now());969
}985
}970
986
971
#expireGatherToolOverlay (entity, now)987
#expireGatherToolOverlay (entity, now)@@ -979,7 +995,7 @@ export class WorldView979
this.#rebuildOverlays(entity);995
this.#rebuildOverlays(entity);980
}996
}981
997
982
/** Prefer the gather tool's equip sprite over the worn weapon while harvesting. */998
/** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */983
#layersForDisplay (entity)999
#layersForDisplay (entity)984
{1000
{985
const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));1001
const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));@@ -987,9 +1003,13 @@ export class WorldView987
if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())1003
if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())988
{ return layers; }1004
{ return layers; }989
const equip = itemEquipSprite(toolId);1005
const equip = itemEquipSprite(toolId);990
if (!equip)1006
if (!equip || !this.game.images[equip])991
{ return layers; }1007
{ return layers; }992
const replacement = { sprite: equip, itemId: toolId };1008
const replacement = {1009
sprite: equip,1010
itemId: toolId,1011
tint: resolveEquipTint(toolId)1012
};993
for (let index = layers.length - 1; index >= 1; index--)1013
for (let index = layers.length - 1; index >= 1; index--)994
{1014
{995
const def = itemDefinition(layers[index].itemId);1015
const def = itemDefinition(layers[index].itemId);@@ -1064,7 +1084,7 @@ export class WorldView1064
? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS1084
? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS1065
: 0;1085
: 0;1066
const tileShade = this.#entityShadeAlpha(entity, now);1086
const tileShade = this.#entityShadeAlpha(entity, now);1067
const wade = isWadeGround(this.#groundTypeAt(entity.tileX, entity.tileY));1087
const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);1068
1088
1069
entity.object.transform.rotation = walkTilt;1089
entity.object.transform.rotation = walkTilt;1070
this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);1090
this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);@@ -1150,11 +1170,12 @@ export class WorldView1150
1170
1151
#waterCoastEdges (tileX, tileY)1171
#waterCoastEdges (tileX, tileY)1152
{1172
{1173
const season = this.worldSeason;1153
return {1174
return {1154
n: !isWaterGround(this.#groundTypeAt(tileX, tileY - 1)) ? 1 : 0,1175
n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,1155
e: !isWaterGround(this.#groundTypeAt(tileX + 1, tileY)) ? 1 : 0,1176
e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,1156
s: !isWaterGround(this.#groundTypeAt(tileX, tileY + 1)) ? 1 : 0,1177
s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,1157
w: !isWaterGround(this.#groundTypeAt(tileX - 1, tileY)) ? 1 : 01178
w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 01158
};1179
};1159
}1180
}1160
1181
@@ -1175,6 +1196,21 @@ export class WorldView1175
};1196
};1176
}1197
}1177
1198
1199
/** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */1200
#syncGroundWaterFx (objects, darkness, timeSec)1201
{1202
if (!objects?.ground)1203
{ return; }1204
if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))1205
{1206
objects.waterEdges = null;1207
this.#syncLitSprite(objects.ground, darkness);1208
return;1209
}1210
objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);1211
this.#syncWaterGroundSprite(objects.ground, darkness, objects.waterEdges, timeSec);1212
}1213
1178
#applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)1214
#applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)1179
{1215
{1180
const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;1216
const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;@@ -1250,6 +1286,12 @@ export class WorldView1250
}1286
}1251
}1287
}1252
1288
1289
#rebakeAllChunks ()1290
{1291
for (const snapshot of this.chunks.values())1292
{ this.#rebuildChunk(snapshot); }1293
}1294
1253
#bakeAndPlaceChunk (snapshot)1295
#bakeAndPlaceChunk (snapshot)1254
{1296
{1255
const key = `${snapshot.chunkX},${snapshot.chunkY}`;1297
const key = `${snapshot.chunkX},${snapshot.chunkY}`;@@ -1257,7 +1299,8 @@ export class WorldView1257
snapshot,1299
snapshot,1258
catalog: this.catalog,1300
catalog: this.catalog,1259
images: this.game.images,1301
images: this.game.images,1260
preview: this.preview1302
preview: this.preview,1303
season: this.worldSeason1261
});1304
});1262
const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;1305
const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;1263
let baked = this.bakedChunks.get(key);1306
let baked = this.bakedChunks.get(key);@@ -1400,8 +1443,7 @@ export class WorldView1400
{ continue; }1443
{ continue; }1401
if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)1444
if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)1402
{ continue; }1445
{ continue; }1403
objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);1446
this.#syncGroundWaterFx(objects, objects.shadeAlpha ?? 0, timeSec);1404
this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, objects.waterEdges, timeSec);1405
}1447
}1406
}1448
}1407
1449
@@ -1441,11 +1483,7 @@ export class WorldView1441
objects.ground.transform.size = new vector(size, size);1483
objects.ground.transform.size = new vector(size, size);1442
objects.ground.layer = LAYER_GROUND;1484
objects.ground.layer = LAYER_GROUND;1443
objects.groundTypeId = animatedGround.typeId;1485
objects.groundTypeId = animatedGround.typeId;1444
const edges = isWaterGround(animatedGround.typeId)1486
this.#syncGroundWaterFx(objects, objects.shadeAlpha ?? 0, performance.now() / 1000);1445
? this.#waterCoastEdges(tileX, tileY)1446
: { n: 0, e: 0, s: 0, w: 0 };1447
objects.waterEdges = edges;1448
this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, edges, performance.now() / 1000);1449
this.#markSortDirty();1487
this.#markSortDirty();1450
}1488
}1451
if (animatedGround.bloom)1489
if (animatedGround.bloom)@@ -1679,10 +1717,9 @@ export class WorldView1679
{ this.#syncLitSprite(objects.block, objects.shadeAlpha); }1717
{ this.#syncLitSprite(objects.block, objects.shadeAlpha); }1680
if (objects.ground && isWaterGround(objects.groundTypeId))1718
if (objects.ground && isWaterGround(objects.groundTypeId))1681
{1719
{1682
this.#syncWaterGroundSprite(1720
this.#syncGroundWaterFx(1683
objects.ground,1721
objects,1684
objects.shadeAlpha,1722
objects.shadeAlpha,1685
objects.waterEdges ?? this.#waterCoastEdges(objects.tileX, objects.tileY),1686
now / 10001723
now / 10001687
);1724
);1688
}1725
}@@ -1099,6 +1099,85 @@ a { color: #d4c48a; }
1099
1099
margin-bottom: 0.75rem;
1100
1100
}
1101
1101
1102
#market-panel {
1103
position: fixed;
1104
z-index: 6;
1105
top: 50%;
1106
left: 50%;
1107
transform: translate(-50%, -50%);
1108
width: min(720px, 94vw);
1109
max-height: min(85vh, 720px);
1110
overflow: auto;
1111
background: #1a1e26;
1112
border: 1px solid #2c3340;
1113
padding: 0.75rem 1rem 1rem;
1114
}
1115
1116
#market-panel[hidden],
1117
#market-backdrop[hidden] {
1118
display: none !important;
1119
}
1120
1121
#market-panel header {
1122
display: flex;
1123
justify-content: space-between;
1124
align-items: center;
1125
gap: 0.75rem;
1126
margin-bottom: 0.5rem;
1127
}
1128
1129
.market-section {
1130
margin-top: 0.75rem;
1131
}
1132
1133
.market-columns {
1134
display: grid;
1135
grid-template-columns: 1fr 1fr;
1136
gap: 1rem;
1137
}
1138
1139
.market-catalog,
1140
.market-sell-list {
1141
display: flex;
1142
flex-direction: column;
1143
gap: 0.25rem;
1144
max-height: 180px;
1145
overflow: auto;
1146
margin-bottom: 0.5rem;
1147
}
1148
1149
.market-catalog-row,
1150
.market-sell-row,
1151
.market-order-row {
1152
display: flex;
1153
align-items: center;
1154
justify-content: space-between;
1155
gap: 0.5rem;
1156
background: #12151b;
1157
border: 1px solid #2c3340;
1158
color: inherit;
1159
padding: 0.35rem 0.5rem;
1160
text-align: left;
1161
}
1162
1163
.market-catalog-row.selected,
1164
.market-sell-row.selected {
1165
border-color: #6a8caf;
1166
}
1167
1168
.market-sell-row img {
1169
width: 24px;
1170
height: 24px;
1171
image-rendering: pixelated;
1172
}
1173
1174
@media (max-width: 700px) {
1175
.market-columns {
1176
grid-template-columns: 1fr;
1177
}
1178
}
1179
1180
1102
1181
#shop-qty-backdrop {
1103
1182
z-index: 7;
1104
1183
}
@@ -1099,6 +1099,85 @@ a { color: #d4c48a; }1099
margin-bottom: 0.75rem;1099
margin-bottom: 0.75rem;1100
}1100
}1101
1101
1102
#market-panel {1103
position: fixed;1104
z-index: 6;1105
top: 50%;1106
left: 50%;1107
transform: translate(-50%, -50%);1108
width: min(720px, 94vw);1109
max-height: min(85vh, 720px);1110
overflow: auto;1111
background: #1a1e26;1112
border: 1px solid #2c3340;1113
padding: 0.75rem 1rem 1rem;1114
}1115
1116
#market-panel[hidden],1117
#market-backdrop[hidden] {1118
display: none !important;1119
}1120
1121
#market-panel header {1122
display: flex;1123
justify-content: space-between;1124
align-items: center;1125
gap: 0.75rem;1126
margin-bottom: 0.5rem;1127
}1128
1129
.market-section {1130
margin-top: 0.75rem;1131
}1132
1133
.market-columns {1134
display: grid;1135
grid-template-columns: 1fr 1fr;1136
gap: 1rem;1137
}1138
1139
.market-catalog,1140
.market-sell-list {1141
display: flex;1142
flex-direction: column;1143
gap: 0.25rem;1144
max-height: 180px;1145
overflow: auto;1146
margin-bottom: 0.5rem;1147
}1148
1149
.market-catalog-row,1150
.market-sell-row,1151
.market-order-row {1152
display: flex;1153
align-items: center;1154
justify-content: space-between;1155
gap: 0.5rem;1156
background: #12151b;1157
border: 1px solid #2c3340;1158
color: inherit;1159
padding: 0.35rem 0.5rem;1160
text-align: left;1161
}1162
1163
.market-catalog-row.selected,1164
.market-sell-row.selected {1165
border-color: #6a8caf;1166
}1167
1168
.market-sell-row img {1169
width: 24px;1170
height: 24px;1171
image-rendering: pixelated;1172
}1173
1174
@media (max-width: 700px) {1175
.market-columns {1176
grid-template-columns: 1fr;1177
}1178
}1179
1180
1102
#shop-qty-backdrop {1181
#shop-qty-backdrop {1103
z-index: 7;1182
z-index: 7;1104
}1183
}@@ -16,8 +16,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16
16
## Ground and block tile layers
17
17
18
18
**Status:** full
19
**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). Live block types include stone wall, torch, bank, and **church altar** (respawn destination — see **Player death and respawn**). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Water tiles use a coast-foam shader on edges against non-water; entity sprites use a wade clip+foam tint that respects night darkness.
20
**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
19
**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants.
20
**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
21
21
22
22
## Open and closed chunks
23
23
@@ -64,13 +64,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
64
64
## World editor (server)
65
65
66
66
**Status:** full
67
**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace stalls wait on later economy work.
67
**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`) are placeable blocks.
68
68
**Code:** `server/src/editor/service.js`
69
69
70
70
## World editor (client)
71
71
72
72
**Status:** full
73
**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, open/closed, per-chunk changelog, night preview slider, world-settings modal, save chunk and Apply now. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). 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.
73
**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, save chunk and Apply now. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). 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.
74
74
**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
75
75
76
76
## Per-chunk changelog
@@ -136,8 +136,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
136
136
## Night shading
137
137
138
138
**Status:** full
139
**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. Tile shade overlays sit above baked ground/block atlases. Sprites larger than 16×16 (and all mobiles) take the full darkness of their standing tile as a uniform sprite-sized shade overlay, so they are not darkened by neighbouring tile shades.
140
**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#placeSpriteShade`), `server/src/simulation/simulation.js` (`worldTime`)
139
**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. Tile shade overlays sit above baked ground/block atlases. Sprites larger than 16×16 (and all mobiles) take the full darkness of their standing tile as a uniform sprite-sized shade overlay, so they are not darkened by neighbouring tile shades. `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
140
**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
141
141
142
142
## FrameworkV3 client bootstrap
143
143
@@ -154,8 +154,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
154
154
## Visual tile states
155
155
156
156
**Status:** full
157
**Spec:** Each ground and block type has a folder of PNG states. The first alphabetical file is the default. States are visual only; the game may set a named state (for example a door). The editor wheel cycles states; hover previews the selected tool on the target tile.
158
**Code:** `server/src/assets/spriteCatalog.js`, `shared/definitions/tileSprites.js`, `client/src/editor/main.js`, `client/src/render/worldView.js`, tests in `server/tests/tile-states.test.js`
157
**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.
158
**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`
159
159
160
160
## Region workers and cross-worker transfer
161
161
@@ -228,16 +228,16 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
228
228
## Equipment tiers and worn stat bonuses
229
229
230
230
**Status:** partial
231
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; trees later — axe sprites (`items/axe`) match pickaxe style for woodcutting; logs may be bought from NPC shops for now.
232
**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), and boulder-ore; tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint.
233
**TODO:** full combat gear catalog; tree nodes / woodcutting gather; silver/gold jewelry / other precious recipes.
231
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting.
232
**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), and boulder-ore; tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
233
**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.
234
234
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
235
235
236
236
## Gathering, crafting, and production skills
237
237
238
**Status:** partial (mining + smelting + pickaxe/axe craft chains live)
239
**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 node shows a cursor tooltip with the resource name (`resourceNodeDisplayName` — ores today; trees / fishing / herbs later). **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. Woodcutting trees / fishing / other stations later.
240
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`), `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/crafting.test.js`
238
**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting live)
239
**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 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. **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.
240
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`), `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`
241
241
242
242
## Crafting stations
243
243
@@ -293,9 +293,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
293
293
294
294
## Banking, cheques, shops, player-driven marketplace
295
295
296
**Status:** partial (banks/cheques/origins live; NPC shops sell stock; player marketplace UI later)
297
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 UTC** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. Player marketplace remains later.
298
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
296
**Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
297
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** `BlockType.marketplace` counters require adjacency. Hidden order book (no browsable asks): place buy/sell with escrow from bag; match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter (`Bobby Pennies` etc., Central Exchange). Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter. Matches update durable `item_last_sales` for shop/tooltip lerp.
298
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
299
299
300
300
## Player scripting hooks
301
301
@@ -16,8 +16,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi16
## Ground and block tile layers16
## Ground and block tile layers17
17
18
**Status:** full 18
**Status:** full 19
**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). Live block types include stone wall, torch, bank, and **church altar** (respawn destination — see **Player death and respawn**). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Water tiles use a coast-foam shader on edges against non-water; entity sprites use a wade clip+foam tint that respects night darkness. 19
**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants. 20
**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`20
**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`21
21
22
## Open and closed chunks22
## Open and closed chunks23
23
@@ -64,13 +64,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi64
## World editor (server)64
## World editor (server)65
65
66
**Status:** full 66
**Status:** full 67
**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace stalls wait on later economy work. 67
**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`) are placeable blocks. 68
**Code:** `server/src/editor/service.js`68
**Code:** `server/src/editor/service.js`69
69
70
## World editor (client)70
## World editor (client)71
71
72
**Status:** full 72
**Status:** full 73
**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, open/closed, per-chunk changelog, night preview slider, world-settings modal, save chunk and Apply now. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). 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. 73
**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, save chunk and Apply now. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). 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. 74
**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`74
**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`75
75
76
## Per-chunk changelog76
## Per-chunk changelog@@ -136,8 +136,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi136
## Night shading136
## Night shading137
137
138
**Status:** full 138
**Status:** full 139
**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. Tile shade overlays sit above baked ground/block atlases. Sprites larger than 16×16 (and all mobiles) take the full darkness of their standing tile as a uniform sprite-sized shade overlay, so they are not darkened by neighbouring tile shades. 139
**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. Tile shade overlays sit above baked ground/block atlases. Sprites larger than 16×16 (and all mobiles) take the full darkness of their standing tile as a uniform sprite-sized shade overlay, so they are not darkened by neighbouring tile shades. `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals. 140
**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#placeSpriteShade`), `server/src/simulation/simulation.js` (`worldTime`)140
**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`141
141
142
## FrameworkV3 client bootstrap142
## FrameworkV3 client bootstrap143
143
@@ -154,8 +154,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi154
## Visual tile states154
## Visual tile states155
155
156
**Status:** full 156
**Status:** full 157
**Spec:** Each ground and block type has a folder of PNG states. The first alphabetical file is the default. States are visual only; the game may set a named state (for example a door). The editor wheel cycles states; hover previews the selected tool on the target tile. 157
**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. 158
**Code:** `server/src/assets/spriteCatalog.js`, `shared/definitions/tileSprites.js`, `client/src/editor/main.js`, `client/src/render/worldView.js`, tests in `server/tests/tile-states.test.js`158
**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`159
159
160
## Region workers and cross-worker transfer160
## Region workers and cross-worker transfer161
161
@@ -228,16 +228,16 @@ Each entry is a short note on behaviour and where the code lives. Update this fi228
## Equipment tiers and worn stat bonuses228
## Equipment tiers and worn stat bonuses229
229
230
**Status:** partial 230
**Status:** partial 231
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; trees later — axe sprites (`items/axe`) match pickaxe style for woodcutting; logs may be bought from NPC shops for now. 231
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. 232
**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), and boulder-ore; tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. 232
**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), and boulder-ore; tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type). 233
**TODO:** full combat gear catalog; tree nodes / woodcutting gather; silver/gold jewelry / other precious recipes. 233
**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.234
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`234
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`235
235
236
## Gathering, crafting, and production skills236
## Gathering, crafting, and production skills237
237
238
**Status:** partial (mining + smelting + pickaxe/axe craft chains live) 238
**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting live) 239
**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 node shows a cursor tooltip with the resource name (`resourceNodeDisplayName` — ores today; trees / fishing / herbs later). **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. Woodcutting trees / fishing / other stations later.239
**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 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. **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. 240
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`), `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/crafting.test.js`240
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`), `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`241
241
242
## Crafting stations242
## Crafting stations243
243
@@ -293,9 +293,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi293
293
294
## Banking, cheques, shops, player-driven marketplace294
## Banking, cheques, shops, player-driven marketplace295
295
296
**Status:** partial (banks/cheques/origins live; NPC shops sell stock; player marketplace UI later) 296
**Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live) 297
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 UTC** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. Player marketplace remains later. 297
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** `BlockType.marketplace` counters require adjacency. Hidden order book (no browsable asks): place buy/sell with escrow from bag; match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter (`Bobby Pennies` etc., Central Exchange). Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter. Matches update durable `item_last_sales` for shop/tooltip lerp. 298
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`298
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`299
299
300
## Player scripting hooks300
## Player scripting hooks301
301
@@ -16,6 +16,7 @@ import {
16
16
parseSpriteStem,
17
17
spriteImageName
18
18
} from "../../../shared/definitions/tileSprites.js";
19
import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
19
20
20
21
const CHARACTER_DEFINITIONS = Object.freeze({
21
22
"player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
@@ -153,7 +154,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
153
154
154
155
if (layer === "block" && def.key === "boulder")
155
156
{
156
states = states.filter((state) => state !== "boulder-ore");
157
states = states.filter((state) => state !== "boulder-ore" && state !== "boulder-ore-winter");
157
158
if (!states.includes("boulder"))
158
159
{ states.unshift("boulder"); }
159
160
for (const material of ORE_BEARING_MATERIALS)
@@ -171,6 +172,18 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
171
172
animationSpeed,
172
173
tint: { r: tint.r, g: tint.g, b: tint.b }
173
174
});
175
const winterState = `${state}-winter`;
176
if (!states.includes(winterState))
177
{ states.push(winterState); }
178
imagesForType.push({
179
name: spriteImageName(layer, def.key, winterState),
180
url: `/assets/${urlFolder}/${def.key}/boulder-ore-winter.png`,
181
subImgTotal: frames,
182
perRow: framesPerRow,
183
loop: animationSpeed > 0,
184
animationSpeed,
185
tint: { r: tint.r, g: tint.g, b: tint.b }
186
});
174
187
}
175
188
}
176
189
@@ -180,23 +193,28 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
180
193
states,
181
194
defaultState: def.key === "boulder" && states.includes("boulder")
182
195
? "boulder"
183
: states[0],
196
: (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
184
197
blooms,
185
198
equips,
186
199
equipBlooms,
187
200
frames,
188
201
framesPerRow,
189
animationSpeed
202
animationSpeed,
203
outdoor: !!def.outdoor,
204
/** Calendar-driven only when outdoor and summer/fall/winter states exist. */
205
seasonal: !!def.outdoor && typeHasSeasonalStates(states)
190
206
};
191
207
for (const state of states)
192
208
{
193
209
if (imagesForType.some((entry) => entry.name === spriteImageName(layer, def.key, state)))
194
210
{ continue; }
211
/** Seasonal overlays (e.g. frozen water-winter) are static single-frame sprites. */
212
const overlay = isSeasonalOverlayVariant(state);
195
213
const sheet = {
196
subImgTotal: frames,
197
perRow: framesPerRow,
198
loop: animationSpeed > 0,
199
animationSpeed
214
subImgTotal: overlay ? 1 : frames,
215
perRow: overlay ? 1 : framesPerRow,
216
loop: !overlay && animationSpeed > 0,
217
animationSpeed: overlay ? 0 : animationSpeed
200
218
};
201
219
images.push({
202
220
name: spriteImageName(layer, def.key, state),
@@ -16,6 +16,7 @@ import {16
parseSpriteStem,16
parseSpriteStem,17
spriteImageName17
spriteImageName18
} from "../../../shared/definitions/tileSprites.js";18
} from "../../../shared/definitions/tileSprites.js";19
import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";19
20
20
const CHARACTER_DEFINITIONS = Object.freeze({21
const CHARACTER_DEFINITIONS = Object.freeze({21
"player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),22
"player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),@@ -153,7 +154,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)153
154
154
if (layer === "block" && def.key === "boulder")155
if (layer === "block" && def.key === "boulder")155
{156
{156
states = states.filter((state) => state !== "boulder-ore");157
states = states.filter((state) => state !== "boulder-ore" && state !== "boulder-ore-winter");157
if (!states.includes("boulder"))158
if (!states.includes("boulder"))158
{ states.unshift("boulder"); }159
{ states.unshift("boulder"); }159
for (const material of ORE_BEARING_MATERIALS)160
for (const material of ORE_BEARING_MATERIALS)@@ -171,6 +172,18 @@ function scanLayer (layerDir, definitions, layer, urlFolder)171
animationSpeed,172
animationSpeed,172
tint: { r: tint.r, g: tint.g, b: tint.b }173
tint: { r: tint.r, g: tint.g, b: tint.b }173
});174
});175
const winterState = `${state}-winter`;176
if (!states.includes(winterState))177
{ states.push(winterState); }178
imagesForType.push({179
name: spriteImageName(layer, def.key, winterState),180
url: `/assets/${urlFolder}/${def.key}/boulder-ore-winter.png`,181
subImgTotal: frames,182
perRow: framesPerRow,183
loop: animationSpeed > 0,184
animationSpeed,185
tint: { r: tint.r, g: tint.g, b: tint.b }186
});174
}187
}175
}188
}176
189
@@ -180,23 +193,28 @@ function scanLayer (layerDir, definitions, layer, urlFolder)180
states,193
states,181
defaultState: def.key === "boulder" && states.includes("boulder")194
defaultState: def.key === "boulder" && states.includes("boulder")182
? "boulder"195
? "boulder"183
: states[0],196
: (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],184
blooms,197
blooms,185
equips,198
equips,186
equipBlooms,199
equipBlooms,187
frames,200
frames,188
framesPerRow,201
framesPerRow,189
animationSpeed202
animationSpeed,203
outdoor: !!def.outdoor,204
/** Calendar-driven only when outdoor and summer/fall/winter states exist. */205
seasonal: !!def.outdoor && typeHasSeasonalStates(states)190
};206
};191
for (const state of states)207
for (const state of states)192
{208
{193
if (imagesForType.some((entry) => entry.name === spriteImageName(layer, def.key, state)))209
if (imagesForType.some((entry) => entry.name === spriteImageName(layer, def.key, state)))194
{ continue; }210
{ continue; }211
/** Seasonal overlays (e.g. frozen water-winter) are static single-frame sprites. */212
const overlay = isSeasonalOverlayVariant(state);195
const sheet = {213
const sheet = {196
subImgTotal: frames,214
subImgTotal: overlay ? 1 : frames,197
perRow: framesPerRow,215
perRow: overlay ? 1 : framesPerRow,198
loop: animationSpeed > 0,216
loop: !overlay && animationSpeed > 0,199
animationSpeed217
animationSpeed: overlay ? 0 : animationSpeed200
};218
};201
images.push({219
images.push({202
name: spriteImageName(layer, def.key, state),220
name: spriteImageName(layer, def.key, state),@@ -12,6 +12,11 @@ import {
12
12
} from "../../../shared/crafting/recipes.js";
13
13
import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
14
14
import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
15
import {
16
attachOrigins,
17
craftOrigin,
18
craftOriginVerbForStation
19
} from "../../../shared/items/origin.js";
15
20
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
16
21
import { bagView } from "../items/bags.js";
17
22
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
@@ -25,6 +30,13 @@ function userError (message)
25
30
return error;
26
31
}
27
32
33
function characterDisplayName (world, handle)
34
{
35
const appearance = world.ecs.get(handle, Component.appearance);
36
const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
37
return name || "someone";
38
}
39
28
40
function ensureCraftSessions (world)
29
41
{
30
42
if (!world.craftSessions)
@@ -269,10 +281,16 @@ export function stepCrafting (world, now)
269
281
continue;
270
282
}
271
283
const outDef = itemDefinition(recipe.output.itemId);
272
const added = insertStack(taken.slots, {
284
const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
285
const origin = craftOrigin(
286
craftOriginVerbForStation(session.stationId),
287
characterDisplayName(world, handle)
288
);
289
const added = insertStack(taken.slots, attachOrigins({
273
290
itemId: recipe.output.itemId,
274
quantity: Math.max(1, recipe.output.quantity | 0 || 1)
275
}, outDef);
291
quantity: outQty,
292
origins: [{ origin, quantity: outQty }]
293
}), outDef);
276
294
if (!added.ok || added.remainder > 0)
277
295
{
278
296
events.push({
@@ -12,6 +12,11 @@ import {12
} from "../../../shared/crafting/recipes.js";12
} from "../../../shared/crafting/recipes.js";13
import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";13
import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";14
import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";14
import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";15
import {16
attachOrigins,17
craftOrigin,18
craftOriginVerbForStation19
} from "../../../shared/items/origin.js";15
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";20
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";16
import { bagView } from "../items/bags.js";21
import { bagView } from "../items/bags.js";17
import { tileToChunk, tileToLocal } from "../world/coordinates.js";22
import { tileToChunk, tileToLocal } from "../world/coordinates.js";@@ -25,6 +30,13 @@ function userError (message)25
return error;30
return error;26
}31
}27
32
33
function characterDisplayName (world, handle)34
{35
const appearance = world.ecs.get(handle, Component.appearance);36
const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();37
return name || "someone";38
}39
28
function ensureCraftSessions (world)40
function ensureCraftSessions (world)29
{41
{30
if (!world.craftSessions)42
if (!world.craftSessions)@@ -269,10 +281,16 @@ export function stepCrafting (world, now)269
continue;281
continue;270
}282
}271
const outDef = itemDefinition(recipe.output.itemId);283
const outDef = itemDefinition(recipe.output.itemId);272
const added = insertStack(taken.slots, {284
const outQty = Math.max(1, recipe.output.quantity | 0 || 1);285
const origin = craftOrigin(286
craftOriginVerbForStation(session.stationId),287
characterDisplayName(world, handle)288
);289
const added = insertStack(taken.slots, attachOrigins({273
itemId: recipe.output.itemId,290
itemId: recipe.output.itemId,274
quantity: Math.max(1, recipe.output.quantity | 0 || 1)291
quantity: outQty,275
}, outDef);292
origins: [{ origin, quantity: outQty }]293
}), outDef);276
if (!added.ok || added.remainder > 0)294
if (!added.ok || added.remainder > 0)277
{295
{278
events.push({296
events.push({@@ -232,6 +232,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
232
232
tileY: message.tileY | 0
233
233
});
234
234
break;
235
case MessageType.chop:
236
requirePlaying(session);
237
simulation.enqueue(session.id, {
238
type: "chop",
239
characterId: session.characterId,
240
tileX: message.tileX | 0,
241
tileY: message.tileY | 0
242
});
243
break;
235
244
case MessageType.cancelGather:
236
245
requirePlaying(session);
237
246
simulation.enqueue(session.id, {
@@ -425,6 +434,48 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
425
434
npcEntityId: message.npcEntityId | 0
426
435
});
427
436
break;
437
case MessageType.openMarket:
438
requirePlaying(session);
439
simulation.enqueue(session.id, {
440
type: "open-market",
441
characterId: session.characterId
442
});
443
break;
444
case MessageType.closeMarket:
445
requirePlaying(session);
446
simulation.enqueue(session.id, {
447
type: "close-market",
448
characterId: session.characterId
449
});
450
break;
451
case MessageType.placeMarketSell:
452
requirePlaying(session);
453
simulation.enqueue(session.id, {
454
type: "place-market-sell",
455
characterId: session.characterId,
456
slotIndex: message.slotIndex | 0,
457
quantity: message.quantity | 0 || 1,
458
minUnitPrice: message.minUnitPrice | 0
459
});
460
break;
461
case MessageType.placeMarketBuy:
462
requirePlaying(session);
463
simulation.enqueue(session.id, {
464
type: "place-market-buy",
465
characterId: session.characterId,
466
itemId: message.itemId | 0,
467
quantity: message.quantity | 0 || 1,
468
maxUnitPrice: message.maxUnitPrice | 0
469
});
470
break;
471
case MessageType.cancelMarketOrder:
472
requirePlaying(session);
473
simulation.enqueue(session.id, {
474
type: "cancel-market-order",
475
characterId: session.characterId,
476
orderId: message.orderId | 0
477
});
478
break;
428
479
case MessageType.follow:
429
480
requirePlaying(session);
430
481
simulation.enqueue(session.id, {
@@ -889,6 +940,47 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
889
940
}
890
941
continue;
891
942
}
943
if (event.type === "market-open")
944
{
945
const session = sessions.get(event.sessionId);
946
if (session)
947
{
948
send(session, {
949
type: MessageType.marketOpen,
950
displayName: event.displayName,
951
orders: event.orders ?? [],
952
catalog: event.catalog ?? []
953
});
954
}
955
continue;
956
}
957
if (event.type === "market-closed")
958
{
959
const session = sessions.get(event.sessionId);
960
if (session)
961
{ send(session, { type: MessageType.marketClosed }); }
962
continue;
963
}
964
if (event.type === "market-trade")
965
{
966
for (const session of sessions.values())
967
{
968
if (
969
session.characterId === event.buyerCharacterId
970
|| session.characterId === event.sellerCharacterId
971
)
972
{
973
send(session, {
974
type: MessageType.marketTrade,
975
itemId: event.itemId,
976
quantity: event.quantity,
977
unitPrice: event.unitPrice,
978
triggeringSide: event.triggeringSide
979
});
980
}
981
}
982
continue;
983
}
892
984
if (event.type === "item-bubble")
893
985
{
894
986
broadcastItemBubble(
@@ -1022,14 +1114,29 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1022
1114
{
1023
1115
if (!seesTo && !seesFrom)
1024
1116
{ continue; }
1025
send(session, {
1026
type: MessageType.tileShove,
1027
attackerId: event.attackerId,
1028
tileX: event.tileX,
1029
tileY: event.tileY,
1030
fromTileX: event.fromTileX,
1031
fromTileY: event.fromTileY
1032
});
1117
if (event.type === "gather-swing")
1118
{
1119
send(session, {
1120
type: MessageType.gatherSwing,
1121
attackerId: event.attackerId,
1122
tileX: event.tileX,
1123
tileY: event.tileY,
1124
fromTileX: event.fromTileX,
1125
fromTileY: event.fromTileY,
1126
toolItemId: event.toolItemId ?? null
1127
});
1128
}
1129
else
1130
{
1131
send(session, {
1132
type: MessageType.tileShove,
1133
attackerId: event.attackerId,
1134
tileX: event.tileX,
1135
tileY: event.tileY,
1136
fromTileX: event.fromTileX,
1137
fromTileY: event.fromTileY
1138
});
1139
}
1033
1140
continue;
1034
1141
}
1035
1142
if (event.type === "chunk-delta")
@@ -232,6 +232,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,232
tileY: message.tileY | 0232
tileY: message.tileY | 0233
});233
});234
break;234
break;235
case MessageType.chop:236
requirePlaying(session);237
simulation.enqueue(session.id, {238
type: "chop",239
characterId: session.characterId,240
tileX: message.tileX | 0,241
tileY: message.tileY | 0242
});243
break;235
case MessageType.cancelGather:244
case MessageType.cancelGather:236
requirePlaying(session);245
requirePlaying(session);237
simulation.enqueue(session.id, {246
simulation.enqueue(session.id, {@@ -425,6 +434,48 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,425
npcEntityId: message.npcEntityId | 0434
npcEntityId: message.npcEntityId | 0426
});435
});427
break;436
break;437
case MessageType.openMarket:438
requirePlaying(session);439
simulation.enqueue(session.id, {440
type: "open-market",441
characterId: session.characterId442
});443
break;444
case MessageType.closeMarket:445
requirePlaying(session);446
simulation.enqueue(session.id, {447
type: "close-market",448
characterId: session.characterId449
});450
break;451
case MessageType.placeMarketSell:452
requirePlaying(session);453
simulation.enqueue(session.id, {454
type: "place-market-sell",455
characterId: session.characterId,456
slotIndex: message.slotIndex | 0,457
quantity: message.quantity | 0 || 1,458
minUnitPrice: message.minUnitPrice | 0459
});460
break;461
case MessageType.placeMarketBuy:462
requirePlaying(session);463
simulation.enqueue(session.id, {464
type: "place-market-buy",465
characterId: session.characterId,466
itemId: message.itemId | 0,467
quantity: message.quantity | 0 || 1,468
maxUnitPrice: message.maxUnitPrice | 0469
});470
break;471
case MessageType.cancelMarketOrder:472
requirePlaying(session);473
simulation.enqueue(session.id, {474
type: "cancel-market-order",475
characterId: session.characterId,476
orderId: message.orderId | 0477
});478
break;428
case MessageType.follow:479
case MessageType.follow:429
requirePlaying(session);480
requirePlaying(session);430
simulation.enqueue(session.id, {481
simulation.enqueue(session.id, {@@ -889,6 +940,47 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,889
}940
}890
continue;941
continue;891
}942
}943
if (event.type === "market-open")944
{945
const session = sessions.get(event.sessionId);946
if (session)947
{948
send(session, {949
type: MessageType.marketOpen,950
displayName: event.displayName,951
orders: event.orders ?? [],952
catalog: event.catalog ?? []953
});954
}955
continue;956
}957
if (event.type === "market-closed")958
{959
const session = sessions.get(event.sessionId);960
if (session)961
{ send(session, { type: MessageType.marketClosed }); }962
continue;963
}964
if (event.type === "market-trade")965
{966
for (const session of sessions.values())967
{968
if (969
session.characterId === event.buyerCharacterId970
|| session.characterId === event.sellerCharacterId971
)972
{973
send(session, {974
type: MessageType.marketTrade,975
itemId: event.itemId,976
quantity: event.quantity,977
unitPrice: event.unitPrice,978
triggeringSide: event.triggeringSide979
});980
}981
}982
continue;983
}892
if (event.type === "item-bubble")984
if (event.type === "item-bubble")893
{985
{894
broadcastItemBubble(986
broadcastItemBubble(@@ -1022,14 +1114,29 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1022
{1114
{1023
if (!seesTo && !seesFrom)1115
if (!seesTo && !seesFrom)1024
{ continue; }1116
{ continue; }1025
send(session, {1117
if (event.type === "gather-swing")1026
type: MessageType.tileShove,1118
{1027
attackerId: event.attackerId,1119
send(session, {1028
tileX: event.tileX,1120
type: MessageType.gatherSwing,1029
tileY: event.tileY,1121
attackerId: event.attackerId,1030
fromTileX: event.fromTileX,1122
tileX: event.tileX,1031
fromTileY: event.fromTileY1123
tileY: event.tileY,1032
});1124
fromTileX: event.fromTileX,1125
fromTileY: event.fromTileY,1126
toolItemId: event.toolItemId ?? null1127
});1128
}1129
else1130
{1131
send(session, {1132
type: MessageType.tileShove,1133
attackerId: event.attackerId,1134
tileX: event.tileX,1135
tileY: event.tileY,1136
fromTileX: event.fromTileX,1137
fromTileY: event.fromTileY1138
});1139
}1033
continue;1140
continue;1034
}1141
}1035
if (event.type === "chunk-delta")1142
if (event.type === "chunk-delta")@@ -1,5 +1,5 @@
1
1
import { Component } from "../ecs/components.js";
2
import { BlockType } from "../../../shared/definitions/tiles.js";
2
import { BlockType, woodTierForTreeBlock, isChopableTreeBlock } from "../../../shared/definitions/tiles.js";
3
3
import { itemDefinition } from "../../../shared/definitions/items.js";
4
4
import { SkillId } from "../../../shared/definitions/skills.js";
5
5
import {
@@ -10,10 +10,17 @@ import {
10
10
oreExhaustDurationMs,
11
11
oreBoulderState,
12
12
EXHAUSTED_ORE_BOULDER_STATE,
13
resolveMiningPickaxe
13
resolveMiningPickaxe,
14
resolveWoodcuttingAxe,
15
woodcuttingDurationMs,
16
woodcuttingXpForWood,
17
treeExhaustDurationMs,
18
logItemIdForWoodTier
14
19
} from "../../../shared/definitions/gathering.js";
15
20
import { insertStack } from "../../../shared/items/inventory.js";
21
import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
16
22
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
23
import { seasonIdAt, treeStumpStateForSeason, SeasonId } from "../../../shared/world/season.js";
17
24
import { bagView } from "../items/bags.js";
18
25
import { chebyshev, clearEngage } from "../combat/service.js";
19
26
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
@@ -28,6 +35,13 @@ function userError (message)
28
35
return error;
29
36
}
30
37
38
function characterDisplayName (world, handle)
39
{
40
const appearance = world.ecs.get(handle, Component.appearance);
41
const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
42
return name || "someone";
43
}
44
31
45
function ensureOreRespawns (world)
32
46
{
33
47
if (!world.oreRespawns)
@@ -35,13 +49,20 @@ function ensureOreRespawns (world)
35
49
return world.oreRespawns;
36
50
}
37
51
52
function ensureTreeRespawns (world)
53
{
54
if (!world.treeRespawns)
55
{ world.treeRespawns = new Map(); }
56
return world.treeRespawns;
57
}
58
38
59
function blockAt (world, tileX, tileY)
39
60
{
40
61
const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
41
62
return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
42
63
}
43
64
44
function setBoulderState (world, tileX, tileY, state)
65
function setBlockState (world, tileX, tileY, typeId, state)
45
66
{
46
67
const chunkX = tileToChunk(tileX);
47
68
const chunkY = tileToChunk(tileY);
@@ -50,7 +71,7 @@ function setBoulderState (world, tileX, tileY, state)
50
71
const data = world.chunkData(chunkX, chunkY);
51
72
const index = localY * CHUNK_SIZE + localX;
52
73
const prev = data?.blocks?.[index];
53
if (!prev || prev.typeId !== BlockType.boulder)
74
if (!prev || prev.typeId !== typeId)
54
75
{ return null; }
55
76
const block = { typeId: prev.typeId, state, config: prev.config ?? null };
56
77
data.blocks[index] = block;
@@ -66,6 +87,16 @@ function setBoulderState (world, tileX, tileY, state)
66
87
};
67
88
}
68
89
90
function setBoulderState (world, tileX, tileY, state)
91
{
92
return setBlockState(world, tileX, tileY, BlockType.boulder, state);
93
}
94
95
function setTreeState (world, tileX, tileY, typeId, state)
96
{
97
return setBlockState(world, tileX, tileY, typeId, state);
98
}
99
69
100
function pickaxeForOre (world, handle, materialId)
70
101
{
71
102
const inventory = world.ecs.get(handle, Component.inventory);
@@ -79,6 +110,19 @@ function pickaxeForOre (world, handle, materialId)
79
110
});
80
111
}
81
112
113
function axeForWood (world, handle, woodTier)
114
{
115
const inventory = world.ecs.get(handle, Component.inventory);
116
const equipment = world.ecs.get(handle, Component.equipment);
117
const skills = world.ecs.get(handle, Component.skills);
118
return resolveWoodcuttingAxe({
119
inventorySlots: inventory?.slots,
120
equipmentSlots: equipment?.slots,
121
skills,
122
woodTier
123
});
124
}
125
82
126
function clearGather (ecs, handle)
83
127
{
84
128
if (ecs.has(handle, Component.gather))
@@ -104,6 +148,20 @@ export function clearOreRespawnsForChunk (world, chunkX, chunkY)
104
148
}
105
149
}
106
150
151
/** Drop scheduled tree respawns when authored chunk data is replaced or unloaded. */
152
export function clearTreeRespawnsForChunk (world, chunkX, chunkY)
153
{
154
const respawns = world.treeRespawns;
155
if (!respawns?.size)
156
{ return; }
157
for (const key of [...respawns.keys()])
158
{
159
const [tileX, tileY] = key.split(",").map(Number);
160
if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
161
{ respawns.delete(key); }
162
}
163
}
164
107
165
/**
108
166
* Restore exhausted ore boulders whose timers have elapsed.
109
167
*/
@@ -125,6 +183,59 @@ export function stepOreRespawns (world, now)
125
183
return { events };
126
184
}
127
185
186
/**
187
* Restore exhausted trees whose timers have elapsed (live seasonal look).
188
*/
189
export function stepTreeRespawns (world, now)
190
{
191
const respawns = world.treeRespawns;
192
if (!respawns?.size)
193
{ return { events: [] }; }
194
const events = [];
195
for (const [key, entry] of [...respawns.entries()])
196
{
197
if (now < entry.respawnsAt)
198
{ continue; }
199
respawns.delete(key);
200
const delta = setTreeState(
201
world,
202
entry.tileX,
203
entry.tileY,
204
entry.typeId,
205
SeasonId.summer
206
);
207
if (delta)
208
{ events.push(delta); }
209
}
210
return { events };
211
}
212
213
function beginGatherSwing (world, handle, entityId, position, gatherFields, now)
214
{
215
clearEngage(world.ecs, entityId);
216
const path = world.ecs.get(handle, Component.path);
217
if (path)
218
{ path.tiles = []; }
219
world.ecs.add(handle, Component.gather, {
220
...gatherFields,
221
startedAt: now,
222
finishesAt: now + gatherFields.durationMs,
223
nextSwingAt: now
224
});
225
return {
226
events: [{
227
type: "gather-swing",
228
attackerId: entityId,
229
tileX: gatherFields.tileX,
230
tileY: gatherFields.tileY,
231
fromTileX: position.tileX,
232
fromTileY: position.tileY,
233
toolItemId: gatherFields.toolItemId ?? null,
234
swipe: false
235
}]
236
};
237
}
238
128
239
/**
129
240
* Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.
130
241
*/
@@ -149,52 +260,224 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)
149
260
{ throw userError("There is nothing to mine there."); }
150
261
const materialId = materialFromOreBoulderState(block.state);
151
262
if (!materialId)
152
{ throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE
153
? "That rock is exhausted."
154
: "That rock has no ore."); }
263
{
264
throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE
265
? "That rock is exhausted."
266
: "That rock has no ore.");
267
}
155
268
156
269
const pickaxe = pickaxeForOre(world, handle, materialId);
157
270
if (!pickaxe.ok)
158
271
{ throw userError(pickaxe.reason); }
159
272
160
273
const durationMs = miningDurationMs(materialId, pickaxe.tool.tier);
161
clearEngage(world.ecs, entityId);
162
const path = world.ecs.get(handle, Component.path);
163
if (path)
164
{ path.tiles = []; }
165
274
const toolItemId = pickaxe.tool.stack?.itemId ?? null;
166
world.ecs.add(handle, Component.gather, {
275
return beginGatherSwing(world, handle, entityId, position, {
167
276
kind: "mining",
168
277
tileX,
169
278
tileY,
170
279
materialId,
171
280
toolTier: pickaxe.tool.tier,
172
281
toolItemId,
173
startedAt: now,
174
finishesAt: now + durationMs,
175
nextSwingAt: now
282
durationMs
283
}, now);
284
}
285
286
/**
287
* Start chopping a tree. Completes via stepGather (stump + log + woodcutting XP).
288
*/
289
export function startChop (world, sessionId, characterId, tileX, tileY, now)
290
{
291
const entityId = world.characterEntities.get(characterId);
292
if (entityId == null)
293
{ throw userError("Character is not in the world."); }
294
const handle = world.ecs.handleOf(entityId);
295
const identity = world.ecs.get(handle, Component.networkIdentity);
296
if (!identity || identity.sessionId !== sessionId)
297
{ throw userError("Character is not in the world."); }
298
if (world.ecs.has(handle, Component.dead))
299
{ throw userError("You are dead."); }
300
301
const position = world.ecs.get(handle, Component.position);
302
if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
303
{ throw userError("You need to stand next to the tree."); }
304
305
const block = blockAt(world, tileX, tileY);
306
if (!isChopableTreeBlock(block))
307
{
308
throw userError(block && woodTierForTreeBlock(block.typeId) != null
309
? "That tree is already felled."
310
: "There is nothing to chop there.");
311
}
312
const woodTier = woodTierForTreeBlock(block.typeId);
313
const axe = axeForWood(world, handle, woodTier);
314
if (!axe.ok)
315
{ throw userError(axe.reason); }
316
317
const durationMs = woodcuttingDurationMs(woodTier, axe.tool.tier);
318
const toolItemId = axe.tool.stack?.itemId ?? null;
319
return beginGatherSwing(world, handle, entityId, position, {
320
kind: "woodcutting",
321
tileX,
322
tileY,
323
typeId: block.typeId,
324
woodTier,
325
toolTier: axe.tool.tier,
326
toolItemId,
327
durationMs
328
}, now);
329
}
330
331
function pushBagUpdate (events, privates, world, handle, character, skillsChanged, skills)
332
{
333
privates.push({
334
characterId: character.characterId,
335
bag: bagView(world.ecs, handle)
176
336
});
337
if (skillsChanged)
338
{
339
events.push({
340
type: "skills-updated",
341
characterId: character.characterId,
342
skills: publicSkillsView(skills),
343
stored: storedSkillXp(skills)
344
});
345
}
346
}
177
347
178
return {
179
events: [{
180
type: "gather-swing",
181
attackerId: entityId,
182
tileX,
183
tileY,
184
fromTileX: position.tileX,
185
fromTileY: position.tileY,
186
toolItemId,
187
swipe: false
188
}]
189
};
348
function completeMining (world, handle, entityId, character, gather, events, privates, now)
349
{
350
const oreItemId = oreItemIdForMaterial(gather.materialId);
351
const def = itemDefinition(oreItemId);
352
const inventory = world.ecs.get(handle, Component.inventory);
353
if (!oreItemId || !def || !inventory)
354
{
355
clearGather(world.ecs, handle);
356
return;
357
}
358
const origin = gatherOrigin(GatherOriginVerb.mined, characterDisplayName(world, handle));
359
const stack = attachOrigins({
360
itemId: oreItemId,
361
quantity: 1,
362
origins: [{ origin, quantity: 1 }]
363
});
364
const inserted = insertStack(inventory.slots, stack, def);
365
if (!inserted.ok || inserted.remainder > 0)
366
{
367
clearGather(world.ecs, handle);
368
events.push({
369
type: "command-error",
370
sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
371
message: "Your inventory is full."
372
});
373
return;
374
}
375
inventory.slots = inserted.slots;
376
377
const skills = world.ecs.get(handle, Component.skills);
378
let skillsChanged = false;
379
if (skills?.xp && addSkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)))
380
{ skillsChanged = true; }
381
382
const exhausted = setBoulderState(
383
world,
384
gather.tileX,
385
gather.tileY,
386
EXHAUSTED_ORE_BOULDER_STATE
387
);
388
if (exhausted)
389
{
390
events.push(exhausted);
391
ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
392
tileX: gather.tileX,
393
tileY: gather.tileY,
394
materialId: gather.materialId,
395
respawnsAt: now + oreExhaustDurationMs(gather.materialId)
396
});
397
}
398
399
clearGather(world.ecs, handle);
400
pushBagUpdate(events, privates, world, handle, character, skillsChanged, skills);
401
events.push({
402
type: "gather-complete",
403
characterId: character.characterId,
404
kind: "mining",
405
materialId: gather.materialId,
406
itemId: oreItemId
407
});
408
}
409
410
function completeWoodcutting (world, handle, entityId, character, gather, events, privates, now)
411
{
412
const logItemId = logItemIdForWoodTier(gather.woodTier);
413
const def = itemDefinition(logItemId);
414
const inventory = world.ecs.get(handle, Component.inventory);
415
if (!logItemId || !def || !inventory)
416
{
417
clearGather(world.ecs, handle);
418
return;
419
}
420
const origin = gatherOrigin(GatherOriginVerb.felled, characterDisplayName(world, handle));
421
const stack = attachOrigins({
422
itemId: logItemId,
423
quantity: 1,
424
origins: [{ origin, quantity: 1 }]
425
});
426
const inserted = insertStack(inventory.slots, stack, def);
427
if (!inserted.ok || inserted.remainder > 0)
428
{
429
clearGather(world.ecs, handle);
430
events.push({
431
type: "command-error",
432
sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
433
message: "Your inventory is full."
434
});
435
return;
436
}
437
inventory.slots = inserted.slots;
438
439
const skills = world.ecs.get(handle, Component.skills);
440
let skillsChanged = false;
441
if (skills?.xp && addSkillXp(skills, SkillId.woodcutting, woodcuttingXpForWood(gather.woodTier)))
442
{ skillsChanged = true; }
443
444
const stumpState = treeStumpStateForSeason(seasonIdAt(now));
445
const exhausted = setTreeState(
446
world,
447
gather.tileX,
448
gather.tileY,
449
gather.typeId,
450
stumpState
451
);
452
if (exhausted)
453
{
454
events.push(exhausted);
455
ensureTreeRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
456
tileX: gather.tileX,
457
tileY: gather.tileY,
458
typeId: gather.typeId,
459
woodTier: gather.woodTier,
460
respawnsAt: now + treeExhaustDurationMs(gather.woodTier)
461
});
462
}
463
464
clearGather(world.ecs, handle);
465
pushBagUpdate(events, privates, world, handle, character, skillsChanged, skills);
466
events.push({
467
type: "gather-complete",
468
characterId: character.characterId,
469
kind: "woodcutting",
470
woodTier: gather.woodTier,
471
itemId: logItemId
472
});
190
473
}
191
474
192
475
export function stepGather (world, now)
193
476
{
194
477
const events = [];
195
478
const privates = [];
196
const respawnEvents = stepOreRespawns(world, now);
197
events.push(...respawnEvents.events);
479
events.push(...stepOreRespawns(world, now).events);
480
events.push(...stepTreeRespawns(world, now).events);
198
481
199
482
for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
200
483
{
@@ -210,8 +493,25 @@ export function stepGather (world, now)
210
493
continue;
211
494
}
212
495
const block = blockAt(world, gather.tileX, gather.tileY);
213
if (!block || block.typeId !== BlockType.boulder
214
|| materialFromOreBoulderState(block.state) !== gather.materialId)
496
497
if (gather.kind === "mining")
498
{
499
if (!block || block.typeId !== BlockType.boulder
500
|| materialFromOreBoulderState(block.state) !== gather.materialId)
501
{
502
clearGather(world.ecs, handle);
503
continue;
504
}
505
}
506
else if (gather.kind === "woodcutting")
507
{
508
if (!block || block.typeId !== gather.typeId || !isChopableTreeBlock(block))
509
{
510
clearGather(world.ecs, handle);
511
continue;
512
}
513
}
514
else
215
515
{
216
516
clearGather(world.ecs, handle);
217
517
continue;
@@ -235,70 +535,10 @@ export function stepGather (world, now)
235
535
if (now < gather.finishesAt)
236
536
{ continue; }
237
537
238
const oreItemId = oreItemIdForMaterial(gather.materialId);
239
const def = itemDefinition(oreItemId);
240
const inventory = world.ecs.get(handle, Component.inventory);
241
if (!oreItemId || !def || !inventory)
242
{
243
clearGather(world.ecs, handle);
244
continue;
245
}
246
const inserted = insertStack(inventory.slots, { itemId: oreItemId, quantity: 1 }, def);
247
if (!inserted.ok || inserted.remainder > 0)
248
{
249
clearGather(world.ecs, handle);
250
events.push({
251
type: "command-error",
252
sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
253
message: "Your inventory is full."
254
});
255
continue;
256
}
257
inventory.slots = inserted.slots;
258
259
const skills = world.ecs.get(handle, Component.skills);
260
let skillsChanged = false;
261
if (skills?.xp && addSkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)))
262
{ skillsChanged = true; }
263
264
const exhausted = setBoulderState(
265
world,
266
gather.tileX,
267
gather.tileY,
268
EXHAUSTED_ORE_BOULDER_STATE
269
);
270
if (exhausted)
271
{
272
events.push(exhausted);
273
ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
274
tileX: gather.tileX,
275
tileY: gather.tileY,
276
materialId: gather.materialId,
277
respawnsAt: now + oreExhaustDurationMs(gather.materialId)
278
});
279
}
280
281
clearGather(world.ecs, handle);
282
privates.push({
283
characterId: character.characterId,
284
bag: bagView(world.ecs, handle)
285
});
286
if (skillsChanged)
287
{
288
events.push({
289
type: "skills-updated",
290
characterId: character.characterId,
291
skills: publicSkillsView(skills),
292
stored: storedSkillXp(skills)
293
});
294
}
295
events.push({
296
type: "gather-complete",
297
characterId: character.characterId,
298
kind: "mining",
299
materialId: gather.materialId,
300
itemId: oreItemId
301
});
538
if (gather.kind === "mining")
539
{ completeMining(world, handle, entityId, character, gather, events, privates, now); }
540
else
541
{ completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }
302
542
}
303
543
return { events, privates };
304
544
}
@@ -309,6 +549,8 @@ export function handleGatherCommand (world, sessionId, command, now)
309
549
{
310
550
case "mine":
311
551
return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
552
case "chop":
553
return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
312
554
case "cancel-gather":
313
555
{
314
556
const entityId = world.characterEntities.get(command.characterId);
@@ -1,5 +1,5 @@1
import { Component } from "../ecs/components.js";1
import { Component } from "../ecs/components.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";2
import { BlockType, woodTierForTreeBlock, isChopableTreeBlock } from "../../../shared/definitions/tiles.js";3
import { itemDefinition } from "../../../shared/definitions/items.js";3
import { itemDefinition } from "../../../shared/definitions/items.js";4
import { SkillId } from "../../../shared/definitions/skills.js";4
import { SkillId } from "../../../shared/definitions/skills.js";5
import {5
import {@@ -10,10 +10,17 @@ import {10
oreExhaustDurationMs,10
oreExhaustDurationMs,11
oreBoulderState,11
oreBoulderState,12
EXHAUSTED_ORE_BOULDER_STATE,12
EXHAUSTED_ORE_BOULDER_STATE,13
resolveMiningPickaxe13
resolveMiningPickaxe,14
resolveWoodcuttingAxe,15
woodcuttingDurationMs,16
woodcuttingXpForWood,17
treeExhaustDurationMs,18
logItemIdForWoodTier14
} from "../../../shared/definitions/gathering.js";19
} from "../../../shared/definitions/gathering.js";15
import { insertStack } from "../../../shared/items/inventory.js";20
import { insertStack } from "../../../shared/items/inventory.js";21
import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";16
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";22
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";23
import { seasonIdAt, treeStumpStateForSeason, SeasonId } from "../../../shared/world/season.js";17
import { bagView } from "../items/bags.js";24
import { bagView } from "../items/bags.js";18
import { chebyshev, clearEngage } from "../combat/service.js";25
import { chebyshev, clearEngage } from "../combat/service.js";19
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";26
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";@@ -28,6 +35,13 @@ function userError (message)28
return error;35
return error;29
}36
}30
37
38
function characterDisplayName (world, handle)39
{40
const appearance = world.ecs.get(handle, Component.appearance);41
const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();42
return name || "someone";43
}44
31
function ensureOreRespawns (world)45
function ensureOreRespawns (world)32
{46
{33
if (!world.oreRespawns)47
if (!world.oreRespawns)@@ -35,13 +49,20 @@ function ensureOreRespawns (world)35
return world.oreRespawns;49
return world.oreRespawns;36
}50
}37
51
52
function ensureTreeRespawns (world)53
{54
if (!world.treeRespawns)55
{ world.treeRespawns = new Map(); }56
return world.treeRespawns;57
}58
38
function blockAt (world, tileX, tileY)59
function blockAt (world, tileX, tileY)39
{60
{40
const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));61
const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));41
return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;62
return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;42
}63
}43
64
44
function setBoulderState (world, tileX, tileY, state)65
function setBlockState (world, tileX, tileY, typeId, state)45
{66
{46
const chunkX = tileToChunk(tileX);67
const chunkX = tileToChunk(tileX);47
const chunkY = tileToChunk(tileY);68
const chunkY = tileToChunk(tileY);@@ -50,7 +71,7 @@ function setBoulderState (world, tileX, tileY, state)50
const data = world.chunkData(chunkX, chunkY);71
const data = world.chunkData(chunkX, chunkY);51
const index = localY * CHUNK_SIZE + localX;72
const index = localY * CHUNK_SIZE + localX;52
const prev = data?.blocks?.[index];73
const prev = data?.blocks?.[index];53
if (!prev || prev.typeId !== BlockType.boulder)74
if (!prev || prev.typeId !== typeId)54
{ return null; }75
{ return null; }55
const block = { typeId: prev.typeId, state, config: prev.config ?? null };76
const block = { typeId: prev.typeId, state, config: prev.config ?? null };56
data.blocks[index] = block;77
data.blocks[index] = block;@@ -66,6 +87,16 @@ function setBoulderState (world, tileX, tileY, state)66
};87
};67
}88
}68
89
90
function setBoulderState (world, tileX, tileY, state)91
{92
return setBlockState(world, tileX, tileY, BlockType.boulder, state);93
}94
95
function setTreeState (world, tileX, tileY, typeId, state)96
{97
return setBlockState(world, tileX, tileY, typeId, state);98
}99
69
function pickaxeForOre (world, handle, materialId)100
function pickaxeForOre (world, handle, materialId)70
{101
{71
const inventory = world.ecs.get(handle, Component.inventory);102
const inventory = world.ecs.get(handle, Component.inventory);@@ -79,6 +110,19 @@ function pickaxeForOre (world, handle, materialId)79
});110
});80
}111
}81
112
113
function axeForWood (world, handle, woodTier)114
{115
const inventory = world.ecs.get(handle, Component.inventory);116
const equipment = world.ecs.get(handle, Component.equipment);117
const skills = world.ecs.get(handle, Component.skills);118
return resolveWoodcuttingAxe({119
inventorySlots: inventory?.slots,120
equipmentSlots: equipment?.slots,121
skills,122
woodTier123
});124
}125
82
function clearGather (ecs, handle)126
function clearGather (ecs, handle)83
{127
{84
if (ecs.has(handle, Component.gather))128
if (ecs.has(handle, Component.gather))@@ -104,6 +148,20 @@ export function clearOreRespawnsForChunk (world, chunkX, chunkY)104
}148
}105
}149
}106
150
151
/** Drop scheduled tree respawns when authored chunk data is replaced or unloaded. */152
export function clearTreeRespawnsForChunk (world, chunkX, chunkY)153
{154
const respawns = world.treeRespawns;155
if (!respawns?.size)156
{ return; }157
for (const key of [...respawns.keys()])158
{159
const [tileX, tileY] = key.split(",").map(Number);160
if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)161
{ respawns.delete(key); }162
}163
}164
107
/**165
/**108
* Restore exhausted ore boulders whose timers have elapsed.166
* Restore exhausted ore boulders whose timers have elapsed.109
*/167
*/@@ -125,6 +183,59 @@ export function stepOreRespawns (world, now)125
return { events };183
return { events };126
}184
}127
185
186
/**187
* Restore exhausted trees whose timers have elapsed (live seasonal look).188
*/189
export function stepTreeRespawns (world, now)190
{191
const respawns = world.treeRespawns;192
if (!respawns?.size)193
{ return { events: [] }; }194
const events = [];195
for (const [key, entry] of [...respawns.entries()])196
{197
if (now < entry.respawnsAt)198
{ continue; }199
respawns.delete(key);200
const delta = setTreeState(201
world,202
entry.tileX,203
entry.tileY,204
entry.typeId,205
SeasonId.summer206
);207
if (delta)208
{ events.push(delta); }209
}210
return { events };211
}212
213
function beginGatherSwing (world, handle, entityId, position, gatherFields, now)214
{215
clearEngage(world.ecs, entityId);216
const path = world.ecs.get(handle, Component.path);217
if (path)218
{ path.tiles = []; }219
world.ecs.add(handle, Component.gather, {220
...gatherFields,221
startedAt: now,222
finishesAt: now + gatherFields.durationMs,223
nextSwingAt: now224
});225
return {226
events: [{227
type: "gather-swing",228
attackerId: entityId,229
tileX: gatherFields.tileX,230
tileY: gatherFields.tileY,231
fromTileX: position.tileX,232
fromTileY: position.tileY,233
toolItemId: gatherFields.toolItemId ?? null,234
swipe: false235
}]236
};237
}238
128
/**239
/**129
* Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.240
* Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.130
*/241
*/@@ -149,52 +260,224 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)149
{ throw userError("There is nothing to mine there."); }260
{ throw userError("There is nothing to mine there."); }150
const materialId = materialFromOreBoulderState(block.state);261
const materialId = materialFromOreBoulderState(block.state);151
if (!materialId)262
if (!materialId)152
{ throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE263
{153
? "That rock is exhausted."264
throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE154
: "That rock has no ore."); }265
? "That rock is exhausted."266
: "That rock has no ore.");267
}155
268
156
const pickaxe = pickaxeForOre(world, handle, materialId);269
const pickaxe = pickaxeForOre(world, handle, materialId);157
if (!pickaxe.ok)270
if (!pickaxe.ok)158
{ throw userError(pickaxe.reason); }271
{ throw userError(pickaxe.reason); }159
272
160
const durationMs = miningDurationMs(materialId, pickaxe.tool.tier);273
const durationMs = miningDurationMs(materialId, pickaxe.tool.tier);161
clearEngage(world.ecs, entityId);162
const path = world.ecs.get(handle, Component.path);163
if (path)164
{ path.tiles = []; }165
const toolItemId = pickaxe.tool.stack?.itemId ?? null;274
const toolItemId = pickaxe.tool.stack?.itemId ?? null;166
world.ecs.add(handle, Component.gather, {275
return beginGatherSwing(world, handle, entityId, position, {167
kind: "mining",276
kind: "mining",168
tileX,277
tileX,169
tileY,278
tileY,170
materialId,279
materialId,171
toolTier: pickaxe.tool.tier,280
toolTier: pickaxe.tool.tier,172
toolItemId,281
toolItemId,173
startedAt: now,282
durationMs174
finishesAt: now + durationMs,283
}, now);175
nextSwingAt: now284
}285
286
/**287
* Start chopping a tree. Completes via stepGather (stump + log + woodcutting XP).288
*/289
export function startChop (world, sessionId, characterId, tileX, tileY, now)290
{291
const entityId = world.characterEntities.get(characterId);292
if (entityId == null)293
{ throw userError("Character is not in the world."); }294
const handle = world.ecs.handleOf(entityId);295
const identity = world.ecs.get(handle, Component.networkIdentity);296
if (!identity || identity.sessionId !== sessionId)297
{ throw userError("Character is not in the world."); }298
if (world.ecs.has(handle, Component.dead))299
{ throw userError("You are dead."); }300
301
const position = world.ecs.get(handle, Component.position);302
if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)303
{ throw userError("You need to stand next to the tree."); }304
305
const block = blockAt(world, tileX, tileY);306
if (!isChopableTreeBlock(block))307
{308
throw userError(block && woodTierForTreeBlock(block.typeId) != null309
? "That tree is already felled."310
: "There is nothing to chop there.");311
}312
const woodTier = woodTierForTreeBlock(block.typeId);313
const axe = axeForWood(world, handle, woodTier);314
if (!axe.ok)315
{ throw userError(axe.reason); }316
317
const durationMs = woodcuttingDurationMs(woodTier, axe.tool.tier);318
const toolItemId = axe.tool.stack?.itemId ?? null;319
return beginGatherSwing(world, handle, entityId, position, {320
kind: "woodcutting",321
tileX,322
tileY,323
typeId: block.typeId,324
woodTier,325
toolTier: axe.tool.tier,326
toolItemId,327
durationMs328
}, now);329
}330
331
function pushBagUpdate (events, privates, world, handle, character, skillsChanged, skills)332
{333
privates.push({334
characterId: character.characterId,335
bag: bagView(world.ecs, handle)176
});336
});337
if (skillsChanged)338
{339
events.push({340
type: "skills-updated",341
characterId: character.characterId,342
skills: publicSkillsView(skills),343
stored: storedSkillXp(skills)344
});345
}346
}177
347
178
return {348
function completeMining (world, handle, entityId, character, gather, events, privates, now)179
events: [{349
{180
type: "gather-swing",350
const oreItemId = oreItemIdForMaterial(gather.materialId);181
attackerId: entityId,351
const def = itemDefinition(oreItemId);182
tileX,352
const inventory = world.ecs.get(handle, Component.inventory);183
tileY,353
if (!oreItemId || !def || !inventory)184
fromTileX: position.tileX,354
{185
fromTileY: position.tileY,355
clearGather(world.ecs, handle);186
toolItemId,356
return;187
swipe: false357
}188
}]358
const origin = gatherOrigin(GatherOriginVerb.mined, characterDisplayName(world, handle));189
};359
const stack = attachOrigins({360
itemId: oreItemId,361
quantity: 1,362
origins: [{ origin, quantity: 1 }]363
});364
const inserted = insertStack(inventory.slots, stack, def);365
if (!inserted.ok || inserted.remainder > 0)366
{367
clearGather(world.ecs, handle);368
events.push({369
type: "command-error",370
sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,371
message: "Your inventory is full."372
});373
return;374
}375
inventory.slots = inserted.slots;376
377
const skills = world.ecs.get(handle, Component.skills);378
let skillsChanged = false;379
if (skills?.xp && addSkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)))380
{ skillsChanged = true; }381
382
const exhausted = setBoulderState(383
world,384
gather.tileX,385
gather.tileY,386
EXHAUSTED_ORE_BOULDER_STATE387
);388
if (exhausted)389
{390
events.push(exhausted);391
ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {392
tileX: gather.tileX,393
tileY: gather.tileY,394
materialId: gather.materialId,395
respawnsAt: now + oreExhaustDurationMs(gather.materialId)396
});397
}398
399
clearGather(world.ecs, handle);400
pushBagUpdate(events, privates, world, handle, character, skillsChanged, skills);401
events.push({402
type: "gather-complete",403
characterId: character.characterId,404
kind: "mining",405
materialId: gather.materialId,406
itemId: oreItemId407
});408
}409
410
function completeWoodcutting (world, handle, entityId, character, gather, events, privates, now)411
{412
const logItemId = logItemIdForWoodTier(gather.woodTier);413
const def = itemDefinition(logItemId);414
const inventory = world.ecs.get(handle, Component.inventory);415
if (!logItemId || !def || !inventory)416
{417
clearGather(world.ecs, handle);418
return;419
}420
const origin = gatherOrigin(GatherOriginVerb.felled, characterDisplayName(world, handle));421
const stack = attachOrigins({422
itemId: logItemId,423
quantity: 1,424
origins: [{ origin, quantity: 1 }]425
});426
const inserted = insertStack(inventory.slots, stack, def);427
if (!inserted.ok || inserted.remainder > 0)428
{429
clearGather(world.ecs, handle);430
events.push({431
type: "command-error",432
sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,433
message: "Your inventory is full."434
});435
return;436
}437
inventory.slots = inserted.slots;438
439
const skills = world.ecs.get(handle, Component.skills);440
let skillsChanged = false;441
if (skills?.xp && addSkillXp(skills, SkillId.woodcutting, woodcuttingXpForWood(gather.woodTier)))442
{ skillsChanged = true; }443
444
const stumpState = treeStumpStateForSeason(seasonIdAt(now));445
const exhausted = setTreeState(446
world,447
gather.tileX,448
gather.tileY,449
gather.typeId,450
stumpState451
);452
if (exhausted)453
{454
events.push(exhausted);455
ensureTreeRespawns(world).set(tileKey(gather.tileX, gather.tileY), {456
tileX: gather.tileX,457
tileY: gather.tileY,458
typeId: gather.typeId,459
woodTier: gather.woodTier,460
respawnsAt: now + treeExhaustDurationMs(gather.woodTier)461
});462
}463
464
clearGather(world.ecs, handle);465
pushBagUpdate(events, privates, world, handle, character, skillsChanged, skills);466
events.push({467
type: "gather-complete",468
characterId: character.characterId,469
kind: "woodcutting",470
woodTier: gather.woodTier,471
itemId: logItemId472
});190
}473
}191
474
192
export function stepGather (world, now)475
export function stepGather (world, now)193
{476
{194
const events = [];477
const events = [];195
const privates = [];478
const privates = [];196
const respawnEvents = stepOreRespawns(world, now);479
events.push(...stepOreRespawns(world, now).events);197
events.push(...respawnEvents.events);480
events.push(...stepTreeRespawns(world, now).events);198
481
199
for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))482
for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))200
{483
{@@ -210,8 +493,25 @@ export function stepGather (world, now)210
continue;493
continue;211
}494
}212
const block = blockAt(world, gather.tileX, gather.tileY);495
const block = blockAt(world, gather.tileX, gather.tileY);213
if (!block || block.typeId !== BlockType.boulder496
214
|| materialFromOreBoulderState(block.state) !== gather.materialId)497
if (gather.kind === "mining")498
{499
if (!block || block.typeId !== BlockType.boulder500
|| materialFromOreBoulderState(block.state) !== gather.materialId)501
{502
clearGather(world.ecs, handle);503
continue;504
}505
}506
else if (gather.kind === "woodcutting")507
{508
if (!block || block.typeId !== gather.typeId || !isChopableTreeBlock(block))509
{510
clearGather(world.ecs, handle);511
continue;512
}513
}514
else215
{515
{216
clearGather(world.ecs, handle);516
clearGather(world.ecs, handle);217
continue;517
continue;@@ -235,70 +535,10 @@ export function stepGather (world, now)235
if (now < gather.finishesAt)535
if (now < gather.finishesAt)236
{ continue; }536
{ continue; }237
537
238
const oreItemId = oreItemIdForMaterial(gather.materialId);538
if (gather.kind === "mining")239
const def = itemDefinition(oreItemId);539
{ completeMining(world, handle, entityId, character, gather, events, privates, now); }240
const inventory = world.ecs.get(handle, Component.inventory);540
else241
if (!oreItemId || !def || !inventory)541
{ completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }242
{243
clearGather(world.ecs, handle);244
continue;245
}246
const inserted = insertStack(inventory.slots, { itemId: oreItemId, quantity: 1 }, def);247
if (!inserted.ok || inserted.remainder > 0)248
{249
clearGather(world.ecs, handle);250
events.push({251
type: "command-error",252
sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,253
message: "Your inventory is full."254
});255
continue;256
}257
inventory.slots = inserted.slots;258
259
const skills = world.ecs.get(handle, Component.skills);260
let skillsChanged = false;261
if (skills?.xp && addSkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)))262
{ skillsChanged = true; }263
264
const exhausted = setBoulderState(265
world,266
gather.tileX,267
gather.tileY,268
EXHAUSTED_ORE_BOULDER_STATE269
);270
if (exhausted)271
{272
events.push(exhausted);273
ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {274
tileX: gather.tileX,275
tileY: gather.tileY,276
materialId: gather.materialId,277
respawnsAt: now + oreExhaustDurationMs(gather.materialId)278
});279
}280
281
clearGather(world.ecs, handle);282
privates.push({283
characterId: character.characterId,284
bag: bagView(world.ecs, handle)285
});286
if (skillsChanged)287
{288
events.push({289
type: "skills-updated",290
characterId: character.characterId,291
skills: publicSkillsView(skills),292
stored: storedSkillXp(skills)293
});294
}295
events.push({296
type: "gather-complete",297
characterId: character.characterId,298
kind: "mining",299
materialId: gather.materialId,300
itemId: oreItemId301
});302
}542
}303
return { events, privates };543
return { events, privates };304
}544
}@@ -309,6 +549,8 @@ export function handleGatherCommand (world, sessionId, command, now)309
{549
{310
case "mine":550
case "mine":311
return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);551
return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);552
case "chop":553
return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);312
case "cancel-gather":554
case "cancel-gather":313
{555
{314
const entityId = world.characterEntities.get(command.characterId);556
const entityId = world.characterEntities.get(command.characterId);@@ -0,0 +1,653 @@
1
import { randomUUID } from "node:crypto";
2
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3
import { BlockType } from "../../../shared/definitions/tiles.js";
4
import { ItemId, itemDefinition, ITEM_DEFINITIONS, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
5
import {
6
addCoinsToSlots,
7
insertStack,
8
insertStackGrowable,
9
normalizeVault,
10
takeCoinsFromSlots,
11
takeFromSlot,
12
cloneStack
13
} from "../../../shared/items/inventory.js";
14
import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js";
15
import { attachOrigins, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js";
16
import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";
17
import {
18
MARKET_ORDER_MAX_AGE_MS,
19
buyFilledLetterBody,
20
midpointTradePrice,
21
orderExpiredLetterBody,
22
orderCancelledLetterBody,
23
pickExchangeClerk,
24
soldLetterBody
25
} from "../../../shared/market/exchange.js";
26
import { decodeChunkBlob } from "../world/chunkData.js";
27
import { withTransaction } from "../persistence/database.js";
28
29
function userError (message)
30
{
31
const error = new Error(message);
32
error.userFacing = true;
33
return error;
34
}
35
36
function chebyshev (ax, ay, bx, by)
37
{
38
return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
39
}
40
41
export class MarketService
42
{
43
constructor ({ stateDb, worldDb, simulation })
44
{
45
this.stateDb = stateDb;
46
this.worldDb = worldDb;
47
this.simulation = simulation;
48
this.marketTiles = [];
49
/** @type {Map<number, object>} */
50
this.lastSales = new Map();
51
this.refreshIndex();
52
this.#loadLastSales();
53
this.#syncLastSalesToWorkers();
54
}
55
56
refreshIndex ()
57
{
58
const revisionId = this.worldDb.getActiveRevisionId();
59
const tiles = [];
60
for (const coord of this.worldDb.listChunkCoords(revisionId))
61
{
62
const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
63
if (!row)
64
{ continue; }
65
const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);
66
for (let localY = 0; localY < CHUNK_SIZE; localY++)
67
{
68
for (let localX = 0; localX < CHUNK_SIZE; localX++)
69
{
70
const block = data.blocks[localY * CHUNK_SIZE + localX];
71
if (block?.typeId !== BlockType.marketplace)
72
{ continue; }
73
tiles.push({
74
tileX: coord.chunk_x * CHUNK_SIZE + localX,
75
tileY: coord.chunk_y * CHUNK_SIZE + localY
76
});
77
}
78
}
79
}
80
this.marketTiles = tiles;
81
}
82
83
nearestMarket (tileX, tileY)
84
{
85
if (!this.marketTiles.length)
86
{ return null; }
87
let best = null;
88
let bestDist = Infinity;
89
for (const tile of this.marketTiles)
90
{
91
const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
92
if (dist < bestDist)
93
{
94
bestDist = dist;
95
best = tile;
96
}
97
}
98
return best;
99
}
100
101
lastSaleFor (itemId)
102
{
103
return this.lastSales.get(itemId | 0) ?? null;
104
}
105
106
snapshot ()
107
{
108
const out = {};
109
for (const [itemId, sale] of this.lastSales.entries())
110
{ out[String(itemId)] = sale; }
111
return out;
112
}
113
114
step (now = Date.now())
115
{
116
const events = [];
117
const expired = this.stateDb.listExpiredMarketOrders(now - MARKET_ORDER_MAX_AGE_MS);
118
for (const order of expired)
119
{
120
try
121
{
122
events.push(...this.#expireOrder(order, now));
123
}
124
catch (error)
125
{
126
console.error("Market order expiry failed", order.orderId, error);
127
}
128
}
129
return events;
130
}
131
132
handleCommand (sessionId, command, now = Date.now())
133
{
134
switch (command.type)
135
{
136
case "open-market":
137
return this.openMarket(sessionId, command.characterId, now);
138
case "place-market-sell":
139
return this.placeSellOrder(
140
sessionId,
141
command.characterId,
142
command.slotIndex | 0,
143
command.quantity | 0 || 1,
144
command.minUnitPrice | 0,
145
now
146
);
147
case "place-market-buy":
148
return this.placeBuyOrder(
149
sessionId,
150
command.characterId,
151
command.itemId | 0,
152
command.quantity | 0 || 1,
153
command.maxUnitPrice | 0,
154
now
155
);
156
case "cancel-market-order":
157
return this.cancelOrder(sessionId, command.characterId, command.orderId | 0, now);
158
case "close-market":
159
return { events: [{ type: "market-closed", sessionId, characterId: command.characterId }] };
160
default:
161
return null;
162
}
163
}
164
165
openMarket (sessionId, characterId, now = Date.now())
166
{
167
const { position } = this.#requireAtMarket(characterId);
168
return {
169
events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
170
};
171
}
172
173
placeSellOrder (sessionId, characterId, slotIndex, quantity, minUnitPrice, now = Date.now())
174
{
175
const { position } = this.#requireAtMarket(characterId);
176
const minPrice = Math.max(1, minUnitPrice | 0);
177
const qty = Math.max(1, quantity | 0 || 1);
178
const bag = this.#loadBag(characterId);
179
const slot = bag.inventory?.[slotIndex];
180
if (!slot)
181
{ throw userError("That slot is empty."); }
182
assertMarketplaceSellable(slot);
183
if ((slot.itemId | 0) === ItemId.coins)
184
{ throw userError("Coins cannot be listed on the marketplace."); }
185
const taken = takeFromSlot(bag.inventory, slotIndex, qty);
186
if (!taken.ok || !taken.taken)
187
{ throw userError("That item is not available."); }
188
bag.inventory = taken.slots;
189
const stack = attachOrigins(taken.taken);
190
const order = this.stateDb.insertMarketOrder({
191
characterId,
192
side: "sell",
193
itemId: stack.itemId,
194
quantity: stack.quantity,
195
limitUnitPrice: minPrice,
196
escrowCoins: 0,
197
escrowStack: stack,
198
createdAt: now,
199
status: "open"
200
});
201
this.#persistBag(characterId, bag);
202
const matchEvents = this.#matchAfterInsert(order, now);
203
return {
204
events: [
205
this.#marketOpenEvent(sessionId, characterId, position, now),
206
...matchEvents
207
]
208
};
209
}
210
211
placeBuyOrder (sessionId, characterId, itemId, quantity, maxUnitPrice, now = Date.now())
212
{
213
const { position } = this.#requireAtMarket(characterId);
214
const maxPrice = Math.max(1, maxUnitPrice | 0);
215
const qty = Math.max(1, quantity | 0 || 1);
216
const def = itemDefinition(itemId);
217
if (!def || !canSellOnMarketplace({ itemId, quantity: 1 }))
218
{ throw userError("That item cannot be bought on the marketplace."); }
219
if ((itemId | 0) === ItemId.coins)
220
{ throw userError("Coins cannot be ordered on the marketplace."); }
221
const escrow = maxPrice * qty;
222
const bag = this.#loadBag(characterId);
223
const paid = takeCoinsFromSlots(bag.inventory, escrow);
224
if (!paid.ok)
225
{ throw userError("You cannot afford that buy order."); }
226
bag.inventory = paid.slots;
227
const order = this.stateDb.insertMarketOrder({
228
characterId,
229
side: "buy",
230
itemId: itemId | 0,
231
quantity: qty,
232
limitUnitPrice: maxPrice,
233
escrowCoins: escrow,
234
escrowStack: null,
235
createdAt: now,
236
status: "open"
237
});
238
this.#persistBag(characterId, bag);
239
const matchEvents = this.#matchAfterInsert(order, now);
240
return {
241
events: [
242
this.#marketOpenEvent(sessionId, characterId, position, now),
243
...matchEvents
244
]
245
};
246
}
247
248
cancelOrder (sessionId, characterId, orderId, now = Date.now())
249
{
250
const { position } = this.#requireAtMarket(characterId);
251
const order = this.stateDb.getMarketOrder(orderId);
252
if (!order || order.status !== "open")
253
{ throw userError("That order is no longer open."); }
254
if (Number(order.characterId) !== Number(characterId))
255
{ throw userError("That is not your order."); }
256
this.#returnEscrowByPigeon(order, {
257
letterBody: orderCancelledLetterBody({
258
side: order.side,
259
itemName: itemDefinition(order.itemId)?.displayName ?? "item",
260
quantity: order.quantity,
261
escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"),
262
clerkName: pickExchangeClerk()
263
}),
264
now
265
});
266
this.stateDb.updateMarketOrder({
267
...order,
268
status: "cancelled",
269
quantity: 0,
270
escrowCoins: 0,
271
escrowStack: null
272
});
273
return {
274
events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
275
};
276
}
277
278
#expireOrder (order, now)
279
{
280
const events = [];
281
this.#returnEscrowByPigeon(order, {
282
letterBody: orderExpiredLetterBody({
283
side: order.side,
284
itemName: itemDefinition(order.itemId)?.displayName ?? "item",
285
quantity: order.quantity,
286
escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"),
287
clerkName: pickExchangeClerk()
288
}),
289
now
290
});
291
this.stateDb.updateMarketOrder({
292
...order,
293
status: "cancelled",
294
quantity: 0,
295
escrowCoins: 0,
296
escrowStack: null
297
});
298
events.push({
299
type: "market-order-expired",
300
orderId: order.orderId,
301
characterId: order.characterId
302
});
303
return events;
304
}
305
306
#matchAfterInsert (incoming, now)
307
{
308
const events = [];
309
let resting = this.stateDb.getMarketOrder(incoming.orderId);
310
if (!resting || resting.status !== "open")
311
{ return events; }
312
313
const counterparts = resting.side === "sell"
314
? this.stateDb.listOpenBuyOrdersForItem(resting.itemId)
315
: this.stateDb.listOpenSellOrdersForItem(resting.itemId);
316
317
for (const other of counterparts)
318
{
319
resting = this.stateDb.getMarketOrder(resting.orderId);
320
if (!resting || resting.status !== "open" || resting.quantity <= 0)
321
{ break; }
322
const liveOther = this.stateDb.getMarketOrder(other.orderId);
323
if (!liveOther || liveOther.status !== "open" || liveOther.quantity <= 0)
324
{ continue; }
325
if (Number(liveOther.characterId) === Number(resting.characterId))
326
{ continue; }
327
328
const buy = resting.side === "buy" ? resting : liveOther;
329
const sell = resting.side === "sell" ? resting : liveOther;
330
if (buy.limitUnitPrice < sell.limitUnitPrice)
331
{ continue; }
332
333
const fillQty = Math.min(buy.quantity, sell.quantity);
334
if (fillQty <= 0)
335
{ continue; }
336
const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice);
337
const tradeEvents = this.#settleMatch({
338
buy,
339
sell,
340
fillQty,
341
unitPrice,
342
triggeringSide: resting.side,
343
now
344
});
345
events.push(...tradeEvents);
346
}
347
return events;
348
}
349
350
#settleMatch ({ buy, sell, fillQty, unitPrice, triggeringSide, now })
351
{
352
const events = [];
353
const total = unitPrice * fillQty;
354
const itemName = itemDefinition(sell.itemId)?.displayName ?? "item";
355
const clerk = pickExchangeClerk();
356
357
const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty);
358
const goods = attachOrigins({
359
itemId: sell.itemId,
360
quantity: fillQty,
361
origins: sellSplit.taken,
362
instance: sell.escrowStack?.instance ?? null
363
});
364
365
const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty;
366
const buyRemainingQty = buy.quantity - fillQty;
367
const sellRemainingQty = sell.quantity - fillQty;
368
369
withTransaction(this.stateDb.db, () =>
370
{
371
this.stateDb.insertMarketTrade({
372
buyOrderId: buy.orderId,
373
sellOrderId: sell.orderId,
374
itemId: sell.itemId,
375
quantity: fillQty,
376
unitPrice,
377
buyerCharacterId: buy.characterId,
378
sellerCharacterId: sell.characterId,
379
createdAt: now
380
});
381
382
this.stateDb.updateMarketOrder({
383
...buy,
384
quantity: buyRemainingQty,
385
escrowCoins: buy.limitUnitPrice * buyRemainingQty,
386
status: buyRemainingQty > 0 ? "open" : "filled"
387
});
388
this.stateDb.updateMarketOrder({
389
...sell,
390
quantity: sellRemainingQty,
391
escrowStack: sellRemainingQty > 0
392
? attachOrigins({
393
...sell.escrowStack,
394
quantity: sellRemainingQty,
395
origins: sellSplit.remain
396
})
397
: null,
398
status: sellRemainingQty > 0 ? "open" : "filled"
399
});
400
});
401
402
this.#recordLastSale(sell.itemId, unitPrice, now);
403
404
const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
405
406
if (triggeringSide === "buy")
407
{
408
this.#grantImmediate(buy.characterId, goods);
409
if (buyRefund > 0)
410
{ this.#grantImmediateCoins(buy.characterId, buyRefund); }
411
this.#dispatchBankCargo(sell.characterId, origin, { kind: "money", amount: total });
412
this.#dispatchBankLetter(sell.characterId, origin, soldLetterBody({
413
itemName,
414
quantity: fillQty,
415
unitPrice,
416
clerkName: clerk
417
}));
418
}
419
else
420
{
421
this.#grantImmediateCoins(sell.characterId, total);
422
this.#dispatchBankCargo(buy.characterId, origin, { kind: "item", stack: goods });
423
if (buyRefund > 0)
424
{ this.#dispatchBankCargo(buy.characterId, origin, { kind: "money", amount: buyRefund }); }
425
this.#dispatchBankLetter(buy.characterId, origin, buyFilledLetterBody({
426
itemName,
427
quantity: fillQty,
428
unitPrice,
429
clerkName: clerk
430
}));
431
}
432
433
events.push({
434
type: "market-trade",
435
itemId: sell.itemId,
436
quantity: fillQty,
437
unitPrice,
438
buyerCharacterId: buy.characterId,
439
sellerCharacterId: sell.characterId,
440
triggeringSide
441
});
442
return events;
443
}
444
445
#returnEscrowByPigeon (order, { letterBody, now })
446
{
447
const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
448
if (order.side === "buy" && (order.escrowCoins | 0) > 0)
449
{
450
this.#dispatchBankCargo(order.characterId, origin, {
451
kind: "money",
452
amount: order.escrowCoins | 0
453
});
454
}
455
if (order.side === "sell" && order.escrowStack && (order.escrowStack.quantity | 0) > 0)
456
{
457
this.#dispatchBankCargo(order.characterId, origin, {
458
kind: "item",
459
stack: cloneStack(order.escrowStack)
460
});
461
}
462
this.#dispatchBankLetter(order.characterId, origin, letterBody);
463
void now;
464
}
465
466
#dispatchBankLetter (characterId, origin, body)
467
{
468
const trimmed = String(body ?? "").replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
469
const signed = /Signed,\n([^\n]+)\nCentral Exchange/.exec(trimmed);
470
const clerkName = signed?.[1] ?? pickExchangeClerk();
471
const stack = {
472
itemId: ItemId.letter,
473
quantity: 1,
474
instance: {
475
kind: "letter",
476
letterId: randomUUID(),
477
authorCharacterId: 0,
478
authorDisplayName: clerkName,
479
body: trimmed,
480
opened: false,
481
writtenAt: Date.now()
482
}
483
};
484
this.#dispatchBankCargo(characterId, origin, { kind: "item", stack });
485
}
486
487
#dispatchBankCargo (characterId, origin, cargo)
488
{
489
this.simulation.courier.dispatchHeldCargo({
490
senderCharacterId: characterId,
491
originTileX: origin.tileX,
492
originTileY: origin.tileY,
493
destination: { kind: "bank" },
494
cargo
495
});
496
}
497
498
#grantImmediate (characterId, stack)
499
{
500
const bag = this.#loadBag(characterId);
501
const def = itemDefinition(stack.itemId);
502
const inserted = insertStack(bag.inventory ?? [], stack, def);
503
bag.inventory = inserted.slots;
504
if (inserted.remainder > 0)
505
{
506
const overflow = attachOrigins({
507
...stack,
508
quantity: inserted.remainder,
509
origins: splitOrigins(normalizeOrigins(stack), stack.quantity - inserted.remainder).remain
510
});
511
const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
512
const vaulted = insertStackGrowable(vault.slots, overflow, def);
513
bag.vault = vaulted.slots;
514
bag.vaultReserved = vault.reserved;
515
}
516
this.#persistBag(characterId, bag);
517
}
518
519
#grantImmediateCoins (characterId, amount)
520
{
521
const qty = Math.max(0, amount | 0);
522
if (qty <= 0)
523
{ return; }
524
const bag = this.#loadBag(characterId);
525
const paid = addCoinsToSlots(bag.inventory ?? [], qty, { growable: false });
526
if (paid.ok && (paid.remainder | 0) === 0)
527
{
528
bag.inventory = paid.slots;
529
this.#persistBag(characterId, bag);
530
return;
531
}
532
const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
533
const withInv = paid.ok ? paid.slots : bag.inventory;
534
const remainder = paid.ok ? (paid.remainder | 0) : qty;
535
bag.inventory = withInv;
536
const vaultPaid = addCoinsToSlots(vault.slots, remainder, { growable: true });
537
bag.vault = vaultPaid.slots;
538
bag.vaultReserved = vault.reserved;
539
this.#persistBag(characterId, bag);
540
}
541
542
#recordLastSale (itemId, unitPrice, now)
543
{
544
const previous = this.lastSales.get(itemId | 0) ?? null;
545
const priceFrom = undiscountedMarketValue(
546
itemId,
547
previous,
548
now,
549
this.simulation.settings?.shopPriceLerpDurationMs,
550
this.simulation.settings
551
);
552
const sale = {
553
itemId: itemId | 0,
554
lastTradePrice: unitPrice,
555
lastTradeAt: now,
556
priceFrom
557
};
558
this.lastSales.set(itemId | 0, sale);
559
this.stateDb.upsertItemLastSale(sale);
560
this.#syncLastSalesToWorkers();
561
}
562
563
#loadLastSales ()
564
{
565
for (const sale of this.stateDb.listItemLastSales())
566
{ this.lastSales.set(sale.itemId | 0, sale); }
567
}
568
569
#syncLastSalesToWorkers ()
570
{
571
this.simulation.syncItemLastSales?.(this.lastSales);
572
}
573
574
#requireAtMarket (characterId)
575
{
576
const entityId = this.simulation.characterEntities.get(characterId);
577
const position = entityId ? this.simulation.positionOf(entityId) : null;
578
if (!position)
579
{ throw userError("Enter the world before using the Central Exchange."); }
580
if (!this.marketTiles.length)
581
{ throw userError("The Central Exchange is not open in this world yet."); }
582
const near = this.marketTiles.some((tile) =>
583
chebyshev(position.tileX, position.tileY, tile.tileX, tile.tileY) <= 1);
584
if (!near)
585
{ throw userError("Stand next to the Central Exchange counter."); }
586
return { position, entityId };
587
}
588
589
#marketOpenEvent (sessionId, characterId, position, now)
590
{
591
const orders = this.stateDb.listOpenMarketOrdersForCharacter(characterId).map((order) => ({
592
orderId: order.orderId,
593
side: order.side,
594
itemId: order.itemId,
595
displayName: itemDefinition(order.itemId)?.displayName ?? `Item ${order.itemId}`,
596
quantity: order.quantity,
597
limitUnitPrice: order.limitUnitPrice,
598
createdAt: order.createdAt
599
}));
600
const catalog = [];
601
for (const def of Object.values(ITEM_DEFINITIONS))
602
{
603
if (!canSellOnMarketplace({ itemId: def.itemId, quantity: 1 }))
604
{ continue; }
605
if (def.itemId === ItemId.coins)
606
{ continue; }
607
catalog.push({
608
itemId: def.itemId,
609
displayName: def.displayName,
610
hintPrice: undiscountedMarketValue(
611
def.itemId,
612
this.lastSaleFor(def.itemId),
613
now,
614
this.simulation.settings?.shopPriceLerpDurationMs,
615
this.simulation.settings
616
)
617
});
618
}
619
catalog.sort((a, b) => a.displayName.localeCompare(b.displayName));
620
return {
621
type: "market-open",
622
sessionId,
623
characterId,
624
displayName: "Central Exchange",
625
orders,
626
catalog,
627
tileX: position.tileX,
628
tileY: position.tileY
629
};
630
}
631
632
#loadBag (characterId)
633
{
634
const onlineId = this.simulation.characterEntities.get(characterId);
635
const bag = onlineId
636
? this.simulation.bagOf(onlineId)
637
: this.stateDb.getBag(characterId);
638
if (!bag)
639
{ throw userError("No bag."); }
640
return bag;
641
}
642
643
#persistBag (characterId, bag)
644
{
645
this.stateDb.saveBag(characterId, bag);
646
const onlineId = this.simulation.characterEntities.get(characterId);
647
if (onlineId)
648
{
649
this.simulation.applyBag(onlineId, bag);
650
this.simulation.pushInventory(characterId, bag);
651
}
652
}
653
}
@@ -0,0 +1,653 @@1
import { randomUUID } from "node:crypto";2
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";3
import { BlockType } from "../../../shared/definitions/tiles.js";4
import { ItemId, itemDefinition, ITEM_DEFINITIONS, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";5
import {6
addCoinsToSlots,7
insertStack,8
insertStackGrowable,9
normalizeVault,10
takeCoinsFromSlots,11
takeFromSlot,12
cloneStack13
} from "../../../shared/items/inventory.js";14
import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js";15
import { attachOrigins, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js";16
import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";17
import {18
MARKET_ORDER_MAX_AGE_MS,19
buyFilledLetterBody,20
midpointTradePrice,21
orderExpiredLetterBody,22
orderCancelledLetterBody,23
pickExchangeClerk,24
soldLetterBody25
} from "../../../shared/market/exchange.js";26
import { decodeChunkBlob } from "../world/chunkData.js";27
import { withTransaction } from "../persistence/database.js";28
29
function userError (message)30
{31
const error = new Error(message);32
error.userFacing = true;33
return error;34
}35
36
function chebyshev (ax, ay, bx, by)37
{38
return Math.max(Math.abs(ax - bx), Math.abs(ay - by));39
}40
41
export class MarketService42
{43
constructor ({ stateDb, worldDb, simulation })44
{45
this.stateDb = stateDb;46
this.worldDb = worldDb;47
this.simulation = simulation;48
this.marketTiles = [];49
/** @type {Map<number, object>} */50
this.lastSales = new Map();51
this.refreshIndex();52
this.#loadLastSales();53
this.#syncLastSalesToWorkers();54
}55
56
refreshIndex ()57
{58
const revisionId = this.worldDb.getActiveRevisionId();59
const tiles = [];60
for (const coord of this.worldDb.listChunkCoords(revisionId))61
{62
const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);63
if (!row)64
{ continue; }65
const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);66
for (let localY = 0; localY < CHUNK_SIZE; localY++)67
{68
for (let localX = 0; localX < CHUNK_SIZE; localX++)69
{70
const block = data.blocks[localY * CHUNK_SIZE + localX];71
if (block?.typeId !== BlockType.marketplace)72
{ continue; }73
tiles.push({74
tileX: coord.chunk_x * CHUNK_SIZE + localX,75
tileY: coord.chunk_y * CHUNK_SIZE + localY76
});77
}78
}79
}80
this.marketTiles = tiles;81
}82
83
nearestMarket (tileX, tileY)84
{85
if (!this.marketTiles.length)86
{ return null; }87
let best = null;88
let bestDist = Infinity;89
for (const tile of this.marketTiles)90
{91
const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);92
if (dist < bestDist)93
{94
bestDist = dist;95
best = tile;96
}97
}98
return best;99
}100
101
lastSaleFor (itemId)102
{103
return this.lastSales.get(itemId | 0) ?? null;104
}105
106
snapshot ()107
{108
const out = {};109
for (const [itemId, sale] of this.lastSales.entries())110
{ out[String(itemId)] = sale; }111
return out;112
}113
114
step (now = Date.now())115
{116
const events = [];117
const expired = this.stateDb.listExpiredMarketOrders(now - MARKET_ORDER_MAX_AGE_MS);118
for (const order of expired)119
{120
try121
{122
events.push(...this.#expireOrder(order, now));123
}124
catch (error)125
{126
console.error("Market order expiry failed", order.orderId, error);127
}128
}129
return events;130
}131
132
handleCommand (sessionId, command, now = Date.now())133
{134
switch (command.type)135
{136
case "open-market":137
return this.openMarket(sessionId, command.characterId, now);138
case "place-market-sell":139
return this.placeSellOrder(140
sessionId,141
command.characterId,142
command.slotIndex | 0,143
command.quantity | 0 || 1,144
command.minUnitPrice | 0,145
now146
);147
case "place-market-buy":148
return this.placeBuyOrder(149
sessionId,150
command.characterId,151
command.itemId | 0,152
command.quantity | 0 || 1,153
command.maxUnitPrice | 0,154
now155
);156
case "cancel-market-order":157
return this.cancelOrder(sessionId, command.characterId, command.orderId | 0, now);158
case "close-market":159
return { events: [{ type: "market-closed", sessionId, characterId: command.characterId }] };160
default:161
return null;162
}163
}164
165
openMarket (sessionId, characterId, now = Date.now())166
{167
const { position } = this.#requireAtMarket(characterId);168
return {169
events: [this.#marketOpenEvent(sessionId, characterId, position, now)]170
};171
}172
173
placeSellOrder (sessionId, characterId, slotIndex, quantity, minUnitPrice, now = Date.now())174
{175
const { position } = this.#requireAtMarket(characterId);176
const minPrice = Math.max(1, minUnitPrice | 0);177
const qty = Math.max(1, quantity | 0 || 1);178
const bag = this.#loadBag(characterId);179
const slot = bag.inventory?.[slotIndex];180
if (!slot)181
{ throw userError("That slot is empty."); }182
assertMarketplaceSellable(slot);183
if ((slot.itemId | 0) === ItemId.coins)184
{ throw userError("Coins cannot be listed on the marketplace."); }185
const taken = takeFromSlot(bag.inventory, slotIndex, qty);186
if (!taken.ok || !taken.taken)187
{ throw userError("That item is not available."); }188
bag.inventory = taken.slots;189
const stack = attachOrigins(taken.taken);190
const order = this.stateDb.insertMarketOrder({191
characterId,192
side: "sell",193
itemId: stack.itemId,194
quantity: stack.quantity,195
limitUnitPrice: minPrice,196
escrowCoins: 0,197
escrowStack: stack,198
createdAt: now,199
status: "open"200
});201
this.#persistBag(characterId, bag);202
const matchEvents = this.#matchAfterInsert(order, now);203
return {204
events: [205
this.#marketOpenEvent(sessionId, characterId, position, now),206
...matchEvents207
]208
};209
}210
211
placeBuyOrder (sessionId, characterId, itemId, quantity, maxUnitPrice, now = Date.now())212
{213
const { position } = this.#requireAtMarket(characterId);214
const maxPrice = Math.max(1, maxUnitPrice | 0);215
const qty = Math.max(1, quantity | 0 || 1);216
const def = itemDefinition(itemId);217
if (!def || !canSellOnMarketplace({ itemId, quantity: 1 }))218
{ throw userError("That item cannot be bought on the marketplace."); }219
if ((itemId | 0) === ItemId.coins)220
{ throw userError("Coins cannot be ordered on the marketplace."); }221
const escrow = maxPrice * qty;222
const bag = this.#loadBag(characterId);223
const paid = takeCoinsFromSlots(bag.inventory, escrow);224
if (!paid.ok)225
{ throw userError("You cannot afford that buy order."); }226
bag.inventory = paid.slots;227
const order = this.stateDb.insertMarketOrder({228
characterId,229
side: "buy",230
itemId: itemId | 0,231
quantity: qty,232
limitUnitPrice: maxPrice,233
escrowCoins: escrow,234
escrowStack: null,235
createdAt: now,236
status: "open"237
});238
this.#persistBag(characterId, bag);239
const matchEvents = this.#matchAfterInsert(order, now);240
return {241
events: [242
this.#marketOpenEvent(sessionId, characterId, position, now),243
...matchEvents244
]245
};246
}247
248
cancelOrder (sessionId, characterId, orderId, now = Date.now())249
{250
const { position } = this.#requireAtMarket(characterId);251
const order = this.stateDb.getMarketOrder(orderId);252
if (!order || order.status !== "open")253
{ throw userError("That order is no longer open."); }254
if (Number(order.characterId) !== Number(characterId))255
{ throw userError("That is not your order."); }256
this.#returnEscrowByPigeon(order, {257
letterBody: orderCancelledLetterBody({258
side: order.side,259
itemName: itemDefinition(order.itemId)?.displayName ?? "item",260
quantity: order.quantity,261
escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"),262
clerkName: pickExchangeClerk()263
}),264
now265
});266
this.stateDb.updateMarketOrder({267
...order,268
status: "cancelled",269
quantity: 0,270
escrowCoins: 0,271
escrowStack: null272
});273
return {274
events: [this.#marketOpenEvent(sessionId, characterId, position, now)]275
};276
}277
278
#expireOrder (order, now)279
{280
const events = [];281
this.#returnEscrowByPigeon(order, {282
letterBody: orderExpiredLetterBody({283
side: order.side,284
itemName: itemDefinition(order.itemId)?.displayName ?? "item",285
quantity: order.quantity,286
escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"),287
clerkName: pickExchangeClerk()288
}),289
now290
});291
this.stateDb.updateMarketOrder({292
...order,293
status: "cancelled",294
quantity: 0,295
escrowCoins: 0,296
escrowStack: null297
});298
events.push({299
type: "market-order-expired",300
orderId: order.orderId,301
characterId: order.characterId302
});303
return events;304
}305
306
#matchAfterInsert (incoming, now)307
{308
const events = [];309
let resting = this.stateDb.getMarketOrder(incoming.orderId);310
if (!resting || resting.status !== "open")311
{ return events; }312
313
const counterparts = resting.side === "sell"314
? this.stateDb.listOpenBuyOrdersForItem(resting.itemId)315
: this.stateDb.listOpenSellOrdersForItem(resting.itemId);316
317
for (const other of counterparts)318
{319
resting = this.stateDb.getMarketOrder(resting.orderId);320
if (!resting || resting.status !== "open" || resting.quantity <= 0)321
{ break; }322
const liveOther = this.stateDb.getMarketOrder(other.orderId);323
if (!liveOther || liveOther.status !== "open" || liveOther.quantity <= 0)324
{ continue; }325
if (Number(liveOther.characterId) === Number(resting.characterId))326
{ continue; }327
328
const buy = resting.side === "buy" ? resting : liveOther;329
const sell = resting.side === "sell" ? resting : liveOther;330
if (buy.limitUnitPrice < sell.limitUnitPrice)331
{ continue; }332
333
const fillQty = Math.min(buy.quantity, sell.quantity);334
if (fillQty <= 0)335
{ continue; }336
const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice);337
const tradeEvents = this.#settleMatch({338
buy,339
sell,340
fillQty,341
unitPrice,342
triggeringSide: resting.side,343
now344
});345
events.push(...tradeEvents);346
}347
return events;348
}349
350
#settleMatch ({ buy, sell, fillQty, unitPrice, triggeringSide, now })351
{352
const events = [];353
const total = unitPrice * fillQty;354
const itemName = itemDefinition(sell.itemId)?.displayName ?? "item";355
const clerk = pickExchangeClerk();356
357
const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty);358
const goods = attachOrigins({359
itemId: sell.itemId,360
quantity: fillQty,361
origins: sellSplit.taken,362
instance: sell.escrowStack?.instance ?? null363
});364
365
const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty;366
const buyRemainingQty = buy.quantity - fillQty;367
const sellRemainingQty = sell.quantity - fillQty;368
369
withTransaction(this.stateDb.db, () =>370
{371
this.stateDb.insertMarketTrade({372
buyOrderId: buy.orderId,373
sellOrderId: sell.orderId,374
itemId: sell.itemId,375
quantity: fillQty,376
unitPrice,377
buyerCharacterId: buy.characterId,378
sellerCharacterId: sell.characterId,379
createdAt: now380
});381
382
this.stateDb.updateMarketOrder({383
...buy,384
quantity: buyRemainingQty,385
escrowCoins: buy.limitUnitPrice * buyRemainingQty,386
status: buyRemainingQty > 0 ? "open" : "filled"387
});388
this.stateDb.updateMarketOrder({389
...sell,390
quantity: sellRemainingQty,391
escrowStack: sellRemainingQty > 0392
? attachOrigins({393
...sell.escrowStack,394
quantity: sellRemainingQty,395
origins: sellSplit.remain396
})397
: null,398
status: sellRemainingQty > 0 ? "open" : "filled"399
});400
});401
402
this.#recordLastSale(sell.itemId, unitPrice, now);403
404
const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };405
406
if (triggeringSide === "buy")407
{408
this.#grantImmediate(buy.characterId, goods);409
if (buyRefund > 0)410
{ this.#grantImmediateCoins(buy.characterId, buyRefund); }411
this.#dispatchBankCargo(sell.characterId, origin, { kind: "money", amount: total });412
this.#dispatchBankLetter(sell.characterId, origin, soldLetterBody({413
itemName,414
quantity: fillQty,415
unitPrice,416
clerkName: clerk417
}));418
}419
else420
{421
this.#grantImmediateCoins(sell.characterId, total);422
this.#dispatchBankCargo(buy.characterId, origin, { kind: "item", stack: goods });423
if (buyRefund > 0)424
{ this.#dispatchBankCargo(buy.characterId, origin, { kind: "money", amount: buyRefund }); }425
this.#dispatchBankLetter(buy.characterId, origin, buyFilledLetterBody({426
itemName,427
quantity: fillQty,428
unitPrice,429
clerkName: clerk430
}));431
}432
433
events.push({434
type: "market-trade",435
itemId: sell.itemId,436
quantity: fillQty,437
unitPrice,438
buyerCharacterId: buy.characterId,439
sellerCharacterId: sell.characterId,440
triggeringSide441
});442
return events;443
}444
445
#returnEscrowByPigeon (order, { letterBody, now })446
{447
const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };448
if (order.side === "buy" && (order.escrowCoins | 0) > 0)449
{450
this.#dispatchBankCargo(order.characterId, origin, {451
kind: "money",452
amount: order.escrowCoins | 0453
});454
}455
if (order.side === "sell" && order.escrowStack && (order.escrowStack.quantity | 0) > 0)456
{457
this.#dispatchBankCargo(order.characterId, origin, {458
kind: "item",459
stack: cloneStack(order.escrowStack)460
});461
}462
this.#dispatchBankLetter(order.characterId, origin, letterBody);463
void now;464
}465
466
#dispatchBankLetter (characterId, origin, body)467
{468
const trimmed = String(body ?? "").replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);469
const signed = /Signed,\n([^\n]+)\nCentral Exchange/.exec(trimmed);470
const clerkName = signed?.[1] ?? pickExchangeClerk();471
const stack = {472
itemId: ItemId.letter,473
quantity: 1,474
instance: {475
kind: "letter",476
letterId: randomUUID(),477
authorCharacterId: 0,478
authorDisplayName: clerkName,479
body: trimmed,480
opened: false,481
writtenAt: Date.now()482
}483
};484
this.#dispatchBankCargo(characterId, origin, { kind: "item", stack });485
}486
487
#dispatchBankCargo (characterId, origin, cargo)488
{489
this.simulation.courier.dispatchHeldCargo({490
senderCharacterId: characterId,491
originTileX: origin.tileX,492
originTileY: origin.tileY,493
destination: { kind: "bank" },494
cargo495
});496
}497
498
#grantImmediate (characterId, stack)499
{500
const bag = this.#loadBag(characterId);501
const def = itemDefinition(stack.itemId);502
const inserted = insertStack(bag.inventory ?? [], stack, def);503
bag.inventory = inserted.slots;504
if (inserted.remainder > 0)505
{506
const overflow = attachOrigins({507
...stack,508
quantity: inserted.remainder,509
origins: splitOrigins(normalizeOrigins(stack), stack.quantity - inserted.remainder).remain510
});511
const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });512
const vaulted = insertStackGrowable(vault.slots, overflow, def);513
bag.vault = vaulted.slots;514
bag.vaultReserved = vault.reserved;515
}516
this.#persistBag(characterId, bag);517
}518
519
#grantImmediateCoins (characterId, amount)520
{521
const qty = Math.max(0, amount | 0);522
if (qty <= 0)523
{ return; }524
const bag = this.#loadBag(characterId);525
const paid = addCoinsToSlots(bag.inventory ?? [], qty, { growable: false });526
if (paid.ok && (paid.remainder | 0) === 0)527
{528
bag.inventory = paid.slots;529
this.#persistBag(characterId, bag);530
return;531
}532
const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });533
const withInv = paid.ok ? paid.slots : bag.inventory;534
const remainder = paid.ok ? (paid.remainder | 0) : qty;535
bag.inventory = withInv;536
const vaultPaid = addCoinsToSlots(vault.slots, remainder, { growable: true });537
bag.vault = vaultPaid.slots;538
bag.vaultReserved = vault.reserved;539
this.#persistBag(characterId, bag);540
}541
542
#recordLastSale (itemId, unitPrice, now)543
{544
const previous = this.lastSales.get(itemId | 0) ?? null;545
const priceFrom = undiscountedMarketValue(546
itemId,547
previous,548
now,549
this.simulation.settings?.shopPriceLerpDurationMs,550
this.simulation.settings551
);552
const sale = {553
itemId: itemId | 0,554
lastTradePrice: unitPrice,555
lastTradeAt: now,556
priceFrom557
};558
this.lastSales.set(itemId | 0, sale);559
this.stateDb.upsertItemLastSale(sale);560
this.#syncLastSalesToWorkers();561
}562
563
#loadLastSales ()564
{565
for (const sale of this.stateDb.listItemLastSales())566
{ this.lastSales.set(sale.itemId | 0, sale); }567
}568
569
#syncLastSalesToWorkers ()570
{571
this.simulation.syncItemLastSales?.(this.lastSales);572
}573
574
#requireAtMarket (characterId)575
{576
const entityId = this.simulation.characterEntities.get(characterId);577
const position = entityId ? this.simulation.positionOf(entityId) : null;578
if (!position)579
{ throw userError("Enter the world before using the Central Exchange."); }580
if (!this.marketTiles.length)581
{ throw userError("The Central Exchange is not open in this world yet."); }582
const near = this.marketTiles.some((tile) =>583
chebyshev(position.tileX, position.tileY, tile.tileX, tile.tileY) <= 1);584
if (!near)585
{ throw userError("Stand next to the Central Exchange counter."); }586
return { position, entityId };587
}588
589
#marketOpenEvent (sessionId, characterId, position, now)590
{591
const orders = this.stateDb.listOpenMarketOrdersForCharacter(characterId).map((order) => ({592
orderId: order.orderId,593
side: order.side,594
itemId: order.itemId,595
displayName: itemDefinition(order.itemId)?.displayName ?? `Item ${order.itemId}`,596
quantity: order.quantity,597
limitUnitPrice: order.limitUnitPrice,598
createdAt: order.createdAt599
}));600
const catalog = [];601
for (const def of Object.values(ITEM_DEFINITIONS))602
{603
if (!canSellOnMarketplace({ itemId: def.itemId, quantity: 1 }))604
{ continue; }605
if (def.itemId === ItemId.coins)606
{ continue; }607
catalog.push({608
itemId: def.itemId,609
displayName: def.displayName,610
hintPrice: undiscountedMarketValue(611
def.itemId,612
this.lastSaleFor(def.itemId),613
now,614
this.simulation.settings?.shopPriceLerpDurationMs,615
this.simulation.settings616
)617
});618
}619
catalog.sort((a, b) => a.displayName.localeCompare(b.displayName));620
return {621
type: "market-open",622
sessionId,623
characterId,624
displayName: "Central Exchange",625
orders,626
catalog,627
tileX: position.tileX,628
tileY: position.tileY629
};630
}631
632
#loadBag (characterId)633
{634
const onlineId = this.simulation.characterEntities.get(characterId);635
const bag = onlineId636
? this.simulation.bagOf(onlineId)637
: this.stateDb.getBag(characterId);638
if (!bag)639
{ throw userError("No bag."); }640
return bag;641
}642
643
#persistBag (characterId, bag)644
{645
this.stateDb.saveBag(characterId, bag);646
const onlineId = this.simulation.characterEntities.get(characterId);647
if (onlineId)648
{649
this.simulation.applyBag(onlineId, bag);650
this.simulation.pushInventory(characterId, bag);651
}652
}653
}@@ -95,6 +95,38 @@ CREATE TABLE IF NOT EXISTS courier_transits (
95
95
updated_at INTEGER NOT NULL,
96
96
created_at INTEGER NOT NULL
97
97
);
98
99
CREATE TABLE IF NOT EXISTS market_orders (
100
order_id INTEGER PRIMARY KEY AUTOINCREMENT,
101
character_id INTEGER NOT NULL,
102
side TEXT NOT NULL,
103
item_id INTEGER NOT NULL,
104
quantity INTEGER NOT NULL,
105
limit_unit_price INTEGER NOT NULL,
106
escrow_coins INTEGER NOT NULL DEFAULT 0,
107
escrow_stack_blob TEXT,
108
created_at INTEGER NOT NULL,
109
status TEXT NOT NULL
110
);
111
112
CREATE TABLE IF NOT EXISTS market_trades (
113
trade_id INTEGER PRIMARY KEY AUTOINCREMENT,
114
buy_order_id INTEGER NOT NULL,
115
sell_order_id INTEGER NOT NULL,
116
item_id INTEGER NOT NULL,
117
quantity INTEGER NOT NULL,
118
unit_price INTEGER NOT NULL,
119
buyer_character_id INTEGER NOT NULL,
120
seller_character_id INTEGER NOT NULL,
121
created_at INTEGER NOT NULL
122
);
123
124
CREATE TABLE IF NOT EXISTS item_last_sales (
125
item_id INTEGER PRIMARY KEY,
126
last_trade_price INTEGER NOT NULL,
127
last_trade_at INTEGER NOT NULL,
128
price_from INTEGER NOT NULL
129
);
98
130
`;
99
131
100
132
export class StateDatabase
@@ -727,6 +759,132 @@ export class StateDatabase
727
759
);
728
760
}
729
761
762
insertMarketOrder (order)
763
{
764
const result = this.db.prepare(`
765
INSERT INTO market_orders (
766
character_id, side, item_id, quantity, limit_unit_price,
767
escrow_coins, escrow_stack_blob, created_at, status
768
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
769
`).run(
770
order.characterId,
771
order.side,
772
order.itemId | 0,
773
order.quantity | 0,
774
order.limitUnitPrice | 0,
775
order.escrowCoins | 0 || 0,
776
order.escrowStack ? JSON.stringify(order.escrowStack) : null,
777
order.createdAt ?? Date.now(),
778
order.status ?? "open"
779
);
780
return this.getMarketOrder(Number(result.lastInsertRowid));
781
}
782
783
getMarketOrder (orderId)
784
{
785
const row = this.db.prepare("SELECT * FROM market_orders WHERE order_id = ?").get(orderId);
786
return row ? parseMarketOrder(row) : null;
787
}
788
789
updateMarketOrder (order)
790
{
791
this.db.prepare(`
792
UPDATE market_orders
793
SET quantity = ?, escrow_coins = ?, escrow_stack_blob = ?, status = ?
794
WHERE order_id = ?
795
`).run(
796
order.quantity | 0,
797
order.escrowCoins | 0 || 0,
798
order.escrowStack ? JSON.stringify(order.escrowStack) : null,
799
order.status,
800
order.orderId
801
);
802
return this.getMarketOrder(order.orderId);
803
}
804
805
listOpenMarketOrdersForCharacter (characterId)
806
{
807
return this.db.prepare(`
808
SELECT * FROM market_orders
809
WHERE character_id = ? AND status = 'open'
810
ORDER BY created_at ASC, order_id ASC
811
`).all(characterId).map(parseMarketOrder);
812
}
813
814
listOpenBuyOrdersForItem (itemId)
815
{
816
return this.db.prepare(`
817
SELECT * FROM market_orders
818
WHERE status = 'open' AND side = 'buy' AND item_id = ?
819
ORDER BY limit_unit_price DESC, created_at ASC, order_id ASC
820
`).all(itemId | 0).map(parseMarketOrder);
821
}
822
823
listOpenSellOrdersForItem (itemId)
824
{
825
return this.db.prepare(`
826
SELECT * FROM market_orders
827
WHERE status = 'open' AND side = 'sell' AND item_id = ?
828
ORDER BY limit_unit_price ASC, created_at ASC, order_id ASC
829
`).all(itemId | 0).map(parseMarketOrder);
830
}
831
832
listExpiredMarketOrders (createdBefore)
833
{
834
return this.db.prepare(`
835
SELECT * FROM market_orders
836
WHERE status = 'open' AND created_at < ?
837
ORDER BY created_at ASC, order_id ASC
838
`).all(createdBefore).map(parseMarketOrder);
839
}
840
841
insertMarketTrade (trade)
842
{
843
const result = this.db.prepare(`
844
INSERT INTO market_trades (
845
buy_order_id, sell_order_id, item_id, quantity, unit_price,
846
buyer_character_id, seller_character_id, created_at
847
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
848
`).run(
849
trade.buyOrderId,
850
trade.sellOrderId,
851
trade.itemId | 0,
852
trade.quantity | 0,
853
trade.unitPrice | 0,
854
trade.buyerCharacterId,
855
trade.sellerCharacterId,
856
trade.createdAt ?? Date.now()
857
);
858
return Number(result.lastInsertRowid);
859
}
860
861
upsertItemLastSale (sale)
862
{
863
this.db.prepare(`
864
INSERT INTO item_last_sales (item_id, last_trade_price, last_trade_at, price_from)
865
VALUES (?, ?, ?, ?)
866
ON CONFLICT(item_id) DO UPDATE SET
867
last_trade_price = excluded.last_trade_price,
868
last_trade_at = excluded.last_trade_at,
869
price_from = excluded.price_from
870
`).run(
871
sale.itemId | 0,
872
sale.lastTradePrice | 0,
873
sale.lastTradeAt,
874
Math.round(Number(sale.priceFrom) || 0)
875
);
876
}
877
878
listItemLastSales ()
879
{
880
return this.db.prepare("SELECT * FROM item_last_sales").all().map((row) => ({
881
itemId: row.item_id,
882
lastTradePrice: row.last_trade_price,
883
lastTradeAt: row.last_trade_at,
884
priceFrom: row.price_from
885
}));
886
}
887
730
888
close ()
731
889
{
732
890
this.db.close();
@@ -757,6 +915,22 @@ function parseGroundItem (row)
757
915
};
758
916
}
759
917
918
function parseMarketOrder (row)
919
{
920
return {
921
orderId: row.order_id,
922
characterId: row.character_id,
923
side: row.side,
924
itemId: row.item_id,
925
quantity: row.quantity,
926
limitUnitPrice: row.limit_unit_price,
927
escrowCoins: row.escrow_coins | 0,
928
escrowStack: row.escrow_stack_blob ? JSON.parse(row.escrow_stack_blob) : null,
929
createdAt: row.created_at,
930
status: row.status
931
};
932
}
933
760
934
function bagContainsItem (inventory, equipment, itemId)
761
935
{
762
936
for (const stack of inventory ?? [])
@@ -95,6 +95,38 @@ CREATE TABLE IF NOT EXISTS courier_transits (95
updated_at INTEGER NOT NULL,95
updated_at INTEGER NOT NULL,96
created_at INTEGER NOT NULL96
created_at INTEGER NOT NULL97
);97
);98
99
CREATE TABLE IF NOT EXISTS market_orders (100
order_id INTEGER PRIMARY KEY AUTOINCREMENT,101
character_id INTEGER NOT NULL,102
side TEXT NOT NULL,103
item_id INTEGER NOT NULL,104
quantity INTEGER NOT NULL,105
limit_unit_price INTEGER NOT NULL,106
escrow_coins INTEGER NOT NULL DEFAULT 0,107
escrow_stack_blob TEXT,108
created_at INTEGER NOT NULL,109
status TEXT NOT NULL110
);111
112
CREATE TABLE IF NOT EXISTS market_trades (113
trade_id INTEGER PRIMARY KEY AUTOINCREMENT,114
buy_order_id INTEGER NOT NULL,115
sell_order_id INTEGER NOT NULL,116
item_id INTEGER NOT NULL,117
quantity INTEGER NOT NULL,118
unit_price INTEGER NOT NULL,119
buyer_character_id INTEGER NOT NULL,120
seller_character_id INTEGER NOT NULL,121
created_at INTEGER NOT NULL122
);123
124
CREATE TABLE IF NOT EXISTS item_last_sales (125
item_id INTEGER PRIMARY KEY,126
last_trade_price INTEGER NOT NULL,127
last_trade_at INTEGER NOT NULL,128
price_from INTEGER NOT NULL129
);98
`;130
`;99
131
100
export class StateDatabase132
export class StateDatabase@@ -727,6 +759,132 @@ export class StateDatabase727
);759
);728
}760
}729
761
762
insertMarketOrder (order)763
{764
const result = this.db.prepare(`765
INSERT INTO market_orders (766
character_id, side, item_id, quantity, limit_unit_price,767
escrow_coins, escrow_stack_blob, created_at, status768
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)769
`).run(770
order.characterId,771
order.side,772
order.itemId | 0,773
order.quantity | 0,774
order.limitUnitPrice | 0,775
order.escrowCoins | 0 || 0,776
order.escrowStack ? JSON.stringify(order.escrowStack) : null,777
order.createdAt ?? Date.now(),778
order.status ?? "open"779
);780
return this.getMarketOrder(Number(result.lastInsertRowid));781
}782
783
getMarketOrder (orderId)784
{785
const row = this.db.prepare("SELECT * FROM market_orders WHERE order_id = ?").get(orderId);786
return row ? parseMarketOrder(row) : null;787
}788
789
updateMarketOrder (order)790
{791
this.db.prepare(`792
UPDATE market_orders793
SET quantity = ?, escrow_coins = ?, escrow_stack_blob = ?, status = ?794
WHERE order_id = ?795
`).run(796
order.quantity | 0,797
order.escrowCoins | 0 || 0,798
order.escrowStack ? JSON.stringify(order.escrowStack) : null,799
order.status,800
order.orderId801
);802
return this.getMarketOrder(order.orderId);803
}804
805
listOpenMarketOrdersForCharacter (characterId)806
{807
return this.db.prepare(`808
SELECT * FROM market_orders809
WHERE character_id = ? AND status = 'open'810
ORDER BY created_at ASC, order_id ASC811
`).all(characterId).map(parseMarketOrder);812
}813
814
listOpenBuyOrdersForItem (itemId)815
{816
return this.db.prepare(`817
SELECT * FROM market_orders818
WHERE status = 'open' AND side = 'buy' AND item_id = ?819
ORDER BY limit_unit_price DESC, created_at ASC, order_id ASC820
`).all(itemId | 0).map(parseMarketOrder);821
}822
823
listOpenSellOrdersForItem (itemId)824
{825
return this.db.prepare(`826
SELECT * FROM market_orders827
WHERE status = 'open' AND side = 'sell' AND item_id = ?828
ORDER BY limit_unit_price ASC, created_at ASC, order_id ASC829
`).all(itemId | 0).map(parseMarketOrder);830
}831
832
listExpiredMarketOrders (createdBefore)833
{834
return this.db.prepare(`835
SELECT * FROM market_orders836
WHERE status = 'open' AND created_at < ?837
ORDER BY created_at ASC, order_id ASC838
`).all(createdBefore).map(parseMarketOrder);839
}840
841
insertMarketTrade (trade)842
{843
const result = this.db.prepare(`844
INSERT INTO market_trades (845
buy_order_id, sell_order_id, item_id, quantity, unit_price,846
buyer_character_id, seller_character_id, created_at847
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)848
`).run(849
trade.buyOrderId,850
trade.sellOrderId,851
trade.itemId | 0,852
trade.quantity | 0,853
trade.unitPrice | 0,854
trade.buyerCharacterId,855
trade.sellerCharacterId,856
trade.createdAt ?? Date.now()857
);858
return Number(result.lastInsertRowid);859
}860
861
upsertItemLastSale (sale)862
{863
this.db.prepare(`864
INSERT INTO item_last_sales (item_id, last_trade_price, last_trade_at, price_from)865
VALUES (?, ?, ?, ?)866
ON CONFLICT(item_id) DO UPDATE SET867
last_trade_price = excluded.last_trade_price,868
last_trade_at = excluded.last_trade_at,869
price_from = excluded.price_from870
`).run(871
sale.itemId | 0,872
sale.lastTradePrice | 0,873
sale.lastTradeAt,874
Math.round(Number(sale.priceFrom) || 0)875
);876
}877
878
listItemLastSales ()879
{880
return this.db.prepare("SELECT * FROM item_last_sales").all().map((row) => ({881
itemId: row.item_id,882
lastTradePrice: row.last_trade_price,883
lastTradeAt: row.last_trade_at,884
priceFrom: row.price_from885
}));886
}887
730
close ()888
close ()731
{889
{732
this.db.close();890
this.db.close();@@ -757,6 +915,22 @@ function parseGroundItem (row)757
};915
};758
}916
}759
917
918
function parseMarketOrder (row)919
{920
return {921
orderId: row.order_id,922
characterId: row.character_id,923
side: row.side,924
itemId: row.item_id,925
quantity: row.quantity,926
limitUnitPrice: row.limit_unit_price,927
escrowCoins: row.escrow_coins | 0,928
escrowStack: row.escrow_stack_blob ? JSON.parse(row.escrow_stack_blob) : null,929
createdAt: row.created_at,930
status: row.status931
};932
}933
760
function bagContainsItem (inventory, equipment, itemId)934
function bagContainsItem (inventory, equipment, itemId)761
{935
{762
for (const stack of inventory ?? [])936
for (const stack of inventory ?? [])@@ -1,7 +1,13 @@
1
1
import { Component } from "../ecs/components.js";
2
2
import { bagView, findReservedChequeIndex } from "../items/bags.js";
3
3
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4
import { ItemOriginKind, attachOrigins } from "../../../shared/items/origin.js";
4
import {
5
ItemOriginKind,
6
attachOrigins,
7
mergeOriginLists,
8
normalizeOrigins,
9
splitOrigins
10
} from "../../../shared/items/origin.js";
5
11
import {
6
12
addCoinsToSlots,
7
13
cloneStack,
@@ -161,7 +167,7 @@ function ensureVault (ecs, handle)
161
167
return vault;
162
168
}
163
169
164
/** Refresh catalog remaining and clear bought-from-players stock at UTC midnight. */
170
/** Refresh catalog remaining and clear bought-from-players stock at local midnight. */
165
171
export function ensureShopRestocked (shop, now = Date.now())
166
172
{
167
173
if (!shop)
@@ -208,9 +214,74 @@ function catalogAvailable (shop, itemId)
208
214
return Math.max(0, shop.remaining?.[itemId] | 0 || 0);
209
215
}
210
216
217
/** Normalize legacy qty-only boughtStock entries into `{ quantity, origins }`. */
218
function boughtLot (shop, itemId)
219
{
220
const raw = shop.boughtStock?.[itemId];
221
if (raw == null)
222
{ return null; }
223
if (typeof raw === "number")
224
{
225
const quantity = Math.max(0, raw | 0);
226
if (quantity <= 0)
227
{ return null; }
228
return {
229
quantity,
230
origins: [{ origin: null, quantity }]
231
};
232
}
233
const quantity = Math.max(0, raw.quantity | 0 || 0);
234
if (quantity <= 0)
235
{ return null; }
236
const origins = normalizeOrigins({ quantity, origins: raw.origins });
237
const originQty = origins.reduce((sum, entry) => sum + entry.quantity, 0);
238
if (originQty < quantity)
239
{
240
origins.push({ origin: null, quantity: quantity - originQty });
241
}
242
return { quantity, origins };
243
}
244
211
245
function boughtAvailable (shop, itemId)
212
246
{
213
return Math.max(0, shop.boughtStock?.[itemId] | 0 || 0);
247
return boughtLot(shop, itemId)?.quantity ?? 0;
248
}
249
250
function addBoughtLot (shop, itemId, quantity, origins)
251
{
252
const qty = Math.max(0, quantity | 0 || 0);
253
if (qty <= 0)
254
{ return; }
255
const existing = boughtLot(shop, itemId);
256
const nextOrigins = mergeOriginLists(
257
existing?.origins ?? [],
258
normalizeOrigins({ quantity: qty, origins })
259
);
260
shop.boughtStock[itemId] = {
261
quantity: (existing?.quantity ?? 0) + qty,
262
origins: nextOrigins
263
};
264
}
265
266
/** Pull FIFO origins from bought stock; returns null if insufficient. */
267
function takeBoughtLot (shop, itemId, quantity)
268
{
269
const qty = Math.max(0, quantity | 0 || 0);
270
const lot = boughtLot(shop, itemId);
271
if (!lot || lot.quantity < qty)
272
{ return null; }
273
const split = splitOrigins(lot.origins, qty);
274
const remainQty = lot.quantity - qty;
275
if (remainQty <= 0)
276
{ delete shop.boughtStock[itemId]; }
277
else
278
{
279
shop.boughtStock[itemId] = {
280
quantity: remainQty,
281
origins: split.remain
282
};
283
}
284
return { quantity: qty, origins: split.taken };
214
285
}
215
286
216
287
function shopStockView (world, shop, now)
@@ -246,10 +317,10 @@ function shopStockView (world, shop, now)
246
317
source: "stock"
247
318
});
248
319
}
249
for (const [key, qty] of Object.entries(shop.boughtStock ?? {}))
320
for (const key of Object.keys(shop.boughtStock ?? {}))
250
321
{
251
322
const itemId = key | 0;
252
const available = qty | 0;
323
const available = boughtAvailable(shop, itemId);
253
324
if (available <= 0 || !canSellInNpcShop(itemId))
254
325
{ continue; }
255
326
const def = itemDefinition(itemId);
@@ -399,20 +470,37 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
399
470
{ throw userError("You cannot afford that."); }
400
471
401
472
const displayName = shopDisplayName(shop, npcHandle, world);
402
const shopOrigin = { kind: ItemOriginKind.shop, displayName };
403
const stack = attachOrigins({
404
itemId: buyItemId,
405
quantity: qty,
406
origins: [{ origin: shopOrigin, quantity: qty }]
407
});
473
let stack;
474
if (listing.source === "bought")
475
{
476
const lot = boughtLot(shop, buyItemId);
477
if (!lot || lot.quantity < qty)
478
{ throw userError("Not enough stock."); }
479
const split = splitOrigins(lot.origins, qty);
480
stack = attachOrigins({
481
itemId: buyItemId,
482
quantity: qty,
483
origins: split.taken
484
});
485
}
486
else
487
{
488
const shopOrigin = { kind: ItemOriginKind.shop, displayName };
489
stack = attachOrigins({
490
itemId: buyItemId,
491
quantity: qty,
492
origins: [{ origin: shopOrigin, quantity: qty }]
493
});
494
}
408
495
const added = insertStack(paid.slots, stack, def);
409
496
inventory.slots = added.slots;
410
497
if (added.remainder > 0)
411
498
{
499
const overflowOrigins = splitOrigins(normalizeOrigins(stack), qty - added.remainder).remain;
412
500
const overflow = attachOrigins({
413
501
itemId: buyItemId,
414
502
quantity: added.remainder,
415
origins: [{ origin: shopOrigin, quantity: added.remainder }]
503
origins: overflowOrigins
416
504
});
417
505
const vault = ensureVault(world.ecs, handle);
418
506
const vaulted = insertStackGrowable(vault.slots, overflow, def);
@@ -423,9 +511,8 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
423
511
424
512
if (listing.source === "bought")
425
513
{
426
shop.boughtStock[buyItemId] = boughtAvailable(shop, buyItemId) - qty;
427
if (shop.boughtStock[buyItemId] <= 0)
428
{ delete shop.boughtStock[buyItemId]; }
514
if (!takeBoughtLot(shop, buyItemId, qty))
515
{ throw userError("Not enough stock."); }
429
516
}
430
517
else
431
518
{
@@ -573,7 +660,13 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde
573
660
if (line && (line.quantity | 0) > 0 && refill > 0)
574
661
{ shop.remaining[goodsItemId] = catalogAvailable(shop, goodsItemId) + refill; }
575
662
if (leftover > 0)
576
{ shop.boughtStock[goodsItemId] = boughtAvailable(shop, goodsItemId) + leftover; }
663
{
664
const soldStack = isCheque ? reservedStack : taken.taken;
665
const soldOrigins = normalizeOrigins(soldStack);
666
// Catalog refill absorbs first; leftover keeps remaining origins for resale.
667
const { remain: resaleOrigins } = splitOrigins(soldOrigins, refill);
668
addBoughtLot(shop, goodsItemId, leftover, resaleOrigins);
669
}
577
670
578
671
const displayName = shopDisplayName(shop, npcHandle, world);
579
672
return {
@@ -1,7 +1,13 @@1
import { Component } from "../ecs/components.js";1
import { Component } from "../ecs/components.js";2
import { bagView, findReservedChequeIndex } from "../items/bags.js";2
import { bagView, findReservedChequeIndex } from "../items/bags.js";3
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";3
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";4
import { ItemOriginKind, attachOrigins } from "../../../shared/items/origin.js";4
import {5
ItemOriginKind,6
attachOrigins,7
mergeOriginLists,8
normalizeOrigins,9
splitOrigins10
} from "../../../shared/items/origin.js";5
import {11
import {6
addCoinsToSlots,12
addCoinsToSlots,7
cloneStack,13
cloneStack,@@ -161,7 +167,7 @@ function ensureVault (ecs, handle)161
return vault;167
return vault;162
}168
}163
169
164
/** Refresh catalog remaining and clear bought-from-players stock at UTC midnight. */170
/** Refresh catalog remaining and clear bought-from-players stock at local midnight. */165
export function ensureShopRestocked (shop, now = Date.now())171
export function ensureShopRestocked (shop, now = Date.now())166
{172
{167
if (!shop)173
if (!shop)@@ -208,9 +214,74 @@ function catalogAvailable (shop, itemId)208
return Math.max(0, shop.remaining?.[itemId] | 0 || 0);214
return Math.max(0, shop.remaining?.[itemId] | 0 || 0);209
}215
}210
216
217
/** Normalize legacy qty-only boughtStock entries into `{ quantity, origins }`. */218
function boughtLot (shop, itemId)219
{220
const raw = shop.boughtStock?.[itemId];221
if (raw == null)222
{ return null; }223
if (typeof raw === "number")224
{225
const quantity = Math.max(0, raw | 0);226
if (quantity <= 0)227
{ return null; }228
return {229
quantity,230
origins: [{ origin: null, quantity }]231
};232
}233
const quantity = Math.max(0, raw.quantity | 0 || 0);234
if (quantity <= 0)235
{ return null; }236
const origins = normalizeOrigins({ quantity, origins: raw.origins });237
const originQty = origins.reduce((sum, entry) => sum + entry.quantity, 0);238
if (originQty < quantity)239
{240
origins.push({ origin: null, quantity: quantity - originQty });241
}242
return { quantity, origins };243
}244
211
function boughtAvailable (shop, itemId)245
function boughtAvailable (shop, itemId)212
{246
{213
return Math.max(0, shop.boughtStock?.[itemId] | 0 || 0);247
return boughtLot(shop, itemId)?.quantity ?? 0;248
}249
250
function addBoughtLot (shop, itemId, quantity, origins)251
{252
const qty = Math.max(0, quantity | 0 || 0);253
if (qty <= 0)254
{ return; }255
const existing = boughtLot(shop, itemId);256
const nextOrigins = mergeOriginLists(257
existing?.origins ?? [],258
normalizeOrigins({ quantity: qty, origins })259
);260
shop.boughtStock[itemId] = {261
quantity: (existing?.quantity ?? 0) + qty,262
origins: nextOrigins263
};264
}265
266
/** Pull FIFO origins from bought stock; returns null if insufficient. */267
function takeBoughtLot (shop, itemId, quantity)268
{269
const qty = Math.max(0, quantity | 0 || 0);270
const lot = boughtLot(shop, itemId);271
if (!lot || lot.quantity < qty)272
{ return null; }273
const split = splitOrigins(lot.origins, qty);274
const remainQty = lot.quantity - qty;275
if (remainQty <= 0)276
{ delete shop.boughtStock[itemId]; }277
else278
{279
shop.boughtStock[itemId] = {280
quantity: remainQty,281
origins: split.remain282
};283
}284
return { quantity: qty, origins: split.taken };214
}285
}215
286
216
function shopStockView (world, shop, now)287
function shopStockView (world, shop, now)@@ -246,10 +317,10 @@ function shopStockView (world, shop, now)246
source: "stock"317
source: "stock"247
});318
});248
}319
}249
for (const [key, qty] of Object.entries(shop.boughtStock ?? {}))320
for (const key of Object.keys(shop.boughtStock ?? {}))250
{321
{251
const itemId = key | 0;322
const itemId = key | 0;252
const available = qty | 0;323
const available = boughtAvailable(shop, itemId);253
if (available <= 0 || !canSellInNpcShop(itemId))324
if (available <= 0 || !canSellInNpcShop(itemId))254
{ continue; }325
{ continue; }255
const def = itemDefinition(itemId);326
const def = itemDefinition(itemId);@@ -399,20 +470,37 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,399
{ throw userError("You cannot afford that."); }470
{ throw userError("You cannot afford that."); }400
471
401
const displayName = shopDisplayName(shop, npcHandle, world);472
const displayName = shopDisplayName(shop, npcHandle, world);402
const shopOrigin = { kind: ItemOriginKind.shop, displayName };473
let stack;403
const stack = attachOrigins({474
if (listing.source === "bought")404
itemId: buyItemId,475
{405
quantity: qty,476
const lot = boughtLot(shop, buyItemId);406
origins: [{ origin: shopOrigin, quantity: qty }]477
if (!lot || lot.quantity < qty)407
});478
{ throw userError("Not enough stock."); }479
const split = splitOrigins(lot.origins, qty);480
stack = attachOrigins({481
itemId: buyItemId,482
quantity: qty,483
origins: split.taken484
});485
}486
else487
{488
const shopOrigin = { kind: ItemOriginKind.shop, displayName };489
stack = attachOrigins({490
itemId: buyItemId,491
quantity: qty,492
origins: [{ origin: shopOrigin, quantity: qty }]493
});494
}408
const added = insertStack(paid.slots, stack, def);495
const added = insertStack(paid.slots, stack, def);409
inventory.slots = added.slots;496
inventory.slots = added.slots;410
if (added.remainder > 0)497
if (added.remainder > 0)411
{498
{499
const overflowOrigins = splitOrigins(normalizeOrigins(stack), qty - added.remainder).remain;412
const overflow = attachOrigins({500
const overflow = attachOrigins({413
itemId: buyItemId,501
itemId: buyItemId,414
quantity: added.remainder,502
quantity: added.remainder,415
origins: [{ origin: shopOrigin, quantity: added.remainder }]503
origins: overflowOrigins416
});504
});417
const vault = ensureVault(world.ecs, handle);505
const vault = ensureVault(world.ecs, handle);418
const vaulted = insertStackGrowable(vault.slots, overflow, def);506
const vaulted = insertStackGrowable(vault.slots, overflow, def);@@ -423,9 +511,8 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,423
511
424
if (listing.source === "bought")512
if (listing.source === "bought")425
{513
{426
shop.boughtStock[buyItemId] = boughtAvailable(shop, buyItemId) - qty;514
if (!takeBoughtLot(shop, buyItemId, qty))427
if (shop.boughtStock[buyItemId] <= 0)515
{ throw userError("Not enough stock."); }428
{ delete shop.boughtStock[buyItemId]; }429
}516
}430
else517
else431
{518
{@@ -573,7 +660,13 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde573
if (line && (line.quantity | 0) > 0 && refill > 0)660
if (line && (line.quantity | 0) > 0 && refill > 0)574
{ shop.remaining[goodsItemId] = catalogAvailable(shop, goodsItemId) + refill; }661
{ shop.remaining[goodsItemId] = catalogAvailable(shop, goodsItemId) + refill; }575
if (leftover > 0)662
if (leftover > 0)576
{ shop.boughtStock[goodsItemId] = boughtAvailable(shop, goodsItemId) + leftover; }663
{664
const soldStack = isCheque ? reservedStack : taken.taken;665
const soldOrigins = normalizeOrigins(soldStack);666
// Catalog refill absorbs first; leftover keeps remaining origins for resale.667
const { remain: resaleOrigins } = splitOrigins(soldOrigins, refill);668
addBoughtLot(shop, goodsItemId, leftover, resaleOrigins);669
}577
670
578
const displayName = shopDisplayName(shop, npcHandle, world);671
const displayName = shopDisplayName(shop, npcHandle, world);579
return {672
return {@@ -33,5 +33,6 @@ export const WorkerMessage = Object.freeze({
33
33
applyCombatHitXp: "applyCombatHitXp",
34
34
spawnCorpseDrops: "spawnCorpseDrops",
35
35
applyRespawn: "applyRespawn",
36
clearCombat: "clearCombat"
36
clearCombat: "clearCombat",
37
setItemLastSales: "setItemLastSales"
37
38
});
@@ -33,5 +33,6 @@ export const WorkerMessage = Object.freeze({33
applyCombatHitXp: "applyCombatHitXp",33
applyCombatHitXp: "applyCombatHitXp",34
spawnCorpseDrops: "spawnCorpseDrops",34
spawnCorpseDrops: "spawnCorpseDrops",35
applyRespawn: "applyRespawn",35
applyRespawn: "applyRespawn",36
clearCombat: "clearCombat"36
clearCombat: "clearCombat",37
setItemLastSales: "setItemLastSales"37
});38
});@@ -33,7 +33,9 @@ import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/
33
33
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
34
34
import { BlockType } from "../../../shared/definitions/tiles.js";
35
35
import { ItemId } from "../../../shared/definitions/items.js";
36
import { seasonIdAt } from "../../../shared/world/season.js";
36
37
import { CourierService } from "../courier/service.js";
38
import { MarketService } from "../market/service.js";
37
39
import { findReservedChequeIndex } from "../items/bags.js";
38
40
39
41
export class Simulation
@@ -55,6 +57,7 @@ export class Simulation
55
57
this.replication = [];
56
58
this.pendingPrivate = [];
57
59
this.courier = null;
60
this.market = null;
58
61
this.altarTiles = [];
59
62
this.authoredCache = new Map();
60
63
this.simulatingChunkKeys = new Set();
@@ -90,6 +93,11 @@ export class Simulation
90
93
worldDb: this.worldDb,
91
94
simulation: this
92
95
});
96
this.market = new MarketService({
97
stateDb: this.stateDb,
98
worldDb: this.worldDb,
99
simulation: this
100
});
93
101
this.#refreshAltarIndex();
94
102
}
95
103
@@ -104,22 +112,24 @@ export class Simulation
104
112
this.#configureWorkers();
105
113
}
106
114
107
/** Sparse last-sale map for editor base-price readouts (empty until marketplace writes). */
115
/** Sparse last-sale map for editor base-price readouts. */
108
116
itemLastSalesSnapshot ()
109
117
{
110
const out = {};
118
return this.market?.snapshot?.() ?? {};
119
}
120
121
syncItemLastSales (lastSales)
122
{
123
const sales = {};
124
for (const [itemId, sale] of lastSales?.entries?.() ?? [])
125
{ sales[String(itemId)] = sale; }
111
126
for (const worker of this.workers)
112
127
{
113
const sales = worker.world?.itemLastSales;
114
if (!sales || typeof sales.entries !== "function")
115
{ continue; }
116
for (const [itemId, sale] of sales.entries())
117
{
118
if (sale)
119
{ out[String(itemId)] = sale; }
120
}
128
worker.call({
129
type: WorkerMessage.setItemLastSales,
130
sales
131
});
121
132
}
122
return out;
123
133
}
124
134
125
135
reloadWorld ()
@@ -138,6 +148,7 @@ export class Simulation
138
148
}
139
149
this.#syncAllReplicas();
140
150
this.courier?.refreshBankIndex();
151
this.market?.refreshIndex();
141
152
this.#refreshAltarIndex();
142
153
}
143
154
@@ -257,6 +268,8 @@ export class Simulation
257
268
258
269
if (this.courier)
259
270
{ events.push(...this.courier.step(now, dt)); }
271
if (this.market)
272
{ events.push(...this.market.step(now)); }
260
273
261
274
this.#syncGhosts();
262
275
events.push(...this.pendingPrivate.splice(0));
@@ -276,7 +289,8 @@ export class Simulation
276
289
unixMs: now,
277
290
worldUnixMs: date.getTime(),
278
291
iso: date.toISOString(),
279
hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600
292
hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600,
293
season: seasonIdAt(now)
280
294
};
281
295
}
282
296
@@ -739,6 +753,17 @@ export class Simulation
739
753
{
740
754
if (item.command.type === "respawn")
741
755
{ return this.#respawnCharacter(item.sessionId, item.command.characterId); }
756
if (
757
item.command.type === "open-market"
758
|| item.command.type === "place-market-sell"
759
|| item.command.type === "place-market-buy"
760
|| item.command.type === "cancel-market-order"
761
|| item.command.type === "close-market"
762
)
763
{
764
const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
765
return result?.events ?? [];
766
}
742
767
const entityId = this.characterEntities.get(item.command.characterId);
743
768
const record = entityId ? this.directory.get(entityId) : null;
744
769
if (!record)
@@ -33,7 +33,9 @@ import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/33
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";33
import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";34
import { BlockType } from "../../../shared/definitions/tiles.js";34
import { BlockType } from "../../../shared/definitions/tiles.js";35
import { ItemId } from "../../../shared/definitions/items.js";35
import { ItemId } from "../../../shared/definitions/items.js";36
import { seasonIdAt } from "../../../shared/world/season.js";36
import { CourierService } from "../courier/service.js";37
import { CourierService } from "../courier/service.js";38
import { MarketService } from "../market/service.js";37
import { findReservedChequeIndex } from "../items/bags.js";39
import { findReservedChequeIndex } from "../items/bags.js";38
40
39
export class Simulation41
export class Simulation@@ -55,6 +57,7 @@ export class Simulation55
this.replication = [];57
this.replication = [];56
this.pendingPrivate = [];58
this.pendingPrivate = [];57
this.courier = null;59
this.courier = null;60
this.market = null;58
this.altarTiles = [];61
this.altarTiles = [];59
this.authoredCache = new Map();62
this.authoredCache = new Map();60
this.simulatingChunkKeys = new Set();63
this.simulatingChunkKeys = new Set();@@ -90,6 +93,11 @@ export class Simulation90
worldDb: this.worldDb,93
worldDb: this.worldDb,91
simulation: this94
simulation: this92
});95
});96
this.market = new MarketService({97
stateDb: this.stateDb,98
worldDb: this.worldDb,99
simulation: this100
});93
this.#refreshAltarIndex();101
this.#refreshAltarIndex();94
}102
}95
103
@@ -104,22 +112,24 @@ export class Simulation104
this.#configureWorkers();112
this.#configureWorkers();105
}113
}106
114
107
/** Sparse last-sale map for editor base-price readouts (empty until marketplace writes). */115
/** Sparse last-sale map for editor base-price readouts. */108
itemLastSalesSnapshot ()116
itemLastSalesSnapshot ()109
{117
{110
const out = {};118
return this.market?.snapshot?.() ?? {};119
}120
121
syncItemLastSales (lastSales)122
{123
const sales = {};124
for (const [itemId, sale] of lastSales?.entries?.() ?? [])125
{ sales[String(itemId)] = sale; }111
for (const worker of this.workers)126
for (const worker of this.workers)112
{127
{113
const sales = worker.world?.itemLastSales;128
worker.call({114
if (!sales || typeof sales.entries !== "function")129
type: WorkerMessage.setItemLastSales,115
{ continue; }130
sales116
for (const [itemId, sale] of sales.entries())131
});117
{118
if (sale)119
{ out[String(itemId)] = sale; }120
}121
}132
}122
return out;123
}133
}124
134
125
reloadWorld ()135
reloadWorld ()@@ -138,6 +148,7 @@ export class Simulation138
}148
}139
this.#syncAllReplicas();149
this.#syncAllReplicas();140
this.courier?.refreshBankIndex();150
this.courier?.refreshBankIndex();151
this.market?.refreshIndex();141
this.#refreshAltarIndex();152
this.#refreshAltarIndex();142
}153
}143
154
@@ -257,6 +268,8 @@ export class Simulation257
268
258
if (this.courier)269
if (this.courier)259
{ events.push(...this.courier.step(now, dt)); }270
{ events.push(...this.courier.step(now, dt)); }271
if (this.market)272
{ events.push(...this.market.step(now)); }260
273
261
this.#syncGhosts();274
this.#syncGhosts();262
events.push(...this.pendingPrivate.splice(0));275
events.push(...this.pendingPrivate.splice(0));@@ -276,7 +289,8 @@ export class Simulation276
unixMs: now,289
unixMs: now,277
worldUnixMs: date.getTime(),290
worldUnixMs: date.getTime(),278
iso: date.toISOString(),291
iso: date.toISOString(),279
hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600292
hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600,293
season: seasonIdAt(now)280
};294
};281
}295
}282
296
@@ -739,6 +753,17 @@ export class Simulation739
{753
{740
if (item.command.type === "respawn")754
if (item.command.type === "respawn")741
{ return this.#respawnCharacter(item.sessionId, item.command.characterId); }755
{ return this.#respawnCharacter(item.sessionId, item.command.characterId); }756
if (757
item.command.type === "open-market"758
|| item.command.type === "place-market-sell"759
|| item.command.type === "place-market-buy"760
|| item.command.type === "cancel-market-order"761
|| item.command.type === "close-market"762
)763
{764
const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);765
return result?.events ?? [];766
}742
const entityId = this.characterEntities.get(item.command.characterId);767
const entityId = this.characterEntities.get(item.command.characterId);743
const record = entityId ? this.directory.get(entityId) : null;768
const record = entityId ? this.directory.get(entityId) : null;744
if (!record)769
if (!record)@@ -35,7 +35,8 @@ import {
35
35
handleGatherCommand,
36
36
stepGather,
37
37
cancelGather,
38
clearOreRespawnsForChunk
38
clearOreRespawnsForChunk,
39
clearTreeRespawnsForChunk
39
40
} from "../gathering/service.js";
40
41
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
41
42
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
@@ -77,6 +78,7 @@ export class WorkerWorld
77
78
this.groundItems = new Map();
78
79
this.groundByTile = new Map();
79
80
this.oreRespawns = new Map();
81
this.treeRespawns = new Map();
80
82
this.settings = { ...DEFAULT_WORLD_SETTINGS };
81
83
this.activeRevisionId = 1;
82
84
}
@@ -162,6 +164,13 @@ export class WorkerWorld
162
164
{ entity.combat.targetEntityId = null; }
163
165
}
164
166
return { ok: true };
167
case WorkerMessage.setItemLastSales:
168
{
169
this.itemLastSales = new Map();
170
for (const [key, sale] of Object.entries(message.sales ?? {}))
171
{ this.itemLastSales.set(Number(key), sale); }
172
return { ok: true };
173
}
165
174
default:
166
175
throw new Error(`Unknown worker message ${message.type}`);
167
176
}
@@ -202,6 +211,7 @@ export class WorkerWorld
202
211
for (const chunk of message.chunks ?? [])
203
212
{
204
213
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
214
clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
205
215
this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
206
216
data: cloneChunkData(chunk.data),
207
217
simulating: false,
@@ -218,6 +228,7 @@ export class WorkerWorld
218
228
const key = chunkKey(chunk.chunkX, chunk.chunkY);
219
229
const existing = this.chunks.get(key);
220
230
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
231
clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
221
232
this.chunks.set(key, {
222
233
data: cloneChunkData(chunk.data),
223
234
simulating: existing?.simulating ?? false,
@@ -249,6 +260,7 @@ export class WorkerWorld
249
260
if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
250
261
{
251
262
clearOreRespawnsForChunk(this, chunkX, chunkY);
263
clearTreeRespawnsForChunk(this, chunkX, chunkY);
252
264
this.chunks.delete(key);
253
265
}
254
266
}
@@ -35,7 +35,8 @@ import {35
handleGatherCommand,35
handleGatherCommand,36
stepGather,36
stepGather,37
cancelGather,37
cancelGather,38
clearOreRespawnsForChunk38
clearOreRespawnsForChunk,39
clearTreeRespawnsForChunk39
} from "../gathering/service.js";40
} from "../gathering/service.js";40
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";41
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";41
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";42
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";@@ -77,6 +78,7 @@ export class WorkerWorld77
this.groundItems = new Map();78
this.groundItems = new Map();78
this.groundByTile = new Map();79
this.groundByTile = new Map();79
this.oreRespawns = new Map();80
this.oreRespawns = new Map();81
this.treeRespawns = new Map();80
this.settings = { ...DEFAULT_WORLD_SETTINGS };82
this.settings = { ...DEFAULT_WORLD_SETTINGS };81
this.activeRevisionId = 1;83
this.activeRevisionId = 1;82
}84
}@@ -162,6 +164,13 @@ export class WorkerWorld162
{ entity.combat.targetEntityId = null; }164
{ entity.combat.targetEntityId = null; }163
}165
}164
return { ok: true };166
return { ok: true };167
case WorkerMessage.setItemLastSales:168
{169
this.itemLastSales = new Map();170
for (const [key, sale] of Object.entries(message.sales ?? {}))171
{ this.itemLastSales.set(Number(key), sale); }172
return { ok: true };173
}165
default:174
default:166
throw new Error(`Unknown worker message ${message.type}`);175
throw new Error(`Unknown worker message ${message.type}`);167
}176
}@@ -202,6 +211,7 @@ export class WorkerWorld202
for (const chunk of message.chunks ?? [])211
for (const chunk of message.chunks ?? [])203
{212
{204
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);213
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);214
clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);205
this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {215
this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {206
data: cloneChunkData(chunk.data),216
data: cloneChunkData(chunk.data),207
simulating: false,217
simulating: false,@@ -218,6 +228,7 @@ export class WorkerWorld218
const key = chunkKey(chunk.chunkX, chunk.chunkY);228
const key = chunkKey(chunk.chunkX, chunk.chunkY);219
const existing = this.chunks.get(key);229
const existing = this.chunks.get(key);220
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);230
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);231
clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);221
this.chunks.set(key, {232
this.chunks.set(key, {222
data: cloneChunkData(chunk.data),233
data: cloneChunkData(chunk.data),223
simulating: existing?.simulating ?? false,234
simulating: existing?.simulating ?? false,@@ -249,6 +260,7 @@ export class WorkerWorld249
if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)260
if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)250
{261
{251
clearOreRespawnsForChunk(this, chunkX, chunkY);262
clearOreRespawnsForChunk(this, chunkX, chunkY);263
clearTreeRespawnsForChunk(this, chunkX, chunkY);252
this.chunks.delete(key);264
this.chunks.delete(key);253
}265
}254
}266
}@@ -200,6 +200,9 @@ test("smelting bronze consumes tin and copper, grants bar and Smithing XP", () =
200
200
assert.equal(countItem(bag.inventory, ItemId.tinOre), 0);
201
201
assert.equal(countItem(bag.inventory, ItemId.copperOre), 0);
202
202
assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 1);
203
const bar = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.bronzeBar);
204
assert.equal(bar?.origins?.[0]?.origin?.verb, "Forged");
205
assert.match(bar?.origins?.[0]?.origin?.displayName ?? "", /^Ada/);
203
206
const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
204
207
assert.ok(smithingAfter > smithingBefore);
205
208
}
@@ -358,6 +361,8 @@ test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe"
358
361
let bag = harness.simulation.bagOf(playerId);
359
362
assert.equal(countItem(bag.inventory, ItemId.pineHandle), 1);
360
363
assert.equal(countItem(bag.inventory, ItemId.pineLog), 0);
364
const handle = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.pineHandle);
365
assert.equal(handle?.origins?.[0]?.origin?.verb, "Carved");
361
366
362
367
harness.simulation.enqueue(1, {
363
368
type: "start-craft",
@@ -369,6 +374,8 @@ test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe"
369
374
bag = harness.simulation.bagOf(playerId);
370
375
assert.equal(countItem(bag.inventory, ItemId.bronzePickaxeHead), 1);
371
376
assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 0);
377
const head = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.bronzePickaxeHead);
378
assert.equal(head?.origins?.[0]?.origin?.verb, "Smithed");
372
379
373
380
harness.simulation.enqueue(1, {
374
381
type: "start-craft",
@@ -381,6 +388,9 @@ test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe"
381
388
assert.equal(countItem(bag.inventory, ItemId.bronzePickaxe), 1);
382
389
assert.equal(countItem(bag.inventory, ItemId.pineHandle), 0);
383
390
assert.equal(countItem(bag.inventory, ItemId.bronzePickaxeHead), 0);
391
const pickaxe = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.bronzePickaxe);
392
assert.equal(pickaxe?.origins?.[0]?.origin?.verb, "Assembled");
393
assert.match(pickaxe?.origins?.[0]?.origin?.displayName ?? "", /^Ada/);
384
394
}
385
395
finally
386
396
{ harness.close(); }
@@ -200,6 +200,9 @@ test("smelting bronze consumes tin and copper, grants bar and Smithing XP", () =200
assert.equal(countItem(bag.inventory, ItemId.tinOre), 0);200
assert.equal(countItem(bag.inventory, ItemId.tinOre), 0);201
assert.equal(countItem(bag.inventory, ItemId.copperOre), 0);201
assert.equal(countItem(bag.inventory, ItemId.copperOre), 0);202
assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 1);202
assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 1);203
const bar = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.bronzeBar);204
assert.equal(bar?.origins?.[0]?.origin?.verb, "Forged");205
assert.match(bar?.origins?.[0]?.origin?.displayName ?? "", /^Ada/);203
const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;206
const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;204
assert.ok(smithingAfter > smithingBefore);207
assert.ok(smithingAfter > smithingBefore);205
}208
}@@ -358,6 +361,8 @@ test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe"358
let bag = harness.simulation.bagOf(playerId);361
let bag = harness.simulation.bagOf(playerId);359
assert.equal(countItem(bag.inventory, ItemId.pineHandle), 1);362
assert.equal(countItem(bag.inventory, ItemId.pineHandle), 1);360
assert.equal(countItem(bag.inventory, ItemId.pineLog), 0);363
assert.equal(countItem(bag.inventory, ItemId.pineLog), 0);364
const handle = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.pineHandle);365
assert.equal(handle?.origins?.[0]?.origin?.verb, "Carved");361
366
362
harness.simulation.enqueue(1, {367
harness.simulation.enqueue(1, {363
type: "start-craft",368
type: "start-craft",@@ -369,6 +374,8 @@ test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe"369
bag = harness.simulation.bagOf(playerId);374
bag = harness.simulation.bagOf(playerId);370
assert.equal(countItem(bag.inventory, ItemId.bronzePickaxeHead), 1);375
assert.equal(countItem(bag.inventory, ItemId.bronzePickaxeHead), 1);371
assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 0);376
assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 0);377
const head = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.bronzePickaxeHead);378
assert.equal(head?.origins?.[0]?.origin?.verb, "Smithed");372
379
373
harness.simulation.enqueue(1, {380
harness.simulation.enqueue(1, {374
type: "start-craft",381
type: "start-craft",@@ -381,6 +388,9 @@ test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe"381
assert.equal(countItem(bag.inventory, ItemId.bronzePickaxe), 1);388
assert.equal(countItem(bag.inventory, ItemId.bronzePickaxe), 1);382
assert.equal(countItem(bag.inventory, ItemId.pineHandle), 0);389
assert.equal(countItem(bag.inventory, ItemId.pineHandle), 0);383
assert.equal(countItem(bag.inventory, ItemId.bronzePickaxeHead), 0);390
assert.equal(countItem(bag.inventory, ItemId.bronzePickaxeHead), 0);391
const pickaxe = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.bronzePickaxe);392
assert.equal(pickaxe?.origins?.[0]?.origin?.verb, "Assembled");393
assert.match(pickaxe?.origins?.[0]?.origin?.displayName ?? "", /^Ada/);384
}394
}385
finally395
finally386
{ harness.close(); }396
{ harness.close(); }@@ -1,7 +1,13 @@
1
1
import test from "node:test";
2
2
import assert from "node:assert/strict";
3
3
import { ItemId } from "../../shared/definitions/items.js";
4
import { BlockType } from "../../shared/definitions/tiles.js";
4
5
import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
6
import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody } from "../../shared/market/exchange.js";
7
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
8
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
9
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
10
import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
5
11
6
12
test("blank cheques cannot be listed on the marketplace", () =>
7
13
{
@@ -28,3 +34,174 @@ test("normal items are marketplace sellable by default", () =>
28
34
{
29
35
assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);
30
36
});
37
38
test("midpoint trade price rounds half units deterministically", () =>
39
{
40
assert.equal(midpointTradePrice(100, 80), 90);
41
assert.equal(midpointTradePrice(101, 80), 91);
42
assert.equal(midpointTradePrice(80, 100), 90);
43
});
44
45
function placePlaza (worldDb)
46
{
47
const data = createEmptyChunkData();
48
data.open = true;
49
data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: null };
50
data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null };
51
worldDb.saveChunkVersion(0, 0, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
52
}
53
54
test("sell then buy at Central Exchange matches at midpoint and pays seller by pigeon letter", () =>
55
{
56
const harness = makeSimulation({ workerCount: 1 });
57
try
58
{
59
placePlaza(harness.worldDb);
60
harness.simulation.reloadWorld();
61
62
const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" });
63
const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" });
64
const sellerBag = addCoinsToSlots(emptySlots(), 0);
65
sellerBag.slots[0] = { itemId: ItemId.apple, quantity: 2 };
66
harness.stateDb.saveBag(seller.character_id, {
67
inventory: sellerBag.slots,
68
equipment: emptyEquipment(),
69
vault: [],
70
vaultReserved: []
71
});
72
const buyerBag = addCoinsToSlots(emptySlots(), 100);
73
assert.equal(buyerBag.ok, true);
74
harness.stateDb.saveBag(buyer.character_id, {
75
inventory: buyerBag.slots,
76
equipment: emptyEquipment(),
77
vault: [],
78
vaultReserved: []
79
});
80
81
const sellerId = harness.simulation.spawnCharacter(1, seller);
82
const buyerId = harness.simulation.spawnCharacter(2, buyer);
83
harness.simulation.step();
84
85
harness.simulation.enqueue(1, {
86
type: "place-market-sell",
87
characterId: seller.character_id,
88
slotIndex: 0,
89
quantity: 2,
90
minUnitPrice: 8
91
});
92
const sellResult = harness.simulation.step();
93
assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events));
94
assert.ok(sellResult.events.some((event) => event.type === "market-open"));
95
96
harness.simulation.enqueue(2, {
97
type: "place-market-buy",
98
characterId: buyer.character_id,
99
itemId: ItemId.apple,
100
quantity: 2,
101
maxUnitPrice: 12
102
});
103
const buyResult = harness.simulation.step();
104
assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
105
const trade = buyResult.events.find((event) => event.type === "market-trade");
106
assert.ok(trade, JSON.stringify(buyResult.events));
107
assert.equal(trade.unitPrice, 10);
108
assert.equal(trade.quantity, 2);
109
110
const buyerBagNow = harness.simulation.bagOf(buyerId);
111
assert.equal((buyerBagNow.inventory ?? []).some((slot) => slot?.itemId === ItemId.apple), true);
112
113
// Advance courier flight until pigeons deliver to bank.
114
for (let i = 0; i < 500; i++)
115
{
116
harness.advance(1000);
117
harness.simulation.step();
118
const sellerVault = harness.stateDb.getBag(seller.character_id);
119
const coins = countCoinsInSlots(sellerVault.vault ?? []);
120
const hasLetter = (sellerVault.vault ?? []).some((slot) => slot?.itemId === ItemId.letter);
121
if (coins >= 20 && hasLetter)
122
{
123
const letter = (sellerVault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
124
assert.match(letter.instance.body, /Central Exchange/);
125
assert.match(letter.instance.body, /sold|filled|proceeds/i);
126
assert.equal(harness.simulation.market.lastSaleFor(ItemId.apple)?.lastTradePrice, 10);
127
return;
128
}
129
}
130
assert.fail("Seller did not receive coins and letter in vault");
131
}
132
finally
133
{ harness.close(); }
134
});
135
136
test("orders older than one month auto-cancel and return escrow to bank", () =>
137
{
138
const harness = makeSimulation({ workerCount: 1 });
139
try
140
{
141
placePlaza(harness.worldDb);
142
harness.simulation.reloadWorld();
143
144
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
145
const bag = addCoinsToSlots(emptySlots(), 50);
146
assert.equal(bag.ok, true);
147
harness.stateDb.saveBag(character.character_id, {
148
inventory: bag.slots,
149
equipment: emptyEquipment(),
150
vault: [],
151
vaultReserved: []
152
});
153
harness.simulation.spawnCharacter(1, character);
154
harness.simulation.step();
155
156
harness.simulation.enqueue(1, {
157
type: "place-market-buy",
158
characterId: character.character_id,
159
itemId: ItemId.apple,
160
quantity: 1,
161
maxUnitPrice: 10
162
});
163
const placed = harness.simulation.step();
164
assert.equal(placed.events.some((event) => event.type === "command-error"), false, JSON.stringify(placed.events));
165
const open = harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id);
166
assert.equal(open.length, 1);
167
168
const order = open[0];
169
harness.stateDb.db.prepare("UPDATE market_orders SET created_at = ? WHERE order_id = ?")
170
.run(Date.now() - MARKET_ORDER_MAX_AGE_MS - 1000, order.orderId);
171
172
const expired = harness.simulation.market.step(Date.now());
173
assert.ok(expired.some((event) => event.type === "market-order-expired"));
174
assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id).length, 0);
175
176
for (let i = 0; i < 500; i++)
177
{
178
harness.advance(1000);
179
harness.simulation.step();
180
const vault = harness.stateDb.getBag(character.character_id);
181
const coins = countCoinsInSlots(vault.vault ?? []);
182
const hasLetter = (vault.vault ?? []).some((slot) => slot?.itemId === ItemId.letter);
183
if (coins >= 10 && hasLetter)
184
{
185
const letter = (vault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
186
assert.match(letter.instance.body, /one month/i);
187
assert.match(letter.instance.body, /Central Exchange/);
188
return;
189
}
190
}
191
assert.fail("Expired order did not return escrow letter to bank");
192
}
193
finally
194
{ harness.close(); }
195
});
196
197
test("exchange letter copy mentions Central Exchange staff signature", () =>
198
{
199
const body = soldLetterBody({
200
itemName: "Apple",
201
quantity: 1,
202
unitPrice: 5,
203
clerkName: "Bobby Pennies"
204
});
205
assert.match(body, /Bobby Pennies/);
206
assert.match(body, /Central Exchange/);
207
});
@@ -1,7 +1,13 @@1
import test from "node:test";1
import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { ItemId } from "../../shared/definitions/items.js";3
import { ItemId } from "../../shared/definitions/items.js";4
import { BlockType } from "../../shared/definitions/tiles.js";4
import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";5
import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";6
import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody } from "../../shared/market/exchange.js";7
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";8
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";9
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";10
import { CHUNK_SIZE } from "../../shared/protocol/constants.js";5
11
6
test("blank cheques cannot be listed on the marketplace", () =>12
test("blank cheques cannot be listed on the marketplace", () =>7
{13
{@@ -28,3 +34,174 @@ test("normal items are marketplace sellable by default", () =>28
{34
{29
assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);35
assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);30
});36
});37
38
test("midpoint trade price rounds half units deterministically", () =>39
{40
assert.equal(midpointTradePrice(100, 80), 90);41
assert.equal(midpointTradePrice(101, 80), 91);42
assert.equal(midpointTradePrice(80, 100), 90);43
});44
45
function placePlaza (worldDb)46
{47
const data = createEmptyChunkData();48
data.open = true;49
data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: null };50
data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null };51
worldDb.saveChunkVersion(0, 0, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));52
}53
54
test("sell then buy at Central Exchange matches at midpoint and pays seller by pigeon letter", () =>55
{56
const harness = makeSimulation({ workerCount: 1 });57
try58
{59
placePlaza(harness.worldDb);60
harness.simulation.reloadWorld();61
62
const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" });63
const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" });64
const sellerBag = addCoinsToSlots(emptySlots(), 0);65
sellerBag.slots[0] = { itemId: ItemId.apple, quantity: 2 };66
harness.stateDb.saveBag(seller.character_id, {67
inventory: sellerBag.slots,68
equipment: emptyEquipment(),69
vault: [],70
vaultReserved: []71
});72
const buyerBag = addCoinsToSlots(emptySlots(), 100);73
assert.equal(buyerBag.ok, true);74
harness.stateDb.saveBag(buyer.character_id, {75
inventory: buyerBag.slots,76
equipment: emptyEquipment(),77
vault: [],78
vaultReserved: []79
});80
81
const sellerId = harness.simulation.spawnCharacter(1, seller);82
const buyerId = harness.simulation.spawnCharacter(2, buyer);83
harness.simulation.step();84
85
harness.simulation.enqueue(1, {86
type: "place-market-sell",87
characterId: seller.character_id,88
slotIndex: 0,89
quantity: 2,90
minUnitPrice: 891
});92
const sellResult = harness.simulation.step();93
assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events));94
assert.ok(sellResult.events.some((event) => event.type === "market-open"));95
96
harness.simulation.enqueue(2, {97
type: "place-market-buy",98
characterId: buyer.character_id,99
itemId: ItemId.apple,100
quantity: 2,101
maxUnitPrice: 12102
});103
const buyResult = harness.simulation.step();104
assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));105
const trade = buyResult.events.find((event) => event.type === "market-trade");106
assert.ok(trade, JSON.stringify(buyResult.events));107
assert.equal(trade.unitPrice, 10);108
assert.equal(trade.quantity, 2);109
110
const buyerBagNow = harness.simulation.bagOf(buyerId);111
assert.equal((buyerBagNow.inventory ?? []).some((slot) => slot?.itemId === ItemId.apple), true);112
113
// Advance courier flight until pigeons deliver to bank.114
for (let i = 0; i < 500; i++)115
{116
harness.advance(1000);117
harness.simulation.step();118
const sellerVault = harness.stateDb.getBag(seller.character_id);119
const coins = countCoinsInSlots(sellerVault.vault ?? []);120
const hasLetter = (sellerVault.vault ?? []).some((slot) => slot?.itemId === ItemId.letter);121
if (coins >= 20 && hasLetter)122
{123
const letter = (sellerVault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);124
assert.match(letter.instance.body, /Central Exchange/);125
assert.match(letter.instance.body, /sold|filled|proceeds/i);126
assert.equal(harness.simulation.market.lastSaleFor(ItemId.apple)?.lastTradePrice, 10);127
return;128
}129
}130
assert.fail("Seller did not receive coins and letter in vault");131
}132
finally133
{ harness.close(); }134
});135
136
test("orders older than one month auto-cancel and return escrow to bank", () =>137
{138
const harness = makeSimulation({ workerCount: 1 });139
try140
{141
placePlaza(harness.worldDb);142
harness.simulation.reloadWorld();143
144
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });145
const bag = addCoinsToSlots(emptySlots(), 50);146
assert.equal(bag.ok, true);147
harness.stateDb.saveBag(character.character_id, {148
inventory: bag.slots,149
equipment: emptyEquipment(),150
vault: [],151
vaultReserved: []152
});153
harness.simulation.spawnCharacter(1, character);154
harness.simulation.step();155
156
harness.simulation.enqueue(1, {157
type: "place-market-buy",158
characterId: character.character_id,159
itemId: ItemId.apple,160
quantity: 1,161
maxUnitPrice: 10162
});163
const placed = harness.simulation.step();164
assert.equal(placed.events.some((event) => event.type === "command-error"), false, JSON.stringify(placed.events));165
const open = harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id);166
assert.equal(open.length, 1);167
168
const order = open[0];169
harness.stateDb.db.prepare("UPDATE market_orders SET created_at = ? WHERE order_id = ?")170
.run(Date.now() - MARKET_ORDER_MAX_AGE_MS - 1000, order.orderId);171
172
const expired = harness.simulation.market.step(Date.now());173
assert.ok(expired.some((event) => event.type === "market-order-expired"));174
assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id).length, 0);175
176
for (let i = 0; i < 500; i++)177
{178
harness.advance(1000);179
harness.simulation.step();180
const vault = harness.stateDb.getBag(character.character_id);181
const coins = countCoinsInSlots(vault.vault ?? []);182
const hasLetter = (vault.vault ?? []).some((slot) => slot?.itemId === ItemId.letter);183
if (coins >= 10 && hasLetter)184
{185
const letter = (vault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);186
assert.match(letter.instance.body, /one month/i);187
assert.match(letter.instance.body, /Central Exchange/);188
return;189
}190
}191
assert.fail("Expired order did not return escrow letter to bank");192
}193
finally194
{ harness.close(); }195
});196
197
test("exchange letter copy mentions Central Exchange staff signature", () =>198
{199
const body = soldLetterBody({200
itemName: "Apple",201
quantity: 1,202
unitPrice: 5,203
clerkName: "Bobby Pennies"204
});205
assert.match(body, /Bobby Pennies/);206
assert.match(body, /Central Exchange/);207
});@@ -250,6 +250,12 @@ test("mining uses the best pickaxe in inventory without equipping", () =>
250
250
251
251
const bag = harness.simulation.bagOf(playerId);
252
252
assert.ok(countItem(bag.inventory, ItemId.ironOre) >= 1);
253
const oreStack = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.ironOre);
254
assert.ok(oreStack?.origins?.some((entry) =>
255
entry.origin?.kind === "gathered"
256
&& entry.origin?.verb === "Mined"
257
&& typeof entry.origin?.displayName === "string"
258
&& entry.origin.displayName.length > 0));
253
259
}
254
260
finally
255
261
{ harness.close(); }
@@ -250,6 +250,12 @@ test("mining uses the best pickaxe in inventory without equipping", () =>250
250
251
const bag = harness.simulation.bagOf(playerId);251
const bag = harness.simulation.bagOf(playerId);252
assert.ok(countItem(bag.inventory, ItemId.ironOre) >= 1);252
assert.ok(countItem(bag.inventory, ItemId.ironOre) >= 1);253
const oreStack = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.ironOre);254
assert.ok(oreStack?.origins?.some((entry) =>255
entry.origin?.kind === "gathered"256
&& entry.origin?.verb === "Mined"257
&& typeof entry.origin?.displayName === "string"258
&& entry.origin.displayName.length > 0));253
}259
}254
finally260
finally255
{ harness.close(); }261
{ harness.close(); }@@ -1,12 +1,49 @@
1
1
import test from "node:test";
2
2
import assert from "node:assert/strict";
3
import { ItemOriginKind, formatOriginBreakdown, mergeOriginLists, splitOrigins } from "../../shared/items/origin.js";
3
import {
4
ItemOriginKind,
5
GatherOriginVerb,
6
CraftOriginVerb,
7
gatherOrigin,
8
craftOrigin,
9
craftOriginVerbForStation,
10
originLabel,
11
formatOriginBreakdown,
12
mergeOriginLists,
13
splitOrigins
14
} from "../../shared/items/origin.js";
15
import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
4
16
import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";
5
17
import { stackRulesFor } from "../../shared/items/stackRules.js";
6
18
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
7
19
8
const crafterA = { kind: ItemOriginKind.crafted, displayName: "Ada" };
9
const crafterB = { kind: ItemOriginKind.crafted, displayName: "Bob" };
20
const crafterA = craftOrigin(CraftOriginVerb.made, "Ada");
21
const crafterB = craftOrigin(CraftOriginVerb.made, "Bob");
22
23
test("gathered origins use Mined by / Felled by labels", () =>
24
{
25
const mined = gatherOrigin(GatherOriginVerb.mined, "Ada Miner");
26
assert.equal(originLabel(mined), "Mined by Ada Miner");
27
assert.equal(formatOriginBreakdown({
28
itemId: ItemId.copperOre,
29
quantity: 2,
30
origins: [{ origin: mined, quantity: 2 }]
31
}), "2 Mined by Ada Miner");
32
assert.equal(originLabel(gatherOrigin(GatherOriginVerb.felled, "Bob")), "Felled by Bob");
33
});
34
35
test("craft origins use station verbs", () =>
36
{
37
assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);
38
assert.equal(craftOriginVerbForStation(CraftingStationId.anvil), CraftOriginVerb.smithed);
39
assert.equal(craftOriginVerbForStation(CraftingStationId.woodworkingBench), CraftOriginVerb.carved);
40
assert.equal(craftOriginVerbForStation(CraftingStationId.craftingBench), CraftOriginVerb.assembled);
41
assert.equal(originLabel(craftOrigin(CraftOriginVerb.forged, "Ada")), "Forged by Ada");
42
assert.equal(originLabel(craftOrigin(CraftOriginVerb.smithed, "Ada")), "Smithed by Ada");
43
assert.equal(originLabel(craftOrigin(CraftOriginVerb.carved, "Ada")), "Carved by Ada");
44
assert.equal(originLabel(craftOrigin(CraftOriginVerb.assembled, "Ada")), "Assembled by Ada");
45
assert.equal(originLabel({ kind: ItemOriginKind.shop, displayName: "Bob Shop" }), "Bought from Bob Shop");
46
});
10
47
11
48
test("mixed-origin stacks merge and show a breakdown label", () =>
12
49
{
@@ -24,7 +61,7 @@ test("mixed-origin stacks merge and show a breakdown label", () =>
24
61
}, def);
25
62
assert.equal(second.ok, true);
26
63
assert.equal(second.slots[0].quantity, 8);
27
assert.equal(formatOriginBreakdown(second.slots[0]), "5 made by Ada, 3 made by Bob");
64
assert.equal(formatOriginBreakdown(second.slots[0]), "5 Made by Ada, 3 Made by Bob");
28
65
});
29
66
30
67
test("splitting a stack distributes origins FIFO", () =>
@@ -1,12 +1,49 @@1
import test from "node:test";1
import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { ItemOriginKind, formatOriginBreakdown, mergeOriginLists, splitOrigins } from "../../shared/items/origin.js";3
import {4
ItemOriginKind,5
GatherOriginVerb,6
CraftOriginVerb,7
gatherOrigin,8
craftOrigin,9
craftOriginVerbForStation,10
originLabel,11
formatOriginBreakdown,12
mergeOriginLists,13
splitOrigins14
} from "../../shared/items/origin.js";15
import { CraftingStationId } from "../../shared/definitions/craftingStations.js";4
import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";16
import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";5
import { stackRulesFor } from "../../shared/items/stackRules.js";17
import { stackRulesFor } from "../../shared/items/stackRules.js";6
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";18
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";7
19
8
const crafterA = { kind: ItemOriginKind.crafted, displayName: "Ada" };20
const crafterA = craftOrigin(CraftOriginVerb.made, "Ada");9
const crafterB = { kind: ItemOriginKind.crafted, displayName: "Bob" };21
const crafterB = craftOrigin(CraftOriginVerb.made, "Bob");22
23
test("gathered origins use Mined by / Felled by labels", () =>24
{25
const mined = gatherOrigin(GatherOriginVerb.mined, "Ada Miner");26
assert.equal(originLabel(mined), "Mined by Ada Miner");27
assert.equal(formatOriginBreakdown({28
itemId: ItemId.copperOre,29
quantity: 2,30
origins: [{ origin: mined, quantity: 2 }]31
}), "2 Mined by Ada Miner");32
assert.equal(originLabel(gatherOrigin(GatherOriginVerb.felled, "Bob")), "Felled by Bob");33
});34
35
test("craft origins use station verbs", () =>36
{37
assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);38
assert.equal(craftOriginVerbForStation(CraftingStationId.anvil), CraftOriginVerb.smithed);39
assert.equal(craftOriginVerbForStation(CraftingStationId.woodworkingBench), CraftOriginVerb.carved);40
assert.equal(craftOriginVerbForStation(CraftingStationId.craftingBench), CraftOriginVerb.assembled);41
assert.equal(originLabel(craftOrigin(CraftOriginVerb.forged, "Ada")), "Forged by Ada");42
assert.equal(originLabel(craftOrigin(CraftOriginVerb.smithed, "Ada")), "Smithed by Ada");43
assert.equal(originLabel(craftOrigin(CraftOriginVerb.carved, "Ada")), "Carved by Ada");44
assert.equal(originLabel(craftOrigin(CraftOriginVerb.assembled, "Ada")), "Assembled by Ada");45
assert.equal(originLabel({ kind: ItemOriginKind.shop, displayName: "Bob Shop" }), "Bought from Bob Shop");46
});10
47
11
test("mixed-origin stacks merge and show a breakdown label", () =>48
test("mixed-origin stacks merge and show a breakdown label", () =>12
{49
{@@ -24,7 +61,7 @@ test("mixed-origin stacks merge and show a breakdown label", () =>24
}, def);61
}, def);25
assert.equal(second.ok, true);62
assert.equal(second.ok, true);26
assert.equal(second.slots[0].quantity, 8);63
assert.equal(second.slots[0].quantity, 8);27
assert.equal(formatOriginBreakdown(second.slots[0]), "5 made by Ada, 3 made by Bob");64
assert.equal(formatOriginBreakdown(second.slots[0]), "5 Made by Ada, 3 Made by Bob");28
});65
});29
66
30
test("splitting a stack distributes origins FIFO", () =>67
test("splitting a stack distributes origins FIFO", () =>@@ -20,6 +20,14 @@ test("a taller sprite keeps its feet 8px from the bottom on the tile centre", ()
20
20
assert.equal(center.y, 0);
21
21
});
22
22
23
test("a 48px-tall tree sprite pivots 8px from its bottom on the tile centre", () =>
24
{
25
const pivot = tilePivot(0, 0, 16);
26
const center = spriteCenterFromPivot(pivot.x, pivot.y, 48, 1);
27
assert.equal(center.x, 8);
28
assert.equal(center.y, -8);
29
});
30
23
31
test("Y-sort puts a southern tile in front of a northern tile", () =>
24
32
{
25
33
assert.ok(ySortLayer(16, 1) > ySortLayer(0, 1));
@@ -20,6 +20,14 @@ test("a taller sprite keeps its feet 8px from the bottom on the tile centre", ()20
assert.equal(center.y, 0);20
assert.equal(center.y, 0);21
});21
});22
22
23
test("a 48px-tall tree sprite pivots 8px from its bottom on the tile centre", () =>24
{25
const pivot = tilePivot(0, 0, 16);26
const center = spriteCenterFromPivot(pivot.x, pivot.y, 48, 1);27
assert.equal(center.x, 8);28
assert.equal(center.y, -8);29
});30
23
test("Y-sort puts a southern tile in front of a northern tile", () =>31
test("Y-sort puts a southern tile in front of a northern tile", () =>24
{32
{25
assert.ok(ySortLayer(16, 1) > ySortLayer(0, 1));33
assert.ok(ySortLayer(16, 1) > ySortLayer(0, 1));@@ -0,0 +1,104 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { fileURLToPath } from "node:url";
4
import { join } from "node:path";
5
import {
6
SeasonId,
7
seasonIdAt,
8
resolveSeasonalVisualState,
9
preferredSeasonalDefaultState,
10
typeHasSeasonalStates,
11
seasonalCycleStates,
12
seasonIdFromVisualState
13
} from "../../shared/world/season.js";
14
import { shopRestockDayKey } from "../../shared/shop/pricing.js";
15
import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
16
17
const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));
18
19
test("seasonIdAt maps local months to summer/fall/winter", () =>
20
{
21
assert.equal(seasonIdAt(new Date(2026, 2, 1).getTime()), SeasonId.summer);
22
assert.equal(seasonIdAt(new Date(2026, 7, 15).getTime()), SeasonId.summer);
23
assert.equal(seasonIdAt(new Date(2026, 8, 1).getTime()), SeasonId.fall);
24
assert.equal(seasonIdAt(new Date(2026, 10, 30).getTime()), SeasonId.fall);
25
assert.equal(seasonIdAt(new Date(2026, 11, 1).getTime()), SeasonId.winter);
26
assert.equal(seasonIdAt(new Date(2026, 0, 15).getTime()), SeasonId.winter);
27
});
28
29
test("seasonal visual state follows calendar, not authored state", () =>
30
{
31
const states = ["fall", "grass", "summer", "winter"];
32
assert.equal(typeHasSeasonalStates(states), true);
33
assert.equal(resolveSeasonalVisualState(states, "winter", SeasonId.summer), SeasonId.summer);
34
assert.equal(resolveSeasonalVisualState(states, "summer", SeasonId.fall), SeasonId.fall);
35
assert.equal(resolveSeasonalVisualState(states, "summer", SeasonId.winter), SeasonId.winter);
36
assert.equal(preferredSeasonalDefaultState(states), SeasonId.summer);
37
});
38
39
test("legacy grass-only summer prefers grass when summer.png is absent from the state list", () =>
40
{
41
const states = ["fall", "grass", "winter"];
42
assert.equal(resolveSeasonalVisualState(states, null, SeasonId.summer), "grass");
43
assert.equal(preferredSeasonalDefaultState(states), "grass");
44
});
45
46
test("seasonal overlay uses *-winter when present, else the base state", () =>
47
{
48
const states = ["boulder", "boulder-winter", "copper-ore", "copper-ore-winter"];
49
assert.equal(resolveSeasonalVisualState(states, "boulder", SeasonId.summer), "boulder");
50
assert.equal(resolveSeasonalVisualState(states, "boulder", SeasonId.fall), "boulder");
51
assert.equal(resolveSeasonalVisualState(states, "boulder", SeasonId.winter), "boulder-winter");
52
assert.equal(resolveSeasonalVisualState(states, "copper-ore", SeasonId.winter), "copper-ore-winter");
53
assert.equal(resolveSeasonalVisualState(states, "copper-ore", SeasonId.summer), "copper-ore");
54
});
55
56
test("seasonalCycleStates lists summer/fall/winter for editor cycling", () =>
57
{
58
assert.deepEqual(
59
seasonalCycleStates(["fall", "grass", "summer", "winter"]),
60
["summer", "fall", "winter"]
61
);
62
assert.deepEqual(
63
seasonalCycleStates(["fall", "grass", "winter"]),
64
["grass", "fall", "winter"]
65
);
66
assert.equal(seasonalCycleStates(["1", "2"]), null);
67
assert.equal(seasonIdFromVisualState("grass"), SeasonId.summer);
68
assert.equal(seasonIdFromVisualState("fall"), SeasonId.fall);
69
});
70
71
test("shopRestockDayKey uses server-local calendar date", () =>
72
{
73
const noon = new Date(2026, 7, 25, 12, 0, 0, 0).getTime();
74
const afterMidnight = new Date(2026, 7, 26, 0, 0, 1, 0).getTime();
75
assert.equal(shopRestockDayKey(noon), "2026-08-25");
76
assert.equal(shopRestockDayKey(afterMidnight), "2026-08-26");
77
});
78
79
test("catalog exposes seasonal grass and pine-tree states", () =>
80
{
81
const catalog = buildSpriteCatalog(ASSET_ROOT);
82
assert.deepEqual(catalog.grounds.grass.states, ["fall", "grass", "summer", "winter"]);
83
assert.equal(catalog.grounds.grass.defaultState, "summer");
84
assert.equal(catalog.grounds.grass.outdoor, true);
85
assert.equal(catalog.grounds.grass.seasonal, true);
86
assert.equal(catalog.grounds.wood.outdoor, false);
87
assert.equal(catalog.grounds.wood.seasonal, false);
88
assert.deepEqual(catalog.blocks["pine-tree"].states, [
89
"fall",
90
"fall-stump",
91
"summer",
92
"summer-stump",
93
"winter",
94
"winter-stump"
95
]);
96
assert.equal(catalog.blocks["pine-tree"].defaultState, "summer");
97
assert.equal(catalog.blocks["pine-tree"].outdoor, true);
98
assert.equal(catalog.blocks["pine-tree"].seasonal, true);
99
assert.equal(catalog.blocks["stone-wall"].outdoor, false);
100
assert.equal(catalog.blocks["stone-wall"].seasonal, false);
101
assert.ok(catalog.images.some((image) => image.name === "block:boulder:boulder-winter"));
102
assert.ok(catalog.images.some((image) => image.name === "block:boulder:copper-ore-winter"));
103
assert.ok(catalog.images.some((image) => image.url.includes("boulder-ore-winter.png")));
104
});
@@ -0,0 +1,104 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { fileURLToPath } from "node:url";4
import { join } from "node:path";5
import {6
SeasonId,7
seasonIdAt,8
resolveSeasonalVisualState,9
preferredSeasonalDefaultState,10
typeHasSeasonalStates,11
seasonalCycleStates,12
seasonIdFromVisualState13
} from "../../shared/world/season.js";14
import { shopRestockDayKey } from "../../shared/shop/pricing.js";15
import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";16
17
const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));18
19
test("seasonIdAt maps local months to summer/fall/winter", () =>20
{21
assert.equal(seasonIdAt(new Date(2026, 2, 1).getTime()), SeasonId.summer);22
assert.equal(seasonIdAt(new Date(2026, 7, 15).getTime()), SeasonId.summer);23
assert.equal(seasonIdAt(new Date(2026, 8, 1).getTime()), SeasonId.fall);24
assert.equal(seasonIdAt(new Date(2026, 10, 30).getTime()), SeasonId.fall);25
assert.equal(seasonIdAt(new Date(2026, 11, 1).getTime()), SeasonId.winter);26
assert.equal(seasonIdAt(new Date(2026, 0, 15).getTime()), SeasonId.winter);27
});28
29
test("seasonal visual state follows calendar, not authored state", () =>30
{31
const states = ["fall", "grass", "summer", "winter"];32
assert.equal(typeHasSeasonalStates(states), true);33
assert.equal(resolveSeasonalVisualState(states, "winter", SeasonId.summer), SeasonId.summer);34
assert.equal(resolveSeasonalVisualState(states, "summer", SeasonId.fall), SeasonId.fall);35
assert.equal(resolveSeasonalVisualState(states, "summer", SeasonId.winter), SeasonId.winter);36
assert.equal(preferredSeasonalDefaultState(states), SeasonId.summer);37
});38
39
test("legacy grass-only summer prefers grass when summer.png is absent from the state list", () =>40
{41
const states = ["fall", "grass", "winter"];42
assert.equal(resolveSeasonalVisualState(states, null, SeasonId.summer), "grass");43
assert.equal(preferredSeasonalDefaultState(states), "grass");44
});45
46
test("seasonal overlay uses *-winter when present, else the base state", () =>47
{48
const states = ["boulder", "boulder-winter", "copper-ore", "copper-ore-winter"];49
assert.equal(resolveSeasonalVisualState(states, "boulder", SeasonId.summer), "boulder");50
assert.equal(resolveSeasonalVisualState(states, "boulder", SeasonId.fall), "boulder");51
assert.equal(resolveSeasonalVisualState(states, "boulder", SeasonId.winter), "boulder-winter");52
assert.equal(resolveSeasonalVisualState(states, "copper-ore", SeasonId.winter), "copper-ore-winter");53
assert.equal(resolveSeasonalVisualState(states, "copper-ore", SeasonId.summer), "copper-ore");54
});55
56
test("seasonalCycleStates lists summer/fall/winter for editor cycling", () =>57
{58
assert.deepEqual(59
seasonalCycleStates(["fall", "grass", "summer", "winter"]),60
["summer", "fall", "winter"]61
);62
assert.deepEqual(63
seasonalCycleStates(["fall", "grass", "winter"]),64
["grass", "fall", "winter"]65
);66
assert.equal(seasonalCycleStates(["1", "2"]), null);67
assert.equal(seasonIdFromVisualState("grass"), SeasonId.summer);68
assert.equal(seasonIdFromVisualState("fall"), SeasonId.fall);69
});70
71
test("shopRestockDayKey uses server-local calendar date", () =>72
{73
const noon = new Date(2026, 7, 25, 12, 0, 0, 0).getTime();74
const afterMidnight = new Date(2026, 7, 26, 0, 0, 1, 0).getTime();75
assert.equal(shopRestockDayKey(noon), "2026-08-25");76
assert.equal(shopRestockDayKey(afterMidnight), "2026-08-26");77
});78
79
test("catalog exposes seasonal grass and pine-tree states", () =>80
{81
const catalog = buildSpriteCatalog(ASSET_ROOT);82
assert.deepEqual(catalog.grounds.grass.states, ["fall", "grass", "summer", "winter"]);83
assert.equal(catalog.grounds.grass.defaultState, "summer");84
assert.equal(catalog.grounds.grass.outdoor, true);85
assert.equal(catalog.grounds.grass.seasonal, true);86
assert.equal(catalog.grounds.wood.outdoor, false);87
assert.equal(catalog.grounds.wood.seasonal, false);88
assert.deepEqual(catalog.blocks["pine-tree"].states, [89
"fall",90
"fall-stump",91
"summer",92
"summer-stump",93
"winter",94
"winter-stump"95
]);96
assert.equal(catalog.blocks["pine-tree"].defaultState, "summer");97
assert.equal(catalog.blocks["pine-tree"].outdoor, true);98
assert.equal(catalog.blocks["pine-tree"].seasonal, true);99
assert.equal(catalog.blocks["stone-wall"].outdoor, false);100
assert.equal(catalog.blocks["stone-wall"].seasonal, false);101
assert.ok(catalog.images.some((image) => image.name === "block:boulder:boulder-winter"));102
assert.ok(catalog.images.some((image) => image.name === "block:boulder:copper-ore-winter"));103
assert.ok(catalog.images.some((image) => image.url.includes("boulder-ore-winter.png")));104
});@@ -21,6 +21,17 @@ import { ItemOriginKind } from "../../shared/items/origin.js";
21
21
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
22
22
import { ensureShopRestocked } from "../src/shop/service.js";
23
23
import { BlockType } from "../../shared/definitions/tiles.js";
24
import { GatherOriginVerb, gatherOrigin } from "../../shared/items/origin.js";
25
26
function boughtQty (shop, itemId)
27
{
28
const raw = shop?.boughtStock?.[itemId];
29
if (raw == null)
30
{ return 0; }
31
if (typeof raw === "number")
32
{ return raw | 0; }
33
return raw.quantity | 0 || 0;
34
}
24
35
25
36
test("shop prices fall back to seedValue and apply hidden discount", () =>
26
37
{
@@ -171,6 +182,7 @@ test("buy copper ore from a spawned shopkeeper", () =>
171
182
const ore = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.copperOre);
172
183
assert.ok(ore, JSON.stringify(bag.inventory));
173
184
assert.equal(ore.origins?.[0]?.origin?.kind, ItemOriginKind.shop);
185
assert.equal(ore.origins?.[0]?.origin?.displayName, "Ore trader");
174
186
}
175
187
finally
176
188
{ harness.close(); }
@@ -186,7 +198,7 @@ test("limited shop stock depletes and restocks on a new day", () =>
186
198
boughtStock: Object.create(null),
187
199
restockDay: null
188
200
};
189
const dayA = Date.parse("2026-08-25T12:00:00Z");
201
const dayA = new Date(2026, 7, 25, 12, 0, 0, 0).getTime();
190
202
ensureShopRestocked(shop, dayA);
191
203
assert.equal(shop.restockDay, shopRestockDayKey(dayA));
192
204
assert.equal(shop.remaining[ItemId.copperOre], 2);
@@ -195,7 +207,7 @@ test("limited shop stock depletes and restocks on a new day", () =>
195
207
ensureShopRestocked(shop, dayA);
196
208
assert.equal(shop.remaining[ItemId.copperOre], 0);
197
209
assert.equal(shop.boughtStock[ItemId.tinOre], 3);
198
const dayB = Date.parse("2026-08-26T00:00:01Z");
210
const dayB = new Date(2026, 7, 26, 0, 0, 1, 0).getTime();
199
211
ensureShopRestocked(shop, dayB);
200
212
assert.equal(shop.remaining[ItemId.copperOre], 2);
201
213
assert.equal(shop.boughtStock[ItemId.tinOre], undefined);
@@ -369,7 +381,7 @@ test("buysItems refills limited catalog then stores extras for 120% resale", ()
369
381
const sold = harness.simulation.step();
370
382
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
371
383
assert.equal(shop.remaining[ItemId.copperOre], 2);
372
assert.equal(shop.boughtStock[ItemId.copperOre], 3);
384
assert.equal(boughtQty(shop, ItemId.copperOre), 3);
373
385
374
386
const open = sold.events.find((event) => event.type === "shop-open");
375
387
assert.ok(open.stock.some((row) => row.source === "stock" && row.available === 2));
@@ -595,7 +607,7 @@ test("buysItems accepts non-ingredient tools like sticks", () =>
595
607
const inv = worker.world.ecs.get(playerHandle, Component.inventory);
596
608
assert.equal(inv.slots[0]?.itemId === ItemId.stick, false);
597
609
assert.ok(countCoinsInSlots(inv.slots) >= beforeCoins + shopBuyFromPlayerPrice(ItemId.stick));
598
assert.equal(shop.boughtStock[ItemId.stick], 1);
610
assert.equal(boughtQty(shop, ItemId.stick), 1);
599
611
}
600
612
finally
601
613
{ harness.close(); }
@@ -703,7 +715,107 @@ test("selling a filled cheque pays reserved-goods price minus 5% admin fee", ()
703
715
const afterCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
704
716
assert.equal(afterCoins - beforeCoins, quote.payout);
705
717
// Infinite catalog absorbs goods without bought-from-player resale stock.
706
assert.equal(shop.boughtStock?.[ItemId.copperOre] | 0, 0);
718
assert.equal(boughtQty(shop, ItemId.copperOre), 0);
719
}
720
finally
721
{ harness.close(); }
722
});
723
724
test("resale stock keeps the seller origin instead of Bought from NPC", () =>
725
{
726
const harness = makeSimulation({ workerCount: 1 });
727
try
728
{
729
const data = createEmptyChunkData();
730
data.open = true;
731
data.spawners = [{
732
localX: 9,
733
localY: 8,
734
config: {
735
mobTypeId: MobId.humanoid,
736
maxAlive: 1,
737
spawnRangeTiles: 0,
738
maxWanderRangeTiles: 0,
739
displayName: "Fence",
740
sells: [],
741
buysItems: true,
742
hiddenDiscount: 1
743
}
744
}];
745
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
746
harness.simulation.reloadWorld();
747
748
const minerOrigin = gatherOrigin(GatherOriginVerb.mined, "Ada Miner");
749
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
750
const funded = addCoinsToSlots(emptySlots(), 50);
751
assert.equal(funded.ok, true);
752
funded.slots[1] = {
753
itemId: ItemId.copperOre,
754
quantity: 2,
755
origins: [{ origin: minerOrigin, quantity: 2 }]
756
};
757
harness.stateDb.saveBag(character.character_id, {
758
inventory: funded.slots,
759
equipment: emptyEquipment(),
760
vault: [],
761
vaultReserved: []
762
});
763
const playerId = harness.simulation.spawnCharacter(1, character);
764
harness.simulation.step();
765
harness.advance(50);
766
harness.simulation.step();
767
768
const record = harness.simulation.entityRecord(playerId);
769
const worker = harness.simulation.workers[record.workerId];
770
let npcId = null;
771
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
772
{
773
if (entity.creature.mobTypeId === MobId.humanoid)
774
{
775
npcId = entity.entityId;
776
break;
777
}
778
}
779
assert.ok(npcId);
780
const npcHandle = worker.world.ecs.handleOf(npcId);
781
const shop = worker.world.ecs.get(npcHandle, Component.shop);
782
const npcPos = worker.world.ecs.get(npcHandle, Component.position);
783
const playerHandle = worker.world.ecs.handleOf(playerId);
784
const playerPos = worker.world.ecs.get(playerHandle, Component.position);
785
playerPos.tileX = npcPos.tileX;
786
playerPos.tileY = npcPos.tileY;
787
788
harness.simulation.enqueue(1, {
789
type: "sell-to-shop",
790
characterId: character.character_id,
791
npcEntityId: npcId,
792
slotIndex: 1,
793
quantity: 2
794
});
795
const sold = harness.simulation.step();
796
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
797
assert.equal(boughtQty(shop, ItemId.copperOre), 2);
798
assert.deepEqual(shop.boughtStock[ItemId.copperOre].origins, [
799
{ origin: minerOrigin, quantity: 2 }
800
]);
801
802
harness.simulation.enqueue(1, {
803
type: "buy-from-shop",
804
characterId: character.character_id,
805
npcEntityId: npcId,
806
itemId: ItemId.copperOre,
807
quantity: 2,
808
listingId: `bought:${ItemId.copperOre}`,
809
source: "bought"
810
});
811
const buy = harness.simulation.step();
812
assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
813
const bag = harness.simulation.bagOf(playerId);
814
const ore = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.copperOre);
815
assert.ok(ore);
816
assert.equal(ore.origins?.[0]?.origin?.kind, ItemOriginKind.gathered);
817
assert.equal(ore.origins?.[0]?.origin?.displayName, "Ada Miner");
818
assert.equal(ore.origins?.[0]?.origin?.kind === ItemOriginKind.shop, false);
707
819
}
708
820
finally
709
821
{ harness.close(); }
@@ -21,6 +21,17 @@ import { ItemOriginKind } from "../../shared/items/origin.js";21
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";21
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";22
import { ensureShopRestocked } from "../src/shop/service.js";22
import { ensureShopRestocked } from "../src/shop/service.js";23
import { BlockType } from "../../shared/definitions/tiles.js";23
import { BlockType } from "../../shared/definitions/tiles.js";24
import { GatherOriginVerb, gatherOrigin } from "../../shared/items/origin.js";25
26
function boughtQty (shop, itemId)27
{28
const raw = shop?.boughtStock?.[itemId];29
if (raw == null)30
{ return 0; }31
if (typeof raw === "number")32
{ return raw | 0; }33
return raw.quantity | 0 || 0;34
}24
35
25
test("shop prices fall back to seedValue and apply hidden discount", () =>36
test("shop prices fall back to seedValue and apply hidden discount", () =>26
{37
{@@ -171,6 +182,7 @@ test("buy copper ore from a spawned shopkeeper", () =>171
const ore = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.copperOre);182
const ore = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.copperOre);172
assert.ok(ore, JSON.stringify(bag.inventory));183
assert.ok(ore, JSON.stringify(bag.inventory));173
assert.equal(ore.origins?.[0]?.origin?.kind, ItemOriginKind.shop);184
assert.equal(ore.origins?.[0]?.origin?.kind, ItemOriginKind.shop);185
assert.equal(ore.origins?.[0]?.origin?.displayName, "Ore trader");174
}186
}175
finally187
finally176
{ harness.close(); }188
{ harness.close(); }@@ -186,7 +198,7 @@ test("limited shop stock depletes and restocks on a new day", () =>186
boughtStock: Object.create(null),198
boughtStock: Object.create(null),187
restockDay: null199
restockDay: null188
};200
};189
const dayA = Date.parse("2026-08-25T12:00:00Z");201
const dayA = new Date(2026, 7, 25, 12, 0, 0, 0).getTime();190
ensureShopRestocked(shop, dayA);202
ensureShopRestocked(shop, dayA);191
assert.equal(shop.restockDay, shopRestockDayKey(dayA));203
assert.equal(shop.restockDay, shopRestockDayKey(dayA));192
assert.equal(shop.remaining[ItemId.copperOre], 2);204
assert.equal(shop.remaining[ItemId.copperOre], 2);@@ -195,7 +207,7 @@ test("limited shop stock depletes and restocks on a new day", () =>195
ensureShopRestocked(shop, dayA);207
ensureShopRestocked(shop, dayA);196
assert.equal(shop.remaining[ItemId.copperOre], 0);208
assert.equal(shop.remaining[ItemId.copperOre], 0);197
assert.equal(shop.boughtStock[ItemId.tinOre], 3);209
assert.equal(shop.boughtStock[ItemId.tinOre], 3);198
const dayB = Date.parse("2026-08-26T00:00:01Z");210
const dayB = new Date(2026, 7, 26, 0, 0, 1, 0).getTime();199
ensureShopRestocked(shop, dayB);211
ensureShopRestocked(shop, dayB);200
assert.equal(shop.remaining[ItemId.copperOre], 2);212
assert.equal(shop.remaining[ItemId.copperOre], 2);201
assert.equal(shop.boughtStock[ItemId.tinOre], undefined);213
assert.equal(shop.boughtStock[ItemId.tinOre], undefined);@@ -369,7 +381,7 @@ test("buysItems refills limited catalog then stores extras for 120% resale", ()369
const sold = harness.simulation.step();381
const sold = harness.simulation.step();370
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));382
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));371
assert.equal(shop.remaining[ItemId.copperOre], 2);383
assert.equal(shop.remaining[ItemId.copperOre], 2);372
assert.equal(shop.boughtStock[ItemId.copperOre], 3);384
assert.equal(boughtQty(shop, ItemId.copperOre), 3);373
385
374
const open = sold.events.find((event) => event.type === "shop-open");386
const open = sold.events.find((event) => event.type === "shop-open");375
assert.ok(open.stock.some((row) => row.source === "stock" && row.available === 2));387
assert.ok(open.stock.some((row) => row.source === "stock" && row.available === 2));@@ -595,7 +607,7 @@ test("buysItems accepts non-ingredient tools like sticks", () =>595
const inv = worker.world.ecs.get(playerHandle, Component.inventory);607
const inv = worker.world.ecs.get(playerHandle, Component.inventory);596
assert.equal(inv.slots[0]?.itemId === ItemId.stick, false);608
assert.equal(inv.slots[0]?.itemId === ItemId.stick, false);597
assert.ok(countCoinsInSlots(inv.slots) >= beforeCoins + shopBuyFromPlayerPrice(ItemId.stick));609
assert.ok(countCoinsInSlots(inv.slots) >= beforeCoins + shopBuyFromPlayerPrice(ItemId.stick));598
assert.equal(shop.boughtStock[ItemId.stick], 1);610
assert.equal(boughtQty(shop, ItemId.stick), 1);599
}611
}600
finally612
finally601
{ harness.close(); }613
{ harness.close(); }@@ -703,7 +715,107 @@ test("selling a filled cheque pays reserved-goods price minus 5% admin fee", ()703
const afterCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);715
const afterCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);704
assert.equal(afterCoins - beforeCoins, quote.payout);716
assert.equal(afterCoins - beforeCoins, quote.payout);705
// Infinite catalog absorbs goods without bought-from-player resale stock.717
// Infinite catalog absorbs goods without bought-from-player resale stock.706
assert.equal(shop.boughtStock?.[ItemId.copperOre] | 0, 0);718
assert.equal(boughtQty(shop, ItemId.copperOre), 0);719
}720
finally721
{ harness.close(); }722
});723
724
test("resale stock keeps the seller origin instead of Bought from NPC", () =>725
{726
const harness = makeSimulation({ workerCount: 1 });727
try728
{729
const data = createEmptyChunkData();730
data.open = true;731
data.spawners = [{732
localX: 9,733
localY: 8,734
config: {735
mobTypeId: MobId.humanoid,736
maxAlive: 1,737
spawnRangeTiles: 0,738
maxWanderRangeTiles: 0,739
displayName: "Fence",740
sells: [],741
buysItems: true,742
hiddenDiscount: 1743
}744
}];745
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));746
harness.simulation.reloadWorld();747
748
const minerOrigin = gatherOrigin(GatherOriginVerb.mined, "Ada Miner");749
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });750
const funded = addCoinsToSlots(emptySlots(), 50);751
assert.equal(funded.ok, true);752
funded.slots[1] = {753
itemId: ItemId.copperOre,754
quantity: 2,755
origins: [{ origin: minerOrigin, quantity: 2 }]756
};757
harness.stateDb.saveBag(character.character_id, {758
inventory: funded.slots,759
equipment: emptyEquipment(),760
vault: [],761
vaultReserved: []762
});763
const playerId = harness.simulation.spawnCharacter(1, character);764
harness.simulation.step();765
harness.advance(50);766
harness.simulation.step();767
768
const record = harness.simulation.entityRecord(playerId);769
const worker = harness.simulation.workers[record.workerId];770
let npcId = null;771
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))772
{773
if (entity.creature.mobTypeId === MobId.humanoid)774
{775
npcId = entity.entityId;776
break;777
}778
}779
assert.ok(npcId);780
const npcHandle = worker.world.ecs.handleOf(npcId);781
const shop = worker.world.ecs.get(npcHandle, Component.shop);782
const npcPos = worker.world.ecs.get(npcHandle, Component.position);783
const playerHandle = worker.world.ecs.handleOf(playerId);784
const playerPos = worker.world.ecs.get(playerHandle, Component.position);785
playerPos.tileX = npcPos.tileX;786
playerPos.tileY = npcPos.tileY;787
788
harness.simulation.enqueue(1, {789
type: "sell-to-shop",790
characterId: character.character_id,791
npcEntityId: npcId,792
slotIndex: 1,793
quantity: 2794
});795
const sold = harness.simulation.step();796
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));797
assert.equal(boughtQty(shop, ItemId.copperOre), 2);798
assert.deepEqual(shop.boughtStock[ItemId.copperOre].origins, [799
{ origin: minerOrigin, quantity: 2 }800
]);801
802
harness.simulation.enqueue(1, {803
type: "buy-from-shop",804
characterId: character.character_id,805
npcEntityId: npcId,806
itemId: ItemId.copperOre,807
quantity: 2,808
listingId: `bought:${ItemId.copperOre}`,809
source: "bought"810
});811
const buy = harness.simulation.step();812
assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));813
const bag = harness.simulation.bagOf(playerId);814
const ore = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.copperOre);815
assert.ok(ore);816
assert.equal(ore.origins?.[0]?.origin?.kind, ItemOriginKind.gathered);817
assert.equal(ore.origins?.[0]?.origin?.displayName, "Ada Miner");818
assert.equal(ore.origins?.[0]?.origin?.kind === ItemOriginKind.shop, false);707
}819
}708
finally820
finally709
{ harness.close(); }821
{ harness.close(); }@@ -1,6 +1,7 @@
1
1
import test from "node:test";
2
2
import assert from "node:assert/strict";
3
import { GroundType, isGroundPassable, isWadeGround, isWaterGround } from "../../shared/definitions/tiles.js";
3
import { GroundType, isGroundPassable, isWadeGround, isWaterGround, isLiquidWaterGround, isWadeGroundInSeason } from "../../shared/definitions/tiles.js";
4
import { SeasonId, resolveSeasonalVisualState } from "../../shared/world/season.js";
4
5
import { createEmptyChunkData, isChunkTilePassable, setGround } from "../src/world/chunkData.js";
5
6
6
7
test("deep water ground is impassable; shallow water is passable and wadeable", () =>
@@ -18,3 +19,20 @@ test("deep water ground is impassable; shallow water is passable and wadeable",
18
19
assert.equal(isChunkTilePassable(data, 1, 1), true);
19
20
assert.equal(isChunkTilePassable(data, 2, 2), false);
20
21
});
22
23
test("shallow water freezes in winter: no wade, not liquid for coast foam", () =>
24
{
25
assert.equal(isLiquidWaterGround(GroundType.water, SeasonId.summer), true);
26
assert.equal(isLiquidWaterGround(GroundType.water, SeasonId.winter), false);
27
assert.equal(isLiquidWaterGround(GroundType.deepWater, SeasonId.winter), true);
28
assert.equal(isWadeGroundInSeason(GroundType.water, SeasonId.summer), true);
29
assert.equal(isWadeGroundInSeason(GroundType.water, SeasonId.winter), false);
30
assert.equal(
31
resolveSeasonalVisualState(["water", "water-winter"], "water", SeasonId.winter),
32
"water-winter"
33
);
34
assert.equal(
35
resolveSeasonalVisualState(["water", "water-winter"], "water", SeasonId.summer),
36
"water"
37
);
38
});
@@ -1,6 +1,7 @@1
import test from "node:test";1
import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { GroundType, isGroundPassable, isWadeGround, isWaterGround } from "../../shared/definitions/tiles.js";3
import { GroundType, isGroundPassable, isWadeGround, isWaterGround, isLiquidWaterGround, isWadeGroundInSeason } from "../../shared/definitions/tiles.js";4
import { SeasonId, resolveSeasonalVisualState } from "../../shared/world/season.js";4
import { createEmptyChunkData, isChunkTilePassable, setGround } from "../src/world/chunkData.js";5
import { createEmptyChunkData, isChunkTilePassable, setGround } from "../src/world/chunkData.js";5
6
6
test("deep water ground is impassable; shallow water is passable and wadeable", () =>7
test("deep water ground is impassable; shallow water is passable and wadeable", () =>@@ -18,3 +19,20 @@ test("deep water ground is impassable; shallow water is passable and wadeable",18
assert.equal(isChunkTilePassable(data, 1, 1), true);19
assert.equal(isChunkTilePassable(data, 1, 1), true);19
assert.equal(isChunkTilePassable(data, 2, 2), false);20
assert.equal(isChunkTilePassable(data, 2, 2), false);20
});21
});22
23
test("shallow water freezes in winter: no wade, not liquid for coast foam", () =>24
{25
assert.equal(isLiquidWaterGround(GroundType.water, SeasonId.summer), true);26
assert.equal(isLiquidWaterGround(GroundType.water, SeasonId.winter), false);27
assert.equal(isLiquidWaterGround(GroundType.deepWater, SeasonId.winter), true);28
assert.equal(isWadeGroundInSeason(GroundType.water, SeasonId.summer), true);29
assert.equal(isWadeGroundInSeason(GroundType.water, SeasonId.winter), false);30
assert.equal(31
resolveSeasonalVisualState(["water", "water-winter"], "water", SeasonId.winter),32
"water-winter"33
);34
assert.equal(35
resolveSeasonalVisualState(["water", "water-winter"], "water", SeasonId.summer),36
"water"37
);38
});@@ -0,0 +1,188 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { WoodTier, tierRank } from "../../shared/definitions/materialTiers.js";
4
import {
5
canChopWood,
6
woodcuttingDurationMs,
7
treeExhaustDurationMs,
8
logItemIdForWoodTier
9
} from "../../shared/definitions/gathering.js";
10
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
11
import { SkillId } from "../../shared/definitions/skills.js";
12
import { BlockType, isChopableTreeBlock, woodTierForTreeBlock } from "../../shared/definitions/tiles.js";
13
import { SeasonId, resolveSeasonalVisualState, treeStumpStateForSeason } from "../../shared/world/season.js";
14
import { ItemOriginKind, GatherOriginVerb } from "../../shared/items/origin.js";
15
import { totalXpForLevel } from "../../shared/skills/progression.js";
16
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
17
import { Component } from "../src/ecs/components.js";
18
19
function countItem (slots, itemId)
20
{
21
return (slots ?? []).reduce((sum, slot) =>
22
{
23
if (slot?.itemId === itemId)
24
{ return sum + (slot.quantity | 0); }
25
return sum;
26
}, 0);
27
}
28
29
function placeTree (worker, tileX, tileY, state = SeasonId.summer)
30
{
31
const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
32
const localX = tileX % 16;
33
const localY = tileY % 16;
34
const index = localY * 16 + localX;
35
data.blocks[index] = { typeId: BlockType.pineTree, state, config: null };
36
return { data, index };
37
}
38
39
function bagAxe (worker, playerId, itemId)
40
{
41
const handle = worker.world.ecs.handleOf(playerId);
42
const inventory = worker.world.ecs.get(handle, Component.inventory);
43
inventory.slots[0] = { itemId, quantity: 1 };
44
}
45
46
function setSkillLevel (worker, playerId, skillId, level)
47
{
48
const handle = worker.world.ecs.handleOf(playerId);
49
const skills = worker.world.ecs.get(handle, Component.skills);
50
skills.xp[skillId] = totalXpForLevel(level);
51
}
52
53
function advanceMs (harness, ms)
54
{
55
const ticks = Math.ceil(ms / 50) + 3;
56
for (let i = 0; i < ticks; i++)
57
{
58
harness.advance(50);
59
harness.simulation.step();
60
}
61
}
62
63
test("pine tree yields pine logs and uses axe gates", () =>
64
{
65
assert.equal(woodTierForTreeBlock(BlockType.pineTree), WoodTier.pine);
66
assert.equal(logItemIdForWoodTier(WoodTier.pine), ItemId.pineLog);
67
assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");
68
assert.equal(canChopWood(1, WoodTier.pine, WoodTier.pine).ok, true);
69
assert.equal(canChopWood(1, WoodTier.pine, WoodTier.birch).ok, false);
70
assert.equal(woodcuttingDurationMs(WoodTier.pine, WoodTier.pine), 5000);
71
assert.equal(treeExhaustDurationMs(WoodTier.pine), 10_000);
72
});
73
74
test("seasonal stump state follows calendar season", () =>
75
{
76
const states = ["fall", "fall-stump", "summer", "summer-stump", "winter", "winter-stump"];
77
assert.equal(
78
resolveSeasonalVisualState(states, "summer-stump", SeasonId.winter),
79
"winter-stump"
80
);
81
assert.equal(
82
resolveSeasonalVisualState(states, "summer", SeasonId.fall),
83
SeasonId.fall
84
);
85
assert.equal(treeStumpStateForSeason(SeasonId.summer), "summer-stump");
86
assert.equal(isChopableTreeBlock({ typeId: BlockType.pineTree, state: "summer" }), true);
87
assert.equal(isChopableTreeBlock({ typeId: BlockType.pineTree, state: "summer-stump" }), false);
88
});
89
90
test("chopping without an axe is rejected", () =>
91
{
92
const harness = makeSimulation({ workerCount: 1 });
93
try
94
{
95
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
96
const playerId = harness.simulation.spawnCharacter(1, character);
97
const record = harness.simulation.entityRecord(playerId);
98
const worker = harness.simulation.workers[record.workerId];
99
placeTree(worker, 9, 8);
100
101
harness.simulation.enqueue(1, {
102
type: "chop",
103
characterId: character.character_id,
104
tileX: 9,
105
tileY: 8
106
});
107
const result = harness.simulation.step();
108
assert.ok(result.events.some((event) =>
109
event.type === "command-error"
110
&& event.message === "You need an axe to chop this!"));
111
}
112
finally
113
{ harness.close(); }
114
});
115
116
test("chopping a pine tree yields a pine log, stump, and woodcutting XP", () =>
117
{
118
const harness = makeSimulation({ workerCount: 1 });
119
try
120
{
121
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
122
const playerId = harness.simulation.spawnCharacter(1, character);
123
const record = harness.simulation.entityRecord(playerId);
124
const worker = harness.simulation.workers[record.workerId];
125
bagAxe(worker, playerId, ItemId.bronzeAxe);
126
setSkillLevel(worker, playerId, SkillId.woodcutting, 1);
127
placeTree(worker, 9, 8, SeasonId.summer);
128
129
harness.simulation.enqueue(1, {
130
type: "chop",
131
characterId: character.character_id,
132
tileX: 9,
133
tileY: 8
134
});
135
const start = harness.simulation.step();
136
assert.ok(start.events.some((event) =>
137
event.type === "gather-swing"
138
&& event.toolItemId === ItemId.bronzeAxe), JSON.stringify(start.events));
139
advanceMs(harness, woodcuttingDurationMs(WoodTier.pine, WoodTier.pine) + 200);
140
141
const handle = worker.world.ecs.handleOf(playerId);
142
const inventory = worker.world.ecs.get(handle, Component.inventory);
143
assert.equal(countItem(inventory.slots, ItemId.pineLog), 1);
144
const log = inventory.slots.find((slot) => slot?.itemId === ItemId.pineLog);
145
assert.equal(log?.origins?.[0]?.origin?.kind, ItemOriginKind.gathered);
146
assert.equal(log?.origins?.[0]?.origin?.verb, GatherOriginVerb.felled);
147
148
const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
149
assert.equal(block.typeId, BlockType.pineTree);
150
assert.ok(String(block.state).endsWith("-stump"));
151
assert.equal(isChopableTreeBlock(block), false);
152
153
const skills = worker.world.ecs.get(handle, Component.skills);
154
assert.ok((skills.xp[SkillId.woodcutting] | 0) > totalXpForLevel(1));
155
}
156
finally
157
{ harness.close(); }
158
});
159
160
test("tree stump respawns after exhaust duration", () =>
161
{
162
const harness = makeSimulation({ workerCount: 1 });
163
try
164
{
165
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
166
const playerId = harness.simulation.spawnCharacter(1, character);
167
const record = harness.simulation.entityRecord(playerId);
168
const worker = harness.simulation.workers[record.workerId];
169
bagAxe(worker, playerId, ItemId.bronzeAxe);
170
placeTree(worker, 9, 8);
171
172
harness.simulation.enqueue(1, {
173
type: "chop",
174
characterId: character.character_id,
175
tileX: 9,
176
tileY: 8
177
});
178
advanceMs(harness, woodcuttingDurationMs(WoodTier.pine, WoodTier.pine) + 200);
179
assert.ok(String(worker.world.chunkData(0, 0).blocks[8 * 16 + 9].state).endsWith("-stump"));
180
181
advanceMs(harness, treeExhaustDurationMs(WoodTier.pine) + 200);
182
const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
183
assert.equal(isChopableTreeBlock(block), true);
184
assert.equal(tierRank(WoodTier.pine), 1);
185
}
186
finally
187
{ harness.close(); }
188
});
@@ -0,0 +1,188 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { WoodTier, tierRank } from "../../shared/definitions/materialTiers.js";4
import {5
canChopWood,6
woodcuttingDurationMs,7
treeExhaustDurationMs,8
logItemIdForWoodTier9
} from "../../shared/definitions/gathering.js";10
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";11
import { SkillId } from "../../shared/definitions/skills.js";12
import { BlockType, isChopableTreeBlock, woodTierForTreeBlock } from "../../shared/definitions/tiles.js";13
import { SeasonId, resolveSeasonalVisualState, treeStumpStateForSeason } from "../../shared/world/season.js";14
import { ItemOriginKind, GatherOriginVerb } from "../../shared/items/origin.js";15
import { totalXpForLevel } from "../../shared/skills/progression.js";16
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";17
import { Component } from "../src/ecs/components.js";18
19
function countItem (slots, itemId)20
{21
return (slots ?? []).reduce((sum, slot) =>22
{23
if (slot?.itemId === itemId)24
{ return sum + (slot.quantity | 0); }25
return sum;26
}, 0);27
}28
29
function placeTree (worker, tileX, tileY, state = SeasonId.summer)30
{31
const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));32
const localX = tileX % 16;33
const localY = tileY % 16;34
const index = localY * 16 + localX;35
data.blocks[index] = { typeId: BlockType.pineTree, state, config: null };36
return { data, index };37
}38
39
function bagAxe (worker, playerId, itemId)40
{41
const handle = worker.world.ecs.handleOf(playerId);42
const inventory = worker.world.ecs.get(handle, Component.inventory);43
inventory.slots[0] = { itemId, quantity: 1 };44
}45
46
function setSkillLevel (worker, playerId, skillId, level)47
{48
const handle = worker.world.ecs.handleOf(playerId);49
const skills = worker.world.ecs.get(handle, Component.skills);50
skills.xp[skillId] = totalXpForLevel(level);51
}52
53
function advanceMs (harness, ms)54
{55
const ticks = Math.ceil(ms / 50) + 3;56
for (let i = 0; i < ticks; i++)57
{58
harness.advance(50);59
harness.simulation.step();60
}61
}62
63
test("pine tree yields pine logs and uses axe gates", () =>64
{65
assert.equal(woodTierForTreeBlock(BlockType.pineTree), WoodTier.pine);66
assert.equal(logItemIdForWoodTier(WoodTier.pine), ItemId.pineLog);67
assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");68
assert.equal(canChopWood(1, WoodTier.pine, WoodTier.pine).ok, true);69
assert.equal(canChopWood(1, WoodTier.pine, WoodTier.birch).ok, false);70
assert.equal(woodcuttingDurationMs(WoodTier.pine, WoodTier.pine), 5000);71
assert.equal(treeExhaustDurationMs(WoodTier.pine), 10_000);72
});73
74
test("seasonal stump state follows calendar season", () =>75
{76
const states = ["fall", "fall-stump", "summer", "summer-stump", "winter", "winter-stump"];77
assert.equal(78
resolveSeasonalVisualState(states, "summer-stump", SeasonId.winter),79
"winter-stump"80
);81
assert.equal(82
resolveSeasonalVisualState(states, "summer", SeasonId.fall),83
SeasonId.fall84
);85
assert.equal(treeStumpStateForSeason(SeasonId.summer), "summer-stump");86
assert.equal(isChopableTreeBlock({ typeId: BlockType.pineTree, state: "summer" }), true);87
assert.equal(isChopableTreeBlock({ typeId: BlockType.pineTree, state: "summer-stump" }), false);88
});89
90
test("chopping without an axe is rejected", () =>91
{92
const harness = makeSimulation({ workerCount: 1 });93
try94
{95
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });96
const playerId = harness.simulation.spawnCharacter(1, character);97
const record = harness.simulation.entityRecord(playerId);98
const worker = harness.simulation.workers[record.workerId];99
placeTree(worker, 9, 8);100
101
harness.simulation.enqueue(1, {102
type: "chop",103
characterId: character.character_id,104
tileX: 9,105
tileY: 8106
});107
const result = harness.simulation.step();108
assert.ok(result.events.some((event) =>109
event.type === "command-error"110
&& event.message === "You need an axe to chop this!"));111
}112
finally113
{ harness.close(); }114
});115
116
test("chopping a pine tree yields a pine log, stump, and woodcutting XP", () =>117
{118
const harness = makeSimulation({ workerCount: 1 });119
try120
{121
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });122
const playerId = harness.simulation.spawnCharacter(1, character);123
const record = harness.simulation.entityRecord(playerId);124
const worker = harness.simulation.workers[record.workerId];125
bagAxe(worker, playerId, ItemId.bronzeAxe);126
setSkillLevel(worker, playerId, SkillId.woodcutting, 1);127
placeTree(worker, 9, 8, SeasonId.summer);128
129
harness.simulation.enqueue(1, {130
type: "chop",131
characterId: character.character_id,132
tileX: 9,133
tileY: 8134
});135
const start = harness.simulation.step();136
assert.ok(start.events.some((event) =>137
event.type === "gather-swing"138
&& event.toolItemId === ItemId.bronzeAxe), JSON.stringify(start.events));139
advanceMs(harness, woodcuttingDurationMs(WoodTier.pine, WoodTier.pine) + 200);140
141
const handle = worker.world.ecs.handleOf(playerId);142
const inventory = worker.world.ecs.get(handle, Component.inventory);143
assert.equal(countItem(inventory.slots, ItemId.pineLog), 1);144
const log = inventory.slots.find((slot) => slot?.itemId === ItemId.pineLog);145
assert.equal(log?.origins?.[0]?.origin?.kind, ItemOriginKind.gathered);146
assert.equal(log?.origins?.[0]?.origin?.verb, GatherOriginVerb.felled);147
148
const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];149
assert.equal(block.typeId, BlockType.pineTree);150
assert.ok(String(block.state).endsWith("-stump"));151
assert.equal(isChopableTreeBlock(block), false);152
153
const skills = worker.world.ecs.get(handle, Component.skills);154
assert.ok((skills.xp[SkillId.woodcutting] | 0) > totalXpForLevel(1));155
}156
finally157
{ harness.close(); }158
});159
160
test("tree stump respawns after exhaust duration", () =>161
{162
const harness = makeSimulation({ workerCount: 1 });163
try164
{165
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });166
const playerId = harness.simulation.spawnCharacter(1, character);167
const record = harness.simulation.entityRecord(playerId);168
const worker = harness.simulation.workers[record.workerId];169
bagAxe(worker, playerId, ItemId.bronzeAxe);170
placeTree(worker, 9, 8);171
172
harness.simulation.enqueue(1, {173
type: "chop",174
characterId: character.character_id,175
tileX: 9,176
tileY: 8177
});178
advanceMs(harness, woodcuttingDurationMs(WoodTier.pine, WoodTier.pine) + 200);179
assert.ok(String(worker.world.chunkData(0, 0).blocks[8 * 16 + 9].state).endsWith("-stump"));180
181
advanceMs(harness, treeExhaustDurationMs(WoodTier.pine) + 200);182
const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];183
assert.equal(isChopableTreeBlock(block), true);184
assert.equal(tierRank(WoodTier.pine), 1);185
}186
finally187
{ harness.close(); }188
});