BlueGit

timfa questward

Add fishing and firestarting, plus lighting and combat pathing fixes.

Fishing with spots, bait, net, pole/rod crafting and line breaks; firestarting, campfires, ovens, and cooking. Dynamic lights reach the outer map ring from the 3×3 sim zone. Combatants share stance tiles instead of sidestepping forever.

timfa Tim Falken · pushed by timfa

Authored 2026-08-28 · 2 months ago

Hash
8c5790c33003ec62d9a01a16c3f32a0a34ee5add
Parent
f27d7926
45 files changed +3198 −77
client/assets/blocks/campfire/campfire-bloom.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/campfire/campfire.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/fishing-spot/exhausted.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/fishing-spot/fishing-spot.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/oven/oven.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/ash/ash.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bait/bait.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/fishing-net/fishing-net-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/fishing-net/fishing-net.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/fishing-pole/fishing-pole.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/fishing-rod/fishing-rod-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/fishing-rod/fishing-rod.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/meat/burnt.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/meat/cooked.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/meat/raw.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/tinderbox/tinderbox.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/skills/firestarting.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#8a3a18"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">FS</text></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#8a3a18"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">FS</text></svg>
client/src/editor/main.js +51 −1
@@ -517,18 +517,28 @@ function paintAt (localX, localY)
517 517 else
518 518 {
519 519 const def = BLOCK_DEFINITIONS[tool.typeId];
520 if (def?.id === BlockType.fishingSpot)
521 {
522 const groundType = draft.grounds[index]?.typeId;
523 if (groundType !== GroundType.water && groundType !== GroundType.deepWater)
524 { return; }
525 }
520 526 let nextState = definitionUsesNeighborConnect(def)
521 527 ? composeNeighborConnectState(def, state, 0)
522 528 : state;
523 529 if (def?.id === BlockType.flower)
524 530 { nextState = flowerBlockState(randomFlowerColorId()); }
531 if (def?.id === BlockType.fishingSpot && !nextState)
532 { nextState = "fishing-spot"; }
525 533 const config = def?.id === BlockType.doorway
526 534 ? {
527 535 targetDimensionId: selectedDimensionId,
528 536 tileX: chunkX * CHUNK_SIZE + localX,
529 537 tileY: chunkY * CHUNK_SIZE + localY
530 538 }
531 : null;
539 : (def?.id === BlockType.fishingSpot
540 ? { fishes: [] }
541 : null);
532 542 if (def?.id === BlockType.doorway && !nextState)
533 543 { nextState = "door"; }
534 544 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
@@ -984,6 +994,23 @@ async function main ()
984 994 afterDraftMutation();
985 995 return;
986 996 }
997 if (ctx.kind === "fishing-spot")
998 {
999 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1000 const existing = draft.blocks[index];
1001 draft.blocks[index] = {
1002 typeId: BlockType.fishingSpot,
1003 state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot",
1004 config: { fishes: [...(config.fishes ?? [])] }
1005 };
1006 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1007 ground: draft.grounds[index],
1008 block: draft.blocks[index],
1009 light: draft.light[index]
1010 });
1011 afterDraftMutation();
1012 return;
1013 }
987 1014 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
988 1015 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
989 1016 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
@@ -1005,6 +1032,18 @@ async function main ()
1005 1032 afterDraftMutation();
1006 1033 return;
1007 1034 }
1035 if (ctx.kind === "fishing-spot")
1036 {
1037 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1038 draft.blocks[index] = null;
1039 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1040 ground: draft.grounds[index],
1041 block: draft.blocks[index],
1042 light: draft.light[index]
1043 });
1044 afterDraftMutation();
1045 return;
1046 }
1008 1047 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1009 1048 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1010 1049 afterDraftMutation();
@@ -1456,6 +1495,17 @@ document.addEventListener("contextmenu", (event) =>
1456 1495 state: block.state ?? "door",
1457 1496 config: block.config ? { ...block.config } : {}
1458 1497 });
1498 return;
1499 }
1500 if (block?.typeId === BlockType.fishingSpot)
1501 {
1502 tileConfigModal.openFishingSpot({
1503 localX,
1504 localY,
1505 tileX: tile.tileX,
1506 tileY: tile.tileY,
1507 config: block.config ? { ...block.config } : { fishes: [] }
1508 });
1459 1509 }
1460 1510 });
1461 1511
@@ -517,18 +517,28 @@ function paintAt (localX, localY)
517 else
517 else
518 {
518 {
519 const def = BLOCK_DEFINITIONS[tool.typeId];
519 const def = BLOCK_DEFINITIONS[tool.typeId];
520 if (def?.id === BlockType.fishingSpot)
521 {
522 const groundType = draft.grounds[index]?.typeId;
523 if (groundType !== GroundType.water && groundType !== GroundType.deepWater)
524 { return; }
525 }
520 let nextState = definitionUsesNeighborConnect(def)
526 let nextState = definitionUsesNeighborConnect(def)
521 ? composeNeighborConnectState(def, state, 0)
527 ? composeNeighborConnectState(def, state, 0)
522 : state;
528 : state;
523 if (def?.id === BlockType.flower)
529 if (def?.id === BlockType.flower)
524 { nextState = flowerBlockState(randomFlowerColorId()); }
530 { nextState = flowerBlockState(randomFlowerColorId()); }
531 if (def?.id === BlockType.fishingSpot && !nextState)
532 { nextState = "fishing-spot"; }
525 const config = def?.id === BlockType.doorway
533 const config = def?.id === BlockType.doorway
526 ? {
534 ? {
527 targetDimensionId: selectedDimensionId,
535 targetDimensionId: selectedDimensionId,
528 tileX: chunkX * CHUNK_SIZE + localX,
536 tileX: chunkX * CHUNK_SIZE + localX,
529 tileY: chunkY * CHUNK_SIZE + localY
537 tileY: chunkY * CHUNK_SIZE + localY
530 }
538 }
531 : null;
539 : (def?.id === BlockType.fishingSpot
540 ? { fishes: [] }
541 : null);
532 if (def?.id === BlockType.doorway && !nextState)
542 if (def?.id === BlockType.doorway && !nextState)
533 { nextState = "door"; }
543 { nextState = "door"; }
534 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
544 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
@@ -984,6 +994,23 @@ async function main ()
984 afterDraftMutation();
994 afterDraftMutation();
985 return;
995 return;
986 }
996 }
997 if (ctx.kind === "fishing-spot")
998 {
999 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1000 const existing = draft.blocks[index];
1001 draft.blocks[index] = {
1002 typeId: BlockType.fishingSpot,
1003 state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot",
1004 config: { fishes: [...(config.fishes ?? [])] }
1005 };
1006 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1007 ground: draft.grounds[index],
1008 block: draft.blocks[index],
1009 light: draft.light[index]
1010 });
1011 afterDraftMutation();
1012 return;
1013 }
987 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1014 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
988 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
1015 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
989 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1016 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
@@ -1005,6 +1032,18 @@ async function main ()
1005 afterDraftMutation();
1032 afterDraftMutation();
1006 return;
1033 return;
1007 }
1034 }
1035 if (ctx.kind === "fishing-spot")
1036 {
1037 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1038 draft.blocks[index] = null;
1039 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1040 ground: draft.grounds[index],
1041 block: draft.blocks[index],
1042 light: draft.light[index]
1043 });
1044 afterDraftMutation();
1045 return;
1046 }
1008 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1047 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1009 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1048 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1010 afterDraftMutation();
1049 afterDraftMutation();
@@ -1456,6 +1495,17 @@ document.addEventListener("contextmenu", (event) =>
1456 state: block.state ?? "door",
1495 state: block.state ?? "door",
1457 config: block.config ? { ...block.config } : {}
1496 config: block.config ? { ...block.config } : {}
1458 });
1497 });
1498 return;
1499 }
1500 if (block?.typeId === BlockType.fishingSpot)
1501 {
1502 tileConfigModal.openFishingSpot({
1503 localX,
1504 localY,
1505 tileX: tile.tileX,
1506 tileY: tile.tileY,
1507 config: block.config ? { ...block.config } : { fishes: [] }
1508 });
1459 }
1509 }
1460});
1510});
1461
1511
client/src/editor/tileConfigModal.js +88 −2
@@ -13,6 +13,7 @@ import { mobSpellCastChancePercent } from "/shared/definitions/mobCombat.js";
13 13 import { SPELL_DEFINITIONS } from "/shared/definitions/spells.js";
14 14 import { centralExchangeStaffCount } from "/shared/market/exchange.js";
15 15 import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing, listAllItemPickerEntries } from "/shared/definitions/items.js";
16 import { listRawFishPickerEntries, normalizeFishingSpotConfig } from "/shared/definitions/fishItems.js";
16 17 import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
17 18 import { normalizeRgb } from "/shared/render/tint.js";
18 19 import { createDimensionCombobox } from "./dimensionCombobox.js";
@@ -107,11 +108,13 @@ export function initTileConfigModal ({
107 108 let context = null;
108 109 /** @type {{ itemId: number, quantity: number }[]} */
109 110 let sellsDraft = [];
111 /** @type {number[]} raw fish item ids for fishing spots */
112 let fishesDraft = [];
110 113 /** @type {{ spellId: string, chance: number }[]} */
111 114 let spellsDraft = [];
112 115 /** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */
113 116 let equipmentDraft = {};
114 /** @type {{ kind: "sells" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */
117 /** @type {{ kind: "sells" } | { kind: "fishes" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */
115 118 let itemSearchMode = null;
116 119 /** @type {string|null} */
117 120 let dyeEditSlot = null;
@@ -156,6 +159,12 @@ export function initTileConfigModal ({
156 159 openItemSearch("Add shop stock");
157 160 }
158 161
162 function openFishItemSearch ()
163 {
164 itemSearchMode = { kind: "fishes" };
165 openItemSearch("Add fish to spot");
166 }
167
159 168 function openEquipItemSearch (slot)
160 169 {
161 170 itemSearchMode = { kind: "equip", slot };
@@ -173,7 +182,9 @@ export function initTileConfigModal ({
173 182 itemSearchMatches = null;
174 183 itemSearchInput.placeholder = itemSearchMode?.kind === "equip"
175 184 ? "Search equipment…"
176 : "Search all items…";
185 : itemSearchMode?.kind === "fishes"
186 ? "Search raw fish…"
187 : "Search all items…";
177 188 renderItemSearchResults("");
178 189 itemSearchBackdrop.hidden = false;
179 190 itemSearchModal.hidden = false;
@@ -184,6 +195,8 @@ export function initTileConfigModal ({
184 195 {
185 196 if (itemSearchMode?.kind === "equip")
186 197 { return listEquippableItemsForSlot(itemSearchMode.slot); }
198 if (itemSearchMode?.kind === "fishes")
199 { return listRawFishPickerEntries(); }
187 200 return listAllItemPickerEntries();
188 201 }
189 202
@@ -257,6 +270,12 @@ export function initTileConfigModal ({
257 270 };
258 271 renderEquipmentRows();
259 272 }
273 else if (itemSearchMode?.kind === "fishes")
274 {
275 if (!fishesDraft.includes(item.itemId))
276 { fishesDraft.push(item.itemId); }
277 renderFishesList();
278 }
260 279 else
261 280 {
262 281 sellsDraft.push({ itemId: item.itemId, quantity: 0 });
@@ -350,6 +369,42 @@ export function initTileConfigModal ({
350 369 bindDyeChannel(dyeG, dyeGNum);
351 370 bindDyeChannel(dyeB, dyeBNum);
352 371
372 function renderFishesList ()
373 {
374 const list = form.querySelector("[data-fishes-list]");
375 if (!list)
376 { return; }
377 list.innerHTML = "";
378 if (!fishesDraft.length)
379 {
380 const empty = document.createElement("p");
381 empty.className = "hint";
382 empty.textContent = "No fish yet. Use + to choose species for this spot.";
383 list.append(empty);
384 return;
385 }
386 for (let index = 0; index < fishesDraft.length; index++)
387 {
388 const itemId = fishesDraft[index];
389 const def = itemDefinition(itemId);
390 const row = document.createElement("div");
391 row.className = "spawner-sells-row";
392 const name = document.createElement("span");
393 name.className = "spawner-sells-name";
394 name.textContent = def?.displayName ?? `Item ${itemId}`;
395 const remove = document.createElement("button");
396 remove.type = "button";
397 remove.textContent = "Remove";
398 remove.addEventListener("click", () =>
399 {
400 fishesDraft.splice(index, 1);
401 renderFishesList();
402 });
403 row.append(name, remove);
404 list.append(row);
405 }
406 }
407
353 408 function renderSellsList ()
354 409 {
355 410 const list = form.querySelector("[data-sells-list]");
@@ -761,6 +816,30 @@ export function initTileConfigModal ({
761 816 show(true);
762 817 }
763 818
819 function openFishingSpot (ctx)
820 {
821 context = { kind: "fishing-spot", ...ctx };
822 const normalized = normalizeFishingSpotConfig(ctx.config);
823 fishesDraft = [...normalized.fishes];
824 title.textContent = `Fishing spot · ${ctx.tileX}, ${ctx.tileY}`;
825 form.innerHTML = "";
826 const header = document.createElement("div");
827 header.className = "spawner-sells-header";
828 const label = document.createElement("strong");
829 label.textContent = "Fishes";
830 const addBtn = document.createElement("button");
831 addBtn.type = "button";
832 addBtn.textContent = "+";
833 addBtn.title = "Add fish";
834 addBtn.addEventListener("click", () => openFishItemSearch());
835 header.append(label, addBtn);
836 const list = document.createElement("div");
837 list.setAttribute("data-fishes-list", "");
838 form.append(header, list);
839 renderFishesList();
840 show(true);
841 }
842
764 843 function openDoorway (ctx)
765 844 {
766 845 context = { kind: "doorway", ...ctx };
@@ -851,6 +930,12 @@ export function initTileConfigModal ({
851 930 show(false);
852 931 return;
853 932 }
933 if (context.kind === "fishing-spot")
934 {
935 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
936 show(false);
937 return;
938 }
854 939 const data = new FormData(form);
855 940 const equipment = {};
856 941 for (const slot of EQUIPMENT_SLOTS)
@@ -888,6 +973,7 @@ export function initTileConfigModal ({
888 973 isOpen: () => open,
889 974 openSpawner,
890 975 openDoorway,
976 openFishingSpot,
891 977 close: () => show(false),
892 978 handleMessage (message)
893 979 {
@@ -13,6 +13,7 @@ import { mobSpellCastChancePercent } from "/shared/definitions/mobCombat.js";
13import { SPELL_DEFINITIONS } from "/shared/definitions/spells.js";
13import { SPELL_DEFINITIONS } from "/shared/definitions/spells.js";
14import { centralExchangeStaffCount } from "/shared/market/exchange.js";
14import { centralExchangeStaffCount } from "/shared/market/exchange.js";
15import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing, listAllItemPickerEntries } from "/shared/definitions/items.js";
15import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing, listAllItemPickerEntries } from "/shared/definitions/items.js";
16import { listRawFishPickerEntries, normalizeFishingSpotConfig } from "/shared/definitions/fishItems.js";
16import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
17import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
17import { normalizeRgb } from "/shared/render/tint.js";
18import { normalizeRgb } from "/shared/render/tint.js";
18import { createDimensionCombobox } from "./dimensionCombobox.js";
19import { createDimensionCombobox } from "./dimensionCombobox.js";
@@ -107,11 +108,13 @@ export function initTileConfigModal ({
107 let context = null;
108 let context = null;
108 /** @type {{ itemId: number, quantity: number }[]} */
109 /** @type {{ itemId: number, quantity: number }[]} */
109 let sellsDraft = [];
110 let sellsDraft = [];
111 /** @type {number[]} raw fish item ids for fishing spots */
112 let fishesDraft = [];
110 /** @type {{ spellId: string, chance: number }[]} */
113 /** @type {{ spellId: string, chance: number }[]} */
111 let spellsDraft = [];
114 let spellsDraft = [];
112 /** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */
115 /** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */
113 let equipmentDraft = {};
116 let equipmentDraft = {};
114 /** @type {{ kind: "sells" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */
117 /** @type {{ kind: "sells" } | { kind: "fishes" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */
115 let itemSearchMode = null;
118 let itemSearchMode = null;
116 /** @type {string|null} */
119 /** @type {string|null} */
117 let dyeEditSlot = null;
120 let dyeEditSlot = null;
@@ -156,6 +159,12 @@ export function initTileConfigModal ({
156 openItemSearch("Add shop stock");
159 openItemSearch("Add shop stock");
157 }
160 }
158
161
162 function openFishItemSearch ()
163 {
164 itemSearchMode = { kind: "fishes" };
165 openItemSearch("Add fish to spot");
166 }
167
159 function openEquipItemSearch (slot)
168 function openEquipItemSearch (slot)
160 {
169 {
161 itemSearchMode = { kind: "equip", slot };
170 itemSearchMode = { kind: "equip", slot };
@@ -173,7 +182,9 @@ export function initTileConfigModal ({
173 itemSearchMatches = null;
182 itemSearchMatches = null;
174 itemSearchInput.placeholder = itemSearchMode?.kind === "equip"
183 itemSearchInput.placeholder = itemSearchMode?.kind === "equip"
175 ? "Search equipment…"
184 ? "Search equipment…"
176 : "Search all items…";
185 : itemSearchMode?.kind === "fishes"
186 ? "Search raw fish…"
187 : "Search all items…";
177 renderItemSearchResults("");
188 renderItemSearchResults("");
178 itemSearchBackdrop.hidden = false;
189 itemSearchBackdrop.hidden = false;
179 itemSearchModal.hidden = false;
190 itemSearchModal.hidden = false;
@@ -184,6 +195,8 @@ export function initTileConfigModal ({
184 {
195 {
185 if (itemSearchMode?.kind === "equip")
196 if (itemSearchMode?.kind === "equip")
186 { return listEquippableItemsForSlot(itemSearchMode.slot); }
197 { return listEquippableItemsForSlot(itemSearchMode.slot); }
198 if (itemSearchMode?.kind === "fishes")
199 { return listRawFishPickerEntries(); }
187 return listAllItemPickerEntries();
200 return listAllItemPickerEntries();
188 }
201 }
189
202
@@ -257,6 +270,12 @@ export function initTileConfigModal ({
257 };
270 };
258 renderEquipmentRows();
271 renderEquipmentRows();
259 }
272 }
273 else if (itemSearchMode?.kind === "fishes")
274 {
275 if (!fishesDraft.includes(item.itemId))
276 { fishesDraft.push(item.itemId); }
277 renderFishesList();
278 }
260 else
279 else
261 {
280 {
262 sellsDraft.push({ itemId: item.itemId, quantity: 0 });
281 sellsDraft.push({ itemId: item.itemId, quantity: 0 });
@@ -350,6 +369,42 @@ export function initTileConfigModal ({
350 bindDyeChannel(dyeG, dyeGNum);
369 bindDyeChannel(dyeG, dyeGNum);
351 bindDyeChannel(dyeB, dyeBNum);
370 bindDyeChannel(dyeB, dyeBNum);
352
371
372 function renderFishesList ()
373 {
374 const list = form.querySelector("[data-fishes-list]");
375 if (!list)
376 { return; }
377 list.innerHTML = "";
378 if (!fishesDraft.length)
379 {
380 const empty = document.createElement("p");
381 empty.className = "hint";
382 empty.textContent = "No fish yet. Use + to choose species for this spot.";
383 list.append(empty);
384 return;
385 }
386 for (let index = 0; index < fishesDraft.length; index++)
387 {
388 const itemId = fishesDraft[index];
389 const def = itemDefinition(itemId);
390 const row = document.createElement("div");
391 row.className = "spawner-sells-row";
392 const name = document.createElement("span");
393 name.className = "spawner-sells-name";
394 name.textContent = def?.displayName ?? `Item ${itemId}`;
395 const remove = document.createElement("button");
396 remove.type = "button";
397 remove.textContent = "Remove";
398 remove.addEventListener("click", () =>
399 {
400 fishesDraft.splice(index, 1);
401 renderFishesList();
402 });
403 row.append(name, remove);
404 list.append(row);
405 }
406 }
407
353 function renderSellsList ()
408 function renderSellsList ()
354 {
409 {
355 const list = form.querySelector("[data-sells-list]");
410 const list = form.querySelector("[data-sells-list]");
@@ -761,6 +816,30 @@ export function initTileConfigModal ({
761 show(true);
816 show(true);
762 }
817 }
763
818
819 function openFishingSpot (ctx)
820 {
821 context = { kind: "fishing-spot", ...ctx };
822 const normalized = normalizeFishingSpotConfig(ctx.config);
823 fishesDraft = [...normalized.fishes];
824 title.textContent = `Fishing spot · ${ctx.tileX}, ${ctx.tileY}`;
825 form.innerHTML = "";
826 const header = document.createElement("div");
827 header.className = "spawner-sells-header";
828 const label = document.createElement("strong");
829 label.textContent = "Fishes";
830 const addBtn = document.createElement("button");
831 addBtn.type = "button";
832 addBtn.textContent = "+";
833 addBtn.title = "Add fish";
834 addBtn.addEventListener("click", () => openFishItemSearch());
835 header.append(label, addBtn);
836 const list = document.createElement("div");
837 list.setAttribute("data-fishes-list", "");
838 form.append(header, list);
839 renderFishesList();
840 show(true);
841 }
842
764 function openDoorway (ctx)
843 function openDoorway (ctx)
765 {
844 {
766 context = { kind: "doorway", ...ctx };
845 context = { kind: "doorway", ...ctx };
@@ -851,6 +930,12 @@ export function initTileConfigModal ({
851 show(false);
930 show(false);
852 return;
931 return;
853 }
932 }
933 if (context.kind === "fishing-spot")
934 {
935 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
936 show(false);
937 return;
938 }
854 const data = new FormData(form);
939 const data = new FormData(form);
855 const equipment = {};
940 const equipment = {};
856 for (const slot of EQUIPMENT_SLOTS)
941 for (const slot of EQUIPMENT_SLOTS)
@@ -888,6 +973,7 @@ export function initTileConfigModal ({
888 isOpen: () => open,
973 isOpen: () => open,
889 openSpawner,
974 openSpawner,
890 openDoorway,
975 openDoorway,
976 openFishingSpot,
891 close: () => show(false),
977 close: () => show(false),
892 handleMessage (message)
978 handleMessage (message)
893 {
979 {
client/src/play/main.js +138 −1
@@ -33,7 +33,9 @@ import { initGraphicsSettings } from "./graphicsSettings.js";
33 33 import { CraftingStationId } from "/shared/definitions/craftingStations.js";
34 34 import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
35 35 import { formatQuantity } from "/shared/items/formatQuantity.js";
36 import { ItemId } from "/shared/definitions/items.js";
36 import { ItemId, itemDefinition } from "/shared/definitions/items.js";
37 import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
38 import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
37 39 import { countCoinsInSlots } from "/shared/items/inventory.js";
38 40
39 41 const game = new Game();
@@ -350,6 +352,35 @@ function requestOpenCraftStation (stationId, tileX, tileY)
350 352 { approachAdjacentTile(tileX, tileY); }
351 353 }
352 354
355 function requestStartFire (ground)
356 {
357 if (!ground)
358 { return; }
359 clearAllPendingActions();
360 pendingInteract = {
361 kind: "start-fire",
362 groundItemId: ground.groundItemId,
363 tileX: ground.tileX,
364 tileY: ground.tileY
365 };
366 const local = view?.entities.get(view.localEntityId);
367 if (local && chebyshev(local.tileX, local.tileY, ground.tileX, ground.tileY) <= 1)
368 { flushPendingInteract(); }
369 else
370 { approachAdjacentTile(ground.tileX, ground.tileY); }
371 }
372
373 function requestFish (tileX, tileY)
374 {
375 clearAllPendingActions();
376 pendingInteract = { kind: "fish", tileX, tileY };
377 const local = view?.entities.get(view.localEntityId);
378 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
379 { flushPendingInteract(); }
380 else
381 { approachAdjacentTile(tileX, tileY); }
382 }
383
353 384 function requestMine (tileX, tileY)
354 385 {
355 386 clearAllPendingActions();
@@ -595,6 +626,31 @@ function flushPendingInteract ()
595 626 return;
596 627 }
597 628
629 if (pendingInteract.kind === "start-fire")
630 {
631 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
632 { return; }
633 socket.send({
634 type: MessageType.startFire,
635 groundItemId: pendingInteract.groundItemId
636 });
637 clearPendingInteract();
638 return;
639 }
640
641 if (pendingInteract.kind === "fish")
642 {
643 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
644 { return; }
645 socket.send({
646 type: MessageType.startFish,
647 tileX: pendingInteract.tileX,
648 tileY: pendingInteract.tileY
649 });
650 clearPendingInteract();
651 return;
652 }
653
598 654 if (pendingInteract.kind === "chop")
599 655 {
600 656 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
@@ -763,6 +819,12 @@ function handleLeftClick (mouseX, mouseY)
763 819 { requestOpenCauldron(tile.tileX, tile.tileY); }
764 820 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
765 821 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
822 else if (isOvenTile(view, tile.tileX, tile.tileY))
823 { requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY); }
824 else if (isCampfireTile(view, tile.tileX, tile.tileY))
825 { requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY); }
826 else if (isFishingSpotTile(view, tile.tileX, tile.tileY))
827 { requestFish(tile.tileX, tile.tileY); }
766 828 else if (isAnvilTile(view, tile.tileX, tile.tileY))
767 829 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
768 830 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
@@ -866,6 +928,13 @@ function handleRightClick (event, mouseX, mouseY)
866 928 label: `Pick up ${name}`,
867 929 onSelect: () => requestPickup(ground)
868 930 });
931 if (playerHasUsableTinderbox() && isGroundWoodLog(ground))
932 {
933 items.push({
934 label: `Start Fire`,
935 onSelect: () => requestStartFire(ground)
936 });
937 }
869 938 }
870 939
871 940 if (isBankTile(view, tile.tileX, tile.tileY))
@@ -928,6 +997,30 @@ function handleRightClick (event, mouseX, mouseY)
928 997 });
929 998 }
930 999
1000 if (isOvenTile(view, tile.tileX, tile.tileY))
1001 {
1002 items.push({
1003 label: "Cook",
1004 onSelect: () => requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY)
1005 });
1006 }
1007
1008 if (isCampfireTile(view, tile.tileX, tile.tileY))
1009 {
1010 items.push({
1011 label: "Cook",
1012 onSelect: () => requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY)
1013 });
1014 }
1015
1016 if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1017 {
1018 items.push({
1019 label: "Fish",
1020 onSelect: () => requestFish(tile.tileX, tile.tileY)
1021 });
1022 }
1023
931 1024 if (isAnvilTile(view, tile.tileX, tile.tileY))
932 1025 {
933 1026 items.push({
@@ -1486,10 +1579,14 @@ async function main ()
1486 1579 { toasts?.show("Failed to cast spell"); }
1487 1580 break;
1488 1581 case MessageType.spellCastFlash:
1582 // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*.
1489 1583 break;
1490 1584 case MessageType.spellLightAppear:
1491 1585 case MessageType.spellLightUpdate:
1586 view?.setSpellLight(message);
1587 break;
1492 1588 case MessageType.spellLightRemove:
1589 view?.removeSpellLight(message);
1493 1590 break;
1494 1591 case MessageType.stamina:
1495 1592 staminaUi?.apply(message);
@@ -1920,11 +2017,51 @@ function isFurnaceTile (view, tileX, tileY)
1920 2017 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
1921 2018 }
1922 2019
2020 function isOvenTile (view, tileX, tileY)
2021 {
2022 return blockTypeAt(view, tileX, tileY) === BlockType.oven;
2023 }
2024
2025 function isCampfireTile (view, tileX, tileY)
2026 {
2027 return blockTypeAt(view, tileX, tileY) === BlockType.campfire;
2028 }
2029
2030 function isFishingSpotTile (view, tileX, tileY)
2031 {
2032 const block = blockAt(view, tileX, tileY);
2033 if (!block || block.typeId !== BlockType.fishingSpot)
2034 { return false; }
2035 return block.state !== "exhausted";
2036 }
2037
1923 2038 function isAnvilTile (view, tileX, tileY)
1924 2039 {
1925 2040 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
1926 2041 }
1927 2042
2043 function isGroundWoodLog (ground)
2044 {
2045 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
2046 return def?.familyId === ItemFamilyId.log;
2047 }
2048
2049 function playerHasUsableTinderbox ()
2050 {
2051 const slots = inventory?.getInventorySlots?.() ?? [];
2052 for (const slot of slots)
2053 {
2054 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
2055 { continue; }
2056 const charges = slot.instance?.kind === "tinderbox"
2057 ? (slot.instance.charges | 0)
2058 : TINDERBOX_MAX_CHARGES;
2059 if (charges > 0)
2060 { return true; }
2061 }
2062 return false;
2063 }
2064
1928 2065 function isWoodworkingBenchTile (view, tileX, tileY)
1929 2066 {
1930 2067 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
@@ -33,7 +33,9 @@ import { initGraphicsSettings } from "./graphicsSettings.js";
33import { CraftingStationId } from "/shared/definitions/craftingStations.js";
33import { CraftingStationId } from "/shared/definitions/craftingStations.js";
34import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
34import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
35import { formatQuantity } from "/shared/items/formatQuantity.js";
35import { formatQuantity } from "/shared/items/formatQuantity.js";
36import { ItemId } from "/shared/definitions/items.js";
36import { ItemId, itemDefinition } from "/shared/definitions/items.js";
37import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
38import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
37import { countCoinsInSlots } from "/shared/items/inventory.js";
39import { countCoinsInSlots } from "/shared/items/inventory.js";
38
40
39const game = new Game();
41const game = new Game();
@@ -350,6 +352,35 @@ function requestOpenCraftStation (stationId, tileX, tileY)
350 { approachAdjacentTile(tileX, tileY); }
352 { approachAdjacentTile(tileX, tileY); }
351}
353}
352
354
355function requestStartFire (ground)
356{
357 if (!ground)
358 { return; }
359 clearAllPendingActions();
360 pendingInteract = {
361 kind: "start-fire",
362 groundItemId: ground.groundItemId,
363 tileX: ground.tileX,
364 tileY: ground.tileY
365 };
366 const local = view?.entities.get(view.localEntityId);
367 if (local && chebyshev(local.tileX, local.tileY, ground.tileX, ground.tileY) <= 1)
368 { flushPendingInteract(); }
369 else
370 { approachAdjacentTile(ground.tileX, ground.tileY); }
371}
372
373function requestFish (tileX, tileY)
374{
375 clearAllPendingActions();
376 pendingInteract = { kind: "fish", tileX, tileY };
377 const local = view?.entities.get(view.localEntityId);
378 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
379 { flushPendingInteract(); }
380 else
381 { approachAdjacentTile(tileX, tileY); }
382}
383
353function requestMine (tileX, tileY)
384function requestMine (tileX, tileY)
354{
385{
355 clearAllPendingActions();
386 clearAllPendingActions();
@@ -595,6 +626,31 @@ function flushPendingInteract ()
595 return;
626 return;
596 }
627 }
597
628
629 if (pendingInteract.kind === "start-fire")
630 {
631 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
632 { return; }
633 socket.send({
634 type: MessageType.startFire,
635 groundItemId: pendingInteract.groundItemId
636 });
637 clearPendingInteract();
638 return;
639 }
640
641 if (pendingInteract.kind === "fish")
642 {
643 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
644 { return; }
645 socket.send({
646 type: MessageType.startFish,
647 tileX: pendingInteract.tileX,
648 tileY: pendingInteract.tileY
649 });
650 clearPendingInteract();
651 return;
652 }
653
598 if (pendingInteract.kind === "chop")
654 if (pendingInteract.kind === "chop")
599 {
655 {
600 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
656 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
@@ -763,6 +819,12 @@ function handleLeftClick (mouseX, mouseY)
763 { requestOpenCauldron(tile.tileX, tile.tileY); }
819 { requestOpenCauldron(tile.tileX, tile.tileY); }
764 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
820 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
765 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
821 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
822 else if (isOvenTile(view, tile.tileX, tile.tileY))
823 { requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY); }
824 else if (isCampfireTile(view, tile.tileX, tile.tileY))
825 { requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY); }
826 else if (isFishingSpotTile(view, tile.tileX, tile.tileY))
827 { requestFish(tile.tileX, tile.tileY); }
766 else if (isAnvilTile(view, tile.tileX, tile.tileY))
828 else if (isAnvilTile(view, tile.tileX, tile.tileY))
767 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
829 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
768 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
830 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
@@ -866,6 +928,13 @@ function handleRightClick (event, mouseX, mouseY)
866 label: `Pick up ${name}`,
928 label: `Pick up ${name}`,
867 onSelect: () => requestPickup(ground)
929 onSelect: () => requestPickup(ground)
868 });
930 });
931 if (playerHasUsableTinderbox() && isGroundWoodLog(ground))
932 {
933 items.push({
934 label: `Start Fire`,
935 onSelect: () => requestStartFire(ground)
936 });
937 }
869 }
938 }
870
939
871 if (isBankTile(view, tile.tileX, tile.tileY))
940 if (isBankTile(view, tile.tileX, tile.tileY))
@@ -928,6 +997,30 @@ function handleRightClick (event, mouseX, mouseY)
928 });
997 });
929 }
998 }
930
999
1000 if (isOvenTile(view, tile.tileX, tile.tileY))
1001 {
1002 items.push({
1003 label: "Cook",
1004 onSelect: () => requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY)
1005 });
1006 }
1007
1008 if (isCampfireTile(view, tile.tileX, tile.tileY))
1009 {
1010 items.push({
1011 label: "Cook",
1012 onSelect: () => requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY)
1013 });
1014 }
1015
1016 if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1017 {
1018 items.push({
1019 label: "Fish",
1020 onSelect: () => requestFish(tile.tileX, tile.tileY)
1021 });
1022 }
1023
931 if (isAnvilTile(view, tile.tileX, tile.tileY))
1024 if (isAnvilTile(view, tile.tileX, tile.tileY))
932 {
1025 {
933 items.push({
1026 items.push({
@@ -1486,10 +1579,14 @@ async function main ()
1486 { toasts?.show("Failed to cast spell"); }
1579 { toasts?.show("Failed to cast spell"); }
1487 break;
1580 break;
1488 case MessageType.spellCastFlash:
1581 case MessageType.spellCastFlash:
1582 // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*.
1489 break;
1583 break;
1490 case MessageType.spellLightAppear:
1584 case MessageType.spellLightAppear:
1491 case MessageType.spellLightUpdate:
1585 case MessageType.spellLightUpdate:
1586 view?.setSpellLight(message);
1587 break;
1492 case MessageType.spellLightRemove:
1588 case MessageType.spellLightRemove:
1589 view?.removeSpellLight(message);
1493 break;
1590 break;
1494 case MessageType.stamina:
1591 case MessageType.stamina:
1495 staminaUi?.apply(message);
1592 staminaUi?.apply(message);
@@ -1920,11 +2017,51 @@ function isFurnaceTile (view, tileX, tileY)
1920 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
2017 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
1921}
2018}
1922
2019
2020function isOvenTile (view, tileX, tileY)
2021{
2022 return blockTypeAt(view, tileX, tileY) === BlockType.oven;
2023}
2024
2025function isCampfireTile (view, tileX, tileY)
2026{
2027 return blockTypeAt(view, tileX, tileY) === BlockType.campfire;
2028}
2029
2030function isFishingSpotTile (view, tileX, tileY)
2031{
2032 const block = blockAt(view, tileX, tileY);
2033 if (!block || block.typeId !== BlockType.fishingSpot)
2034 { return false; }
2035 return block.state !== "exhausted";
2036}
2037
1923function isAnvilTile (view, tileX, tileY)
2038function isAnvilTile (view, tileX, tileY)
1924{
2039{
1925 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2040 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
1926}
2041}
1927
2042
2043function isGroundWoodLog (ground)
2044{
2045 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
2046 return def?.familyId === ItemFamilyId.log;
2047}
2048
2049function playerHasUsableTinderbox ()
2050{
2051 const slots = inventory?.getInventorySlots?.() ?? [];
2052 for (const slot of slots)
2053 {
2054 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
2055 { continue; }
2056 const charges = slot.instance?.kind === "tinderbox"
2057 ? (slot.instance.charges | 0)
2058 : TINDERBOX_MAX_CHARGES;
2059 if (charges > 0)
2060 { return true; }
2061 }
2062 return false;
2063}
2064
1928function isWoodworkingBenchTile (view, tileX, tileY)
2065function isWoodworkingBenchTile (view, tileX, tileY)
1929{
2066{
1930 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
2067 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
client/src/render/worldView.js +78 −7
@@ -420,6 +420,8 @@ export class WorldView
420 420 this.nightPreview = null;
421 421 this.followPlayer = true;
422 422 this.dynamicLights = [];
423 /** Persistent Light-spell tile lights (server-driven). */
424 this.spellLights = new Map();
423 425 this.swipes = [];
424 426 this.damageFloats = [];
425 427 this.damageNumbersEl = document.getElementById("damage-numbers");
@@ -1520,7 +1522,28 @@ export class WorldView
1520 1522
1521 1523 spawnSpellFizzleFx (_payload)
1522 1524 {
1523 // Visual-only fizzle; no dynamic light (too expensive for lightmap rebakes).
1525 // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes).
1526 }
1527
1528 /**
1529 * Authoritative Light-spell tile light from the server.
1530 * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates.
1531 */
1532 setSpellLight (payload)
1533 {
1534 const key = `${payload.tileX},${payload.tileY}`;
1535 this.spellLights.set(key, {
1536 tileX: payload.tileX,
1537 tileY: payload.tileY,
1538 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1539 range: payload.rangeTiles ?? 6,
1540 intensity: payload.intensity ?? 0.88
1541 });
1542 }
1543
1544 removeSpellLight (payload)
1545 {
1546 this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
1524 1547 }
1525 1548
1526 1549 #spellProjectileImage (baseSprite, frameIndex)
@@ -3242,6 +3265,36 @@ export class WorldView
3242 3265 );
3243 3266 }
3244 3267
3268 /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */
3269 #innerDynamicLights (activeLights)
3270 {
3271 return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY));
3272 }
3273
3274 /**
3275 * Lights to simulate for one chunk: inner chunks get all inner sources; outer ring
3276 * chunks only receive inner sources close enough to reach the chunk bounds.
3277 */
3278 #dynamicLightsForChunk (chunkX, chunkY, activeLights)
3279 {
3280 const center = this.#activeLightingCenterChunk();
3281 if (!center)
3282 { return activeLights; }
3283 const inner = this.#innerDynamicLights(activeLights);
3284 if (this.#isActiveLightingChunk(chunkX, chunkY))
3285 { return inner; }
3286 return inner.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3287 }
3288
3289 #dynamicLightsForTile (tileX, tileY, activeLights)
3290 {
3291 return this.#dynamicLightsForChunk(
3292 Math.floor(tileX / CHUNK_SIZE),
3293 Math.floor(tileY / CHUNK_SIZE),
3294 activeLights
3295 );
3296 }
3297
3245 3298 #updateShade ()
3246 3299 {
3247 3300 const ambientDark = this.#ambientDarkness();
@@ -3249,6 +3302,22 @@ export class WorldView
3249 3302 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
3250 3303
3251 3304 const activeLights = [...this.dynamicLights];
3305 for (const light of this.spellLights.values())
3306 {
3307 if (light.until <= now)
3308 { continue; }
3309 activeLights.push({
3310 tileX: light.tileX,
3311 tileY: light.tileY,
3312 range: light.range,
3313 intensity: light.intensity
3314 });
3315 }
3316 for (const key of [...this.spellLights.keys()])
3317 {
3318 if (this.spellLights.get(key).until <= now)
3319 { this.spellLights.delete(key); }
3320 }
3252 3321 const tileSize = this.tileSize();
3253 3322 const blindLight = this.#blindVisionLight();
3254 3323 if (blindLight)
@@ -3272,7 +3341,7 @@ export class WorldView
3272 3341 {
3273 3342 if (objects._inViewport === false)
3274 3343 { continue; }
3275 const lights = this.#isActiveLightingTile(objects.tileX, objects.tileY) ? activeLights : [];
3344 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, activeLights);
3276 3345 const intensity = this.#tileLightIntensity(objects, lights, lightOcclusion);
3277 3346 objects.shadeAlpha = ambientDark * (1 - intensity);
3278 3347 }
@@ -3281,7 +3350,7 @@ export class WorldView
3281 3350 {
3282 3351 if (baked._inViewport === false)
3283 3352 { continue; }
3284 const lights = this.#isActiveLightingChunk(baked.chunkX, baked.chunkY) ? activeLights : [];
3353 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
3285 3354 this.#writeChunkLightmap(baked, lights, lightOcclusion);
3286 3355 if (baked.groundObject?.renderer?.shaderUniforms)
3287 3356 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
@@ -3482,11 +3551,12 @@ export class WorldView
3482 3551 if (!snapshot?.light)
3483 3552 { return null; }
3484 3553 const bakedHash = this.#hashUint8Array(snapshot.light);
3485 if (!this.#isActiveLightingChunk(baked.chunkX, baked.chunkY))
3554 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
3555 if (!lights.length)
3486 3556 { return `i:${bakedHash}`; }
3487 3557 const mode = this.lightingMode === "simple" ? "s" : "f";
3488 3558 let lightsKey = "";
3489 for (const light of activeLights)
3559 for (const light of lights)
3490 3560 {
3491 3561 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
3492 3562 { continue; }
@@ -3497,9 +3567,10 @@ export class WorldView
3497 3567
3498 3568 #invalidateNeighborLightmapCaches (chunkX, chunkY)
3499 3569 {
3500 for (let dy = -1; dy <= 1; dy++)
3570 // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player.
3571 for (let dy = -2; dy <= 2; dy++)
3501 3572 {
3502 for (let dx = -1; dx <= 1; dx++)
3573 for (let dx = -2; dx <= 2; dx++)
3503 3574 {
3504 3575 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
3505 3576 if (baked)
@@ -420,6 +420,8 @@ export class WorldView
420 this.nightPreview = null;
420 this.nightPreview = null;
421 this.followPlayer = true;
421 this.followPlayer = true;
422 this.dynamicLights = [];
422 this.dynamicLights = [];
423 /** Persistent Light-spell tile lights (server-driven). */
424 this.spellLights = new Map();
423 this.swipes = [];
425 this.swipes = [];
424 this.damageFloats = [];
426 this.damageFloats = [];
425 this.damageNumbersEl = document.getElementById("damage-numbers");
427 this.damageNumbersEl = document.getElementById("damage-numbers");
@@ -1520,7 +1522,28 @@ export class WorldView
1520
1522
1521 spawnSpellFizzleFx (_payload)
1523 spawnSpellFizzleFx (_payload)
1522 {
1524 {
1523 // Visual-only fizzle; no dynamic light (too expensive for lightmap rebakes).
1525 // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes).
1526 }
1527
1528 /**
1529 * Authoritative Light-spell tile light from the server.
1530 * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates.
1531 */
1532 setSpellLight (payload)
1533 {
1534 const key = `${payload.tileX},${payload.tileY}`;
1535 this.spellLights.set(key, {
1536 tileX: payload.tileX,
1537 tileY: payload.tileY,
1538 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1539 range: payload.rangeTiles ?? 6,
1540 intensity: payload.intensity ?? 0.88
1541 });
1542 }
1543
1544 removeSpellLight (payload)
1545 {
1546 this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
1524 }
1547 }
1525
1548
1526 #spellProjectileImage (baseSprite, frameIndex)
1549 #spellProjectileImage (baseSprite, frameIndex)
@@ -3242,6 +3265,36 @@ export class WorldView
3242 );
3265 );
3243 }
3266 }
3244
3267
3268 /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */
3269 #innerDynamicLights (activeLights)
3270 {
3271 return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY));
3272 }
3273
3274 /**
3275 * Lights to simulate for one chunk: inner chunks get all inner sources; outer ring
3276 * chunks only receive inner sources close enough to reach the chunk bounds.
3277 */
3278 #dynamicLightsForChunk (chunkX, chunkY, activeLights)
3279 {
3280 const center = this.#activeLightingCenterChunk();
3281 if (!center)
3282 { return activeLights; }
3283 const inner = this.#innerDynamicLights(activeLights);
3284 if (this.#isActiveLightingChunk(chunkX, chunkY))
3285 { return inner; }
3286 return inner.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3287 }
3288
3289 #dynamicLightsForTile (tileX, tileY, activeLights)
3290 {
3291 return this.#dynamicLightsForChunk(
3292 Math.floor(tileX / CHUNK_SIZE),
3293 Math.floor(tileY / CHUNK_SIZE),
3294 activeLights
3295 );
3296 }
3297
3245 #updateShade ()
3298 #updateShade ()
3246 {
3299 {
3247 const ambientDark = this.#ambientDarkness();
3300 const ambientDark = this.#ambientDarkness();
@@ -3249,6 +3302,22 @@ export class WorldView
3249 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
3302 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
3250
3303
3251 const activeLights = [...this.dynamicLights];
3304 const activeLights = [...this.dynamicLights];
3305 for (const light of this.spellLights.values())
3306 {
3307 if (light.until <= now)
3308 { continue; }
3309 activeLights.push({
3310 tileX: light.tileX,
3311 tileY: light.tileY,
3312 range: light.range,
3313 intensity: light.intensity
3314 });
3315 }
3316 for (const key of [...this.spellLights.keys()])
3317 {
3318 if (this.spellLights.get(key).until <= now)
3319 { this.spellLights.delete(key); }
3320 }
3252 const tileSize = this.tileSize();
3321 const tileSize = this.tileSize();
3253 const blindLight = this.#blindVisionLight();
3322 const blindLight = this.#blindVisionLight();
3254 if (blindLight)
3323 if (blindLight)
@@ -3272,7 +3341,7 @@ export class WorldView
3272 {
3341 {
3273 if (objects._inViewport === false)
3342 if (objects._inViewport === false)
3274 { continue; }
3343 { continue; }
3275 const lights = this.#isActiveLightingTile(objects.tileX, objects.tileY) ? activeLights : [];
3344 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, activeLights);
3276 const intensity = this.#tileLightIntensity(objects, lights, lightOcclusion);
3345 const intensity = this.#tileLightIntensity(objects, lights, lightOcclusion);
3277 objects.shadeAlpha = ambientDark * (1 - intensity);
3346 objects.shadeAlpha = ambientDark * (1 - intensity);
3278 }
3347 }
@@ -3281,7 +3350,7 @@ export class WorldView
3281 {
3350 {
3282 if (baked._inViewport === false)
3351 if (baked._inViewport === false)
3283 { continue; }
3352 { continue; }
3284 const lights = this.#isActiveLightingChunk(baked.chunkX, baked.chunkY) ? activeLights : [];
3353 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
3285 this.#writeChunkLightmap(baked, lights, lightOcclusion);
3354 this.#writeChunkLightmap(baked, lights, lightOcclusion);
3286 if (baked.groundObject?.renderer?.shaderUniforms)
3355 if (baked.groundObject?.renderer?.shaderUniforms)
3287 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
3356 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
@@ -3482,11 +3551,12 @@ export class WorldView
3482 if (!snapshot?.light)
3551 if (!snapshot?.light)
3483 { return null; }
3552 { return null; }
3484 const bakedHash = this.#hashUint8Array(snapshot.light);
3553 const bakedHash = this.#hashUint8Array(snapshot.light);
3485 if (!this.#isActiveLightingChunk(baked.chunkX, baked.chunkY))
3554 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
3555 if (!lights.length)
3486 { return `i:${bakedHash}`; }
3556 { return `i:${bakedHash}`; }
3487 const mode = this.lightingMode === "simple" ? "s" : "f";
3557 const mode = this.lightingMode === "simple" ? "s" : "f";
3488 let lightsKey = "";
3558 let lightsKey = "";
3489 for (const light of activeLights)
3559 for (const light of lights)
3490 {
3560 {
3491 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
3561 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
3492 { continue; }
3562 { continue; }
@@ -3497,9 +3567,10 @@ export class WorldView
3497
3567
3498 #invalidateNeighborLightmapCaches (chunkX, chunkY)
3568 #invalidateNeighborLightmapCaches (chunkX, chunkY)
3499 {
3569 {
3500 for (let dy = -1; dy <= 1; dy++)
3570 // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player.
3571 for (let dy = -2; dy <= 2; dy++)
3501 {
3572 {
3502 for (let dx = -1; dx <= 1; dx++)
3573 for (let dx = -2; dx <= 2; dx++)
3503 {
3574 {
3504 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
3575 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
3505 if (baked)
3576 if (baked)
server/src/assets/spriteCatalog.js +35 −2
@@ -237,7 +237,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
237 237 for (const def of Object.values(definitions))
238 238 {
239 239 const folder = join(layerDir, def.key);
240 const { states: fileStates, blooms, equips, equipBlooms } = listVisualStates(folder);
240 const { states: fileStates, blooms: fileBlooms, equips, equipBlooms } = listVisualStates(folder);
241 241 if (fileStates.length === 0)
242 242 { throw new Error(`No PNG states in ${folder}`); }
243 243
@@ -245,6 +245,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
245 245 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
246 246 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
247 247 let states = [...fileStates];
248 let blooms = fileBlooms;
248 249 const imagesForType = [];
249 250
250 251 if (layer === "block" && def.key === "boulder")
@@ -302,6 +303,36 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
302 303 }
303 304 }
304 305
306 if (layer === "block" && def.key === "campfire")
307 {
308 states = [];
309 const nextBlooms = {};
310 for (const material of WOOD_TIER_ORDER)
311 {
312 states.push(material);
313 const tint = materialTintColor(material);
314 imagesForType.push({
315 name: spriteImageName(layer, def.key, material),
316 url: `/assets/${urlFolder}/${def.key}/campfire.png`,
317 subImgTotal: frames,
318 perRow: framesPerRow,
319 loop: animationSpeed > 0,
320 animationSpeed,
321 tint: { r: tint.r, g: tint.g, b: tint.b }
322 });
323 imagesForType.push({
324 name: bloomImageName(layer, def.key, material),
325 url: `/assets/${urlFolder}/${def.key}/campfire-bloom.png`,
326 subImgTotal: frames,
327 perRow: framesPerRow,
328 loop: animationSpeed > 0,
329 animationSpeed
330 });
331 nextBlooms[material] = true;
332 }
333 blooms = nextBlooms;
334 }
335
305 336 if (layer === "block" && def.key === "table")
306 337 {
307 338 // Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.
@@ -332,7 +363,9 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
332 363 states,
333 364 defaultState: def.key === "boulder" && states.includes("boulder")
334 365 ? "boulder"
335 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
366 : def.key === "fishing-spot" && states.includes("fishing-spot")
367 ? "fishing-spot"
368 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
336 369 blooms,
337 370 equips,
338 371 equipBlooms,
@@ -237,7 +237,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
237 for (const def of Object.values(definitions))
237 for (const def of Object.values(definitions))
238 {
238 {
239 const folder = join(layerDir, def.key);
239 const folder = join(layerDir, def.key);
240 const { states: fileStates, blooms, equips, equipBlooms } = listVisualStates(folder);
240 const { states: fileStates, blooms: fileBlooms, equips, equipBlooms } = listVisualStates(folder);
241 if (fileStates.length === 0)
241 if (fileStates.length === 0)
242 { throw new Error(`No PNG states in ${folder}`); }
242 { throw new Error(`No PNG states in ${folder}`); }
243
243
@@ -245,6 +245,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
245 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
245 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
246 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
246 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
247 let states = [...fileStates];
247 let states = [...fileStates];
248 let blooms = fileBlooms;
248 const imagesForType = [];
249 const imagesForType = [];
249
250
250 if (layer === "block" && def.key === "boulder")
251 if (layer === "block" && def.key === "boulder")
@@ -302,6 +303,36 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
302 }
303 }
303 }
304 }
304
305
306 if (layer === "block" && def.key === "campfire")
307 {
308 states = [];
309 const nextBlooms = {};
310 for (const material of WOOD_TIER_ORDER)
311 {
312 states.push(material);
313 const tint = materialTintColor(material);
314 imagesForType.push({
315 name: spriteImageName(layer, def.key, material),
316 url: `/assets/${urlFolder}/${def.key}/campfire.png`,
317 subImgTotal: frames,
318 perRow: framesPerRow,
319 loop: animationSpeed > 0,
320 animationSpeed,
321 tint: { r: tint.r, g: tint.g, b: tint.b }
322 });
323 imagesForType.push({
324 name: bloomImageName(layer, def.key, material),
325 url: `/assets/${urlFolder}/${def.key}/campfire-bloom.png`,
326 subImgTotal: frames,
327 perRow: framesPerRow,
328 loop: animationSpeed > 0,
329 animationSpeed
330 });
331 nextBlooms[material] = true;
332 }
333 blooms = nextBlooms;
334 }
335
305 if (layer === "block" && def.key === "table")
336 if (layer === "block" && def.key === "table")
306 {
337 {
307 // Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.
338 // Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.
@@ -332,7 +363,9 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
332 states,
363 states,
333 defaultState: def.key === "boulder" && states.includes("boulder")
364 defaultState: def.key === "boulder" && states.includes("boulder")
334 ? "boulder"
365 ? "boulder"
335 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
366 : def.key === "fishing-spot" && states.includes("fishing-spot")
367 ? "fishing-spot"
368 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
336 blooms,
369 blooms,
337 equips,
370 equips,
338 equipBlooms,
371 equipBlooms,
server/src/combat/service.js +92 −24
@@ -646,6 +646,42 @@ function clearCombatApproachPath (ecs, handle)
646 646 { path.tiles = []; }
647 647 }
648 648
649 function combatTileKey (tileX, tileY)
650 {
651 return `${tileX},${tileY}`;
652 }
653
654 /** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */
655 function collectCombatAllyReservations (world, entityId, targetEntityId)
656 {
657 const reserved = new Set();
658 if (targetEntityId == null)
659 { return reserved; }
660 for (const entity of world.ecs.query(Component.combat, Component.position))
661 {
662 if (entity.entityId === entityId)
663 { continue; }
664 if (entity.combat.targetEntityId !== targetEntityId)
665 { continue; }
666 reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY));
667 const allyPath = world.ecs.get(entity.handle, Component.path);
668 if (!allyPath?.tiles?.length)
669 { continue; }
670 const next = allyPath.tiles[0];
671 if (next)
672 { reserved.add(combatTileKey(next.x, next.y)); }
673 const dest = allyPath.tiles[allyPath.tiles.length - 1];
674 if (dest)
675 { reserved.add(combatTileKey(dest.x, dest.y)); }
676 }
677 return reserved;
678 }
679
680 function combatGoalPreference (entityId, tileX, tileY)
681 {
682 return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0;
683 }
684
649 685 export function queueMeleeApproach (world, entityId, handle, position, targetPos)
650 686 {
651 687 if (world.frozen?.has?.(entityId))
@@ -662,7 +698,9 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
662 698 return;
663 699 }
664 700
665 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
701 const combat = world.ecs.get(handle, Component.combat);
702 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
703 const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved);
666 704 if (!goal)
667 705 {
668 706 path.tiles = [];
@@ -675,7 +713,7 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
675 713 return;
676 714 }
677 715
678 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))
716 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))
679 717 { return; }
680 718
681 719 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
@@ -711,22 +749,6 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
711 749 { movement.walkCarry = 0; }
712 750 }
713 751
714 function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist)
715 {
716 const dest = path.tiles[path.tiles.length - 1];
717 if (dest.x !== goal.x || dest.y !== goal.y)
718 { return true; }
719 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
720 if (standOff < minStandDist || standOff > maxRange)
721 { return true; }
722 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
723 { return true; }
724 const next = path.tiles[0];
725 if (!next)
726 { return true; }
727 return !world.walkableFor(entityId, next.x, next.y);
728 }
729
730 752 /**
731 753 * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS.
732 754 * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left).
@@ -750,9 +772,11 @@ export function queueStandInRangeApproach (
750 772 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
751 773
752 774 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
775 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
753 776 if (
754 777 distToTarget <= maxRange
755 778 && distToTarget >= minStandDist
779 && aloneHere
756 780 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
757 781 )
758 782 {
@@ -760,6 +784,8 @@ export function queueStandInRangeApproach (
760 784 return;
761 785 }
762 786
787 const combat = world.ecs.get(handle, Component.combat);
788 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
763 789 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
764 790 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
765 791 const isGoal = (x, y) =>
@@ -767,6 +793,11 @@ export function queueStandInRangeApproach (
767 793 const standOff = chebyshev(x, y, targetTileX, targetTileY);
768 794 if (standOff < minStandDist || standOff > maxRange)
769 795 { return false; }
796 if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))
797 { return false; }
798 const key = combatTileKey(x, y);
799 if (reserved.has(key) && !(x === position.tileX && y === position.tileY))
800 { return false; }
770 801 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY);
771 802 };
772 803
@@ -794,7 +825,9 @@ export function queueStandInRangeApproach (
794 825 targetTileX,
795 826 targetTileY,
796 827 maxRange,
797 minStandDist
828 minStandDist,
829 reserved,
830 position
798 831 ))
799 832 { return; }
800 833 path.tiles = tiles;
@@ -899,7 +932,30 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D
899 932 return events.concat(hitEvents);
900 933 }
901 934
902 function meleePathStale (world, entityId, position, targetPos, path, goal)
935 function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position)
936 {
937 const dest = path.tiles[path.tiles.length - 1];
938 if (dest.x !== goal.x || dest.y !== goal.y)
939 { return true; }
940 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
941 if (standOff < minStandDist || standOff > maxRange)
942 { return true; }
943 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
944 { return true; }
945 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
946 { return true; }
947 const destKey = combatTileKey(dest.x, dest.y);
948 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
949 { return true; }
950 const next = path.tiles[0];
951 if (!next)
952 { return true; }
953 if (!world.walkableFor(entityId, next.x, next.y))
954 { return true; }
955 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
956 }
957
958 function meleePathStale (world, entityId, position, targetPos, path, goal, reserved)
903 959 {
904 960 const dest = path.tiles[path.tiles.length - 1];
905 961 if (dest.x !== goal.x || dest.y !== goal.y)
@@ -908,13 +964,18 @@ function meleePathStale (world, entityId, position, targetPos, path, goal)
908 964 { return true; }
909 965 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
910 966 { return true; }
967 const destKey = combatTileKey(dest.x, dest.y);
968 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
969 { return true; }
911 970 const next = path.tiles[0];
912 971 if (!next)
913 972 { return true; }
914 return !world.walkableFor(entityId, next.x, next.y);
973 if (!world.walkableFor(entityId, next.x, next.y))
974 { return true; }
975 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
915 976 }
916 977
917 function bestAdjacentGoal (world, entityId, position, targetPos)
978 function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null)
918 979 {
919 980 const dirs = [
920 981 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
@@ -922,21 +983,28 @@ function bestAdjacentGoal (world, entityId, position, targetPos)
922 983 ];
923 984 let best = null;
924 985 let bestDist = Infinity;
986 let bestPref = Infinity;
925 987 for (const dir of dirs)
926 988 {
927 989 const x = targetPos.tileX + dir.x;
928 990 const y = targetPos.tileY + dir.y;
929 991 const isHere = x === position.tileX && y === position.tileY;
992 const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;
993 const key = combatTileKey(x, y);
994 if (reserved?.has(key) && !(isHere && aloneHere))
995 { continue; }
930 996 const clear = world.isClearStanding?.(entityId, x, y)
931 997 ?? world.walkableFor(entityId, x, y);
932 998 if (!clear && !isHere)
933 999 { continue; }
934 if (isHere && !(world.isClearStanding?.(entityId, x, y) ?? true))
1000 if (isHere && !aloneHere)
935 1001 { continue; }
936 1002 const dist = chebyshev(position.tileX, position.tileY, x, y);
937 if (dist < bestDist)
1003 const pref = combatGoalPreference(entityId, x, y);
1004 if (dist < bestDist || (dist === bestDist && pref < bestPref))
938 1005 {
939 1006 bestDist = dist;
1007 bestPref = pref;
940 1008 best = { x, y };
941 1009 }
942 1010 }
@@ -646,6 +646,42 @@ function clearCombatApproachPath (ecs, handle)
646 { path.tiles = []; }
646 { path.tiles = []; }
647}
647}
648
648
649function combatTileKey (tileX, tileY)
650{
651 return `${tileX},${tileY}`;
652}
653
654/** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */
655function collectCombatAllyReservations (world, entityId, targetEntityId)
656{
657 const reserved = new Set();
658 if (targetEntityId == null)
659 { return reserved; }
660 for (const entity of world.ecs.query(Component.combat, Component.position))
661 {
662 if (entity.entityId === entityId)
663 { continue; }
664 if (entity.combat.targetEntityId !== targetEntityId)
665 { continue; }
666 reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY));
667 const allyPath = world.ecs.get(entity.handle, Component.path);
668 if (!allyPath?.tiles?.length)
669 { continue; }
670 const next = allyPath.tiles[0];
671 if (next)
672 { reserved.add(combatTileKey(next.x, next.y)); }
673 const dest = allyPath.tiles[allyPath.tiles.length - 1];
674 if (dest)
675 { reserved.add(combatTileKey(dest.x, dest.y)); }
676 }
677 return reserved;
678}
679
680function combatGoalPreference (entityId, tileX, tileY)
681{
682 return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0;
683}
684
649export function queueMeleeApproach (world, entityId, handle, position, targetPos)
685export function queueMeleeApproach (world, entityId, handle, position, targetPos)
650{
686{
651 if (world.frozen?.has?.(entityId))
687 if (world.frozen?.has?.(entityId))
@@ -662,7 +698,9 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
662 return;
698 return;
663 }
699 }
664
700
665 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
701 const combat = world.ecs.get(handle, Component.combat);
702 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
703 const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved);
666 if (!goal)
704 if (!goal)
667 {
705 {
668 path.tiles = [];
706 path.tiles = [];
@@ -675,7 +713,7 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
675 return;
713 return;
676 }
714 }
677
715
678 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))
716 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))
679 { return; }
717 { return; }
680
718
681 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
719 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
@@ -711,22 +749,6 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
711 { movement.walkCarry = 0; }
749 { movement.walkCarry = 0; }
712}
750}
713
751
714function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist)
715{
716 const dest = path.tiles[path.tiles.length - 1];
717 if (dest.x !== goal.x || dest.y !== goal.y)
718 { return true; }
719 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
720 if (standOff < minStandDist || standOff > maxRange)
721 { return true; }
722 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
723 { return true; }
724 const next = path.tiles[0];
725 if (!next)
726 { return true; }
727 return !world.walkableFor(entityId, next.x, next.y);
728}
729
730/**
752/**
731 * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS.
753 * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS.
732 * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left).
754 * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left).
@@ -750,9 +772,11 @@ export function queueStandInRangeApproach (
750 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
772 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
751
773
752 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
774 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
775 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
753 if (
776 if (
754 distToTarget <= maxRange
777 distToTarget <= maxRange
755 && distToTarget >= minStandDist
778 && distToTarget >= minStandDist
779 && aloneHere
756 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
780 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
757 )
781 )
758 {
782 {
@@ -760,6 +784,8 @@ export function queueStandInRangeApproach (
760 return;
784 return;
761 }
785 }
762
786
787 const combat = world.ecs.get(handle, Component.combat);
788 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
763 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
789 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
764 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
790 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
765 const isGoal = (x, y) =>
791 const isGoal = (x, y) =>
@@ -767,6 +793,11 @@ export function queueStandInRangeApproach (
767 const standOff = chebyshev(x, y, targetTileX, targetTileY);
793 const standOff = chebyshev(x, y, targetTileX, targetTileY);
768 if (standOff < minStandDist || standOff > maxRange)
794 if (standOff < minStandDist || standOff > maxRange)
769 { return false; }
795 { return false; }
796 if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))
797 { return false; }
798 const key = combatTileKey(x, y);
799 if (reserved.has(key) && !(x === position.tileX && y === position.tileY))
800 { return false; }
770 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY);
801 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY);
771 };
802 };
772
803
@@ -794,7 +825,9 @@ export function queueStandInRangeApproach (
794 targetTileX,
825 targetTileX,
795 targetTileY,
826 targetTileY,
796 maxRange,
827 maxRange,
797 minStandDist
828 minStandDist,
829 reserved,
830 position
798 ))
831 ))
799 { return; }
832 { return; }
800 path.tiles = tiles;
833 path.tiles = tiles;
@@ -899,7 +932,30 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D
899 return events.concat(hitEvents);
932 return events.concat(hitEvents);
900}
933}
901
934
902function meleePathStale (world, entityId, position, targetPos, path, goal)
935function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position)
936{
937 const dest = path.tiles[path.tiles.length - 1];
938 if (dest.x !== goal.x || dest.y !== goal.y)
939 { return true; }
940 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
941 if (standOff < minStandDist || standOff > maxRange)
942 { return true; }
943 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
944 { return true; }
945 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
946 { return true; }
947 const destKey = combatTileKey(dest.x, dest.y);
948 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
949 { return true; }
950 const next = path.tiles[0];
951 if (!next)
952 { return true; }
953 if (!world.walkableFor(entityId, next.x, next.y))
954 { return true; }
955 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
956}
957
958function meleePathStale (world, entityId, position, targetPos, path, goal, reserved)
903{
959{
904 const dest = path.tiles[path.tiles.length - 1];
960 const dest = path.tiles[path.tiles.length - 1];
905 if (dest.x !== goal.x || dest.y !== goal.y)
961 if (dest.x !== goal.x || dest.y !== goal.y)
@@ -908,13 +964,18 @@ function meleePathStale (world, entityId, position, targetPos, path, goal)
908 { return true; }
964 { return true; }
909 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
965 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
910 { return true; }
966 { return true; }
967 const destKey = combatTileKey(dest.x, dest.y);
968 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
969 { return true; }
911 const next = path.tiles[0];
970 const next = path.tiles[0];
912 if (!next)
971 if (!next)
913 { return true; }
972 { return true; }
914 return !world.walkableFor(entityId, next.x, next.y);
973 if (!world.walkableFor(entityId, next.x, next.y))
974 { return true; }
975 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
915}
976}
916
977
917function bestAdjacentGoal (world, entityId, position, targetPos)
978function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null)
918{
979{
919 const dirs = [
980 const dirs = [
920 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
981 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
@@ -922,21 +983,28 @@ function bestAdjacentGoal (world, entityId, position, targetPos)
922 ];
983 ];
923 let best = null;
984 let best = null;
924 let bestDist = Infinity;
985 let bestDist = Infinity;
986 let bestPref = Infinity;
925 for (const dir of dirs)
987 for (const dir of dirs)
926 {
988 {
927 const x = targetPos.tileX + dir.x;
989 const x = targetPos.tileX + dir.x;
928 const y = targetPos.tileY + dir.y;
990 const y = targetPos.tileY + dir.y;
929 const isHere = x === position.tileX && y === position.tileY;
991 const isHere = x === position.tileX && y === position.tileY;
992 const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;
993 const key = combatTileKey(x, y);
994 if (reserved?.has(key) && !(isHere && aloneHere))
995 { continue; }
930 const clear = world.isClearStanding?.(entityId, x, y)
996 const clear = world.isClearStanding?.(entityId, x, y)
931 ?? world.walkableFor(entityId, x, y);
997 ?? world.walkableFor(entityId, x, y);
932 if (!clear && !isHere)
998 if (!clear && !isHere)
933 { continue; }
999 { continue; }
934 if (isHere && !(world.isClearStanding?.(entityId, x, y) ?? true))
1000 if (isHere && !aloneHere)
935 { continue; }
1001 { continue; }
936 const dist = chebyshev(position.tileX, position.tileY, x, y);
1002 const dist = chebyshev(position.tileX, position.tileY, x, y);
937 if (dist < bestDist)
1003 const pref = combatGoalPreference(entityId, x, y);
1004 if (dist < bestDist || (dist === bestDist && pref < bestPref))
938 {
1005 {
939 bestDist = dist;
1006 bestDist = dist;
1007 bestPref = pref;
940 best = { x, y };
1008 best = { x, y };
941 }
1009 }
942 }
1010 }
server/src/crafting/service.js +36 −8
@@ -1,6 +1,6 @@
1 1 import { Component } from "../ecs/components.js";
2 2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
3 import { CraftingStationId, CRAFT_DURATION_MS, COOK_BURN_CHANCE_OVEN, COOK_BURN_CHANCE_CAMPFIRE } from "../../../shared/definitions/craftingStations.js";
4 4 import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5 5 import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6 6 import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
@@ -78,9 +78,22 @@ function stationBlockType (stationId)
78 78 { return BlockType.tailorBench; }
79 79 if (stationId === CraftingStationId.leatherworkingStation)
80 80 { return BlockType.leatherworkingTable; }
81 if (stationId === CraftingStationId.oven)
82 { return BlockType.oven; }
83 if (stationId === CraftingStationId.fireplace)
84 { return BlockType.campfire; }
81 85 return null;
82 86 }
83 87
88 function cookBurnChance (stationId)
89 {
90 if (stationId === CraftingStationId.fireplace)
91 { return COOK_BURN_CHANCE_CAMPFIRE; }
92 if (stationId === CraftingStationId.oven)
93 { return COOK_BURN_CHANCE_OVEN; }
94 return 0;
95 }
96
84 97 function takeInputs (slots, inputs)
85 98 {
86 99 let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
@@ -371,17 +384,23 @@ export function stepCrafting (world, now)
371 384 }
372 385 slotsAfter = dyeTaken.slots;
373 386 }
374 const outDef = itemDefinition(recipe.output.itemId);
375 const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
387
388 const burnChance = cookBurnChance(session.stationId);
389 const burned = burnChance > 0
390 && recipe.burntOutput?.itemId
391 && ((world.rng?.() ?? Math.random()) < burnChance);
392 const outSpec = burned ? recipe.burntOutput : recipe.output;
393 const outDef = itemDefinition(outSpec.itemId);
394 const outQty = Math.max(1, outSpec.quantity | 0 || 1);
376 395 const origin = craftOrigin(
377 396 craftOriginVerbForStation(session.stationId),
378 397 characterDisplayName(world, handle)
379 398 );
380 399 const outStack = {
381 itemId: recipe.output.itemId,
400 itemId: outSpec.itemId,
382 401 quantity: outQty,
383 402 origins: [{ origin, quantity: outQty }],
384 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
403 ...(recipe.dyeColor && !burned ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
385 404 };
386 405 const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
387 406 if (!added.ok || added.remainder > 0)
@@ -399,7 +418,7 @@ export function stepCrafting (world, now)
399 418
400 419 let skillsChanged = false;
401 420 const levelUps = [];
402 if (skills?.xp && stationDef?.skillId)
421 if (!burned && skills?.xp && stationDef?.skillId)
403 422 {
404 423 const result = applySkillXp(
405 424 skills,
@@ -425,6 +444,15 @@ export function stepCrafting (world, now)
425 444 });
426 445 }
427 446
447 if (burned)
448 {
449 events.push({
450 type: "command-error",
451 sessionId: session.sessionId,
452 message: "You burn the food."
453 });
454 }
455
428 456 let continuing = false;
429 457 const batchRemaining = session.batchRemaining ?? 1;
430 458 const nextRemaining = batchRemaining === Infinity
@@ -449,8 +477,8 @@ export function stepCrafting (world, now)
449 477 events.push({
450 478 type: "item-bubble",
451 479 entityId,
452 itemId: recipe.output.itemId,
453 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
480 itemId: outSpec.itemId,
481 quantity: outQty
454 482 });
455 483 }
456 484 events.push({
@@ -1,6 +1,6 @@
1import { Component } from "../ecs/components.js";
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
3import { CraftingStationId, CRAFT_DURATION_MS, COOK_BURN_CHANCE_OVEN, COOK_BURN_CHANCE_CAMPFIRE } from "../../../shared/definitions/craftingStations.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
6import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
@@ -78,9 +78,22 @@ function stationBlockType (stationId)
78 { return BlockType.tailorBench; }
78 { return BlockType.tailorBench; }
79 if (stationId === CraftingStationId.leatherworkingStation)
79 if (stationId === CraftingStationId.leatherworkingStation)
80 { return BlockType.leatherworkingTable; }
80 { return BlockType.leatherworkingTable; }
81 if (stationId === CraftingStationId.oven)
82 { return BlockType.oven; }
83 if (stationId === CraftingStationId.fireplace)
84 { return BlockType.campfire; }
81 return null;
85 return null;
82}
86}
83
87
88function cookBurnChance (stationId)
89{
90 if (stationId === CraftingStationId.fireplace)
91 { return COOK_BURN_CHANCE_CAMPFIRE; }
92 if (stationId === CraftingStationId.oven)
93 { return COOK_BURN_CHANCE_OVEN; }
94 return 0;
95}
96
84function takeInputs (slots, inputs)
97function takeInputs (slots, inputs)
85{
98{
86 let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
99 let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
@@ -371,17 +384,23 @@ export function stepCrafting (world, now)
371 }
384 }
372 slotsAfter = dyeTaken.slots;
385 slotsAfter = dyeTaken.slots;
373 }
386 }
374 const outDef = itemDefinition(recipe.output.itemId);
387
375 const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
388 const burnChance = cookBurnChance(session.stationId);
389 const burned = burnChance > 0
390 && recipe.burntOutput?.itemId
391 && ((world.rng?.() ?? Math.random()) < burnChance);
392 const outSpec = burned ? recipe.burntOutput : recipe.output;
393 const outDef = itemDefinition(outSpec.itemId);
394 const outQty = Math.max(1, outSpec.quantity | 0 || 1);
376 const origin = craftOrigin(
395 const origin = craftOrigin(
377 craftOriginVerbForStation(session.stationId),
396 craftOriginVerbForStation(session.stationId),
378 characterDisplayName(world, handle)
397 characterDisplayName(world, handle)
379 );
398 );
380 const outStack = {
399 const outStack = {
381 itemId: recipe.output.itemId,
400 itemId: outSpec.itemId,
382 quantity: outQty,
401 quantity: outQty,
383 origins: [{ origin, quantity: outQty }],
402 origins: [{ origin, quantity: outQty }],
384 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
403 ...(recipe.dyeColor && !burned ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
385 };
404 };
386 const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
405 const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
387 if (!added.ok || added.remainder > 0)
406 if (!added.ok || added.remainder > 0)
@@ -399,7 +418,7 @@ export function stepCrafting (world, now)
399
418
400 let skillsChanged = false;
419 let skillsChanged = false;
401 const levelUps = [];
420 const levelUps = [];
402 if (skills?.xp && stationDef?.skillId)
421 if (!burned && skills?.xp && stationDef?.skillId)
403 {
422 {
404 const result = applySkillXp(
423 const result = applySkillXp(
405 skills,
424 skills,
@@ -425,6 +444,15 @@ export function stepCrafting (world, now)
425 });
444 });
426 }
445 }
427
446
447 if (burned)
448 {
449 events.push({
450 type: "command-error",
451 sessionId: session.sessionId,
452 message: "You burn the food."
453 });
454 }
455
428 let continuing = false;
456 let continuing = false;
429 const batchRemaining = session.batchRemaining ?? 1;
457 const batchRemaining = session.batchRemaining ?? 1;
430 const nextRemaining = batchRemaining === Infinity
458 const nextRemaining = batchRemaining === Infinity
@@ -449,8 +477,8 @@ export function stepCrafting (world, now)
449 events.push({
477 events.push({
450 type: "item-bubble",
478 type: "item-bubble",
451 entityId,
479 entityId,
452 itemId: recipe.output.itemId,
480 itemId: outSpec.itemId,
453 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
481 quantity: outQty
454 });
482 });
455 }
483 }
456 events.push({
484 events.push({
server/src/firestarting/service.js added +481 −0
@@ -0,0 +1,481 @@
1 import { Component } from "../ecs/components.js";
2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "../../../shared/definitions/craftingItems.js";
4 import {
5 ashItemIdForWood,
6 logItemIdForWood
7 } from "../../../shared/definitions/woodItems.js";
8 import {
9 campfireDurationMs,
10 firestartingDifficulty,
11 woodTierRank
12 } from "../../../shared/definitions/craftingStations.js";
13 import { MATERIAL_DISPLAY_NAME, WOOD_TIER_ORDER } from "../../../shared/definitions/materialTiers.js";
14 import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js";
15 import { itemDefinition } from "../../../shared/definitions/items.js";
16 import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
17 import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
18 import { rollSkill } from "../../../shared/combat/rolls.js";
19 import { stackQuantity } from "../../../shared/items/inventory.js";
20 import { attachOrigins } from "../../../shared/items/origin.js";
21 import { addGroundItem, publicGroundItem, removeGroundItem, bagView } from "../items/bags.js";
22 import { chebyshev } from "../combat/service.js";
23 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
24 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25
26 const FIRE_ATTEMPT_MS = 1100;
27 const MAX_LIGHT_ATTEMPTS = 3;
28
29 function userError (message)
30 {
31 const error = new Error(message);
32 error.userFacing = true;
33 return error;
34 }
35
36 function tileKey (tileX, tileY)
37 {
38 return `${tileX},${tileY}`;
39 }
40
41 function ensureCampfires (world)
42 {
43 if (!world.campfireExpires)
44 { world.campfireExpires = new Map(); }
45 return world.campfireExpires;
46 }
47
48 function ensureFireSessions (world)
49 {
50 if (!world.fireSessions)
51 { world.fireSessions = new Map(); }
52 return world.fireSessions;
53 }
54
55 function clearFireSession (world, characterId)
56 {
57 ensureFireSessions(world).delete(characterId);
58 }
59
60 function woodTierFromLogItemId (itemId)
61 {
62 const def = itemDefinition(itemId);
63 if (!def || def.familyId !== ItemFamilyId.log)
64 { return null; }
65 return def.tier ?? null;
66 }
67
68 function findTinderboxSlot (slots)
69 {
70 for (let i = 0; i < (slots?.length ?? 0); i++)
71 {
72 const slot = slots[i];
73 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
74 { continue; }
75 const charges = slot.instance?.kind === "tinderbox"
76 ? (slot.instance.charges | 0)
77 : TINDERBOX_MAX_CHARGES;
78 if (charges > 0)
79 { return i; }
80 }
81 return -1;
82 }
83
84 /** Consume one tinderbox charge in place; remove item at 0. */
85 function consumeTinderboxCharge (slots, slotIndex)
86 {
87 const next = slots.map((s) => (s ? structuredClone(s) : null));
88 const slot = next[slotIndex];
89 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
90 { return { ok: false, slots }; }
91 const charges = slot.instance?.kind === "tinderbox"
92 ? (slot.instance.charges | 0)
93 : TINDERBOX_MAX_CHARGES;
94 if (charges <= 0)
95 { return { ok: false, slots }; }
96 if (charges <= 1)
97 {
98 next[slotIndex] = null;
99 return { ok: true, slots: next, exhausted: true };
100 }
101 next[slotIndex].instance = {
102 kind: "tinderbox",
103 charges: charges - 1
104 };
105 return { ok: true, slots: next, exhausted: false };
106 }
107
108 function placeBlock (world, tileX, tileY, typeId, state, config = null)
109 {
110 const chunkX = tileToChunk(tileX);
111 const chunkY = tileToChunk(tileY);
112 const localX = tileToLocal(tileX);
113 const localY = tileToLocal(tileY);
114 const data = world.chunkData(chunkX, chunkY);
115 const index = localY * CHUNK_SIZE + localX;
116 const block = { typeId, state, config };
117 data.blocks[index] = block;
118 return {
119 type: "chunk-delta",
120 chunkX,
121 chunkY,
122 tileX,
123 tileY,
124 localX,
125 localY,
126 block
127 };
128 }
129
130 function clearBlockAt (world, tileX, tileY)
131 {
132 const chunkX = tileToChunk(tileX);
133 const chunkY = tileToChunk(tileY);
134 const localX = tileToLocal(tileX);
135 const localY = tileToLocal(tileY);
136 const data = world.chunkData(chunkX, chunkY);
137 const index = localY * CHUNK_SIZE + localX;
138 if (!data.blocks[index])
139 { return null; }
140 data.blocks[index] = null;
141 return {
142 type: "chunk-delta",
143 chunkX,
144 chunkY,
145 tileX,
146 tileY,
147 localX,
148 localY,
149 block: null
150 };
151 }
152
153 function blockAt (world, tileX, tileY)
154 {
155 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
156 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
157 return data.blocks[index] ?? null;
158 }
159
160 function consumeOneGroundLog (world, item, events)
161 {
162 const qty = stackQuantity(item.stack?.quantity);
163 if (qty <= 1)
164 {
165 removeGroundItem(world, item.groundItemId);
166 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
167 return;
168 }
169 item.stack.quantity = qty - 1;
170 events.push({
171 type: "ground-item-appear",
172 ...publicGroundItem(item),
173 stack: item.stack,
174 droppedAt: item.droppedAt,
175 source: item.source,
176 expiresAt: item.expiresAt
177 });
178 }
179
180 function spawnAsh (world, tileX, tileY, woodTier, now, events)
181 {
182 const ashItemId = ashItemIdForWood(woodTier);
183 if (!ashItemId)
184 { return; }
185 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
186 const stack = attachOrigins({
187 itemId: ashItemId,
188 quantity: 1,
189 origins: []
190 });
191 const item = {
192 groundItemId,
193 tileX,
194 tileY,
195 stack,
196 droppedAt: now,
197 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
198 source: "campfire-ash"
199 };
200 addGroundItem(world, item);
201 events.push({
202 type: "ground-item-appear",
203 ...publicGroundItem(item),
204 stack: item.stack,
205 droppedAt: item.droppedAt,
206 source: item.source,
207 expiresAt: item.expiresAt
208 });
209 }
210
211 /**
212 * Start lighting a ground log with a tinderbox (up to 3 skill rolls).
213 */
214 export function startFire (world, sessionId, characterId, groundItemId, now)
215 {
216 const entityId = world.characterEntities.get(characterId);
217 if (entityId == null)
218 { throw userError("Character is not in the world."); }
219 const handle = world.ecs.handleOf(entityId);
220 const identity = world.ecs.get(handle, Component.networkIdentity);
221 if (!identity || identity.sessionId !== sessionId)
222 { throw userError("Character is not in the world."); }
223 if (world.ecs.has(handle, Component.dead))
224 { throw userError("You are dead."); }
225
226 const item = world.groundItems.get(groundItemId | 0);
227 if (!item)
228 { throw userError("That item is no longer on the ground."); }
229 const woodTier = woodTierFromLogItemId(item.stack?.itemId);
230 if (!woodTier)
231 { throw userError("You can only light wood logs."); }
232
233 const position = world.ecs.get(handle, Component.position);
234 if (chebyshev(position.tileX, position.tileY, item.tileX, item.tileY) > 1)
235 { throw userError("You need to stand next to the logs."); }
236
237 if (blockAt(world, item.tileX, item.tileY))
238 { throw userError("There is no room for a fire there."); }
239
240 const difficulty = firestartingDifficulty(woodTier);
241 const skills = world.ecs.get(handle, Component.skills);
242 const level = skillLevel(skills, SkillId.firestarting);
243 if (level < difficulty)
244 {
245 const label = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
246 throw userError(`Your Firestarting skill is too low to light ${label} logs.`);
247 }
248
249 const inventory = world.ecs.get(handle, Component.inventory);
250 const tinderSlot = findTinderboxSlot(inventory?.slots);
251 if (tinderSlot < 0)
252 { throw userError("You need a tinderbox with charges remaining."); }
253
254 const consumed = consumeTinderboxCharge(inventory.slots, tinderSlot);
255 if (!consumed.ok)
256 { throw userError("You need a tinderbox with charges remaining."); }
257 inventory.slots = consumed.slots;
258
259 clearFireSession(world, characterId);
260 if (world.ecs.has(handle, Component.gather))
261 { world.ecs.remove(handle, Component.gather); }
262 const path = world.ecs.get(handle, Component.path);
263 if (path)
264 { path.tiles = []; }
265
266 ensureFireSessions(world).set(characterId, {
267 sessionId,
268 groundItemId: item.groundItemId,
269 tileX: item.tileX,
270 tileY: item.tileY,
271 woodTier,
272 difficulty,
273 attemptsLeft: MAX_LIGHT_ATTEMPTS,
274 nextAttemptAt: now,
275 toolItemId: CraftingItemId.tinderbox
276 });
277
278 return {
279 events: [],
280 private: bagView(world.ecs, handle)
281 };
282 }
283
284 export function cancelFirestarting (world, characterId)
285 {
286 clearFireSession(world, characterId);
287 }
288
289 export function handleFirestartingCommand (world, sessionId, command, now = Date.now())
290 {
291 if (command.type === "start-fire")
292 {
293 return startFire(world, sessionId, command.characterId, command.groundItemId, now);
294 }
295 if (command.type === "cancel-fire")
296 {
297 cancelFirestarting(world, command.characterId);
298 return { events: [] };
299 }
300 return null;
301 }
302
303 function succeedLight (world, handle, entityId, characterId, session, events, privates, now)
304 {
305 const item = world.groundItems.get(session.groundItemId);
306 if (!item || woodTierFromLogItemId(item.stack?.itemId) !== session.woodTier)
307 {
308 events.push({
309 type: "command-error",
310 sessionId: session.sessionId,
311 message: "Those logs are gone."
312 });
313 clearFireSession(world, characterId);
314 return;
315 }
316 if (blockAt(world, session.tileX, session.tileY))
317 {
318 events.push({
319 type: "command-error",
320 sessionId: session.sessionId,
321 message: "There is no room for a fire there."
322 });
323 clearFireSession(world, characterId);
324 return;
325 }
326
327 consumeOneGroundLog(world, item, events);
328 const expiresAt = now + campfireDurationMs(session.woodTier);
329 const delta = placeBlock(
330 world,
331 session.tileX,
332 session.tileY,
333 BlockType.campfire,
334 session.woodTier,
335 { woodTier: session.woodTier, litAt: now, expiresAt }
336 );
337 events.push(delta);
338 ensureCampfires(world).set(tileKey(session.tileX, session.tileY), {
339 tileX: session.tileX,
340 tileY: session.tileY,
341 woodTier: session.woodTier,
342 expiresAt
343 });
344
345 const skills = world.ecs.get(handle, Component.skills);
346 let skillsChanged = false;
347 const levelUps = [];
348 if (skills?.xp)
349 {
350 const result = applySkillXp(skills, SkillId.firestarting, session.difficulty);
351 if (result.changed)
352 { skillsChanged = true; }
353 if (result.levelUp)
354 { levelUps.push(result.levelUp); }
355 }
356 if (skillsChanged)
357 {
358 events.push({
359 type: "skills-updated",
360 entityId,
361 characterId,
362 skills: publicSkillsView(skills),
363 stored: storedSkillXp(skills),
364 levelUps
365 });
366 }
367 privates.push({ characterId, bag: bagView(world.ecs, handle) });
368 clearFireSession(world, characterId);
369 }
370
371 /**
372 * Advance lighting attempts and expire campfires.
373 */
374 export function stepFirestarting (world, now)
375 {
376 const events = [];
377 const privates = [];
378 events.push(...stepCampfireExpires(world, now).events);
379
380 const sessions = ensureFireSessions(world);
381 for (const [characterId, session] of [...sessions.entries()])
382 {
383 if (now < session.nextAttemptAt)
384 { continue; }
385 const entityId = world.characterEntities.get(characterId);
386 if (entityId == null)
387 {
388 clearFireSession(world, characterId);
389 continue;
390 }
391 const handle = world.ecs.handleOf(entityId);
392 if (world.ecs.has(handle, Component.dead))
393 {
394 clearFireSession(world, characterId);
395 continue;
396 }
397 const position = world.ecs.get(handle, Component.position);
398 if (chebyshev(position.tileX, position.tileY, session.tileX, session.tileY) > 1)
399 {
400 clearFireSession(world, characterId);
401 continue;
402 }
403
404 const item = world.groundItems.get(session.groundItemId);
405 if (!item)
406 {
407 events.push({
408 type: "command-error",
409 sessionId: session.sessionId,
410 message: "Those logs are gone."
411 });
412 clearFireSession(world, characterId);
413 continue;
414 }
415
416 events.push({
417 type: "gather-swing",
418 attackerId: entityId,
419 tileX: session.tileX,
420 tileY: session.tileY,
421 fromTileX: position.tileX,
422 fromTileY: position.tileY,
423 toolItemId: session.toolItemId,
424 swipe: false
425 });
426
427 const skills = world.ecs.get(handle, Component.skills);
428 const level = skillLevel(skills, SkillId.firestarting);
429 const roll = rollSkill(level, world.rng ?? Math.random);
430 session.attemptsLeft -= 1;
431 if (roll >= session.difficulty)
432 {
433 succeedLight(world, handle, entityId, characterId, session, events, privates, now);
434 continue;
435 }
436 if (session.attemptsLeft <= 0)
437 {
438 events.push({
439 type: "command-error",
440 sessionId: session.sessionId,
441 message: "The sparks fail to catch."
442 });
443 clearFireSession(world, characterId);
444 continue;
445 }
446 session.nextAttemptAt = now + FIRE_ATTEMPT_MS;
447 }
448
449 return { events, privates };
450 }
451
452 export function stepCampfireExpires (world, now)
453 {
454 const expires = world.campfireExpires;
455 if (!expires?.size)
456 { return { events: [] }; }
457 const events = [];
458 for (const [key, entry] of [...expires.entries()])
459 {
460 if (now < entry.expiresAt)
461 { continue; }
462 expires.delete(key);
463 const block = blockAt(world, entry.tileX, entry.tileY);
464 if (!block || block.typeId !== BlockType.campfire)
465 { continue; }
466 const delta = clearBlockAt(world, entry.tileX, entry.tileY);
467 if (delta)
468 { events.push(delta); }
469 spawnAsh(world, entry.tileX, entry.tileY, entry.woodTier, now, events);
470 }
471 return { events };
472 }
473
474 /** True if itemId is any wood log. */
475 export function isWoodLogItemId (itemId)
476 {
477 return woodTierFromLogItemId(itemId) != null
478 || WOOD_TIER_ORDER.some((tier) => logItemIdForWood(tier) === itemId);
479 }
480
481 export { woodTierFromLogItemId, woodTierRank, findTinderboxSlot };
@@ -0,0 +1,481 @@
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "../../../shared/definitions/craftingItems.js";
4import {
5 ashItemIdForWood,
6 logItemIdForWood
7} from "../../../shared/definitions/woodItems.js";
8import {
9 campfireDurationMs,
10 firestartingDifficulty,
11 woodTierRank
12} from "../../../shared/definitions/craftingStations.js";
13import { MATERIAL_DISPLAY_NAME, WOOD_TIER_ORDER } from "../../../shared/definitions/materialTiers.js";
14import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js";
15import { itemDefinition } from "../../../shared/definitions/items.js";
16import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
17import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
18import { rollSkill } from "../../../shared/combat/rolls.js";
19import { stackQuantity } from "../../../shared/items/inventory.js";
20import { attachOrigins } from "../../../shared/items/origin.js";
21import { addGroundItem, publicGroundItem, removeGroundItem, bagView } from "../items/bags.js";
22import { chebyshev } from "../combat/service.js";
23import { tileToChunk, tileToLocal } from "../world/coordinates.js";
24import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25
26const FIRE_ATTEMPT_MS = 1100;
27const MAX_LIGHT_ATTEMPTS = 3;
28
29function userError (message)
30{
31 const error = new Error(message);
32 error.userFacing = true;
33 return error;
34}
35
36function tileKey (tileX, tileY)
37{
38 return `${tileX},${tileY}`;
39}
40
41function ensureCampfires (world)
42{
43 if (!world.campfireExpires)
44 { world.campfireExpires = new Map(); }
45 return world.campfireExpires;
46}
47
48function ensureFireSessions (world)
49{
50 if (!world.fireSessions)
51 { world.fireSessions = new Map(); }
52 return world.fireSessions;
53}
54
55function clearFireSession (world, characterId)
56{
57 ensureFireSessions(world).delete(characterId);
58}
59
60function woodTierFromLogItemId (itemId)
61{
62 const def = itemDefinition(itemId);
63 if (!def || def.familyId !== ItemFamilyId.log)
64 { return null; }
65 return def.tier ?? null;
66}
67
68function findTinderboxSlot (slots)
69{
70 for (let i = 0; i < (slots?.length ?? 0); i++)
71 {
72 const slot = slots[i];
73 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
74 { continue; }
75 const charges = slot.instance?.kind === "tinderbox"
76 ? (slot.instance.charges | 0)
77 : TINDERBOX_MAX_CHARGES;
78 if (charges > 0)
79 { return i; }
80 }
81 return -1;
82}
83
84/** Consume one tinderbox charge in place; remove item at 0. */
85function consumeTinderboxCharge (slots, slotIndex)
86{
87 const next = slots.map((s) => (s ? structuredClone(s) : null));
88 const slot = next[slotIndex];
89 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
90 { return { ok: false, slots }; }
91 const charges = slot.instance?.kind === "tinderbox"
92 ? (slot.instance.charges | 0)
93 : TINDERBOX_MAX_CHARGES;
94 if (charges <= 0)
95 { return { ok: false, slots }; }
96 if (charges <= 1)
97 {
98 next[slotIndex] = null;
99 return { ok: true, slots: next, exhausted: true };
100 }
101 next[slotIndex].instance = {
102 kind: "tinderbox",
103 charges: charges - 1
104 };
105 return { ok: true, slots: next, exhausted: false };
106}
107
108function placeBlock (world, tileX, tileY, typeId, state, config = null)
109{
110 const chunkX = tileToChunk(tileX);
111 const chunkY = tileToChunk(tileY);
112 const localX = tileToLocal(tileX);
113 const localY = tileToLocal(tileY);
114 const data = world.chunkData(chunkX, chunkY);
115 const index = localY * CHUNK_SIZE + localX;
116 const block = { typeId, state, config };
117 data.blocks[index] = block;
118 return {
119 type: "chunk-delta",
120 chunkX,
121 chunkY,
122 tileX,
123 tileY,
124 localX,
125 localY,
126 block
127 };
128}
129
130function clearBlockAt (world, tileX, tileY)
131{
132 const chunkX = tileToChunk(tileX);
133 const chunkY = tileToChunk(tileY);
134 const localX = tileToLocal(tileX);
135 const localY = tileToLocal(tileY);
136 const data = world.chunkData(chunkX, chunkY);
137 const index = localY * CHUNK_SIZE + localX;
138 if (!data.blocks[index])
139 { return null; }
140 data.blocks[index] = null;
141 return {
142 type: "chunk-delta",
143 chunkX,
144 chunkY,
145 tileX,
146 tileY,
147 localX,
148 localY,
149 block: null
150 };
151}
152
153function blockAt (world, tileX, tileY)
154{
155 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
156 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
157 return data.blocks[index] ?? null;
158}
159
160function consumeOneGroundLog (world, item, events)
161{
162 const qty = stackQuantity(item.stack?.quantity);
163 if (qty <= 1)
164 {
165 removeGroundItem(world, item.groundItemId);
166 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
167 return;
168 }
169 item.stack.quantity = qty - 1;
170 events.push({
171 type: "ground-item-appear",
172 ...publicGroundItem(item),
173 stack: item.stack,
174 droppedAt: item.droppedAt,
175 source: item.source,
176 expiresAt: item.expiresAt
177 });
178}
179
180function spawnAsh (world, tileX, tileY, woodTier, now, events)
181{
182 const ashItemId = ashItemIdForWood(woodTier);
183 if (!ashItemId)
184 { return; }
185 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
186 const stack = attachOrigins({
187 itemId: ashItemId,
188 quantity: 1,
189 origins: []
190 });
191 const item = {
192 groundItemId,
193 tileX,
194 tileY,
195 stack,
196 droppedAt: now,
197 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
198 source: "campfire-ash"
199 };
200 addGroundItem(world, item);
201 events.push({
202 type: "ground-item-appear",
203 ...publicGroundItem(item),
204 stack: item.stack,
205 droppedAt: item.droppedAt,
206 source: item.source,
207 expiresAt: item.expiresAt
208 });
209}
210
211/**
212 * Start lighting a ground log with a tinderbox (up to 3 skill rolls).
213 */
214export function startFire (world, sessionId, characterId, groundItemId, now)
215{
216 const entityId = world.characterEntities.get(characterId);
217 if (entityId == null)
218 { throw userError("Character is not in the world."); }
219 const handle = world.ecs.handleOf(entityId);
220 const identity = world.ecs.get(handle, Component.networkIdentity);
221 if (!identity || identity.sessionId !== sessionId)
222 { throw userError("Character is not in the world."); }
223 if (world.ecs.has(handle, Component.dead))
224 { throw userError("You are dead."); }
225
226 const item = world.groundItems.get(groundItemId | 0);
227 if (!item)
228 { throw userError("That item is no longer on the ground."); }
229 const woodTier = woodTierFromLogItemId(item.stack?.itemId);
230 if (!woodTier)
231 { throw userError("You can only light wood logs."); }
232
233 const position = world.ecs.get(handle, Component.position);
234 if (chebyshev(position.tileX, position.tileY, item.tileX, item.tileY) > 1)
235 { throw userError("You need to stand next to the logs."); }
236
237 if (blockAt(world, item.tileX, item.tileY))
238 { throw userError("There is no room for a fire there."); }
239
240 const difficulty = firestartingDifficulty(woodTier);
241 const skills = world.ecs.get(handle, Component.skills);
242 const level = skillLevel(skills, SkillId.firestarting);
243 if (level < difficulty)
244 {
245 const label = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
246 throw userError(`Your Firestarting skill is too low to light ${label} logs.`);
247 }
248
249 const inventory = world.ecs.get(handle, Component.inventory);
250 const tinderSlot = findTinderboxSlot(inventory?.slots);
251 if (tinderSlot < 0)
252 { throw userError("You need a tinderbox with charges remaining."); }
253
254 const consumed = consumeTinderboxCharge(inventory.slots, tinderSlot);
255 if (!consumed.ok)
256 { throw userError("You need a tinderbox with charges remaining."); }
257 inventory.slots = consumed.slots;
258
259 clearFireSession(world, characterId);
260 if (world.ecs.has(handle, Component.gather))
261 { world.ecs.remove(handle, Component.gather); }
262 const path = world.ecs.get(handle, Component.path);
263 if (path)
264 { path.tiles = []; }
265
266 ensureFireSessions(world).set(characterId, {
267 sessionId,
268 groundItemId: item.groundItemId,
269 tileX: item.tileX,
270 tileY: item.tileY,
271 woodTier,
272 difficulty,
273 attemptsLeft: MAX_LIGHT_ATTEMPTS,
274 nextAttemptAt: now,
275 toolItemId: CraftingItemId.tinderbox
276 });
277
278 return {
279 events: [],
280 private: bagView(world.ecs, handle)
281 };
282}
283
284export function cancelFirestarting (world, characterId)
285{
286 clearFireSession(world, characterId);
287}
288
289export function handleFirestartingCommand (world, sessionId, command, now = Date.now())
290{
291 if (command.type === "start-fire")
292 {
293 return startFire(world, sessionId, command.characterId, command.groundItemId, now);
294 }
295 if (command.type === "cancel-fire")
296 {
297 cancelFirestarting(world, command.characterId);
298 return { events: [] };
299 }
300 return null;
301}
302
303function succeedLight (world, handle, entityId, characterId, session, events, privates, now)
304{
305 const item = world.groundItems.get(session.groundItemId);
306 if (!item || woodTierFromLogItemId(item.stack?.itemId) !== session.woodTier)
307 {
308 events.push({
309 type: "command-error",
310 sessionId: session.sessionId,
311 message: "Those logs are gone."
312 });
313 clearFireSession(world, characterId);
314 return;
315 }
316 if (blockAt(world, session.tileX, session.tileY))
317 {
318 events.push({
319 type: "command-error",
320 sessionId: session.sessionId,
321 message: "There is no room for a fire there."
322 });
323 clearFireSession(world, characterId);
324 return;
325 }
326
327 consumeOneGroundLog(world, item, events);
328 const expiresAt = now + campfireDurationMs(session.woodTier);
329 const delta = placeBlock(
330 world,
331 session.tileX,
332 session.tileY,
333 BlockType.campfire,
334 session.woodTier,
335 { woodTier: session.woodTier, litAt: now, expiresAt }
336 );
337 events.push(delta);
338 ensureCampfires(world).set(tileKey(session.tileX, session.tileY), {
339 tileX: session.tileX,
340 tileY: session.tileY,
341 woodTier: session.woodTier,
342 expiresAt
343 });
344
345 const skills = world.ecs.get(handle, Component.skills);
346 let skillsChanged = false;
347 const levelUps = [];
348 if (skills?.xp)
349 {
350 const result = applySkillXp(skills, SkillId.firestarting, session.difficulty);
351 if (result.changed)
352 { skillsChanged = true; }
353 if (result.levelUp)
354 { levelUps.push(result.levelUp); }
355 }
356 if (skillsChanged)
357 {
358 events.push({
359 type: "skills-updated",
360 entityId,
361 characterId,
362 skills: publicSkillsView(skills),
363 stored: storedSkillXp(skills),
364 levelUps
365 });
366 }
367 privates.push({ characterId, bag: bagView(world.ecs, handle) });
368 clearFireSession(world, characterId);
369}
370
371/**
372 * Advance lighting attempts and expire campfires.
373 */
374export function stepFirestarting (world, now)
375{
376 const events = [];
377 const privates = [];
378 events.push(...stepCampfireExpires(world, now).events);
379
380 const sessions = ensureFireSessions(world);
381 for (const [characterId, session] of [...sessions.entries()])
382 {
383 if (now < session.nextAttemptAt)
384 { continue; }
385 const entityId = world.characterEntities.get(characterId);
386 if (entityId == null)
387 {
388 clearFireSession(world, characterId);
389 continue;
390 }
391 const handle = world.ecs.handleOf(entityId);
392 if (world.ecs.has(handle, Component.dead))
393 {
394 clearFireSession(world, characterId);
395 continue;
396 }
397 const position = world.ecs.get(handle, Component.position);
398 if (chebyshev(position.tileX, position.tileY, session.tileX, session.tileY) > 1)
399 {
400 clearFireSession(world, characterId);
401 continue;
402 }
403
404 const item = world.groundItems.get(session.groundItemId);
405 if (!item)
406 {
407 events.push({
408 type: "command-error",
409 sessionId: session.sessionId,
410 message: "Those logs are gone."
411 });
412 clearFireSession(world, characterId);
413 continue;
414 }
415
416 events.push({
417 type: "gather-swing",
418 attackerId: entityId,
419 tileX: session.tileX,
420 tileY: session.tileY,
421 fromTileX: position.tileX,
422 fromTileY: position.tileY,
423 toolItemId: session.toolItemId,
424 swipe: false
425 });
426
427 const skills = world.ecs.get(handle, Component.skills);
428 const level = skillLevel(skills, SkillId.firestarting);
429 const roll = rollSkill(level, world.rng ?? Math.random);
430 session.attemptsLeft -= 1;
431 if (roll >= session.difficulty)
432 {
433 succeedLight(world, handle, entityId, characterId, session, events, privates, now);
434 continue;
435 }
436 if (session.attemptsLeft <= 0)
437 {
438 events.push({
439 type: "command-error",
440 sessionId: session.sessionId,
441 message: "The sparks fail to catch."
442 });
443 clearFireSession(world, characterId);
444 continue;
445 }
446 session.nextAttemptAt = now + FIRE_ATTEMPT_MS;
447 }
448
449 return { events, privates };
450}
451
452export function stepCampfireExpires (world, now)
453{
454 const expires = world.campfireExpires;
455 if (!expires?.size)
456 { return { events: [] }; }
457 const events = [];
458 for (const [key, entry] of [...expires.entries()])
459 {
460 if (now < entry.expiresAt)
461 { continue; }
462 expires.delete(key);
463 const block = blockAt(world, entry.tileX, entry.tileY);
464 if (!block || block.typeId !== BlockType.campfire)
465 { continue; }
466 const delta = clearBlockAt(world, entry.tileX, entry.tileY);
467 if (delta)
468 { events.push(delta); }
469 spawnAsh(world, entry.tileX, entry.tileY, entry.woodTier, now, events);
470 }
471 return { events };
472}
473
474/** True if itemId is any wood log. */
475export function isWoodLogItemId (itemId)
476{
477 return woodTierFromLogItemId(itemId) != null
478 || WOOD_TIER_ORDER.some((tier) => logItemIdForWood(tier) === itemId);
479}
480
481export { woodTierFromLogItemId, woodTierRank, findTinderboxSlot };
server/src/fishing/service.js added +602 −0
@@ -0,0 +1,602 @@
1 import { Component } from "../ecs/components.js";
2 import {
3 BlockType,
4 GroundType,
5 isLiquidWaterGround,
6 normalizeGround
7 } from "../../../shared/definitions/tiles.js";
8 import {
9 FISH_SPECIES,
10 fishTierRankFromItemId,
11 fishingDifficulty,
12 fishingExhaustDurationMs,
13 baitItemIdForCloth,
14 BaitItemId,
15 normalizeFishingSpotConfig,
16 fishingPoleItemIdForWood,
17 woodTierFromFishingRodItemId
18 } from "../../../shared/definitions/fishItems.js";
19 import { resolveFishingTool } from "../../../shared/definitions/gathering.js";
20 import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
21 import {
22 ClothTier,
23 tierRank,
24 clothTierForWood
25 } from "../../../shared/definitions/materialTiers.js";
26 import { yarnItemId } from "../../../shared/definitions/clothItems.js";
27 import { itemDefinition } from "../../../shared/definitions/items.js";
28 import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
29 import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
30 import { rollSkill } from "../../../shared/combat/rolls.js";
31 import {
32 insertStack,
33 stackQuantity,
34 takeMatchingFromSlots,
35 takeFromSlot
36 } from "../../../shared/items/inventory.js";
37 import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";
38 import { addGroundItem, publicGroundItem, bagView } from "../items/bags.js";
39 import { chebyshev } from "../combat/service.js";
40 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
41 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
42 import { tileShoveEvent } from "../simulation/tileInteract.js";
43 import { seasonIdAt } from "../../../shared/world/season.js";
44
45 const FISH_ATTEMPT_MS = 3000;
46 const FISH_SHOVE_MS = 1000;
47 const MAX_FISH_ATTEMPTS = 3;
48 /** Chance the fishing line snaps after a fully failed rod session. */
49 const LINE_BREAK_CHANCE = 0.05;
50
51 function userError (message)
52 {
53 const error = new Error(message);
54 error.userFacing = true;
55 return error;
56 }
57
58 function tileKey (tileX, tileY)
59 {
60 return `${tileX},${tileY}`;
61 }
62
63 function characterDisplayName (world, handle)
64 {
65 const appearance = world.ecs.get(handle, Component.appearance);
66 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
67 return name || "someone";
68 }
69
70 function ensureFishSessions (world)
71 {
72 if (!world.fishSessions)
73 { world.fishSessions = new Map(); }
74 return world.fishSessions;
75 }
76
77 function ensureFishSpotRespawns (world)
78 {
79 if (!world.fishingSpotRespawns)
80 { world.fishingSpotRespawns = new Map(); }
81 return world.fishingSpotRespawns;
82 }
83
84 function clearFishSession (world, characterId)
85 {
86 ensureFishSessions(world).delete(characterId);
87 }
88
89 function blockAt (world, tileX, tileY)
90 {
91 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
92 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
93 return data.blocks[index] ?? null;
94 }
95
96 function groundAt (world, tileX, tileY)
97 {
98 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
99 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
100 return normalizeGround(data.grounds[index]).typeId;
101 }
102
103 function setBlockState (world, tileX, tileY, state)
104 {
105 const chunkX = tileToChunk(tileX);
106 const chunkY = tileToChunk(tileY);
107 const localX = tileToLocal(tileX);
108 const localY = tileToLocal(tileY);
109 const data = world.chunkData(chunkX, chunkY);
110 const index = localY * CHUNK_SIZE + localX;
111 const existing = data.blocks[index];
112 if (!existing)
113 { return null; }
114 const block = { ...existing, state };
115 data.blocks[index] = block;
116 return {
117 type: "chunk-delta",
118 chunkX,
119 chunkY,
120 tileX,
121 tileY,
122 localX,
123 localY,
124 block
125 };
126 }
127
128 function spotFishItemIds (block)
129 {
130 return normalizeFishingSpotConfig(block?.config).fishes;
131 }
132
133 function maxFishTierInList (fishItemIds)
134 {
135 let max = 0;
136 for (const itemId of fishItemIds)
137 { max = Math.max(max, fishTierRankFromItemId(itemId)); }
138 return max;
139 }
140
141 function eligibleFishItemIds (fishItemIds, baitTierRank)
142 {
143 return fishItemIds.filter((itemId) => fishTierRankFromItemId(itemId) <= baitTierRank);
144 }
145
146 function findBestBaitSlot (slots, maxRank)
147 {
148 let best = null;
149 for (let i = 0; i < (slots?.length ?? 0); i++)
150 {
151 const slot = slots[i];
152 if (!slot || stackQuantity(slot.quantity) <= 0)
153 { continue; }
154 const def = itemDefinition(slot.itemId);
155 if (!def?.bait || !def.tier)
156 { continue; }
157 const rank = tierRank(def.tier);
158 if (rank < 1 || rank > maxRank)
159 { continue; }
160 if (!best || rank > best.rank)
161 { best = { slotIndex: i, itemId: slot.itemId, rank, tier: def.tier }; }
162 }
163 return best;
164 }
165
166 function toolTierRank (tool)
167 {
168 const tier = tool?.def?.equipment?.tier ?? tool?.tier;
169 return tierRank(tier);
170 }
171
172 /**
173 * Start fishing at a fishing-spot block tile.
174 */
175 export function startFish (world, sessionId, characterId, tileX, tileY, now = Date.now())
176 {
177 const entityId = world.characterEntities.get(characterId);
178 if (entityId == null)
179 { throw userError("Character is not in the world."); }
180 const handle = world.ecs.handleOf(entityId);
181 const identity = world.ecs.get(handle, Component.networkIdentity);
182 if (!identity || identity.sessionId !== sessionId)
183 { throw userError("Character is not in the world."); }
184 if (world.ecs.has(handle, Component.dead))
185 { throw userError("You are dead."); }
186
187 const position = world.ecs.get(handle, Component.position);
188 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
189 { throw userError("You need to stand next to the fishing spot."); }
190
191 const block = blockAt(world, tileX, tileY);
192 if (!block || block.typeId !== BlockType.fishingSpot)
193 { throw userError("There is no fishing spot there."); }
194 if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY)))
195 { throw userError("The fish have scattered. Wait for them to return."); }
196
197 const ground = groundAt(world, tileX, tileY);
198 const season = seasonIdAt(now);
199 if (ground !== GroundType.water && ground !== GroundType.deepWater)
200 { throw userError("Fishing spots must be on water."); }
201 if (!isLiquidWaterGround(ground, season))
202 { throw userError("The water is frozen solid."); }
203
204 const fishList = spotFishItemIds(block);
205 if (!fishList.length)
206 { throw userError("No fish swim here."); }
207
208 const inventory = world.ecs.get(handle, Component.inventory);
209 const equipment = world.ecs.get(handle, Component.equipment);
210 const skills = world.ecs.get(handle, Component.skills);
211 const resolved = resolveFishingTool({
212 inventorySlots: inventory?.slots,
213 equipmentSlots: equipment?.slots,
214 skills
215 });
216 if (!resolved.ok)
217 { throw userError(resolved.reason); }
218
219 const isNet = resolved.kind === EquipmentKind.fishingNet;
220 const rodRank = isNet ? 1 : toolTierRank(resolved.tool);
221 const maxInSpot = maxFishTierInList(fishList);
222 const usefulMax = Math.min(rodRank, maxInSpot);
223
224 let baitRank = 1;
225 let baitItemId = null;
226 let baitConsumedRank = 0;
227
228 if (isNet)
229 {
230 baitRank = 1;
231 baitConsumedRank = 0;
232 }
233 else
234 {
235 const bait = findBestBaitSlot(inventory?.slots, usefulMax);
236 if (!bait)
237 { throw userError("You need suitable bait for this spot."); }
238 baitRank = bait.rank;
239 baitItemId = bait.itemId;
240 baitConsumedRank = bait.rank;
241 }
242
243 const eligible = eligibleFishItemIds(fishList, baitRank);
244 if (!eligible.length)
245 { throw userError("No fish here match your bait."); }
246
247 if (!isNet)
248 {
249 const taken = takeMatchingFromSlots(inventory.slots, {
250 itemId: baitItemId,
251 quantity: 1,
252 compact: false
253 });
254 if (!taken.ok)
255 { throw userError("You need suitable bait for this spot."); }
256 inventory.slots = taken.slots;
257 }
258
259 clearFishSession(world, characterId);
260 if (world.ecs.has(handle, Component.gather))
261 { world.ecs.remove(handle, Component.gather); }
262 const path = world.ecs.get(handle, Component.path);
263 if (path)
264 { path.tiles = []; }
265
266 ensureFishSessions(world).set(characterId, {
267 sessionId,
268 tileX,
269 tileY,
270 toolItemId: resolved.tool.def.itemId,
271 isNet,
272 baitRank,
273 baitConsumedRank,
274 baitItemId,
275 eligible,
276 difficulty: fishingDifficulty(baitRank),
277 attemptsLeft: MAX_FISH_ATTEMPTS,
278 attemptStartedAt: now,
279 nextShoveAt: now,
280 attemptEndsAt: now + FISH_ATTEMPT_MS
281 });
282
283 return {
284 events: [],
285 private: isNet ? null : bagView(world.ecs, handle)
286 };
287 }
288
289 export function handleFishingCommand (world, sessionId, command, now = Date.now())
290 {
291 if (command.type === "start-fish")
292 {
293 return startFish(
294 world,
295 sessionId,
296 command.characterId,
297 command.tileX | 0,
298 command.tileY | 0,
299 now
300 );
301 }
302 if (command.type === "cancel-fish")
303 {
304 clearFishSession(world, command.characterId);
305 return { events: [] };
306 }
307 return null;
308 }
309
310 function completeCatch (world, handle, entityId, characterId, session, events, privates, now)
311 {
312 const eligible = session.eligible ?? [];
313 if (!eligible.length)
314 {
315 events.push({
316 type: "command-error",
317 sessionId: session.sessionId,
318 message: "The fish got away."
319 });
320 clearFishSession(world, characterId);
321 return;
322 }
323 const rng = world.rng ?? Math.random;
324 const pick = eligible[Math.floor(rng() * eligible.length) % eligible.length];
325 const fishRank = fishTierRankFromItemId(pick);
326 const inventory = world.ecs.get(handle, Component.inventory);
327 const def = itemDefinition(pick);
328 const origin = gatherOrigin(GatherOriginVerb.caught, characterDisplayName(world, handle));
329 const stack = attachOrigins({
330 itemId: pick,
331 quantity: 1,
332 origins: [{ origin, quantity: 1 }]
333 });
334 const inserted = insertStack(inventory.slots, stack, def);
335 if (!inserted.ok || inserted.remainder > 0)
336 {
337 events.push({
338 type: "command-error",
339 sessionId: session.sessionId,
340 message: "Your inventory is full."
341 });
342 clearFishSession(world, characterId);
343 return;
344 }
345 inventory.slots = inserted.slots;
346
347 const xpAmount = (session.baitConsumedRank | 0) + fishRank;
348 const skills = world.ecs.get(handle, Component.skills);
349 let skillsChanged = false;
350 const levelUps = [];
351 if (skills?.xp && xpAmount > 0)
352 {
353 const result = applySkillXp(skills, SkillId.fishing, xpAmount);
354 if (result.changed)
355 { skillsChanged = true; }
356 if (result.levelUp)
357 { levelUps.push(result.levelUp); }
358 }
359 if (skillsChanged)
360 {
361 events.push({
362 type: "skills-updated",
363 entityId,
364 characterId,
365 skills: publicSkillsView(skills),
366 stored: storedSkillXp(skills),
367 levelUps
368 });
369 }
370
371 const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted");
372 if (exhausted)
373 { events.push(exhausted); }
374 ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY), {
375 tileX: session.tileX,
376 tileY: session.tileY,
377 respawnsAt: now + fishingExhaustDurationMs(fishRank)
378 });
379
380 privates.push({ characterId, bag: bagView(world.ecs, handle) });
381 events.push({
382 type: "item-bubble",
383 entityId,
384 itemId: pick,
385 quantity: 1
386 });
387 clearFishSession(world, characterId);
388 }
389
390 export function stepFishing (world, now)
391 {
392 const events = [];
393 const privates = [];
394 events.push(...stepFishingSpotRespawns(world, now).events);
395
396 const sessions = ensureFishSessions(world);
397 for (const [characterId, session] of [...sessions.entries()])
398 {
399 const entityId = world.characterEntities.get(characterId);
400 if (entityId == null)
401 {
402 clearFishSession(world, characterId);
403 continue;
404 }
405 const handle = world.ecs.handleOf(entityId);
406 if (world.ecs.has(handle, Component.dead))
407 {
408 clearFishSession(world, characterId);
409 continue;
410 }
411 const position = world.ecs.get(handle, Component.position);
412 if (chebyshev(position.tileX, position.tileY, session.tileX, session.tileY) > 1)
413 {
414 clearFishSession(world, characterId);
415 continue;
416 }
417
418 if (now >= session.nextShoveAt && now < session.attemptEndsAt)
419 {
420 session.nextShoveAt = now + FISH_SHOVE_MS;
421 events.push(tileShoveEvent(
422 entityId,
423 position.tileX,
424 position.tileY,
425 session.tileX,
426 session.tileY
427 ));
428 // Also emit gather-swing so tool overlay shows.
429 events.push({
430 type: "gather-swing",
431 attackerId: entityId,
432 tileX: session.tileX,
433 tileY: session.tileY,
434 fromTileX: position.tileX,
435 fromTileY: position.tileY,
436 toolItemId: session.toolItemId,
437 swipe: false
438 });
439 }
440
441 if (now < session.attemptEndsAt)
442 { continue; }
443
444 const skills = world.ecs.get(handle, Component.skills);
445 const level = skillLevel(skills, SkillId.fishing);
446 const roll = rollSkill(level, world.rng ?? Math.random);
447 session.attemptsLeft -= 1;
448
449 if (roll >= session.difficulty)
450 {
451 completeCatch(world, handle, entityId, characterId, session, events, privates, now);
452 continue;
453 }
454
455 if (session.attemptsLeft <= 0)
456 {
457 events.push({
458 type: "command-error",
459 sessionId: session.sessionId,
460 message: "The fish got away."
461 });
462 maybeBreakFishingLine(world, handle, entityId, characterId, session, events, privates, now);
463 clearFishSession(world, characterId);
464 continue;
465 }
466
467 session.attemptStartedAt = now;
468 session.nextShoveAt = now;
469 session.attemptEndsAt = now + FISH_ATTEMPT_MS;
470 }
471
472 return { events, privates };
473 }
474
475 function spawnGroundStack (world, tileX, tileY, itemId, now, events, source = "fishing-line-break")
476 {
477 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
478 const stack = attachOrigins({
479 itemId,
480 quantity: 1,
481 origins: []
482 });
483 const item = {
484 groundItemId,
485 tileX,
486 tileY,
487 stack,
488 droppedAt: now,
489 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
490 source
491 };
492 addGroundItem(world, item);
493 events.push({
494 type: "ground-item-appear",
495 ...publicGroundItem(item),
496 stack: item.stack,
497 droppedAt: item.droppedAt,
498 source: item.source,
499 expiresAt: item.expiresAt
500 });
501 }
502
503 /**
504 * After a fully failed rod session: 5% chance the line snaps → rod becomes pole + 1 yarn.
505 */
506 function maybeBreakFishingLine (world, handle, entityId, characterId, session, events, privates, now)
507 {
508 if (session.isNet)
509 { return; }
510 const rng = world.rng ?? Math.random;
511 if (rng() >= LINE_BREAK_CHANCE)
512 { return; }
513
514 const rodItemId = session.toolItemId | 0;
515 const rodDef = itemDefinition(rodItemId);
516 const woodTier = woodTierFromFishingRodItemId(rodItemId) ?? rodDef?.tier;
517 const poleItemId = rodDef?.poleItemId ?? fishingPoleItemIdForWood(woodTier);
518 const clothTier = rodDef?.clothTier ?? clothTierForWood(woodTier);
519 const yarnId = yarnItemId(clothTier);
520 if (!poleItemId || !yarnId)
521 { return; }
522
523 const inventory = world.ecs.get(handle, Component.inventory);
524 const equipment = world.ecs.get(handle, Component.equipment);
525 let removed = false;
526 let appearanceChanged = false;
527
528 if (inventory?.slots)
529 {
530 const idx = inventory.slots.findIndex((s) => s?.itemId === rodItemId);
531 if (idx >= 0)
532 {
533 const taken = takeFromSlot(inventory.slots, idx, 1);
534 if (taken.ok)
535 {
536 inventory.slots = taken.slots;
537 removed = true;
538 }
539 }
540 }
541 if (!removed && equipment?.slots?.weapon?.itemId === rodItemId)
542 {
543 equipment.slots.weapon = null;
544 removed = true;
545 appearanceChanged = true;
546 }
547 if (!removed)
548 { return; }
549
550 const position = world.ecs.get(handle, Component.position);
551 const poleDef = itemDefinition(poleItemId);
552 const yarnDef = itemDefinition(yarnId);
553 let slots = inventory.slots;
554
555 const poleIns = insertStack(slots, attachOrigins({ itemId: poleItemId, quantity: 1, origins: [] }), poleDef);
556 if (poleIns.ok && poleIns.remainder === 0)
557 { slots = poleIns.slots; }
558 else
559 { spawnGroundStack(world, position.tileX, position.tileY, poleItemId, now, events); }
560
561 const yarnIns = insertStack(slots, attachOrigins({ itemId: yarnId, quantity: 1, origins: [] }), yarnDef);
562 if (yarnIns.ok && yarnIns.remainder === 0)
563 { slots = yarnIns.slots; }
564 else
565 { spawnGroundStack(world, position.tileX, position.tileY, yarnId, now, events); }
566
567 inventory.slots = slots;
568
569 events.push({
570 type: "command-error",
571 sessionId: session.sessionId,
572 message: "Your fishing line broke!"
573 });
574 privates.push({
575 characterId,
576 bag: bagView(world.ecs, handle),
577 ...(appearanceChanged ? { appearanceChanged: true } : {})
578 });
579 }
580
581 export function stepFishingSpotRespawns (world, now)
582 {
583 const respawns = world.fishingSpotRespawns;
584 if (!respawns?.size)
585 { return { events: [] }; }
586 const events = [];
587 for (const [key, entry] of [...respawns.entries()])
588 {
589 if (now < entry.respawnsAt)
590 { continue; }
591 respawns.delete(key);
592 const block = blockAt(world, entry.tileX, entry.tileY);
593 if (!block || block.typeId !== BlockType.fishingSpot)
594 { continue; }
595 const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot");
596 if (delta)
597 { events.push(delta); }
598 }
599 return { events };
600 }
601
602 export { ClothTier, BaitItemId, baitItemIdForCloth, FISH_SPECIES };
@@ -0,0 +1,602 @@
1import { Component } from "../ecs/components.js";
2import {
3 BlockType,
4 GroundType,
5 isLiquidWaterGround,
6 normalizeGround
7} from "../../../shared/definitions/tiles.js";
8import {
9 FISH_SPECIES,
10 fishTierRankFromItemId,
11 fishingDifficulty,
12 fishingExhaustDurationMs,
13 baitItemIdForCloth,
14 BaitItemId,
15 normalizeFishingSpotConfig,
16 fishingPoleItemIdForWood,
17 woodTierFromFishingRodItemId
18} from "../../../shared/definitions/fishItems.js";
19import { resolveFishingTool } from "../../../shared/definitions/gathering.js";
20import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
21import {
22 ClothTier,
23 tierRank,
24 clothTierForWood
25} from "../../../shared/definitions/materialTiers.js";
26import { yarnItemId } from "../../../shared/definitions/clothItems.js";
27import { itemDefinition } from "../../../shared/definitions/items.js";
28import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
29import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
30import { rollSkill } from "../../../shared/combat/rolls.js";
31import {
32 insertStack,
33 stackQuantity,
34 takeMatchingFromSlots,
35 takeFromSlot
36} from "../../../shared/items/inventory.js";
37import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";
38import { addGroundItem, publicGroundItem, bagView } from "../items/bags.js";
39import { chebyshev } from "../combat/service.js";
40import { tileToChunk, tileToLocal } from "../world/coordinates.js";
41import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
42import { tileShoveEvent } from "../simulation/tileInteract.js";
43import { seasonIdAt } from "../../../shared/world/season.js";
44
45const FISH_ATTEMPT_MS = 3000;
46const FISH_SHOVE_MS = 1000;
47const MAX_FISH_ATTEMPTS = 3;
48/** Chance the fishing line snaps after a fully failed rod session. */
49const LINE_BREAK_CHANCE = 0.05;
50
51function userError (message)
52{
53 const error = new Error(message);
54 error.userFacing = true;
55 return error;
56}
57
58function tileKey (tileX, tileY)
59{
60 return `${tileX},${tileY}`;
61}
62
63function characterDisplayName (world, handle)
64{
65 const appearance = world.ecs.get(handle, Component.appearance);
66 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
67 return name || "someone";
68}
69
70function ensureFishSessions (world)
71{
72 if (!world.fishSessions)
73 { world.fishSessions = new Map(); }
74 return world.fishSessions;
75}
76
77function ensureFishSpotRespawns (world)
78{
79 if (!world.fishingSpotRespawns)
80 { world.fishingSpotRespawns = new Map(); }
81 return world.fishingSpotRespawns;
82}
83
84function clearFishSession (world, characterId)
85{
86 ensureFishSessions(world).delete(characterId);
87}
88
89function blockAt (world, tileX, tileY)
90{
91 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
92 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
93 return data.blocks[index] ?? null;
94}
95
96function groundAt (world, tileX, tileY)
97{
98 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
99 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
100 return normalizeGround(data.grounds[index]).typeId;
101}
102
103function setBlockState (world, tileX, tileY, state)
104{
105 const chunkX = tileToChunk(tileX);
106 const chunkY = tileToChunk(tileY);
107 const localX = tileToLocal(tileX);
108 const localY = tileToLocal(tileY);
109 const data = world.chunkData(chunkX, chunkY);
110 const index = localY * CHUNK_SIZE + localX;
111 const existing = data.blocks[index];
112 if (!existing)
113 { return null; }
114 const block = { ...existing, state };
115 data.blocks[index] = block;
116 return {
117 type: "chunk-delta",
118 chunkX,
119 chunkY,
120 tileX,
121 tileY,
122 localX,
123 localY,
124 block
125 };
126}
127
128function spotFishItemIds (block)
129{
130 return normalizeFishingSpotConfig(block?.config).fishes;
131}
132
133function maxFishTierInList (fishItemIds)
134{
135 let max = 0;
136 for (const itemId of fishItemIds)
137 { max = Math.max(max, fishTierRankFromItemId(itemId)); }
138 return max;
139}
140
141function eligibleFishItemIds (fishItemIds, baitTierRank)
142{
143 return fishItemIds.filter((itemId) => fishTierRankFromItemId(itemId) <= baitTierRank);
144}
145
146function findBestBaitSlot (slots, maxRank)
147{
148 let best = null;
149 for (let i = 0; i < (slots?.length ?? 0); i++)
150 {
151 const slot = slots[i];
152 if (!slot || stackQuantity(slot.quantity) <= 0)
153 { continue; }
154 const def = itemDefinition(slot.itemId);
155 if (!def?.bait || !def.tier)
156 { continue; }
157 const rank = tierRank(def.tier);
158 if (rank < 1 || rank > maxRank)
159 { continue; }
160 if (!best || rank > best.rank)
161 { best = { slotIndex: i, itemId: slot.itemId, rank, tier: def.tier }; }
162 }
163 return best;
164}
165
166function toolTierRank (tool)
167{
168 const tier = tool?.def?.equipment?.tier ?? tool?.tier;
169 return tierRank(tier);
170}
171
172/**
173 * Start fishing at a fishing-spot block tile.
174 */
175export function startFish (world, sessionId, characterId, tileX, tileY, now = Date.now())
176{
177 const entityId = world.characterEntities.get(characterId);
178 if (entityId == null)
179 { throw userError("Character is not in the world."); }
180 const handle = world.ecs.handleOf(entityId);
181 const identity = world.ecs.get(handle, Component.networkIdentity);
182 if (!identity || identity.sessionId !== sessionId)
183 { throw userError("Character is not in the world."); }
184 if (world.ecs.has(handle, Component.dead))
185 { throw userError("You are dead."); }
186
187 const position = world.ecs.get(handle, Component.position);
188 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
189 { throw userError("You need to stand next to the fishing spot."); }
190
191 const block = blockAt(world, tileX, tileY);
192 if (!block || block.typeId !== BlockType.fishingSpot)
193 { throw userError("There is no fishing spot there."); }
194 if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY)))
195 { throw userError("The fish have scattered. Wait for them to return."); }
196
197 const ground = groundAt(world, tileX, tileY);
198 const season = seasonIdAt(now);
199 if (ground !== GroundType.water && ground !== GroundType.deepWater)
200 { throw userError("Fishing spots must be on water."); }
201 if (!isLiquidWaterGround(ground, season))
202 { throw userError("The water is frozen solid."); }
203
204 const fishList = spotFishItemIds(block);
205 if (!fishList.length)
206 { throw userError("No fish swim here."); }
207
208 const inventory = world.ecs.get(handle, Component.inventory);
209 const equipment = world.ecs.get(handle, Component.equipment);
210 const skills = world.ecs.get(handle, Component.skills);
211 const resolved = resolveFishingTool({
212 inventorySlots: inventory?.slots,
213 equipmentSlots: equipment?.slots,
214 skills
215 });
216 if (!resolved.ok)
217 { throw userError(resolved.reason); }
218
219 const isNet = resolved.kind === EquipmentKind.fishingNet;
220 const rodRank = isNet ? 1 : toolTierRank(resolved.tool);
221 const maxInSpot = maxFishTierInList(fishList);
222 const usefulMax = Math.min(rodRank, maxInSpot);
223
224 let baitRank = 1;
225 let baitItemId = null;
226 let baitConsumedRank = 0;
227
228 if (isNet)
229 {
230 baitRank = 1;
231 baitConsumedRank = 0;
232 }
233 else
234 {
235 const bait = findBestBaitSlot(inventory?.slots, usefulMax);
236 if (!bait)
237 { throw userError("You need suitable bait for this spot."); }
238 baitRank = bait.rank;
239 baitItemId = bait.itemId;
240 baitConsumedRank = bait.rank;
241 }
242
243 const eligible = eligibleFishItemIds(fishList, baitRank);
244 if (!eligible.length)
245 { throw userError("No fish here match your bait."); }
246
247 if (!isNet)
248 {
249 const taken = takeMatchingFromSlots(inventory.slots, {
250 itemId: baitItemId,
251 quantity: 1,
252 compact: false
253 });
254 if (!taken.ok)
255 { throw userError("You need suitable bait for this spot."); }
256 inventory.slots = taken.slots;
257 }
258
259 clearFishSession(world, characterId);
260 if (world.ecs.has(handle, Component.gather))
261 { world.ecs.remove(handle, Component.gather); }
262 const path = world.ecs.get(handle, Component.path);
263 if (path)
264 { path.tiles = []; }
265
266 ensureFishSessions(world).set(characterId, {
267 sessionId,
268 tileX,
269 tileY,
270 toolItemId: resolved.tool.def.itemId,
271 isNet,
272 baitRank,
273 baitConsumedRank,
274 baitItemId,
275 eligible,
276 difficulty: fishingDifficulty(baitRank),
277 attemptsLeft: MAX_FISH_ATTEMPTS,
278 attemptStartedAt: now,
279 nextShoveAt: now,
280 attemptEndsAt: now + FISH_ATTEMPT_MS
281 });
282
283 return {
284 events: [],
285 private: isNet ? null : bagView(world.ecs, handle)
286 };
287}
288
289export function handleFishingCommand (world, sessionId, command, now = Date.now())
290{
291 if (command.type === "start-fish")
292 {
293 return startFish(
294 world,
295 sessionId,
296 command.characterId,
297 command.tileX | 0,
298 command.tileY | 0,
299 now
300 );
301 }
302 if (command.type === "cancel-fish")
303 {
304 clearFishSession(world, command.characterId);
305 return { events: [] };
306 }
307 return null;
308}
309
310function completeCatch (world, handle, entityId, characterId, session, events, privates, now)
311{
312 const eligible = session.eligible ?? [];
313 if (!eligible.length)
314 {
315 events.push({
316 type: "command-error",
317 sessionId: session.sessionId,
318 message: "The fish got away."
319 });
320 clearFishSession(world, characterId);
321 return;
322 }
323 const rng = world.rng ?? Math.random;
324 const pick = eligible[Math.floor(rng() * eligible.length) % eligible.length];
325 const fishRank = fishTierRankFromItemId(pick);
326 const inventory = world.ecs.get(handle, Component.inventory);
327 const def = itemDefinition(pick);
328 const origin = gatherOrigin(GatherOriginVerb.caught, characterDisplayName(world, handle));
329 const stack = attachOrigins({
330 itemId: pick,
331 quantity: 1,
332 origins: [{ origin, quantity: 1 }]
333 });
334 const inserted = insertStack(inventory.slots, stack, def);
335 if (!inserted.ok || inserted.remainder > 0)
336 {
337 events.push({
338 type: "command-error",
339 sessionId: session.sessionId,
340 message: "Your inventory is full."
341 });
342 clearFishSession(world, characterId);
343 return;
344 }
345 inventory.slots = inserted.slots;
346
347 const xpAmount = (session.baitConsumedRank | 0) + fishRank;
348 const skills = world.ecs.get(handle, Component.skills);
349 let skillsChanged = false;
350 const levelUps = [];
351 if (skills?.xp && xpAmount > 0)
352 {
353 const result = applySkillXp(skills, SkillId.fishing, xpAmount);
354 if (result.changed)
355 { skillsChanged = true; }
356 if (result.levelUp)
357 { levelUps.push(result.levelUp); }
358 }
359 if (skillsChanged)
360 {
361 events.push({
362 type: "skills-updated",
363 entityId,
364 characterId,
365 skills: publicSkillsView(skills),
366 stored: storedSkillXp(skills),
367 levelUps
368 });
369 }
370
371 const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted");
372 if (exhausted)
373 { events.push(exhausted); }
374 ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY), {
375 tileX: session.tileX,
376 tileY: session.tileY,
377 respawnsAt: now + fishingExhaustDurationMs(fishRank)
378 });
379
380 privates.push({ characterId, bag: bagView(world.ecs, handle) });
381 events.push({
382 type: "item-bubble",
383 entityId,
384 itemId: pick,
385 quantity: 1
386 });
387 clearFishSession(world, characterId);
388}
389
390export function stepFishing (world, now)
391{
392 const events = [];
393 const privates = [];
394 events.push(...stepFishingSpotRespawns(world, now).events);
395
396 const sessions = ensureFishSessions(world);
397 for (const [characterId, session] of [...sessions.entries()])
398 {
399 const entityId = world.characterEntities.get(characterId);
400 if (entityId == null)
401 {
402 clearFishSession(world, characterId);
403 continue;
404 }
405 const handle = world.ecs.handleOf(entityId);
406 if (world.ecs.has(handle, Component.dead))
407 {
408 clearFishSession(world, characterId);
409 continue;
410 }
411 const position = world.ecs.get(handle, Component.position);
412 if (chebyshev(position.tileX, position.tileY, session.tileX, session.tileY) > 1)
413 {
414 clearFishSession(world, characterId);
415 continue;
416 }
417
418 if (now >= session.nextShoveAt && now < session.attemptEndsAt)
419 {
420 session.nextShoveAt = now + FISH_SHOVE_MS;
421 events.push(tileShoveEvent(
422 entityId,
423 position.tileX,
424 position.tileY,
425 session.tileX,
426 session.tileY
427 ));
428 // Also emit gather-swing so tool overlay shows.
429 events.push({
430 type: "gather-swing",
431 attackerId: entityId,
432 tileX: session.tileX,
433 tileY: session.tileY,
434 fromTileX: position.tileX,
435 fromTileY: position.tileY,
436 toolItemId: session.toolItemId,
437 swipe: false
438 });
439 }
440
441 if (now < session.attemptEndsAt)
442 { continue; }
443
444 const skills = world.ecs.get(handle, Component.skills);
445 const level = skillLevel(skills, SkillId.fishing);
446 const roll = rollSkill(level, world.rng ?? Math.random);
447 session.attemptsLeft -= 1;
448
449 if (roll >= session.difficulty)
450 {
451 completeCatch(world, handle, entityId, characterId, session, events, privates, now);
452 continue;
453 }
454
455 if (session.attemptsLeft <= 0)
456 {
457 events.push({
458 type: "command-error",
459 sessionId: session.sessionId,
460 message: "The fish got away."
461 });
462 maybeBreakFishingLine(world, handle, entityId, characterId, session, events, privates, now);
463 clearFishSession(world, characterId);
464 continue;
465 }
466
467 session.attemptStartedAt = now;
468 session.nextShoveAt = now;
469 session.attemptEndsAt = now + FISH_ATTEMPT_MS;
470 }
471
472 return { events, privates };
473}
474
475function spawnGroundStack (world, tileX, tileY, itemId, now, events, source = "fishing-line-break")
476{
477 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
478 const stack = attachOrigins({
479 itemId,
480 quantity: 1,
481 origins: []
482 });
483 const item = {
484 groundItemId,
485 tileX,
486 tileY,
487 stack,
488 droppedAt: now,
489 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
490 source
491 };
492 addGroundItem(world, item);
493 events.push({
494 type: "ground-item-appear",
495 ...publicGroundItem(item),
496 stack: item.stack,
497 droppedAt: item.droppedAt,
498 source: item.source,
499 expiresAt: item.expiresAt
500 });
501}
502
503/**
504 * After a fully failed rod session: 5% chance the line snaps → rod becomes pole + 1 yarn.
505 */
506function maybeBreakFishingLine (world, handle, entityId, characterId, session, events, privates, now)
507{
508 if (session.isNet)
509 { return; }
510 const rng = world.rng ?? Math.random;
511 if (rng() >= LINE_BREAK_CHANCE)
512 { return; }
513
514 const rodItemId = session.toolItemId | 0;
515 const rodDef = itemDefinition(rodItemId);
516 const woodTier = woodTierFromFishingRodItemId(rodItemId) ?? rodDef?.tier;
517 const poleItemId = rodDef?.poleItemId ?? fishingPoleItemIdForWood(woodTier);
518 const clothTier = rodDef?.clothTier ?? clothTierForWood(woodTier);
519 const yarnId = yarnItemId(clothTier);
520 if (!poleItemId || !yarnId)
521 { return; }
522
523 const inventory = world.ecs.get(handle, Component.inventory);
524 const equipment = world.ecs.get(handle, Component.equipment);
525 let removed = false;
526 let appearanceChanged = false;
527
528 if (inventory?.slots)
529 {
530 const idx = inventory.slots.findIndex((s) => s?.itemId === rodItemId);
531 if (idx >= 0)
532 {
533 const taken = takeFromSlot(inventory.slots, idx, 1);
534 if (taken.ok)
535 {
536 inventory.slots = taken.slots;
537 removed = true;
538 }
539 }
540 }
541 if (!removed && equipment?.slots?.weapon?.itemId === rodItemId)
542 {
543 equipment.slots.weapon = null;
544 removed = true;
545 appearanceChanged = true;
546 }
547 if (!removed)
548 { return; }
549
550 const position = world.ecs.get(handle, Component.position);
551 const poleDef = itemDefinition(poleItemId);
552 const yarnDef = itemDefinition(yarnId);
553 let slots = inventory.slots;
554
555 const poleIns = insertStack(slots, attachOrigins({ itemId: poleItemId, quantity: 1, origins: [] }), poleDef);
556 if (poleIns.ok && poleIns.remainder === 0)
557 { slots = poleIns.slots; }
558 else
559 { spawnGroundStack(world, position.tileX, position.tileY, poleItemId, now, events); }
560
561 const yarnIns = insertStack(slots, attachOrigins({ itemId: yarnId, quantity: 1, origins: [] }), yarnDef);
562 if (yarnIns.ok && yarnIns.remainder === 0)
563 { slots = yarnIns.slots; }
564 else
565 { spawnGroundStack(world, position.tileX, position.tileY, yarnId, now, events); }
566
567 inventory.slots = slots;
568
569 events.push({
570 type: "command-error",
571 sessionId: session.sessionId,
572 message: "Your fishing line broke!"
573 });
574 privates.push({
575 characterId,
576 bag: bagView(world.ecs, handle),
577 ...(appearanceChanged ? { appearanceChanged: true } : {})
578 });
579}
580
581export function stepFishingSpotRespawns (world, now)
582{
583 const respawns = world.fishingSpotRespawns;
584 if (!respawns?.size)
585 { return { events: [] }; }
586 const events = [];
587 for (const [key, entry] of [...respawns.entries()])
588 {
589 if (now < entry.respawnsAt)
590 { continue; }
591 respawns.delete(key);
592 const block = blockAt(world, entry.tileX, entry.tileY);
593 if (!block || block.typeId !== BlockType.fishingSpot)
594 { continue; }
595 const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot");
596 if (delta)
597 { events.push(delta); }
598 }
599 return { events };
600}
601
602export { ClothTier, BaitItemId, baitItemIdForCloth, FISH_SPECIES };
server/src/gateway/websocket.js +17 −0
@@ -426,6 +426,23 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
426 426 batchAll: !!message.batchAll
427 427 });
428 428 break;
429 case MessageType.startFire:
430 requirePlaying(session);
431 simulation.enqueue(session.id, {
432 type: "start-fire",
433 characterId: session.characterId,
434 groundItemId: message.groundItemId | 0
435 });
436 break;
437 case MessageType.startFish:
438 requirePlaying(session);
439 simulation.enqueue(session.id, {
440 type: "start-fish",
441 characterId: session.characterId,
442 tileX: message.tileX | 0,
443 tileY: message.tileY | 0
444 });
445 break;
429 446 case MessageType.cancelCraft:
430 447 requirePlaying(session);
431 448 simulation.enqueue(session.id, {
@@ -426,6 +426,23 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
426 batchAll: !!message.batchAll
426 batchAll: !!message.batchAll
427 });
427 });
428 break;
428 break;
429 case MessageType.startFire:
430 requirePlaying(session);
431 simulation.enqueue(session.id, {
432 type: "start-fire",
433 characterId: session.characterId,
434 groundItemId: message.groundItemId | 0
435 });
436 break;
437 case MessageType.startFish:
438 requirePlaying(session);
439 simulation.enqueue(session.id, {
440 type: "start-fish",
441 characterId: session.characterId,
442 tileX: message.tileX | 0,
443 tileY: message.tileY | 0
444 });
445 break;
429 case MessageType.cancelCraft:
446 case MessageType.cancelCraft:
430 requirePlaying(session);
447 requirePlaying(session);
431 simulation.enqueue(session.id, {
448 simulation.enqueue(session.id, {
server/src/items/bags.js +11 −1
@@ -481,10 +481,20 @@ function eatItem (world, sessionId, command)
481 481 { throw userError("That inventory slot is empty."); }
482 482 inventory.slots = taken.slots;
483 483 health.current = Math.min(health.max | 0, (health.current | 0) + healing);
484 let statusEffectsChanged = false;
485 if (def?.eatStatusEffect)
486 {
487 let component = world.ecs.get(handle, Component.statusEffects);
488 if (!component)
489 { component = world.ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }
490 applyStatusEffect(component, def.eatStatusEffect, Date.now());
491 statusEffectsChanged = true;
492 }
484 493 return {
485 494 events: [],
486 495 private: bagView(world.ecs, handle),
487 healthChanged: true
496 healthChanged: true,
497 statusEffectsChanged
488 498 };
489 499 }
490 500
@@ -481,10 +481,20 @@ function eatItem (world, sessionId, command)
481 { throw userError("That inventory slot is empty."); }
481 { throw userError("That inventory slot is empty."); }
482 inventory.slots = taken.slots;
482 inventory.slots = taken.slots;
483 health.current = Math.min(health.max | 0, (health.current | 0) + healing);
483 health.current = Math.min(health.max | 0, (health.current | 0) + healing);
484 let statusEffectsChanged = false;
485 if (def?.eatStatusEffect)
486 {
487 let component = world.ecs.get(handle, Component.statusEffects);
488 if (!component)
489 { component = world.ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }
490 applyStatusEffect(component, def.eatStatusEffect, Date.now());
491 statusEffectsChanged = true;
492 }
484 return {
493 return {
485 events: [],
494 events: [],
486 private: bagView(world.ecs, handle),
495 private: bagView(world.ecs, handle),
487 healthChanged: true
496 healthChanged: true,
497 statusEffectsChanged
488 };
498 };
489}
499}
490
500
server/src/shop/service.js +4 −0
@@ -576,9 +576,13 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
576 576 else
577 577 {
578 578 const shopOriginEntry = { kind: ItemOriginKind.shop, displayName };
579 const defaultInstance = def?.defaultInstance
580 ? structuredClone(def.defaultInstance)
581 : null;
579 582 stack = attachOrigins({
580 583 itemId: buyItemId,
581 584 quantity: qty,
585 instance: defaultInstance,
582 586 origins: [{ origin: shopOriginEntry, quantity: qty }]
583 587 });
584 588 }
@@ -576,9 +576,13 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
576 else
576 else
577 {
577 {
578 const shopOriginEntry = { kind: ItemOriginKind.shop, displayName };
578 const shopOriginEntry = { kind: ItemOriginKind.shop, displayName };
579 const defaultInstance = def?.defaultInstance
580 ? structuredClone(def.defaultInstance)
581 : null;
579 stack = attachOrigins({
582 stack = attachOrigins({
580 itemId: buyItemId,
583 itemId: buyItemId,
581 quantity: qty,
584 quantity: qty,
585 instance: defaultInstance,
582 origins: [{ origin: shopOriginEntry, quantity: qty }]
586 origins: [{ origin: shopOriginEntry, quantity: qty }]
583 });
587 });
584 }
588 }
server/src/simulation/workerWorld.js +36 −0
@@ -43,6 +43,8 @@ import {
43 43 clearPlantRespawnsForChunk
44 44 } from "../gathering/service.js";
45 45 import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
46 import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
47 import { handleFishingCommand, stepFishing } from "../fishing/service.js";
46 48 import { handleAlchemyCommand } from "../alchemy/service.js";
47 49 import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
48 50 import {
@@ -90,6 +92,10 @@ export class WorkerWorld
90 92 this.groundByTile = new Map();
91 93 this.oreRespawns = new Map();
92 94 this.treeRespawns = new Map();
95 this.campfireExpires = new Map();
96 this.fireSessions = new Map();
97 this.fishingSpotRespawns = new Map();
98 this.fishSessions = new Map();
93 99 this.pendingSpellImpacts = [];
94 100 this.settings = { ...DEFAULT_WORLD_SETTINGS };
95 101 this.activeRevisionId = 1;
@@ -478,6 +484,12 @@ export class WorkerWorld
478 484 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
479 485 if (gather)
480 486 { return gather; }
487 const fire = handleFirestartingCommand(this, sessionId, command, message.now ?? Date.now());
488 if (fire)
489 { return fire; }
490 const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());
491 if (fishing)
492 { return fishing; }
481 493 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
482 494 if (craft)
483 495 { return craft; }
@@ -1276,6 +1288,26 @@ export class WorkerWorld
1276 1288 ...entry.bag
1277 1289 });
1278 1290 }
1291 const fire = stepFirestarting(this, now);
1292 events.push(...fire.events);
1293 for (const entry of fire.privates ?? [])
1294 {
1295 events.push({
1296 type: "inventory",
1297 characterId: entry.characterId,
1298 ...entry.bag
1299 });
1300 }
1301 const fishing = stepFishing(this, now);
1302 events.push(...fishing.events);
1303 for (const entry of fishing.privates ?? [])
1304 {
1305 events.push({
1306 type: "inventory",
1307 characterId: entry.characterId,
1308 ...entry.bag
1309 });
1310 }
1279 1311 const craft = stepCrafting(this, now);
1280 1312 events.push(...craft.events);
1281 1313 for (const entry of craft.privates ?? [])
@@ -1370,6 +1402,10 @@ export class WorkerWorld
1370 1402 continue;
1371 1403 }
1372 1404
1405 const combat = this.ecs.get(handle, Component.combat);
1406 if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y))
1407 { continue; }
1408
1373 1409 const fromTileX = position.tileX;
1374 1410 const fromTileY = position.tileY;
1375 1411 const flying = this.#isFlying(handle);
@@ -43,6 +43,8 @@ import {
43 clearPlantRespawnsForChunk
43 clearPlantRespawnsForChunk
44} from "../gathering/service.js";
44} from "../gathering/service.js";
45import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
45import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
46import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
47import { handleFishingCommand, stepFishing } from "../fishing/service.js";
46import { handleAlchemyCommand } from "../alchemy/service.js";
48import { handleAlchemyCommand } from "../alchemy/service.js";
47import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
49import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
48import {
50import {
@@ -90,6 +92,10 @@ export class WorkerWorld
90 this.groundByTile = new Map();
92 this.groundByTile = new Map();
91 this.oreRespawns = new Map();
93 this.oreRespawns = new Map();
92 this.treeRespawns = new Map();
94 this.treeRespawns = new Map();
95 this.campfireExpires = new Map();
96 this.fireSessions = new Map();
97 this.fishingSpotRespawns = new Map();
98 this.fishSessions = new Map();
93 this.pendingSpellImpacts = [];
99 this.pendingSpellImpacts = [];
94 this.settings = { ...DEFAULT_WORLD_SETTINGS };
100 this.settings = { ...DEFAULT_WORLD_SETTINGS };
95 this.activeRevisionId = 1;
101 this.activeRevisionId = 1;
@@ -478,6 +484,12 @@ export class WorkerWorld
478 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
484 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
479 if (gather)
485 if (gather)
480 { return gather; }
486 { return gather; }
487 const fire = handleFirestartingCommand(this, sessionId, command, message.now ?? Date.now());
488 if (fire)
489 { return fire; }
490 const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());
491 if (fishing)
492 { return fishing; }
481 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
493 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
482 if (craft)
494 if (craft)
483 { return craft; }
495 { return craft; }
@@ -1276,6 +1288,26 @@ export class WorkerWorld
1276 ...entry.bag
1288 ...entry.bag
1277 });
1289 });
1278 }
1290 }
1291 const fire = stepFirestarting(this, now);
1292 events.push(...fire.events);
1293 for (const entry of fire.privates ?? [])
1294 {
1295 events.push({
1296 type: "inventory",
1297 characterId: entry.characterId,
1298 ...entry.bag
1299 });
1300 }
1301 const fishing = stepFishing(this, now);
1302 events.push(...fishing.events);
1303 for (const entry of fishing.privates ?? [])
1304 {
1305 events.push({
1306 type: "inventory",
1307 characterId: entry.characterId,
1308 ...entry.bag
1309 });
1310 }
1279 const craft = stepCrafting(this, now);
1311 const craft = stepCrafting(this, now);
1280 events.push(...craft.events);
1312 events.push(...craft.events);
1281 for (const entry of craft.privates ?? [])
1313 for (const entry of craft.privates ?? [])
@@ -1370,6 +1402,10 @@ export class WorkerWorld
1370 continue;
1402 continue;
1371 }
1403 }
1372
1404
1405 const combat = this.ecs.get(handle, Component.combat);
1406 if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y))
1407 { continue; }
1408
1373 const fromTileX = position.tileX;
1409 const fromTileX = position.tileX;
1374 const fromTileY = position.tileY;
1410 const fromTileY = position.tileY;
1375 const flying = this.#isFlying(handle);
1411 const flying = this.#isFlying(handle);
server/tests/combat.test.js +91 −0
@@ -1025,3 +1025,94 @@ test("blocking a hit awards Defence XP equal to avoided damage", () =>
1025 1025 harness.close();
1026 1026 }
1027 1027 });
1028
1029 test("stacked combatants against the same target spread to different tiles", () =>
1030 {
1031 const harness = makeSimulation({ workerCount: 1 });
1032 try
1033 {
1034 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1035 const playerId = harness.simulation.spawnCharacter(1, character);
1036 const rat1 = harness.simulation.spawnEntity(mobComponents({
1037 tileX: 9,
1038 tileY: 8,
1039 mobTypeId: MobId.rat,
1040 spawnerId: null
1041 }));
1042 const rat2 = harness.simulation.spawnEntity(mobComponents({
1043 tileX: 9,
1044 tileY: 7,
1045 mobTypeId: MobId.rat,
1046 spawnerId: null
1047 }));
1048 const worker = workerOf(harness.simulation, playerId);
1049 teleportEntity(worker, rat2, 9, 8);
1050
1051 for (let i = 0; i < 200; i++)
1052 {
1053 harness.advance(50);
1054 harness.simulation.step();
1055 }
1056
1057 const pos1 = componentsOf(harness.simulation, rat1).position;
1058 const pos2 = componentsOf(harness.simulation, rat2).position;
1059 assert.notEqual(
1060 `${pos1.tileX},${pos1.tileY}`,
1061 `${pos2.tileX},${pos2.tileY}`,
1062 "expected stacked rats to spread apart"
1063 );
1064 assert.equal(componentsOf(harness.simulation, rat1).combat?.targetEntityId, playerId);
1065 assert.equal(componentsOf(harness.simulation, rat2).combat?.targetEntityId, playerId);
1066 }
1067 finally
1068 { harness.close(); }
1069 });
1070
1071 test("approaching combatants pick different adjacent goals", () =>
1072 {
1073 const harness = makeSimulation({ workerCount: 1 });
1074 try
1075 {
1076 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1077 const playerId = harness.simulation.spawnCharacter(1, character);
1078 const rat1 = harness.simulation.spawnEntity(mobComponents({
1079 tileX: 6,
1080 tileY: 8,
1081 mobTypeId: MobId.rat,
1082 spawnerId: null
1083 }));
1084 const rat2 = harness.simulation.spawnEntity(mobComponents({
1085 tileX: 6,
1086 tileY: 7,
1087 mobTypeId: MobId.rat,
1088 spawnerId: null
1089 }));
1090 const worker = workerOf(harness.simulation, playerId);
1091 teleportEntity(worker, rat2, 6, 8);
1092
1093 for (let i = 0; i < 120; i++)
1094 {
1095 harness.advance(50);
1096 harness.simulation.step();
1097 }
1098
1099 const path1 = componentsOf(harness.simulation, rat1).path?.tiles ?? [];
1100 const path2 = componentsOf(harness.simulation, rat2).path?.tiles ?? [];
1101 const goal1 = path1[path1.length - 1];
1102 const goal2 = path2[path2.length - 1];
1103 if (goal1 && goal2)
1104 {
1105 assert.notEqual(
1106 `${goal1.x},${goal1.y}`,
1107 `${goal2.x},${goal2.y}`,
1108 "expected different approach goals"
1109 );
1110 }
1111
1112 const pos1 = componentsOf(harness.simulation, rat1).position;
1113 const pos2 = componentsOf(harness.simulation, rat2).position;
1114 assert.notEqual(`${pos1.tileX},${pos1.tileY}`, `${pos2.tileX},${pos2.tileY}`);
1115 }
1116 finally
1117 { harness.close(); }
1118 });
@@ -1025,3 +1025,94 @@ test("blocking a hit awards Defence XP equal to avoided damage", () =>
1025 harness.close();
1025 harness.close();
1026 }
1026 }
1027});
1027});
1028
1029test("stacked combatants against the same target spread to different tiles", () =>
1030{
1031 const harness = makeSimulation({ workerCount: 1 });
1032 try
1033 {
1034 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1035 const playerId = harness.simulation.spawnCharacter(1, character);
1036 const rat1 = harness.simulation.spawnEntity(mobComponents({
1037 tileX: 9,
1038 tileY: 8,
1039 mobTypeId: MobId.rat,
1040 spawnerId: null
1041 }));
1042 const rat2 = harness.simulation.spawnEntity(mobComponents({
1043 tileX: 9,
1044 tileY: 7,
1045 mobTypeId: MobId.rat,
1046 spawnerId: null
1047 }));
1048 const worker = workerOf(harness.simulation, playerId);
1049 teleportEntity(worker, rat2, 9, 8);
1050
1051 for (let i = 0; i < 200; i++)
1052 {
1053 harness.advance(50);
1054 harness.simulation.step();
1055 }
1056
1057 const pos1 = componentsOf(harness.simulation, rat1).position;
1058 const pos2 = componentsOf(harness.simulation, rat2).position;
1059 assert.notEqual(
1060 `${pos1.tileX},${pos1.tileY}`,
1061 `${pos2.tileX},${pos2.tileY}`,
1062 "expected stacked rats to spread apart"
1063 );
1064 assert.equal(componentsOf(harness.simulation, rat1).combat?.targetEntityId, playerId);
1065 assert.equal(componentsOf(harness.simulation, rat2).combat?.targetEntityId, playerId);
1066 }
1067 finally
1068 { harness.close(); }
1069});
1070
1071test("approaching combatants pick different adjacent goals", () =>
1072{
1073 const harness = makeSimulation({ workerCount: 1 });
1074 try
1075 {
1076 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1077 const playerId = harness.simulation.spawnCharacter(1, character);
1078 const rat1 = harness.simulation.spawnEntity(mobComponents({
1079 tileX: 6,
1080 tileY: 8,
1081 mobTypeId: MobId.rat,
1082 spawnerId: null
1083 }));
1084 const rat2 = harness.simulation.spawnEntity(mobComponents({
1085 tileX: 6,
1086 tileY: 7,
1087 mobTypeId: MobId.rat,
1088 spawnerId: null
1089 }));
1090 const worker = workerOf(harness.simulation, playerId);
1091 teleportEntity(worker, rat2, 6, 8);
1092
1093 for (let i = 0; i < 120; i++)
1094 {
1095 harness.advance(50);
1096 harness.simulation.step();
1097 }
1098
1099 const path1 = componentsOf(harness.simulation, rat1).path?.tiles ?? [];
1100 const path2 = componentsOf(harness.simulation, rat2).path?.tiles ?? [];
1101 const goal1 = path1[path1.length - 1];
1102 const goal2 = path2[path2.length - 1];
1103 if (goal1 && goal2)
1104 {
1105 assert.notEqual(
1106 `${goal1.x},${goal1.y}`,
1107 `${goal2.x},${goal2.y}`,
1108 "expected different approach goals"
1109 );
1110 }
1111
1112 const pos1 = componentsOf(harness.simulation, rat1).position;
1113 const pos2 = componentsOf(harness.simulation, rat2).position;
1114 assert.notEqual(`${pos1.tileX},${pos1.tileY}`, `${pos2.tileX},${pos2.tileY}`);
1115 }
1116 finally
1117 { harness.close(); }
1118});
server/tests/firestarting-cooking.test.js added +298 −0
@@ -0,0 +1,298 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { BlockType } from "../../shared/definitions/tiles.js";
4 import {
5 CraftingStationId,
6 firestartingDifficulty,
7 campfireDurationMs,
8 COOK_BURN_CHANCE_OVEN,
9 COOK_BURN_CHANCE_CAMPFIRE,
10 CRAFT_DURATION_MS
11 } from "../../shared/definitions/craftingStations.js";
12 import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";
13 import { WoodItemId, ashItemIdForWood } from "../../shared/definitions/woodItems.js";
14 import { WoodTier } from "../../shared/definitions/materialTiers.js";
15 import { SkillId } from "../../shared/definitions/skills.js";
16 import { recipeDefinition } from "../../shared/crafting/stationRecipes.js";
17 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
18 import { totalXpForLevel } from "../../shared/skills/progression.js";
19 import { ashTintColor } from "../../shared/render/tint.js";
20 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
21 import { Component } from "../src/ecs/components.js";
22 import { addGroundItem } from "../src/items/bags.js";
23 import { StatusEffectType } from "../../shared/statusEffects/rules.js";
24
25 function countItem (slots, itemId)
26 {
27 return (slots ?? []).reduce((sum, slot) =>
28 {
29 if (slot?.itemId === itemId)
30 { return sum + (slot.quantity | 0); }
31 return sum;
32 }, 0);
33 }
34
35 function workerOf (simulation, playerId)
36 {
37 const record = simulation.entityRecord(playerId);
38 return simulation.workers[record.workerId];
39 }
40
41 function setSkillLevel (worker, playerId, skillId, level)
42 {
43 const handle = worker.world.ecs.handleOf(playerId);
44 const skills = worker.world.ecs.get(handle, Component.skills);
45 skills.xp[skillId] = totalXpForLevel(level);
46 }
47
48 function giveInventory (harness, playerId, items)
49 {
50 const inventory = emptySlots();
51 items.forEach((stack, index) =>
52 {
53 inventory[index] = {
54 itemId: stack.itemId,
55 quantity: stack.quantity,
56 ...(stack.instance ? { instance: structuredClone(stack.instance) } : {})
57 };
58 });
59 harness.simulation.applyBag(playerId, {
60 inventory,
61 equipment: emptyEquipment(),
62 vault: [],
63 vaultReserved: []
64 });
65 }
66
67 function advanceMs (harness, ms)
68 {
69 const ticks = Math.ceil(ms / 50) + 3;
70 for (let i = 0; i < ticks; i++)
71 {
72 harness.advance(50);
73 harness.simulation.step();
74 }
75 }
76
77 function placeStation (worker, tileX, tileY, typeId, state)
78 {
79 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
80 const localX = ((tileX % 16) + 16) % 16;
81 const localY = ((tileY % 16) + 16) % 16;
82 data.blocks[localY * 16 + localX] = {
83 typeId,
84 state,
85 config: null
86 };
87 }
88
89 test("firestarting difficulty and campfire duration scale with wood tier", () =>
90 {
91 assert.equal(firestartingDifficulty(WoodTier.pine), 1);
92 assert.equal(firestartingDifficulty(WoodTier.birch), 10);
93 assert.equal(firestartingDifficulty(WoodTier.oak), 20);
94 assert.equal(campfireDurationMs(WoodTier.pine), 3 * 60_000);
95 assert.equal(campfireDurationMs(WoodTier.oak), 9 * 60_000);
96 assert.equal(COOK_BURN_CHANCE_OVEN, 0.1);
97 assert.equal(COOK_BURN_CHANCE_CAMPFIRE, 0.35);
98 });
99
100 test("ash tint sits between dark grey and wood colour", () =>
101 {
102 const tint = ashTintColor(WoodTier.pine);
103 assert.ok(tint.r > 0.12 && tint.r < 0.9);
104 });
105
106 test("cook-venison recipe exists for oven and campfire with burnt output", () =>
107 {
108 const recipe = recipeDefinition("cook-venison");
109 assert.ok(recipe);
110 assert.deepEqual(recipe.stationIds, [CraftingStationId.oven, CraftingStationId.fireplace]);
111 assert.equal(recipe.output.itemId, CraftingItemId.cookedMeat);
112 assert.equal(recipe.burntOutput.itemId, CraftingItemId.burntMeat);
113 assert.equal(recipe.inputs[0].itemId, CraftingItemId.rawMeat);
114 });
115
116 test("start-fire places campfire and expiry drops ash", () =>
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 worker = workerOf(harness.simulation, playerId);
124 worker.world.rng = () => 0.999;
125 setSkillLevel(worker, playerId, SkillId.firestarting, 1);
126 giveInventory(harness, playerId, [
127 { itemId: CraftingItemId.tinderbox, quantity: 1, instance: tinderboxItemInstance(20) }
128 ]);
129
130 const groundItemId = 9001;
131 addGroundItem(worker.world, {
132 groundItemId,
133 tileX: 9,
134 tileY: 8,
135 stack: { itemId: WoodItemId.pineLog, quantity: 1 },
136 droppedAt: harness.now(),
137 expiresAt: harness.now() + 600_000,
138 source: "test"
139 });
140
141 harness.simulation.enqueue(1, {
142 type: "start-fire",
143 characterId: character.character_id,
144 groundItemId
145 });
146 advanceMs(harness, 4000);
147
148 const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
149 assert.equal(block?.typeId, BlockType.campfire);
150 assert.equal(block?.state, WoodTier.pine);
151 assert.ok(worker.world.campfireExpires.has("9,8"));
152
153 const bag = harness.simulation.bagOf(playerId);
154 const tinder = bag.inventory.find((s) => s?.itemId === CraftingItemId.tinderbox);
155 assert.equal(tinder?.instance?.charges, 19);
156
157 const entry = worker.world.campfireExpires.get("9,8");
158 entry.expiresAt = 0;
159 advanceMs(harness, 200);
160 assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null);
161 const ashOnGround = [...worker.world.groundItems.values()].some(
162 (item) => item.stack?.itemId === ashItemIdForWood(WoodTier.pine)
163 );
164 assert.equal(ashOnGround, true);
165 }
166 finally
167 { harness.close(); }
168 });
169
170 test("start-fire rejects too-low Firestarting for birch", () =>
171 {
172 const harness = makeSimulation({ workerCount: 1 });
173 try
174 {
175 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
176 const playerId = harness.simulation.spawnCharacter(1, character);
177 const worker = workerOf(harness.simulation, playerId);
178 setSkillLevel(worker, playerId, SkillId.firestarting, 1);
179 giveInventory(harness, playerId, [
180 { itemId: CraftingItemId.tinderbox, quantity: 1, instance: tinderboxItemInstance(5) }
181 ]);
182 addGroundItem(worker.world, {
183 groundItemId: 9002,
184 tileX: 9,
185 tileY: 8,
186 stack: { itemId: WoodItemId.birchLog, quantity: 1 },
187 droppedAt: harness.now(),
188 expiresAt: harness.now() + 600_000,
189 source: "test"
190 });
191
192 harness.simulation.enqueue(1, {
193 type: "start-fire",
194 characterId: character.character_id,
195 groundItemId: 9002
196 });
197 advanceMs(harness, 200);
198 assert.equal(worker.world.groundItems.has(9002), true);
199 assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null);
200 }
201 finally
202 { harness.close(); }
203 });
204
205 test("oven cook can burn to burnt venison with seeded rng", () =>
206 {
207 const harness = makeSimulation({ workerCount: 1 });
208 try
209 {
210 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
211 const playerId = harness.simulation.spawnCharacter(1, character);
212 const worker = workerOf(harness.simulation, playerId);
213 worker.world.rng = () => 0.01;
214 setSkillLevel(worker, playerId, SkillId.cooking, 1);
215 placeStation(worker, 9, 8, BlockType.oven, "oven");
216 giveInventory(harness, playerId, [
217 { itemId: CraftingItemId.rawMeat, quantity: 1 }
218 ]);
219
220 harness.simulation.enqueue(1, {
221 type: "start-craft",
222 characterId: character.character_id,
223 stationId: CraftingStationId.oven,
224 recipeId: "cook-venison"
225 });
226 advanceMs(harness, CRAFT_DURATION_MS + 500);
227
228 const bag = harness.simulation.bagOf(playerId);
229 assert.equal(countItem(bag.inventory, CraftingItemId.rawMeat), 0);
230 assert.equal(countItem(bag.inventory, CraftingItemId.burntMeat), 1);
231 assert.equal(countItem(bag.inventory, CraftingItemId.cookedMeat), 0);
232 }
233 finally
234 { harness.close(); }
235 });
236
237 test("oven cook succeeds when rng avoids burn", () =>
238 {
239 const harness = makeSimulation({ workerCount: 1 });
240 try
241 {
242 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
243 const playerId = harness.simulation.spawnCharacter(1, character);
244 const worker = workerOf(harness.simulation, playerId);
245 worker.world.rng = () => 0.99;
246 setSkillLevel(worker, playerId, SkillId.cooking, 1);
247 placeStation(worker, 9, 8, BlockType.oven, "oven");
248 giveInventory(harness, playerId, [
249 { itemId: CraftingItemId.rawMeat, quantity: 1 }
250 ]);
251
252 harness.simulation.enqueue(1, {
253 type: "start-craft",
254 characterId: character.character_id,
255 stationId: CraftingStationId.oven,
256 recipeId: "cook-venison"
257 });
258 advanceMs(harness, CRAFT_DURATION_MS + 500);
259
260 const bag = harness.simulation.bagOf(playerId);
261 assert.equal(countItem(bag.inventory, CraftingItemId.cookedMeat), 1);
262 }
263 finally
264 { harness.close(); }
265 });
266
267 test("eating cooked venison heals and applies health regen", () =>
268 {
269 const harness = makeSimulation({ workerCount: 1 });
270 try
271 {
272 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
273 const playerId = harness.simulation.spawnCharacter(1, character);
274 const worker = workerOf(harness.simulation, playerId);
275 const handle = worker.world.ecs.handleOf(playerId);
276 const health = worker.world.ecs.get(handle, Component.health);
277 health.current = 5;
278 health.max = 20;
279 giveInventory(harness, playerId, [
280 { itemId: CraftingItemId.cookedMeat, quantity: 1 }
281 ]);
282
283 harness.simulation.enqueue(1, {
284 type: "eat-item",
285 characterId: character.character_id,
286 slotIndex: 0
287 });
288 harness.simulation.step();
289
290 assert.equal(health.current, 10);
291 const status = worker.world.ecs.get(handle, Component.statusEffects);
292 const regen = status?.effects?.find((e) => e.type === StatusEffectType.healthRegen);
293 assert.ok(regen);
294 assert.equal(regen.amountPerSecond, 1);
295 }
296 finally
297 { harness.close(); }
298 });
@@ -0,0 +1,298 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { BlockType } from "../../shared/definitions/tiles.js";
4import {
5 CraftingStationId,
6 firestartingDifficulty,
7 campfireDurationMs,
8 COOK_BURN_CHANCE_OVEN,
9 COOK_BURN_CHANCE_CAMPFIRE,
10 CRAFT_DURATION_MS
11} from "../../shared/definitions/craftingStations.js";
12import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";
13import { WoodItemId, ashItemIdForWood } from "../../shared/definitions/woodItems.js";
14import { WoodTier } from "../../shared/definitions/materialTiers.js";
15import { SkillId } from "../../shared/definitions/skills.js";
16import { recipeDefinition } from "../../shared/crafting/stationRecipes.js";
17import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
18import { totalXpForLevel } from "../../shared/skills/progression.js";
19import { ashTintColor } from "../../shared/render/tint.js";
20import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
21import { Component } from "../src/ecs/components.js";
22import { addGroundItem } from "../src/items/bags.js";
23import { StatusEffectType } from "../../shared/statusEffects/rules.js";
24
25function countItem (slots, itemId)
26{
27 return (slots ?? []).reduce((sum, slot) =>
28 {
29 if (slot?.itemId === itemId)
30 { return sum + (slot.quantity | 0); }
31 return sum;
32 }, 0);
33}
34
35function workerOf (simulation, playerId)
36{
37 const record = simulation.entityRecord(playerId);
38 return simulation.workers[record.workerId];
39}
40
41function setSkillLevel (worker, playerId, skillId, level)
42{
43 const handle = worker.world.ecs.handleOf(playerId);
44 const skills = worker.world.ecs.get(handle, Component.skills);
45 skills.xp[skillId] = totalXpForLevel(level);
46}
47
48function giveInventory (harness, playerId, items)
49{
50 const inventory = emptySlots();
51 items.forEach((stack, index) =>
52 {
53 inventory[index] = {
54 itemId: stack.itemId,
55 quantity: stack.quantity,
56 ...(stack.instance ? { instance: structuredClone(stack.instance) } : {})
57 };
58 });
59 harness.simulation.applyBag(playerId, {
60 inventory,
61 equipment: emptyEquipment(),
62 vault: [],
63 vaultReserved: []
64 });
65}
66
67function advanceMs (harness, ms)
68{
69 const ticks = Math.ceil(ms / 50) + 3;
70 for (let i = 0; i < ticks; i++)
71 {
72 harness.advance(50);
73 harness.simulation.step();
74 }
75}
76
77function placeStation (worker, tileX, tileY, typeId, state)
78{
79 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
80 const localX = ((tileX % 16) + 16) % 16;
81 const localY = ((tileY % 16) + 16) % 16;
82 data.blocks[localY * 16 + localX] = {
83 typeId,
84 state,
85 config: null
86 };
87}
88
89test("firestarting difficulty and campfire duration scale with wood tier", () =>
90{
91 assert.equal(firestartingDifficulty(WoodTier.pine), 1);
92 assert.equal(firestartingDifficulty(WoodTier.birch), 10);
93 assert.equal(firestartingDifficulty(WoodTier.oak), 20);
94 assert.equal(campfireDurationMs(WoodTier.pine), 3 * 60_000);
95 assert.equal(campfireDurationMs(WoodTier.oak), 9 * 60_000);
96 assert.equal(COOK_BURN_CHANCE_OVEN, 0.1);
97 assert.equal(COOK_BURN_CHANCE_CAMPFIRE, 0.35);
98});
99
100test("ash tint sits between dark grey and wood colour", () =>
101{
102 const tint = ashTintColor(WoodTier.pine);
103 assert.ok(tint.r > 0.12 && tint.r < 0.9);
104});
105
106test("cook-venison recipe exists for oven and campfire with burnt output", () =>
107{
108 const recipe = recipeDefinition("cook-venison");
109 assert.ok(recipe);
110 assert.deepEqual(recipe.stationIds, [CraftingStationId.oven, CraftingStationId.fireplace]);
111 assert.equal(recipe.output.itemId, CraftingItemId.cookedMeat);
112 assert.equal(recipe.burntOutput.itemId, CraftingItemId.burntMeat);
113 assert.equal(recipe.inputs[0].itemId, CraftingItemId.rawMeat);
114});
115
116test("start-fire places campfire and expiry drops ash", () =>
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 worker = workerOf(harness.simulation, playerId);
124 worker.world.rng = () => 0.999;
125 setSkillLevel(worker, playerId, SkillId.firestarting, 1);
126 giveInventory(harness, playerId, [
127 { itemId: CraftingItemId.tinderbox, quantity: 1, instance: tinderboxItemInstance(20) }
128 ]);
129
130 const groundItemId = 9001;
131 addGroundItem(worker.world, {
132 groundItemId,
133 tileX: 9,
134 tileY: 8,
135 stack: { itemId: WoodItemId.pineLog, quantity: 1 },
136 droppedAt: harness.now(),
137 expiresAt: harness.now() + 600_000,
138 source: "test"
139 });
140
141 harness.simulation.enqueue(1, {
142 type: "start-fire",
143 characterId: character.character_id,
144 groundItemId
145 });
146 advanceMs(harness, 4000);
147
148 const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
149 assert.equal(block?.typeId, BlockType.campfire);
150 assert.equal(block?.state, WoodTier.pine);
151 assert.ok(worker.world.campfireExpires.has("9,8"));
152
153 const bag = harness.simulation.bagOf(playerId);
154 const tinder = bag.inventory.find((s) => s?.itemId === CraftingItemId.tinderbox);
155 assert.equal(tinder?.instance?.charges, 19);
156
157 const entry = worker.world.campfireExpires.get("9,8");
158 entry.expiresAt = 0;
159 advanceMs(harness, 200);
160 assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null);
161 const ashOnGround = [...worker.world.groundItems.values()].some(
162 (item) => item.stack?.itemId === ashItemIdForWood(WoodTier.pine)
163 );
164 assert.equal(ashOnGround, true);
165 }
166 finally
167 { harness.close(); }
168});
169
170test("start-fire rejects too-low Firestarting for birch", () =>
171{
172 const harness = makeSimulation({ workerCount: 1 });
173 try
174 {
175 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
176 const playerId = harness.simulation.spawnCharacter(1, character);
177 const worker = workerOf(harness.simulation, playerId);
178 setSkillLevel(worker, playerId, SkillId.firestarting, 1);
179 giveInventory(harness, playerId, [
180 { itemId: CraftingItemId.tinderbox, quantity: 1, instance: tinderboxItemInstance(5) }
181 ]);
182 addGroundItem(worker.world, {
183 groundItemId: 9002,
184 tileX: 9,
185 tileY: 8,
186 stack: { itemId: WoodItemId.birchLog, quantity: 1 },
187 droppedAt: harness.now(),
188 expiresAt: harness.now() + 600_000,
189 source: "test"
190 });
191
192 harness.simulation.enqueue(1, {
193 type: "start-fire",
194 characterId: character.character_id,
195 groundItemId: 9002
196 });
197 advanceMs(harness, 200);
198 assert.equal(worker.world.groundItems.has(9002), true);
199 assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null);
200 }
201 finally
202 { harness.close(); }
203});
204
205test("oven cook can burn to burnt venison with seeded rng", () =>
206{
207 const harness = makeSimulation({ workerCount: 1 });
208 try
209 {
210 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
211 const playerId = harness.simulation.spawnCharacter(1, character);
212 const worker = workerOf(harness.simulation, playerId);
213 worker.world.rng = () => 0.01;
214 setSkillLevel(worker, playerId, SkillId.cooking, 1);
215 placeStation(worker, 9, 8, BlockType.oven, "oven");
216 giveInventory(harness, playerId, [
217 { itemId: CraftingItemId.rawMeat, quantity: 1 }
218 ]);
219
220 harness.simulation.enqueue(1, {
221 type: "start-craft",
222 characterId: character.character_id,
223 stationId: CraftingStationId.oven,
224 recipeId: "cook-venison"
225 });
226 advanceMs(harness, CRAFT_DURATION_MS + 500);
227
228 const bag = harness.simulation.bagOf(playerId);
229 assert.equal(countItem(bag.inventory, CraftingItemId.rawMeat), 0);
230 assert.equal(countItem(bag.inventory, CraftingItemId.burntMeat), 1);
231 assert.equal(countItem(bag.inventory, CraftingItemId.cookedMeat), 0);
232 }
233 finally
234 { harness.close(); }
235});
236
237test("oven cook succeeds when rng avoids burn", () =>
238{
239 const harness = makeSimulation({ workerCount: 1 });
240 try
241 {
242 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
243 const playerId = harness.simulation.spawnCharacter(1, character);
244 const worker = workerOf(harness.simulation, playerId);
245 worker.world.rng = () => 0.99;
246 setSkillLevel(worker, playerId, SkillId.cooking, 1);
247 placeStation(worker, 9, 8, BlockType.oven, "oven");
248 giveInventory(harness, playerId, [
249 { itemId: CraftingItemId.rawMeat, quantity: 1 }
250 ]);
251
252 harness.simulation.enqueue(1, {
253 type: "start-craft",
254 characterId: character.character_id,
255 stationId: CraftingStationId.oven,
256 recipeId: "cook-venison"
257 });
258 advanceMs(harness, CRAFT_DURATION_MS + 500);
259
260 const bag = harness.simulation.bagOf(playerId);
261 assert.equal(countItem(bag.inventory, CraftingItemId.cookedMeat), 1);
262 }
263 finally
264 { harness.close(); }
265});
266
267test("eating cooked venison heals and applies health regen", () =>
268{
269 const harness = makeSimulation({ workerCount: 1 });
270 try
271 {
272 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
273 const playerId = harness.simulation.spawnCharacter(1, character);
274 const worker = workerOf(harness.simulation, playerId);
275 const handle = worker.world.ecs.handleOf(playerId);
276 const health = worker.world.ecs.get(handle, Component.health);
277 health.current = 5;
278 health.max = 20;
279 giveInventory(harness, playerId, [
280 { itemId: CraftingItemId.cookedMeat, quantity: 1 }
281 ]);
282
283 harness.simulation.enqueue(1, {
284 type: "eat-item",
285 characterId: character.character_id,
286 slotIndex: 0
287 });
288 harness.simulation.step();
289
290 assert.equal(health.current, 10);
291 const status = worker.world.ecs.get(handle, Component.statusEffects);
292 const regen = status?.effects?.find((e) => e.type === StatusEffectType.healthRegen);
293 assert.ok(regen);
294 assert.equal(regen.amountPerSecond, 1);
295 }
296 finally
297 { harness.close(); }
298});
server/tests/fishing.test.js added +299 −0
@@ -0,0 +1,299 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { BlockType, GroundType } from "../../shared/definitions/tiles.js";
4 import {
5 rawFishItemId,
6 cookedFishItemId,
7 baitItemIdForCloth,
8 FishingToolItemId,
9 fishingDifficulty,
10 fishingExhaustDurationMs,
11 normalizeFishingSpotConfig
12 } from "../../shared/definitions/fishItems.js";
13 import { ClothTier } from "../../shared/definitions/materialTiers.js";
14 import { yarnItemId } from "../../shared/definitions/clothItems.js";
15 import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
16 import { SkillId } from "../../shared/definitions/skills.js";
17 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
18 import { totalXpForLevel } from "../../shared/skills/progression.js";
19 import { itemDefinition } from "../../shared/definitions/items.js";
20 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
21 import { Component } from "../src/ecs/components.js";
22
23 function workerOf (simulation, playerId)
24 {
25 const record = simulation.entityRecord(playerId);
26 return simulation.workers[record.workerId];
27 }
28
29 function setSkillLevel (worker, playerId, skillId, level)
30 {
31 const handle = worker.world.ecs.handleOf(playerId);
32 const skills = worker.world.ecs.get(handle, Component.skills);
33 skills.xp[skillId] = totalXpForLevel(level);
34 }
35
36 function giveInventory (harness, playerId, items)
37 {
38 const inventory = emptySlots();
39 items.forEach((stack, index) =>
40 {
41 inventory[index] = { itemId: stack.itemId, quantity: stack.quantity };
42 });
43 harness.simulation.applyBag(playerId, {
44 inventory,
45 equipment: emptyEquipment(),
46 vault: [],
47 vaultReserved: []
48 });
49 }
50
51 function advanceMs (harness, ms)
52 {
53 const ticks = Math.ceil(ms / 50) + 3;
54 for (let i = 0; i < ticks; i++)
55 {
56 harness.advance(50);
57 harness.simulation.step();
58 }
59 }
60
61 function placeFishingSpot (worker, tileX, tileY, fishes, groundType = GroundType.deepWater)
62 {
63 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
64 const localX = ((tileX % 16) + 16) % 16;
65 const localY = ((tileY % 16) + 16) % 16;
66 const index = localY * 16 + localX;
67 data.grounds[index] = { typeId: groundType, state: null };
68 data.blocks[index] = {
69 typeId: BlockType.fishingSpot,
70 state: "fishing-spot",
71 config: normalizeFishingSpotConfig({ fishes })
72 };
73 }
74
75 test("fishing difficulty and exhaust scale with tier", () =>
76 {
77 assert.equal(fishingDifficulty(1), 1);
78 assert.equal(fishingDifficulty(2), 10);
79 assert.equal(fishingExhaustDurationMs(3), 30_000);
80 });
81
82 test("cooked fish healing is tier times 5", () =>
83 {
84 assert.equal(itemDefinition(cookedFishItemId("minnow")).healing, 5);
85 assert.equal(itemDefinition(cookedFishItemId("shark")).healing, 35);
86 });
87
88 test("net catches tier-1 fish without bait and exhausts spot", () =>
89 {
90 const harness = makeSimulation({ workerCount: 1 });
91 try
92 {
93 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
94 const playerId = harness.simulation.spawnCharacter(1, character);
95 const worker = workerOf(harness.simulation, playerId);
96 worker.world.rng = () => 0.999;
97 setSkillLevel(worker, playerId, SkillId.fishing, 1);
98 const minnow = rawFishItemId("minnow");
99 const trout = rawFishItemId("trout");
100 placeFishingSpot(worker, 9, 8, [minnow, trout]);
101 giveInventory(harness, playerId, [
102 { itemId: FishingToolItemId.net, quantity: 1 }
103 ]);
104
105 harness.simulation.enqueue(1, {
106 type: "start-fish",
107 characterId: character.character_id,
108 tileX: 9,
109 tileY: 8
110 });
111 advanceMs(harness, 10_000);
112
113 const bag = harness.simulation.bagOf(playerId);
114 assert.ok(bag.inventory.some((s) => s?.itemId === minnow), "expected minnow");
115 assert.equal(bag.inventory.some((s) => s?.itemId === trout), false);
116 const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
117 assert.equal(block.state, "exhausted");
118 assert.ok(worker.world.fishingSpotRespawns.has("9,8"));
119 }
120 finally
121 { harness.close(); }
122 });
123
124 test("rod consumes highest useful bait for spot", () =>
125 {
126 const harness = makeSimulation({ workerCount: 1 });
127 try
128 {
129 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
130 const playerId = harness.simulation.spawnCharacter(1, character);
131 const worker = workerOf(harness.simulation, playerId);
132 worker.world.rng = () => 0.999;
133 setSkillLevel(worker, playerId, SkillId.fishing, 20);
134 const trout = rawFishItemId("trout");
135 placeFishingSpot(worker, 9, 8, [trout]);
136 const worms = baitItemIdForCloth(ClothTier.cotton);
137 const maggots = baitItemIdForCloth(ClothTier.wool);
138 const crickets = baitItemIdForCloth(ClothTier.linen);
139 giveInventory(harness, playerId, [
140 { itemId: FishingToolItemId.oakRod, quantity: 1 },
141 { itemId: worms, quantity: 2 },
142 { itemId: maggots, quantity: 2 },
143 { itemId: crickets, quantity: 2 }
144 ]);
145
146 harness.simulation.enqueue(1, {
147 type: "start-fish",
148 characterId: character.character_id,
149 tileX: 9,
150 tileY: 8
151 });
152 advanceMs(harness, 200);
153
154 const bag = harness.simulation.bagOf(playerId);
155 assert.equal(bag.inventory.find((s) => s?.itemId === crickets)?.quantity ?? 0, 1);
156 assert.equal(bag.inventory.find((s) => s?.itemId === maggots)?.quantity ?? 0, 2);
157 }
158 finally
159 { harness.close(); }
160 });
161
162 test("shallow water fishing blocked in winter", () =>
163 {
164 const harness = makeSimulation({ workerCount: 1, now: Date.UTC(2026, 0, 15) });
165 try
166 {
167 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
168 const playerId = harness.simulation.spawnCharacter(1, character);
169 const worker = workerOf(harness.simulation, playerId);
170 setSkillLevel(worker, playerId, SkillId.fishing, 1);
171 placeFishingSpot(worker, 9, 8, [rawFishItemId("minnow")], GroundType.water);
172 giveInventory(harness, playerId, [
173 { itemId: FishingToolItemId.net, quantity: 1 }
174 ]);
175
176 harness.simulation.enqueue(1, {
177 type: "start-fish",
178 characterId: character.character_id,
179 tileX: 9,
180 tileY: 8
181 });
182 const result = harness.simulation.step();
183 assert.ok(result.events.some((e) => e.type === "command-error"));
184 assert.equal(worker.world.fishSessions.size, 0);
185 }
186 finally
187 { harness.close(); }
188 });
189
190 test("pole + yarn recipes: log makes pole, pole+2 yarn makes rod", () =>
191 {
192 const pole = itemDefinition(FishingToolItemId.birchPole);
193 const rod = itemDefinition(FishingToolItemId.birchRod);
194 assert.equal(pole?.fishingPole, true);
195 assert.equal(rod?.poleItemId, FishingToolItemId.birchPole);
196 assert.equal(rod?.equipment?.kind, EquipmentKind.fishingRod);
197 assert.equal(pole?.equipment, undefined);
198 });
199
200 test("failed rod fishing can snap the line into pole + yarn", () =>
201 {
202 const harness = makeSimulation({ workerCount: 1 });
203 try
204 {
205 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
206 const playerId = harness.simulation.spawnCharacter(1, character);
207 const worker = workerOf(harness.simulation, playerId);
208 // Always fail skill rolls (0) and always snap the line (0 < 0.05).
209 worker.world.rng = () => 0;
210 setSkillLevel(worker, playerId, SkillId.fishing, 10);
211 const perch = rawFishItemId("perch");
212 placeFishingSpot(worker, 9, 8, [perch]);
213 const maggots = baitItemIdForCloth(ClothTier.wool);
214 giveInventory(harness, playerId, [
215 { itemId: FishingToolItemId.birchRod, quantity: 1 },
216 { itemId: maggots, quantity: 1 }
217 ]);
218
219 harness.simulation.enqueue(1, {
220 type: "start-fish",
221 characterId: character.character_id,
222 tileX: 9,
223 tileY: 8
224 });
225 const events = [];
226 const ticks = Math.ceil(12_000 / 50) + 5;
227 for (let i = 0; i < ticks; i++)
228 {
229 harness.advance(50);
230 const step = harness.simulation.step();
231 events.push(...(step.events ?? []));
232 }
233
234 assert.ok(events.some((e) => e.type === "command-error" && e.message === "The fish got away."));
235 assert.ok(events.some((e) => e.type === "command-error" && e.message === "Your fishing line broke!"));
236 const bag = harness.simulation.bagOf(playerId);
237 assert.equal(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchRod), false);
238 assert.ok(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchPole), "expected pole");
239 assert.ok(bag.inventory.some((s) => s?.itemId === yarnItemId(ClothTier.wool)), "expected wool yarn");
240 }
241 finally
242 { harness.close(); }
243 });
244
245 test("line-break yarn drops to ground when bag is full", () =>
246 {
247 const harness = makeSimulation({ workerCount: 1 });
248 try
249 {
250 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
251 const playerId = harness.simulation.spawnCharacter(1, character);
252 const worker = workerOf(harness.simulation, playerId);
253 worker.world.rng = () => 0;
254 setSkillLevel(worker, playerId, SkillId.fishing, 10);
255 const perch = rawFishItemId("perch");
256 placeFishingSpot(worker, 9, 8, [perch]);
257 const maggots = baitItemIdForCloth(ClothTier.wool);
258 const yarn = yarnItemId(ClothTier.wool);
259 // Rod equipped; bag full except bait (consumed on start → one free slot for pole only).
260 const slots = emptySlots();
261 slots[0] = { itemId: maggots, quantity: 1 };
262 for (let i = 1; i < slots.length; i++)
263 { slots[i] = { itemId: rawFishItemId("minnow"), quantity: 1 }; }
264 const equipment = emptyEquipment();
265 equipment.slots.weapon = { itemId: FishingToolItemId.birchRod, quantity: 1 };
266 harness.simulation.applyBag(playerId, {
267 inventory: slots,
268 equipment,
269 vault: [],
270 vaultReserved: []
271 });
272
273 harness.simulation.enqueue(1, {
274 type: "start-fish",
275 characterId: character.character_id,
276 tileX: 9,
277 tileY: 8
278 });
279 const events = [];
280 const ticks = Math.ceil(12_000 / 50) + 5;
281 for (let i = 0; i < ticks; i++)
282 {
283 harness.advance(50);
284 const step = harness.simulation.step();
285 events.push(...(step.events ?? []));
286 }
287
288 assert.ok(events.some((e) => e.message === "Your fishing line broke!"));
289 const bag = harness.simulation.bagOf(playerId);
290 assert.ok(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchPole));
291 assert.equal(bag.equipment?.slots?.weapon, null);
292 assert.equal(bag.inventory.some((s) => s?.itemId === yarn), false);
293 assert.ok(events.some((e) =>
294 e.type === "ground-item-appear" && e.stack?.itemId === yarn
295 ), "yarn should appear on the ground");
296 }
297 finally
298 { harness.close(); }
299 });
@@ -0,0 +1,299 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { BlockType, GroundType } from "../../shared/definitions/tiles.js";
4import {
5 rawFishItemId,
6 cookedFishItemId,
7 baitItemIdForCloth,
8 FishingToolItemId,
9 fishingDifficulty,
10 fishingExhaustDurationMs,
11 normalizeFishingSpotConfig
12} from "../../shared/definitions/fishItems.js";
13import { ClothTier } from "../../shared/definitions/materialTiers.js";
14import { yarnItemId } from "../../shared/definitions/clothItems.js";
15import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
16import { SkillId } from "../../shared/definitions/skills.js";
17import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
18import { totalXpForLevel } from "../../shared/skills/progression.js";
19import { itemDefinition } from "../../shared/definitions/items.js";
20import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
21import { Component } from "../src/ecs/components.js";
22
23function workerOf (simulation, playerId)
24{
25 const record = simulation.entityRecord(playerId);
26 return simulation.workers[record.workerId];
27}
28
29function setSkillLevel (worker, playerId, skillId, level)
30{
31 const handle = worker.world.ecs.handleOf(playerId);
32 const skills = worker.world.ecs.get(handle, Component.skills);
33 skills.xp[skillId] = totalXpForLevel(level);
34}
35
36function giveInventory (harness, playerId, items)
37{
38 const inventory = emptySlots();
39 items.forEach((stack, index) =>
40 {
41 inventory[index] = { itemId: stack.itemId, quantity: stack.quantity };
42 });
43 harness.simulation.applyBag(playerId, {
44 inventory,
45 equipment: emptyEquipment(),
46 vault: [],
47 vaultReserved: []
48 });
49}
50
51function advanceMs (harness, ms)
52{
53 const ticks = Math.ceil(ms / 50) + 3;
54 for (let i = 0; i < ticks; i++)
55 {
56 harness.advance(50);
57 harness.simulation.step();
58 }
59}
60
61function placeFishingSpot (worker, tileX, tileY, fishes, groundType = GroundType.deepWater)
62{
63 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
64 const localX = ((tileX % 16) + 16) % 16;
65 const localY = ((tileY % 16) + 16) % 16;
66 const index = localY * 16 + localX;
67 data.grounds[index] = { typeId: groundType, state: null };
68 data.blocks[index] = {
69 typeId: BlockType.fishingSpot,
70 state: "fishing-spot",
71 config: normalizeFishingSpotConfig({ fishes })
72 };
73}
74
75test("fishing difficulty and exhaust scale with tier", () =>
76{
77 assert.equal(fishingDifficulty(1), 1);
78 assert.equal(fishingDifficulty(2), 10);
79 assert.equal(fishingExhaustDurationMs(3), 30_000);
80});
81
82test("cooked fish healing is tier times 5", () =>
83{
84 assert.equal(itemDefinition(cookedFishItemId("minnow")).healing, 5);
85 assert.equal(itemDefinition(cookedFishItemId("shark")).healing, 35);
86});
87
88test("net catches tier-1 fish without bait and exhausts spot", () =>
89{
90 const harness = makeSimulation({ workerCount: 1 });
91 try
92 {
93 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
94 const playerId = harness.simulation.spawnCharacter(1, character);
95 const worker = workerOf(harness.simulation, playerId);
96 worker.world.rng = () => 0.999;
97 setSkillLevel(worker, playerId, SkillId.fishing, 1);
98 const minnow = rawFishItemId("minnow");
99 const trout = rawFishItemId("trout");
100 placeFishingSpot(worker, 9, 8, [minnow, trout]);
101 giveInventory(harness, playerId, [
102 { itemId: FishingToolItemId.net, quantity: 1 }
103 ]);
104
105 harness.simulation.enqueue(1, {
106 type: "start-fish",
107 characterId: character.character_id,
108 tileX: 9,
109 tileY: 8
110 });
111 advanceMs(harness, 10_000);
112
113 const bag = harness.simulation.bagOf(playerId);
114 assert.ok(bag.inventory.some((s) => s?.itemId === minnow), "expected minnow");
115 assert.equal(bag.inventory.some((s) => s?.itemId === trout), false);
116 const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
117 assert.equal(block.state, "exhausted");
118 assert.ok(worker.world.fishingSpotRespawns.has("9,8"));
119 }
120 finally
121 { harness.close(); }
122});
123
124test("rod consumes highest useful bait for spot", () =>
125{
126 const harness = makeSimulation({ workerCount: 1 });
127 try
128 {
129 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
130 const playerId = harness.simulation.spawnCharacter(1, character);
131 const worker = workerOf(harness.simulation, playerId);
132 worker.world.rng = () => 0.999;
133 setSkillLevel(worker, playerId, SkillId.fishing, 20);
134 const trout = rawFishItemId("trout");
135 placeFishingSpot(worker, 9, 8, [trout]);
136 const worms = baitItemIdForCloth(ClothTier.cotton);
137 const maggots = baitItemIdForCloth(ClothTier.wool);
138 const crickets = baitItemIdForCloth(ClothTier.linen);
139 giveInventory(harness, playerId, [
140 { itemId: FishingToolItemId.oakRod, quantity: 1 },
141 { itemId: worms, quantity: 2 },
142 { itemId: maggots, quantity: 2 },
143 { itemId: crickets, quantity: 2 }
144 ]);
145
146 harness.simulation.enqueue(1, {
147 type: "start-fish",
148 characterId: character.character_id,
149 tileX: 9,
150 tileY: 8
151 });
152 advanceMs(harness, 200);
153
154 const bag = harness.simulation.bagOf(playerId);
155 assert.equal(bag.inventory.find((s) => s?.itemId === crickets)?.quantity ?? 0, 1);
156 assert.equal(bag.inventory.find((s) => s?.itemId === maggots)?.quantity ?? 0, 2);
157 }
158 finally
159 { harness.close(); }
160});
161
162test("shallow water fishing blocked in winter", () =>
163{
164 const harness = makeSimulation({ workerCount: 1, now: Date.UTC(2026, 0, 15) });
165 try
166 {
167 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
168 const playerId = harness.simulation.spawnCharacter(1, character);
169 const worker = workerOf(harness.simulation, playerId);
170 setSkillLevel(worker, playerId, SkillId.fishing, 1);
171 placeFishingSpot(worker, 9, 8, [rawFishItemId("minnow")], GroundType.water);
172 giveInventory(harness, playerId, [
173 { itemId: FishingToolItemId.net, quantity: 1 }
174 ]);
175
176 harness.simulation.enqueue(1, {
177 type: "start-fish",
178 characterId: character.character_id,
179 tileX: 9,
180 tileY: 8
181 });
182 const result = harness.simulation.step();
183 assert.ok(result.events.some((e) => e.type === "command-error"));
184 assert.equal(worker.world.fishSessions.size, 0);
185 }
186 finally
187 { harness.close(); }
188});
189
190test("pole + yarn recipes: log makes pole, pole+2 yarn makes rod", () =>
191{
192 const pole = itemDefinition(FishingToolItemId.birchPole);
193 const rod = itemDefinition(FishingToolItemId.birchRod);
194 assert.equal(pole?.fishingPole, true);
195 assert.equal(rod?.poleItemId, FishingToolItemId.birchPole);
196 assert.equal(rod?.equipment?.kind, EquipmentKind.fishingRod);
197 assert.equal(pole?.equipment, undefined);
198});
199
200test("failed rod fishing can snap the line into pole + yarn", () =>
201{
202 const harness = makeSimulation({ workerCount: 1 });
203 try
204 {
205 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
206 const playerId = harness.simulation.spawnCharacter(1, character);
207 const worker = workerOf(harness.simulation, playerId);
208 // Always fail skill rolls (0) and always snap the line (0 < 0.05).
209 worker.world.rng = () => 0;
210 setSkillLevel(worker, playerId, SkillId.fishing, 10);
211 const perch = rawFishItemId("perch");
212 placeFishingSpot(worker, 9, 8, [perch]);
213 const maggots = baitItemIdForCloth(ClothTier.wool);
214 giveInventory(harness, playerId, [
215 { itemId: FishingToolItemId.birchRod, quantity: 1 },
216 { itemId: maggots, quantity: 1 }
217 ]);
218
219 harness.simulation.enqueue(1, {
220 type: "start-fish",
221 characterId: character.character_id,
222 tileX: 9,
223 tileY: 8
224 });
225 const events = [];
226 const ticks = Math.ceil(12_000 / 50) + 5;
227 for (let i = 0; i < ticks; i++)
228 {
229 harness.advance(50);
230 const step = harness.simulation.step();
231 events.push(...(step.events ?? []));
232 }
233
234 assert.ok(events.some((e) => e.type === "command-error" && e.message === "The fish got away."));
235 assert.ok(events.some((e) => e.type === "command-error" && e.message === "Your fishing line broke!"));
236 const bag = harness.simulation.bagOf(playerId);
237 assert.equal(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchRod), false);
238 assert.ok(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchPole), "expected pole");
239 assert.ok(bag.inventory.some((s) => s?.itemId === yarnItemId(ClothTier.wool)), "expected wool yarn");
240 }
241 finally
242 { harness.close(); }
243});
244
245test("line-break yarn drops to ground when bag is full", () =>
246{
247 const harness = makeSimulation({ workerCount: 1 });
248 try
249 {
250 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
251 const playerId = harness.simulation.spawnCharacter(1, character);
252 const worker = workerOf(harness.simulation, playerId);
253 worker.world.rng = () => 0;
254 setSkillLevel(worker, playerId, SkillId.fishing, 10);
255 const perch = rawFishItemId("perch");
256 placeFishingSpot(worker, 9, 8, [perch]);
257 const maggots = baitItemIdForCloth(ClothTier.wool);
258 const yarn = yarnItemId(ClothTier.wool);
259 // Rod equipped; bag full except bait (consumed on start → one free slot for pole only).
260 const slots = emptySlots();
261 slots[0] = { itemId: maggots, quantity: 1 };
262 for (let i = 1; i < slots.length; i++)
263 { slots[i] = { itemId: rawFishItemId("minnow"), quantity: 1 }; }
264 const equipment = emptyEquipment();
265 equipment.slots.weapon = { itemId: FishingToolItemId.birchRod, quantity: 1 };
266 harness.simulation.applyBag(playerId, {
267 inventory: slots,
268 equipment,
269 vault: [],
270 vaultReserved: []
271 });
272
273 harness.simulation.enqueue(1, {
274 type: "start-fish",
275 characterId: character.character_id,
276 tileX: 9,
277 tileY: 8
278 });
279 const events = [];
280 const ticks = Math.ceil(12_000 / 50) + 5;
281 for (let i = 0; i < ticks; i++)
282 {
283 harness.advance(50);
284 const step = harness.simulation.step();
285 events.push(...(step.events ?? []));
286 }
287
288 assert.ok(events.some((e) => e.message === "Your fishing line broke!"));
289 const bag = harness.simulation.bagOf(playerId);
290 assert.ok(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchPole));
291 assert.equal(bag.equipment?.slots?.weapon, null);
292 assert.equal(bag.inventory.some((s) => s?.itemId === yarn), false);
293 assert.ok(events.some((e) =>
294 e.type === "ground-item-appear" && e.stack?.itemId === yarn
295 ), "yarn should appear on the ground");
296 }
297 finally
298 { harness.close(); }
299});
shared/crafting/stationRecipes.js +15 −1
@@ -14,6 +14,7 @@ import {
14 14 tierCraftSkillLevel
15 15 } from "../definitions/materialTiers.js";
16 16 import { TIER_FAMILY_RECIPES } from "./tierRecipes.js";
17 import { fishingToolRecipes, fishingCookRecipes } from "../definitions/fishItems.js";
17 18
18 19 /**
19 20 * Craft recipe schema (shared client + server):
@@ -179,7 +180,20 @@ export const CRAFT_RECIPES = Object.freeze([
179 180 minSkillLevel: tierCraftSkillLevel(LeatherTier.reinforcedLeather),
180 181 skillId: "leatherworking",
181 182 xpMaterial: LeatherTier.reinforcedLeather
182 })
183 }),
184
185 Object.freeze({
186 recipeId: "cook-venison",
187 stationIds: [CraftingStationId.oven, CraftingStationId.fireplace],
188 output: { itemId: CraftingItemId.cookedMeat, quantity: 1 },
189 inputs: [{ itemId: CraftingItemId.rawMeat, quantity: 1 }],
190 minSkillLevel: 1,
191 skillId: "cooking",
192 burntOutput: { itemId: CraftingItemId.burntMeat, quantity: 1 }
193 }),
194
195 ...fishingToolRecipes(),
196 ...fishingCookRecipes()
183 197 ]);
184 198
185 199 const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
@@ -14,6 +14,7 @@ import {
14 tierCraftSkillLevel
14 tierCraftSkillLevel
15} from "../definitions/materialTiers.js";
15} from "../definitions/materialTiers.js";
16import { TIER_FAMILY_RECIPES } from "./tierRecipes.js";
16import { TIER_FAMILY_RECIPES } from "./tierRecipes.js";
17import { fishingToolRecipes, fishingCookRecipes } from "../definitions/fishItems.js";
17
18
18/**
19/**
19 * Craft recipe schema (shared client + server):
20 * Craft recipe schema (shared client + server):
@@ -179,7 +180,20 @@ export const CRAFT_RECIPES = Object.freeze([
179 minSkillLevel: tierCraftSkillLevel(LeatherTier.reinforcedLeather),
180 minSkillLevel: tierCraftSkillLevel(LeatherTier.reinforcedLeather),
180 skillId: "leatherworking",
181 skillId: "leatherworking",
181 xpMaterial: LeatherTier.reinforcedLeather
182 xpMaterial: LeatherTier.reinforcedLeather
182 })
183 }),
184
185 Object.freeze({
186 recipeId: "cook-venison",
187 stationIds: [CraftingStationId.oven, CraftingStationId.fireplace],
188 output: { itemId: CraftingItemId.cookedMeat, quantity: 1 },
189 inputs: [{ itemId: CraftingItemId.rawMeat, quantity: 1 }],
190 minSkillLevel: 1,
191 skillId: "cooking",
192 burntOutput: { itemId: CraftingItemId.burntMeat, quantity: 1 }
193 }),
194
195 ...fishingToolRecipes(),
196 ...fishingCookRecipes()
183]);
197]);
184
198
185const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
199const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
shared/definitions/craftingItems.js +91 −22
@@ -1,30 +1,54 @@
1 1 import { ItemCategory } from "./itemCategories.js";
2 2 import { MaterialTier, GatherMaterialId } from "./materialTiers.js";
3 import { StatusEffectType } from "../statusEffects/rules.js";
3 4
4 5 const DEFAULT_STACK = 99;
5 6
7 /** Default spark charges on a fresh tinderbox. */
8 export const TINDERBOX_MAX_CHARGES = 20;
9
6 10 /**
7 11 * Reserved numeric IDs for gathering, crafting, and cooking content (9–25).
8 12 * Metal ores/bars/pickaxes above bronze live in metalItems.js (35+).
9 13 * IDs 11 / 12 / 25 are cotton fibre / yarn / cloth (see clothItems.js).
14 * Burnt venison uses 280; ash tiers live in woodItems.js (281+).
10 15 */
11 16 export const CraftingItemId = Object.freeze({
12 17 tinderbox: 10,
13 18 copperOre: 13,
14 19 bronzeBar: 14,
20 /** Uncooked Venison */
15 21 rawMeat: 15,
22 /** Cooked Venison */
16 23 cookedMeat: 16,
17 24 leather: 17,
18 25 arrowTip: 18,
19 26 arrow: 19,
20 27 bronzeAxe: 20,
21 28 bronzePickaxe: 21,
22 fishingRod: 22,
23 fishingNet: 23,
24 rawFish: 24,
25 tinOre: 53
29 tinOre: 53,
30 burntMeat: 280
31 });
32
33 /** Magenta cookable base; tinted per cook state. */
34 const VENISON_COOK_COLORS = Object.freeze({
35 raw: Object.freeze({ r: 0.72, g: 0.28, b: 0.32 }),
36 cooked: Object.freeze({ r: 0.55, g: 0.32, b: 0.18 }),
37 burnt: Object.freeze({ r: 0.18, g: 0.14, b: 0.12 })
26 38 });
27 39
40 /**
41 * Fresh tinderbox instance payload (charges, not potion fill 1–5).
42 * @param {number} [charges]
43 */
44 export function tinderboxItemInstance (charges = TINDERBOX_MAX_CHARGES)
45 {
46 return Object.freeze({
47 kind: "tinderbox",
48 charges: Math.max(0, Math.min(TINDERBOX_MAX_CHARGES, charges | 0 || TINDERBOX_MAX_CHARGES))
49 });
50 }
51
28 52 function stub (itemId, key, displayName, category, extra = {})
29 53 {
30 54 return Object.freeze({
@@ -45,10 +69,19 @@ function stub (itemId, key, displayName, category, extra = {})
45 69
46 70 /** Minimal defs so recipes and the craft UI can resolve names/icons before art exists. */
47 71 export const CRAFTING_ITEM_STUBS = Object.freeze({
48 [CraftingItemId.tinderbox]: stub(CraftingItemId.tinderbox, "tinderbox", "Tinderbox", ItemCategory.tool, {
72 [CraftingItemId.tinderbox]: Object.freeze({
73 itemId: CraftingItemId.tinderbox,
74 key: "tinderbox",
75 displayName: "Tinderbox",
76 description: "A flint and steel kit for coaxing sparks onto dry wood.",
77 seedValue: 8,
49 78 stackable: false,
50 79 maxStackSize: 1,
51 description: "A small kit for striking sparks onto dry tinder."
80 uniqueInstance: true,
81 category: ItemCategory.tool,
82 iconKey: "tinderbox",
83 npcShopAllowed: true,
84 defaultInstance: tinderboxItemInstance()
52 85 }),
53 86 [CraftingItemId.copperOre]: Object.freeze({
54 87 itemId: CraftingItemId.copperOre,
@@ -95,23 +128,59 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
95 128 tier: MaterialTier.bronze,
96 129 tintFromTier: true
97 130 }),
98 [CraftingItemId.rawMeat]: stub(CraftingItemId.rawMeat, "raw-meat", "Raw meat", ItemCategory.ingredient, {
99 description: "Fresh meat. Cook at an oven or campfire."
100 }),
101 [CraftingItemId.cookedMeat]: stub(CraftingItemId.cookedMeat, "cooked-meat", "Cooked meat", ItemCategory.food, {
102 description: "Meat roasted until tender."
103 }),
104 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
105 stackable: false,
106 maxStackSize: 1,
107 description: "A simple rod and line for still waters."
131 [CraftingItemId.rawMeat]: Object.freeze({
132 itemId: CraftingItemId.rawMeat,
133 key: "uncooked-venison",
134 displayName: "Uncooked Venison",
135 description: "Fresh deer meat. Cook at an oven or campfire.",
136 seedValue: 3,
137 stackable: true,
138 maxStackSize: DEFAULT_STACK,
139 uniqueInstance: false,
140 category: ItemCategory.ingredient,
141 iconKey: "meat",
142 defaultState: "raw",
143 cookable: true,
144 cookState: "raw",
145 burntItemId: CraftingItemId.burntMeat,
146 tint: VENISON_COOK_COLORS.raw
108 147 }),
109 [CraftingItemId.fishingNet]: stub(CraftingItemId.fishingNet, "fishing-net", "Fishing net", ItemCategory.tool, {
110 stackable: false,
111 maxStackSize: 1,
112 description: "A woven net for scooping fish."
148 [CraftingItemId.cookedMeat]: Object.freeze({
149 itemId: CraftingItemId.cookedMeat,
150 key: "cooked-venison",
151 displayName: "Cooked Venison",
152 description: "Roasted deer meat, still warm from the fire.",
153 seedValue: 4,
154 stackable: true,
155 maxStackSize: DEFAULT_STACK,
156 uniqueInstance: false,
157 category: ItemCategory.food,
158 iconKey: "meat",
159 defaultState: "cooked",
160 cookable: true,
161 cookState: "cooked",
162 tint: VENISON_COOK_COLORS.cooked,
163 healing: 5,
164 eatStatusEffect: Object.freeze({
165 type: StatusEffectType.healthRegen,
166 amountPerSecond: 1,
167 durationMs: 5_000
168 })
113 169 }),
114 [CraftingItemId.rawFish]: stub(CraftingItemId.rawFish, "raw-fish", "Raw fish", ItemCategory.ingredient, {
115 description: "A fresh catch. Cook at an oven or campfire."
170 [CraftingItemId.burntMeat]: Object.freeze({
171 itemId: CraftingItemId.burntMeat,
172 key: "burnt-venison",
173 displayName: "Burnt Venison",
174 description: "Charred beyond saving — little more than a bitter lump.",
175 seedValue: 1,
176 stackable: true,
177 maxStackSize: DEFAULT_STACK,
178 uniqueInstance: false,
179 category: ItemCategory.food,
180 iconKey: "meat",
181 defaultState: "burnt",
182 cookable: true,
183 cookState: "burnt",
184 tint: VENISON_COOK_COLORS.burnt
116 185 })
117 186 });
@@ -1,30 +1,54 @@
1import { ItemCategory } from "./itemCategories.js";
1import { ItemCategory } from "./itemCategories.js";
2import { MaterialTier, GatherMaterialId } from "./materialTiers.js";
2import { MaterialTier, GatherMaterialId } from "./materialTiers.js";
3import { StatusEffectType } from "../statusEffects/rules.js";
3
4
4const DEFAULT_STACK = 99;
5const DEFAULT_STACK = 99;
5
6
7/** Default spark charges on a fresh tinderbox. */
8export const TINDERBOX_MAX_CHARGES = 20;
9
6/**
10/**
7 * Reserved numeric IDs for gathering, crafting, and cooking content (9–25).
11 * Reserved numeric IDs for gathering, crafting, and cooking content (9–25).
8 * Metal ores/bars/pickaxes above bronze live in metalItems.js (35+).
12 * Metal ores/bars/pickaxes above bronze live in metalItems.js (35+).
9 * IDs 11 / 12 / 25 are cotton fibre / yarn / cloth (see clothItems.js).
13 * IDs 11 / 12 / 25 are cotton fibre / yarn / cloth (see clothItems.js).
14 * Burnt venison uses 280; ash tiers live in woodItems.js (281+).
10 */
15 */
11export const CraftingItemId = Object.freeze({
16export const CraftingItemId = Object.freeze({
12 tinderbox: 10,
17 tinderbox: 10,
13 copperOre: 13,
18 copperOre: 13,
14 bronzeBar: 14,
19 bronzeBar: 14,
20 /** Uncooked Venison */
15 rawMeat: 15,
21 rawMeat: 15,
22 /** Cooked Venison */
16 cookedMeat: 16,
23 cookedMeat: 16,
17 leather: 17,
24 leather: 17,
18 arrowTip: 18,
25 arrowTip: 18,
19 arrow: 19,
26 arrow: 19,
20 bronzeAxe: 20,
27 bronzeAxe: 20,
21 bronzePickaxe: 21,
28 bronzePickaxe: 21,
22 fishingRod: 22,
29 tinOre: 53,
23 fishingNet: 23,
30 burntMeat: 280
24 rawFish: 24,
31});
25 tinOre: 53
32
33/** Magenta cookable base; tinted per cook state. */
34const VENISON_COOK_COLORS = Object.freeze({
35 raw: Object.freeze({ r: 0.72, g: 0.28, b: 0.32 }),
36 cooked: Object.freeze({ r: 0.55, g: 0.32, b: 0.18 }),
37 burnt: Object.freeze({ r: 0.18, g: 0.14, b: 0.12 })
26});
38});
27
39
40/**
41 * Fresh tinderbox instance payload (charges, not potion fill 1–5).
42 * @param {number} [charges]
43 */
44export function tinderboxItemInstance (charges = TINDERBOX_MAX_CHARGES)
45{
46 return Object.freeze({
47 kind: "tinderbox",
48 charges: Math.max(0, Math.min(TINDERBOX_MAX_CHARGES, charges | 0 || TINDERBOX_MAX_CHARGES))
49 });
50}
51
28function stub (itemId, key, displayName, category, extra = {})
52function stub (itemId, key, displayName, category, extra = {})
29{
53{
30 return Object.freeze({
54 return Object.freeze({
@@ -45,10 +69,19 @@ function stub (itemId, key, displayName, category, extra = {})
45
69
46/** Minimal defs so recipes and the craft UI can resolve names/icons before art exists. */
70/** Minimal defs so recipes and the craft UI can resolve names/icons before art exists. */
47export const CRAFTING_ITEM_STUBS = Object.freeze({
71export const CRAFTING_ITEM_STUBS = Object.freeze({
48 [CraftingItemId.tinderbox]: stub(CraftingItemId.tinderbox, "tinderbox", "Tinderbox", ItemCategory.tool, {
72 [CraftingItemId.tinderbox]: Object.freeze({
73 itemId: CraftingItemId.tinderbox,
74 key: "tinderbox",
75 displayName: "Tinderbox",
76 description: "A flint and steel kit for coaxing sparks onto dry wood.",
77 seedValue: 8,
49 stackable: false,
78 stackable: false,
50 maxStackSize: 1,
79 maxStackSize: 1,
51 description: "A small kit for striking sparks onto dry tinder."
80 uniqueInstance: true,
81 category: ItemCategory.tool,
82 iconKey: "tinderbox",
83 npcShopAllowed: true,
84 defaultInstance: tinderboxItemInstance()
52 }),
85 }),
53 [CraftingItemId.copperOre]: Object.freeze({
86 [CraftingItemId.copperOre]: Object.freeze({
54 itemId: CraftingItemId.copperOre,
87 itemId: CraftingItemId.copperOre,
@@ -95,23 +128,59 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
95 tier: MaterialTier.bronze,
128 tier: MaterialTier.bronze,
96 tintFromTier: true
129 tintFromTier: true
97 }),
130 }),
98 [CraftingItemId.rawMeat]: stub(CraftingItemId.rawMeat, "raw-meat", "Raw meat", ItemCategory.ingredient, {
131 [CraftingItemId.rawMeat]: Object.freeze({
99 description: "Fresh meat. Cook at an oven or campfire."
132 itemId: CraftingItemId.rawMeat,
100 }),
133 key: "uncooked-venison",
101 [CraftingItemId.cookedMeat]: stub(CraftingItemId.cookedMeat, "cooked-meat", "Cooked meat", ItemCategory.food, {
134 displayName: "Uncooked Venison",
102 description: "Meat roasted until tender."
135 description: "Fresh deer meat. Cook at an oven or campfire.",
103 }),
136 seedValue: 3,
104 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
137 stackable: true,
105 stackable: false,
138 maxStackSize: DEFAULT_STACK,
106 maxStackSize: 1,
139 uniqueInstance: false,
107 description: "A simple rod and line for still waters."
140 category: ItemCategory.ingredient,
141 iconKey: "meat",
142 defaultState: "raw",
143 cookable: true,
144 cookState: "raw",
145 burntItemId: CraftingItemId.burntMeat,
146 tint: VENISON_COOK_COLORS.raw
108 }),
147 }),
109 [CraftingItemId.fishingNet]: stub(CraftingItemId.fishingNet, "fishing-net", "Fishing net", ItemCategory.tool, {
148 [CraftingItemId.cookedMeat]: Object.freeze({
110 stackable: false,
149 itemId: CraftingItemId.cookedMeat,
111 maxStackSize: 1,
150 key: "cooked-venison",
112 description: "A woven net for scooping fish."
151 displayName: "Cooked Venison",
152 description: "Roasted deer meat, still warm from the fire.",
153 seedValue: 4,
154 stackable: true,
155 maxStackSize: DEFAULT_STACK,
156 uniqueInstance: false,
157 category: ItemCategory.food,
158 iconKey: "meat",
159 defaultState: "cooked",
160 cookable: true,
161 cookState: "cooked",
162 tint: VENISON_COOK_COLORS.cooked,
163 healing: 5,
164 eatStatusEffect: Object.freeze({
165 type: StatusEffectType.healthRegen,
166 amountPerSecond: 1,
167 durationMs: 5_000
168 })
113 }),
169 }),
114 [CraftingItemId.rawFish]: stub(CraftingItemId.rawFish, "raw-fish", "Raw fish", ItemCategory.ingredient, {
170 [CraftingItemId.burntMeat]: Object.freeze({
115 description: "A fresh catch. Cook at an oven or campfire."
171 itemId: CraftingItemId.burntMeat,
172 key: "burnt-venison",
173 displayName: "Burnt Venison",
174 description: "Charred beyond saving — little more than a bitter lump.",
175 seedValue: 1,
176 stackable: true,
177 maxStackSize: DEFAULT_STACK,
178 uniqueInstance: false,
179 category: ItemCategory.food,
180 iconKey: "meat",
181 defaultState: "burnt",
182 cookable: true,
183 cookState: "burnt",
184 tint: VENISON_COOK_COLORS.burnt
116 })
185 })
117});
186});
shared/definitions/craftingStations.js +39 −1
@@ -1,4 +1,12 @@
1 1 import { SkillId } from "./skills.js";
2 import { WOOD_TIER_ORDER } from "./materialTiers.js";
3
4 /** 1-based rank in wood tier order (pine = 1 … elder = 7). */
5 export function woodTierRank (woodTier)
6 {
7 const idx = WOOD_TIER_ORDER.indexOf(woodTier);
8 return idx >= 0 ? idx + 1 : 1;
9 }
2 10
3 11 /** Placeable or fixed world stations that gate recipes (blocks / ground objects later). */
4 12 export const CraftingStationId = Object.freeze({
@@ -14,9 +22,39 @@ export const CraftingStationId = Object.freeze({
14 22 fireplace: "fireplace"
15 23 });
16 24
17 /** How long a player-lit campfire stays usable (ms). */
25 /** Legacy fixed duration; prefer {@link campfireDurationMs}. */
18 26 export const FIREPLACE_DURATION_MS = 10 * 60 * 1000;
19 27
28 /** Base duration per wood-tier rank (3 minutes × rank). */
29 export const CAMPFIRE_DURATION_PER_RANK_MS = 3 * 60_000;
30
31 /** Burn chance when cooking on an oven (0–1). */
32 export const COOK_BURN_CHANCE_OVEN = 0.10;
33
34 /** Burn chance when cooking on a campfire (0–1). */
35 export const COOK_BURN_CHANCE_CAMPFIRE = 0.35;
36
37 /**
38 * Campfire lifetime from the wood tier used to light it.
39 * @param {string|number} woodTierOrRank wood tier id or 1-based rank
40 */
41 export function campfireDurationMs (woodTierOrRank)
42 {
43 const rank = typeof woodTierOrRank === "number"
44 ? Math.max(1, woodTierOrRank | 0)
45 : Math.max(1, woodTierRank(woodTierOrRank));
46 return CAMPFIRE_DURATION_PER_RANK_MS * rank;
47 }
48
49 /**
50 * Firestarting difficulty for a wood log tier: max((rank - 1) * 10, 1).
51 */
52 export function firestartingDifficulty (woodTier)
53 {
54 const rank = woodTierRank(woodTier);
55 return Math.max((rank - 1) * 10, 1);
56 }
57
20 58 /** Fixed craft action duration at any station (ms). */
21 59 export const CRAFT_DURATION_MS = 2000;
22 60
@@ -1,4 +1,12 @@
1import { SkillId } from "./skills.js";
1import { SkillId } from "./skills.js";
2import { WOOD_TIER_ORDER } from "./materialTiers.js";
3
4/** 1-based rank in wood tier order (pine = 1 … elder = 7). */
5export function woodTierRank (woodTier)
6{
7 const idx = WOOD_TIER_ORDER.indexOf(woodTier);
8 return idx >= 0 ? idx + 1 : 1;
9}
2
10
3/** Placeable or fixed world stations that gate recipes (blocks / ground objects later). */
11/** Placeable or fixed world stations that gate recipes (blocks / ground objects later). */
4export const CraftingStationId = Object.freeze({
12export const CraftingStationId = Object.freeze({
@@ -14,9 +22,39 @@ export const CraftingStationId = Object.freeze({
14 fireplace: "fireplace"
22 fireplace: "fireplace"
15});
23});
16
24
17/** How long a player-lit campfire stays usable (ms). */
25/** Legacy fixed duration; prefer {@link campfireDurationMs}. */
18export const FIREPLACE_DURATION_MS = 10 * 60 * 1000;
26export const FIREPLACE_DURATION_MS = 10 * 60 * 1000;
19
27
28/** Base duration per wood-tier rank (3 minutes × rank). */
29export const CAMPFIRE_DURATION_PER_RANK_MS = 3 * 60_000;
30
31/** Burn chance when cooking on an oven (0–1). */
32export const COOK_BURN_CHANCE_OVEN = 0.10;
33
34/** Burn chance when cooking on a campfire (0–1). */
35export const COOK_BURN_CHANCE_CAMPFIRE = 0.35;
36
37/**
38 * Campfire lifetime from the wood tier used to light it.
39 * @param {string|number} woodTierOrRank wood tier id or 1-based rank
40 */
41export function campfireDurationMs (woodTierOrRank)
42{
43 const rank = typeof woodTierOrRank === "number"
44 ? Math.max(1, woodTierOrRank | 0)
45 : Math.max(1, woodTierRank(woodTierOrRank));
46 return CAMPFIRE_DURATION_PER_RANK_MS * rank;
47}
48
49/**
50 * Firestarting difficulty for a wood log tier: max((rank - 1) * 10, 1).
51 */
52export function firestartingDifficulty (woodTier)
53{
54 const rank = woodTierRank(woodTier);
55 return Math.max((rank - 1) * 10, 1);
56}
57
20/** Fixed craft action duration at any station (ms). */
58/** Fixed craft action duration at any station (ms). */
21export const CRAFT_DURATION_MS = 2000;
59export const CRAFT_DURATION_MS = 2000;
22
60
shared/definitions/fishItems.js added +529 −0
@@ -0,0 +1,529 @@
1 import { ItemCategory } from "./itemCategories.js";
2 import {
3 ClothTier,
4 CLOTH_TIER_ORDER,
5 CLOTH_DISPLAY_NAME,
6 WoodTier,
7 WOOD_TIER_ORDER,
8 MATERIAL_DISPLAY_NAME,
9 tierRank,
10 tierMinSkillLevel,
11 clothTierForWood
12 } from "./materialTiers.js";
13 import { EquipmentKind } from "./equipmentKinds.js";
14 import { SkillId } from "./skills.js";
15 import { CraftingStationId } from "./craftingStations.js";
16 import { yarnItemId } from "./clothItems.js";
17 import { logItemIdForWood } from "./woodItems.js";
18
19 const DEFAULT_STACK = 99;
20
21 /**
22 * Fish species keyed by stable id. `tier` is cloth/wood rank 1–7.
23 * Item IDs: raw / cooked / burnt are allocated in {@link FISH_ITEM_IDS}.
24 */
25 export const FISH_SPECIES = Object.freeze({
26 minnow: Object.freeze({ key: "minnow", displayName: "Minnow", tier: 1 }),
27 guppy: Object.freeze({ key: "guppy", displayName: "Guppy", tier: 1 }),
28 shrimp: Object.freeze({ key: "shrimp", displayName: "Shrimp", tier: 1 }),
29 anchovies: Object.freeze({ key: "anchovies", displayName: "Anchovies", tier: 1 }),
30 sardine: Object.freeze({ key: "sardine", displayName: "Sardine", tier: 1 }),
31 perch: Object.freeze({ key: "perch", displayName: "Perch", tier: 2 }),
32 herring: Object.freeze({ key: "herring", displayName: "Herring", tier: 2 }),
33 crab: Object.freeze({ key: "crab", displayName: "Crab", tier: 2 }),
34 trout: Object.freeze({ key: "trout", displayName: "Trout", tier: 3 }),
35 cod: Object.freeze({ key: "cod", displayName: "Cod", tier: 3 }),
36 bass: Object.freeze({ key: "bass", displayName: "Bass", tier: 3 }),
37 pike: Object.freeze({ key: "pike", displayName: "Pike", tier: 4 }),
38 squid: Object.freeze({ key: "squid", displayName: "Squid", tier: 4 }),
39 salmon: Object.freeze({ key: "salmon", displayName: "Salmon", tier: 5 }),
40 tuna: Object.freeze({ key: "tuna", displayName: "Tuna", tier: 5 }),
41 lobster: Object.freeze({ key: "lobster", displayName: "Lobster", tier: 5 }),
42 sturgeon: Object.freeze({ key: "sturgeon", displayName: "Sturgeon", tier: 6 }),
43 swordfish: Object.freeze({ key: "swordfish", displayName: "Swordfish", tier: 6 }),
44 giantKrill: Object.freeze({ key: "giant-krill", displayName: "Giant Krill", tier: 6 }),
45 marlin: Object.freeze({ key: "marlin", displayName: "Marlin", tier: 7 }),
46 shark: Object.freeze({ key: "shark", displayName: "Shark", tier: 7 })
47 });
48
49 export const FISH_SPECIES_ORDER = Object.freeze(Object.keys(FISH_SPECIES));
50
51 /** Magenta cook tints vary slightly per species (hue shift from tier). */
52 function fishCookColors (tier)
53 {
54 const t = (tier - 1) / 6;
55 return Object.freeze({
56 raw: Object.freeze({ r: 0.45 + t * 0.2, g: 0.55 + t * 0.1, b: 0.72 - t * 0.15 }),
57 cooked: Object.freeze({ r: 0.55 + t * 0.15, g: 0.38 + t * 0.05, b: 0.22 }),
58 burnt: Object.freeze({ r: 0.16, g: 0.13, b: 0.11 })
59 });
60 }
61
62 /** Allocated from 288 upward: each species gets raw, cooked, burnt. */
63 const FISH_ITEM_IDS = (() =>
64 {
65 const out = {};
66 let next = 288;
67 for (const speciesId of FISH_SPECIES_ORDER)
68 {
69 out[speciesId] = Object.freeze({
70 raw: next++,
71 cooked: next++,
72 burnt: next++
73 });
74 }
75 return Object.freeze(out);
76 })();
77
78 export function fishSpeciesDefinition (speciesId)
79 {
80 return FISH_SPECIES[speciesId] ?? null;
81 }
82
83 export function fishItemIdsForSpecies (speciesId)
84 {
85 return FISH_ITEM_IDS[speciesId] ?? null;
86 }
87
88 export function rawFishItemId (speciesId)
89 {
90 return FISH_ITEM_IDS[speciesId]?.raw ?? null;
91 }
92
93 export function cookedFishItemId (speciesId)
94 {
95 return FISH_ITEM_IDS[speciesId]?.cooked ?? null;
96 }
97
98 export function burntFishItemId (speciesId)
99 {
100 return FISH_ITEM_IDS[speciesId]?.burnt ?? null;
101 }
102
103 /** Resolve species id from any cook-state item id. */
104 export function fishSpeciesIdFromItemId (itemId)
105 {
106 const id = itemId | 0;
107 for (const speciesId of FISH_SPECIES_ORDER)
108 {
109 const ids = FISH_ITEM_IDS[speciesId];
110 if (ids.raw === id || ids.cooked === id || ids.burnt === id)
111 { return speciesId; }
112 }
113 return null;
114 }
115
116 export function fishTierRankFromItemId (itemId)
117 {
118 const speciesId = fishSpeciesIdFromItemId(itemId);
119 if (!speciesId)
120 { return 0; }
121 return FISH_SPECIES[speciesId].tier | 0;
122 }
123
124 function buildFishItemDefinitions ()
125 {
126 const out = {};
127 for (const speciesId of FISH_SPECIES_ORDER)
128 {
129 const species = FISH_SPECIES[speciesId];
130 const ids = FISH_ITEM_IDS[speciesId];
131 const colors = fishCookColors(species.tier);
132 const heal = species.tier * 5;
133 const clothTier = CLOTH_TIER_ORDER[species.tier - 1] ?? ClothTier.cotton;
134
135 out[ids.raw] = Object.freeze({
136 itemId: ids.raw,
137 key: `uncooked-${species.key}`,
138 displayName: `Uncooked ${species.displayName}`,
139 description: `Fresh ${species.displayName.toLowerCase()}. Cook at an oven or campfire.`,
140 seedValue: species.tier,
141 stackable: true,
142 maxStackSize: DEFAULT_STACK,
143 uniqueInstance: false,
144 category: ItemCategory.ingredient,
145 iconKey: "meat",
146 defaultState: "raw",
147 cookable: true,
148 cookState: "raw",
149 fishSpeciesId: speciesId,
150 fishTier: species.tier,
151 tier: clothTier,
152 burntItemId: ids.burnt,
153 tint: colors.raw,
154 npcShopAllowed: true
155 });
156 out[ids.cooked] = Object.freeze({
157 itemId: ids.cooked,
158 key: `cooked-${species.key}`,
159 displayName: `Cooked ${species.displayName}`,
160 description: `Roasted ${species.displayName.toLowerCase()}, ready to eat.`,
161 seedValue: species.tier + 1,
162 stackable: true,
163 maxStackSize: DEFAULT_STACK,
164 uniqueInstance: false,
165 category: ItemCategory.food,
166 iconKey: "meat",
167 defaultState: "cooked",
168 cookable: true,
169 cookState: "cooked",
170 fishSpeciesId: speciesId,
171 fishTier: species.tier,
172 tier: clothTier,
173 tint: colors.cooked,
174 healing: heal,
175 npcShopAllowed: true
176 });
177 out[ids.burnt] = Object.freeze({
178 itemId: ids.burnt,
179 key: `burnt-${species.key}`,
180 displayName: `Burnt ${species.displayName}`,
181 description: `Charred ${species.displayName.toLowerCase()} — inedible.`,
182 seedValue: 1,
183 stackable: true,
184 maxStackSize: DEFAULT_STACK,
185 uniqueInstance: false,
186 category: ItemCategory.food,
187 iconKey: "meat",
188 defaultState: "burnt",
189 cookable: true,
190 cookState: "burnt",
191 fishSpeciesId: speciesId,
192 fishTier: species.tier,
193 tier: clothTier,
194 tint: colors.burnt
195 });
196 }
197 return out;
198 }
199
200 /** Bait display names by cloth tier (rank 1–7). */
201 const BAIT_NAMES = Object.freeze({
202 [ClothTier.cotton]: "Worms",
203 [ClothTier.wool]: "Maggots",
204 [ClothTier.linen]: "Crickets",
205 [ClothTier.cashmere]: "Leeches",
206 [ClothTier.silk]: "Roe",
207 [ClothTier.fairySilk]: "Glowworms",
208 [ClothTier.dragonweave]: "Fairy flies"
209 });
210
211 /** Bait item IDs by cloth tier (358+). */
212 export const BaitItemId = Object.freeze({
213 [ClothTier.cotton]: 358,
214 [ClothTier.wool]: 359,
215 [ClothTier.linen]: 360,
216 [ClothTier.cashmere]: 361,
217 [ClothTier.silk]: 362,
218 [ClothTier.fairySilk]: 363,
219 [ClothTier.dragonweave]: 364
220 });
221
222 export function baitItemIdForCloth (clothTier)
223 {
224 return BaitItemId[clothTier] ?? null;
225 }
226
227 export function baitItemIdForRank (rank)
228 {
229 const cloth = CLOTH_TIER_ORDER[(rank | 0) - 1];
230 return cloth ? BaitItemId[cloth] : null;
231 }
232
233 function buildBaitDefinitions ()
234 {
235 const out = {};
236 for (const clothTier of CLOTH_TIER_ORDER)
237 {
238 const itemId = BaitItemId[clothTier];
239 const name = BAIT_NAMES[clothTier] ?? `${CLOTH_DISPLAY_NAME[clothTier]} bait`;
240 out[itemId] = Object.freeze({
241 itemId,
242 key: `${clothTier}-bait`,
243 displayName: name,
244 description: `Bait for a fishing rod. Attracts fish up to this grade.`,
245 seedValue: tierRank(clothTier),
246 stackable: true,
247 maxStackSize: DEFAULT_STACK,
248 uniqueInstance: false,
249 category: ItemCategory.ingredient,
250 iconKey: "bait",
251 defaultState: "bait",
252 tier: clothTier,
253 tintFromTier: true,
254 bait: true,
255 npcShopAllowed: true
256 });
257 }
258 return out;
259 }
260
261 /**
262 * Fishing tools.
263 * Net = tier 1 (id 23). Poles + rods from birch…elder (tier 2–7).
264 * Pole = unstrung; rod = pole + line (usable).
265 */
266 export const FishingToolItemId = Object.freeze({
267 net: 23,
268 birchRod: 365,
269 oakRod: 366,
270 ebonyRod: 367,
271 lignumRod: 368,
272 heartwoodRod: 369,
273 elderRod: 370,
274 birchPole: 371,
275 oakPole: 372,
276 ebonyPole: 373,
277 lignumPole: 374,
278 heartwoodPole: 375,
279 elderPole: 376
280 });
281
282 const ROD_BY_WOOD = Object.freeze({
283 [WoodTier.birch]: FishingToolItemId.birchRod,
284 [WoodTier.oak]: FishingToolItemId.oakRod,
285 [WoodTier.ebony]: FishingToolItemId.ebonyRod,
286 [WoodTier.lignum]: FishingToolItemId.lignumRod,
287 [WoodTier.heartwood]: FishingToolItemId.heartwoodRod,
288 [WoodTier.elder]: FishingToolItemId.elderRod
289 });
290
291 const POLE_BY_WOOD = Object.freeze({
292 [WoodTier.birch]: FishingToolItemId.birchPole,
293 [WoodTier.oak]: FishingToolItemId.oakPole,
294 [WoodTier.ebony]: FishingToolItemId.ebonyPole,
295 [WoodTier.lignum]: FishingToolItemId.lignumPole,
296 [WoodTier.heartwood]: FishingToolItemId.heartwoodPole,
297 [WoodTier.elder]: FishingToolItemId.elderPole
298 });
299
300 export function fishingRodItemIdForWood (woodTier)
301 {
302 return ROD_BY_WOOD[woodTier] ?? null;
303 }
304
305 export function fishingPoleItemIdForWood (woodTier)
306 {
307 return POLE_BY_WOOD[woodTier] ?? null;
308 }
309
310 export function woodTierFromFishingRodItemId (itemId)
311 {
312 for (const [woodTier, id] of Object.entries(ROD_BY_WOOD))
313 {
314 if (id === (itemId | 0))
315 { return woodTier; }
316 }
317 return null;
318 }
319
320 function buildToolDefinitions ()
321 {
322 const out = {};
323 out[FishingToolItemId.net] = Object.freeze({
324 itemId: FishingToolItemId.net,
325 key: "fishing-net",
326 displayName: "Fishing net",
327 description: "A cotton mesh for scooping small fish from the shallows. Needs no bait.",
328 seedValue: 6,
329 stackable: false,
330 maxStackSize: 1,
331 uniqueInstance: false,
332 category: ItemCategory.tool,
333 iconKey: "fishing-net",
334 defaultState: "fishing-net",
335 tier: ClothTier.cotton,
336 tintFromTier: true,
337 equipment: Object.freeze({
338 slot: "weapon",
339 tier: ClothTier.cotton,
340 kind: EquipmentKind.fishingNet,
341 tintFromTier: true
342 }),
343 npcShopAllowed: true
344 });
345
346 for (const woodTier of WOOD_TIER_ORDER)
347 {
348 const poleId = POLE_BY_WOOD[woodTier];
349 const rodId = ROD_BY_WOOD[woodTier];
350 if (!poleId || !rodId)
351 { continue; }
352 const woodName = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
353 const clothTier = clothTierForWood(woodTier);
354 out[poleId] = Object.freeze({
355 itemId: poleId,
356 key: `${woodTier}-fishing-pole`,
357 displayName: `${woodName} fishing pole`,
358 description: `A shaped ${woodName.toLowerCase()} pole, waiting for a fishing line.`,
359 seedValue: tierRank(woodTier),
360 stackable: false,
361 maxStackSize: 1,
362 uniqueInstance: false,
363 category: ItemCategory.intermediate,
364 iconKey: "fishing-pole",
365 defaultState: "fishing-pole",
366 tier: woodTier,
367 clothTier,
368 tintFromTier: true,
369 fishingPole: true,
370 npcShopAllowed: true
371 });
372 out[rodId] = Object.freeze({
373 itemId: rodId,
374 key: `${woodTier}-fishing-rod`,
375 displayName: `${woodName} fishing rod`,
376 description: `A ${woodName.toLowerCase()} rod strung for deeper water.`,
377 seedValue: tierRank(woodTier) * 2,
378 stackable: false,
379 maxStackSize: 1,
380 uniqueInstance: false,
381 category: ItemCategory.tool,
382 iconKey: "fishing-rod",
383 defaultState: "fishing-rod",
384 tier: woodTier,
385 clothTier,
386 tintFromTier: true,
387 fishingRod: true,
388 poleItemId: poleId,
389 equipment: Object.freeze({
390 slot: "weapon",
391 tier: woodTier,
392 kind: EquipmentKind.fishingRod,
393 tintFromTier: true
394 }),
395 npcShopAllowed: true
396 });
397 }
398 return out;
399 }
400
401 export const FISH_ITEM_DEFINITIONS = Object.freeze({
402 ...buildFishItemDefinitions(),
403 ...buildBaitDefinitions(),
404 ...buildToolDefinitions()
405 });
406
407 /** All raw fish item ids (for editor picker). */
408 export function listRawFishPickerEntries ()
409 {
410 return FISH_SPECIES_ORDER.map((speciesId) =>
411 {
412 const species = FISH_SPECIES[speciesId];
413 const itemId = FISH_ITEM_IDS[speciesId].raw;
414 return {
415 itemId,
416 speciesId,
417 displayName: `Uncooked ${species.displayName}`,
418 tier: species.tier,
419 key: `uncooked-${species.key}`
420 };
421 });
422 }
423
424 /** Normalize fishing-spot config to unique raw fish item ids. */
425 export function normalizeFishingSpotConfig (config)
426 {
427 const fishes = [];
428 const seen = new Set();
429 for (const entry of config?.fishes ?? [])
430 {
431 const itemId = typeof entry === "number" ? entry | 0 : entry?.itemId | 0;
432 if (!itemId || seen.has(itemId))
433 { continue; }
434 const speciesId = fishSpeciesIdFromItemId(itemId);
435 if (!speciesId)
436 { continue; }
437 const ids = FISH_ITEM_IDS[speciesId];
438 const rawId = ids?.raw ?? itemId;
439 if (seen.has(rawId))
440 { continue; }
441 seen.add(rawId);
442 fishes.push(rawId);
443 }
444 return { fishes };
445 }
446
447 /** Craft recipes for fishing tools. */
448 export function fishingToolRecipes ()
449 {
450 const recipes = [
451 Object.freeze({
452 recipeId: "fishing-net",
453 stationId: CraftingStationId.craftingBench,
454 output: { itemId: FishingToolItemId.net, quantity: 1 },
455 inputs: [{ itemId: yarnItemId(ClothTier.cotton), quantity: 3 }],
456 minSkillLevel: 1,
457 skillId: "crafting",
458 xpMaterial: ClothTier.cotton
459 })
460 ];
461 for (const woodTier of WOOD_TIER_ORDER)
462 {
463 const poleId = POLE_BY_WOOD[woodTier];
464 const rodId = ROD_BY_WOOD[woodTier];
465 if (!poleId || !rodId)
466 { continue; }
467 const clothTier = clothTierForWood(woodTier);
468 recipes.push(Object.freeze({
469 recipeId: `fishing-pole-${woodTier}`,
470 craftGroup: "fishing-pole",
471 craftGroupLabel: "Fishing pole",
472 stationId: CraftingStationId.woodworkingBench,
473 output: { itemId: poleId, quantity: 1 },
474 inputs: [{ itemId: logItemIdForWood(woodTier), quantity: 1 }],
475 minSkillLevel: tierMinSkillLevel(woodTier),
476 skillId: "crafting",
477 xpMaterial: woodTier
478 }));
479 recipes.push(Object.freeze({
480 recipeId: `fishing-rod-${woodTier}`,
481 craftGroup: "fishing-rod",
482 craftGroupLabel: "Fishing rod",
483 stationId: CraftingStationId.craftingBench,
484 output: { itemId: rodId, quantity: 1 },
485 inputs: [
486 { itemId: poleId, quantity: 1 },
487 { itemId: yarnItemId(clothTier), quantity: 2 }
488 ],
489 minSkillLevel: tierMinSkillLevel(woodTier),
490 skillId: "crafting",
491 xpMaterial: woodTier
492 }));
493 }
494 return recipes;
495 }
496
497 /** Cook recipes for every fish species (oven + fireplace). */
498 export function fishingCookRecipes ()
499 {
500 return FISH_SPECIES_ORDER.map((speciesId) =>
501 {
502 const ids = FISH_ITEM_IDS[speciesId];
503 const species = FISH_SPECIES[speciesId];
504 return Object.freeze({
505 recipeId: `cook-${species.key}`,
506 craftGroup: "cook-fish",
507 craftGroupLabel: "Fish",
508 stationIds: [CraftingStationId.oven, CraftingStationId.fireplace],
509 output: { itemId: ids.cooked, quantity: 1 },
510 inputs: [{ itemId: ids.raw, quantity: 1 }],
511 minSkillLevel: 1,
512 skillId: "cooking",
513 xpMaterial: CLOTH_TIER_ORDER[species.tier - 1] ?? ClothTier.cotton,
514 burntOutput: { itemId: ids.burnt, quantity: 1 }
515 });
516 });
517 }
518
519 /** Fishing roll difficulty from bait tier rank. */
520 export function fishingDifficulty (baitTierRank)
521 {
522 const rank = Math.max(1, baitTierRank | 0);
523 return Math.max((rank - 1) * 10, 1);
524 }
525
526 export function fishingExhaustDurationMs (fishTierRank)
527 {
528 return Math.max(1, fishTierRank | 0) * 10_000;
529 }
@@ -0,0 +1,529 @@
1import { ItemCategory } from "./itemCategories.js";
2import {
3 ClothTier,
4 CLOTH_TIER_ORDER,
5 CLOTH_DISPLAY_NAME,
6 WoodTier,
7 WOOD_TIER_ORDER,
8 MATERIAL_DISPLAY_NAME,
9 tierRank,
10 tierMinSkillLevel,
11 clothTierForWood
12} from "./materialTiers.js";
13import { EquipmentKind } from "./equipmentKinds.js";
14import { SkillId } from "./skills.js";
15import { CraftingStationId } from "./craftingStations.js";
16import { yarnItemId } from "./clothItems.js";
17import { logItemIdForWood } from "./woodItems.js";
18
19const DEFAULT_STACK = 99;
20
21/**
22 * Fish species keyed by stable id. `tier` is cloth/wood rank 1–7.
23 * Item IDs: raw / cooked / burnt are allocated in {@link FISH_ITEM_IDS}.
24 */
25export const FISH_SPECIES = Object.freeze({
26 minnow: Object.freeze({ key: "minnow", displayName: "Minnow", tier: 1 }),
27 guppy: Object.freeze({ key: "guppy", displayName: "Guppy", tier: 1 }),
28 shrimp: Object.freeze({ key: "shrimp", displayName: "Shrimp", tier: 1 }),
29 anchovies: Object.freeze({ key: "anchovies", displayName: "Anchovies", tier: 1 }),
30 sardine: Object.freeze({ key: "sardine", displayName: "Sardine", tier: 1 }),
31 perch: Object.freeze({ key: "perch", displayName: "Perch", tier: 2 }),
32 herring: Object.freeze({ key: "herring", displayName: "Herring", tier: 2 }),
33 crab: Object.freeze({ key: "crab", displayName: "Crab", tier: 2 }),
34 trout: Object.freeze({ key: "trout", displayName: "Trout", tier: 3 }),
35 cod: Object.freeze({ key: "cod", displayName: "Cod", tier: 3 }),
36 bass: Object.freeze({ key: "bass", displayName: "Bass", tier: 3 }),
37 pike: Object.freeze({ key: "pike", displayName: "Pike", tier: 4 }),
38 squid: Object.freeze({ key: "squid", displayName: "Squid", tier: 4 }),
39 salmon: Object.freeze({ key: "salmon", displayName: "Salmon", tier: 5 }),
40 tuna: Object.freeze({ key: "tuna", displayName: "Tuna", tier: 5 }),
41 lobster: Object.freeze({ key: "lobster", displayName: "Lobster", tier: 5 }),
42 sturgeon: Object.freeze({ key: "sturgeon", displayName: "Sturgeon", tier: 6 }),
43 swordfish: Object.freeze({ key: "swordfish", displayName: "Swordfish", tier: 6 }),
44 giantKrill: Object.freeze({ key: "giant-krill", displayName: "Giant Krill", tier: 6 }),
45 marlin: Object.freeze({ key: "marlin", displayName: "Marlin", tier: 7 }),
46 shark: Object.freeze({ key: "shark", displayName: "Shark", tier: 7 })
47});
48
49export const FISH_SPECIES_ORDER = Object.freeze(Object.keys(FISH_SPECIES));
50
51/** Magenta cook tints vary slightly per species (hue shift from tier). */
52function fishCookColors (tier)
53{
54 const t = (tier - 1) / 6;
55 return Object.freeze({
56 raw: Object.freeze({ r: 0.45 + t * 0.2, g: 0.55 + t * 0.1, b: 0.72 - t * 0.15 }),
57 cooked: Object.freeze({ r: 0.55 + t * 0.15, g: 0.38 + t * 0.05, b: 0.22 }),
58 burnt: Object.freeze({ r: 0.16, g: 0.13, b: 0.11 })
59 });
60}
61
62/** Allocated from 288 upward: each species gets raw, cooked, burnt. */
63const FISH_ITEM_IDS = (() =>
64{
65 const out = {};
66 let next = 288;
67 for (const speciesId of FISH_SPECIES_ORDER)
68 {
69 out[speciesId] = Object.freeze({
70 raw: next++,
71 cooked: next++,
72 burnt: next++
73 });
74 }
75 return Object.freeze(out);
76})();
77
78export function fishSpeciesDefinition (speciesId)
79{
80 return FISH_SPECIES[speciesId] ?? null;
81}
82
83export function fishItemIdsForSpecies (speciesId)
84{
85 return FISH_ITEM_IDS[speciesId] ?? null;
86}
87
88export function rawFishItemId (speciesId)
89{
90 return FISH_ITEM_IDS[speciesId]?.raw ?? null;
91}
92
93export function cookedFishItemId (speciesId)
94{
95 return FISH_ITEM_IDS[speciesId]?.cooked ?? null;
96}
97
98export function burntFishItemId (speciesId)
99{
100 return FISH_ITEM_IDS[speciesId]?.burnt ?? null;
101}
102
103/** Resolve species id from any cook-state item id. */
104export function fishSpeciesIdFromItemId (itemId)
105{
106 const id = itemId | 0;
107 for (const speciesId of FISH_SPECIES_ORDER)
108 {
109 const ids = FISH_ITEM_IDS[speciesId];
110 if (ids.raw === id || ids.cooked === id || ids.burnt === id)
111 { return speciesId; }
112 }
113 return null;
114}
115
116export function fishTierRankFromItemId (itemId)
117{
118 const speciesId = fishSpeciesIdFromItemId(itemId);
119 if (!speciesId)
120 { return 0; }
121 return FISH_SPECIES[speciesId].tier | 0;
122}
123
124function buildFishItemDefinitions ()
125{
126 const out = {};
127 for (const speciesId of FISH_SPECIES_ORDER)
128 {
129 const species = FISH_SPECIES[speciesId];
130 const ids = FISH_ITEM_IDS[speciesId];
131 const colors = fishCookColors(species.tier);
132 const heal = species.tier * 5;
133 const clothTier = CLOTH_TIER_ORDER[species.tier - 1] ?? ClothTier.cotton;
134
135 out[ids.raw] = Object.freeze({
136 itemId: ids.raw,
137 key: `uncooked-${species.key}`,
138 displayName: `Uncooked ${species.displayName}`,
139 description: `Fresh ${species.displayName.toLowerCase()}. Cook at an oven or campfire.`,
140 seedValue: species.tier,
141 stackable: true,
142 maxStackSize: DEFAULT_STACK,
143 uniqueInstance: false,
144 category: ItemCategory.ingredient,
145 iconKey: "meat",
146 defaultState: "raw",
147 cookable: true,
148 cookState: "raw",
149 fishSpeciesId: speciesId,
150 fishTier: species.tier,
151 tier: clothTier,
152 burntItemId: ids.burnt,
153 tint: colors.raw,
154 npcShopAllowed: true
155 });
156 out[ids.cooked] = Object.freeze({
157 itemId: ids.cooked,
158 key: `cooked-${species.key}`,
159 displayName: `Cooked ${species.displayName}`,
160 description: `Roasted ${species.displayName.toLowerCase()}, ready to eat.`,
161 seedValue: species.tier + 1,
162 stackable: true,
163 maxStackSize: DEFAULT_STACK,
164 uniqueInstance: false,
165 category: ItemCategory.food,
166 iconKey: "meat",
167 defaultState: "cooked",
168 cookable: true,
169 cookState: "cooked",
170 fishSpeciesId: speciesId,
171 fishTier: species.tier,
172 tier: clothTier,
173 tint: colors.cooked,
174 healing: heal,
175 npcShopAllowed: true
176 });
177 out[ids.burnt] = Object.freeze({
178 itemId: ids.burnt,
179 key: `burnt-${species.key}`,
180 displayName: `Burnt ${species.displayName}`,
181 description: `Charred ${species.displayName.toLowerCase()} — inedible.`,
182 seedValue: 1,
183 stackable: true,
184 maxStackSize: DEFAULT_STACK,
185 uniqueInstance: false,
186 category: ItemCategory.food,
187 iconKey: "meat",
188 defaultState: "burnt",
189 cookable: true,
190 cookState: "burnt",
191 fishSpeciesId: speciesId,
192 fishTier: species.tier,
193 tier: clothTier,
194 tint: colors.burnt
195 });
196 }
197 return out;
198}
199
200/** Bait display names by cloth tier (rank 1–7). */
201const BAIT_NAMES = Object.freeze({
202 [ClothTier.cotton]: "Worms",
203 [ClothTier.wool]: "Maggots",
204 [ClothTier.linen]: "Crickets",
205 [ClothTier.cashmere]: "Leeches",
206 [ClothTier.silk]: "Roe",
207 [ClothTier.fairySilk]: "Glowworms",
208 [ClothTier.dragonweave]: "Fairy flies"
209});
210
211/** Bait item IDs by cloth tier (358+). */
212export const BaitItemId = Object.freeze({
213 [ClothTier.cotton]: 358,
214 [ClothTier.wool]: 359,
215 [ClothTier.linen]: 360,
216 [ClothTier.cashmere]: 361,
217 [ClothTier.silk]: 362,
218 [ClothTier.fairySilk]: 363,
219 [ClothTier.dragonweave]: 364
220});
221
222export function baitItemIdForCloth (clothTier)
223{
224 return BaitItemId[clothTier] ?? null;
225}
226
227export function baitItemIdForRank (rank)
228{
229 const cloth = CLOTH_TIER_ORDER[(rank | 0) - 1];
230 return cloth ? BaitItemId[cloth] : null;
231}
232
233function buildBaitDefinitions ()
234{
235 const out = {};
236 for (const clothTier of CLOTH_TIER_ORDER)
237 {
238 const itemId = BaitItemId[clothTier];
239 const name = BAIT_NAMES[clothTier] ?? `${CLOTH_DISPLAY_NAME[clothTier]} bait`;
240 out[itemId] = Object.freeze({
241 itemId,
242 key: `${clothTier}-bait`,
243 displayName: name,
244 description: `Bait for a fishing rod. Attracts fish up to this grade.`,
245 seedValue: tierRank(clothTier),
246 stackable: true,
247 maxStackSize: DEFAULT_STACK,
248 uniqueInstance: false,
249 category: ItemCategory.ingredient,
250 iconKey: "bait",
251 defaultState: "bait",
252 tier: clothTier,
253 tintFromTier: true,
254 bait: true,
255 npcShopAllowed: true
256 });
257 }
258 return out;
259}
260
261/**
262 * Fishing tools.
263 * Net = tier 1 (id 23). Poles + rods from birch…elder (tier 2–7).
264 * Pole = unstrung; rod = pole + line (usable).
265 */
266export const FishingToolItemId = Object.freeze({
267 net: 23,
268 birchRod: 365,
269 oakRod: 366,
270 ebonyRod: 367,
271 lignumRod: 368,
272 heartwoodRod: 369,
273 elderRod: 370,
274 birchPole: 371,
275 oakPole: 372,
276 ebonyPole: 373,
277 lignumPole: 374,
278 heartwoodPole: 375,
279 elderPole: 376
280});
281
282const ROD_BY_WOOD = Object.freeze({
283 [WoodTier.birch]: FishingToolItemId.birchRod,
284 [WoodTier.oak]: FishingToolItemId.oakRod,
285 [WoodTier.ebony]: FishingToolItemId.ebonyRod,
286 [WoodTier.lignum]: FishingToolItemId.lignumRod,
287 [WoodTier.heartwood]: FishingToolItemId.heartwoodRod,
288 [WoodTier.elder]: FishingToolItemId.elderRod
289});
290
291const POLE_BY_WOOD = Object.freeze({
292 [WoodTier.birch]: FishingToolItemId.birchPole,
293 [WoodTier.oak]: FishingToolItemId.oakPole,
294 [WoodTier.ebony]: FishingToolItemId.ebonyPole,
295 [WoodTier.lignum]: FishingToolItemId.lignumPole,
296 [WoodTier.heartwood]: FishingToolItemId.heartwoodPole,
297 [WoodTier.elder]: FishingToolItemId.elderPole
298});
299
300export function fishingRodItemIdForWood (woodTier)
301{
302 return ROD_BY_WOOD[woodTier] ?? null;
303}
304
305export function fishingPoleItemIdForWood (woodTier)
306{
307 return POLE_BY_WOOD[woodTier] ?? null;
308}
309
310export function woodTierFromFishingRodItemId (itemId)
311{
312 for (const [woodTier, id] of Object.entries(ROD_BY_WOOD))
313 {
314 if (id === (itemId | 0))
315 { return woodTier; }
316 }
317 return null;
318}
319
320function buildToolDefinitions ()
321{
322 const out = {};
323 out[FishingToolItemId.net] = Object.freeze({
324 itemId: FishingToolItemId.net,
325 key: "fishing-net",
326 displayName: "Fishing net",
327 description: "A cotton mesh for scooping small fish from the shallows. Needs no bait.",
328 seedValue: 6,
329 stackable: false,
330 maxStackSize: 1,
331 uniqueInstance: false,
332 category: ItemCategory.tool,
333 iconKey: "fishing-net",
334 defaultState: "fishing-net",
335 tier: ClothTier.cotton,
336 tintFromTier: true,
337 equipment: Object.freeze({
338 slot: "weapon",
339 tier: ClothTier.cotton,
340 kind: EquipmentKind.fishingNet,
341 tintFromTier: true
342 }),
343 npcShopAllowed: true
344 });
345
346 for (const woodTier of WOOD_TIER_ORDER)
347 {
348 const poleId = POLE_BY_WOOD[woodTier];
349 const rodId = ROD_BY_WOOD[woodTier];
350 if (!poleId || !rodId)
351 { continue; }
352 const woodName = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
353 const clothTier = clothTierForWood(woodTier);
354 out[poleId] = Object.freeze({
355 itemId: poleId,
356 key: `${woodTier}-fishing-pole`,
357 displayName: `${woodName} fishing pole`,
358 description: `A shaped ${woodName.toLowerCase()} pole, waiting for a fishing line.`,
359 seedValue: tierRank(woodTier),
360 stackable: false,
361 maxStackSize: 1,
362 uniqueInstance: false,
363 category: ItemCategory.intermediate,
364 iconKey: "fishing-pole",
365 defaultState: "fishing-pole",
366 tier: woodTier,
367 clothTier,
368 tintFromTier: true,
369 fishingPole: true,
370 npcShopAllowed: true
371 });
372 out[rodId] = Object.freeze({
373 itemId: rodId,
374 key: `${woodTier}-fishing-rod`,
375 displayName: `${woodName} fishing rod`,
376 description: `A ${woodName.toLowerCase()} rod strung for deeper water.`,
377 seedValue: tierRank(woodTier) * 2,
378 stackable: false,
379 maxStackSize: 1,
380 uniqueInstance: false,
381 category: ItemCategory.tool,
382 iconKey: "fishing-rod",
383 defaultState: "fishing-rod",
384 tier: woodTier,
385 clothTier,
386 tintFromTier: true,
387 fishingRod: true,
388 poleItemId: poleId,
389 equipment: Object.freeze({
390 slot: "weapon",
391 tier: woodTier,
392 kind: EquipmentKind.fishingRod,
393 tintFromTier: true
394 }),
395 npcShopAllowed: true
396 });
397 }
398 return out;
399}
400
401export const FISH_ITEM_DEFINITIONS = Object.freeze({
402 ...buildFishItemDefinitions(),
403 ...buildBaitDefinitions(),
404 ...buildToolDefinitions()
405});
406
407/** All raw fish item ids (for editor picker). */
408export function listRawFishPickerEntries ()
409{
410 return FISH_SPECIES_ORDER.map((speciesId) =>
411 {
412 const species = FISH_SPECIES[speciesId];
413 const itemId = FISH_ITEM_IDS[speciesId].raw;
414 return {
415 itemId,
416 speciesId,
417 displayName: `Uncooked ${species.displayName}`,
418 tier: species.tier,
419 key: `uncooked-${species.key}`
420 };
421 });
422}
423
424/** Normalize fishing-spot config to unique raw fish item ids. */
425export function normalizeFishingSpotConfig (config)
426{
427 const fishes = [];
428 const seen = new Set();
429 for (const entry of config?.fishes ?? [])
430 {
431 const itemId = typeof entry === "number" ? entry | 0 : entry?.itemId | 0;
432 if (!itemId || seen.has(itemId))
433 { continue; }
434 const speciesId = fishSpeciesIdFromItemId(itemId);
435 if (!speciesId)
436 { continue; }
437 const ids = FISH_ITEM_IDS[speciesId];
438 const rawId = ids?.raw ?? itemId;
439 if (seen.has(rawId))
440 { continue; }
441 seen.add(rawId);
442 fishes.push(rawId);
443 }
444 return { fishes };
445}
446
447/** Craft recipes for fishing tools. */
448export function fishingToolRecipes ()
449{
450 const recipes = [
451 Object.freeze({
452 recipeId: "fishing-net",
453 stationId: CraftingStationId.craftingBench,
454 output: { itemId: FishingToolItemId.net, quantity: 1 },
455 inputs: [{ itemId: yarnItemId(ClothTier.cotton), quantity: 3 }],
456 minSkillLevel: 1,
457 skillId: "crafting",
458 xpMaterial: ClothTier.cotton
459 })
460 ];
461 for (const woodTier of WOOD_TIER_ORDER)
462 {
463 const poleId = POLE_BY_WOOD[woodTier];
464 const rodId = ROD_BY_WOOD[woodTier];
465 if (!poleId || !rodId)
466 { continue; }
467 const clothTier = clothTierForWood(woodTier);
468 recipes.push(Object.freeze({
469 recipeId: `fishing-pole-${woodTier}`,
470 craftGroup: "fishing-pole",
471 craftGroupLabel: "Fishing pole",
472 stationId: CraftingStationId.woodworkingBench,
473 output: { itemId: poleId, quantity: 1 },
474 inputs: [{ itemId: logItemIdForWood(woodTier), quantity: 1 }],
475 minSkillLevel: tierMinSkillLevel(woodTier),
476 skillId: "crafting",
477 xpMaterial: woodTier
478 }));
479 recipes.push(Object.freeze({
480 recipeId: `fishing-rod-${woodTier}`,
481 craftGroup: "fishing-rod",
482 craftGroupLabel: "Fishing rod",
483 stationId: CraftingStationId.craftingBench,
484 output: { itemId: rodId, quantity: 1 },
485 inputs: [
486 { itemId: poleId, quantity: 1 },
487 { itemId: yarnItemId(clothTier), quantity: 2 }
488 ],
489 minSkillLevel: tierMinSkillLevel(woodTier),
490 skillId: "crafting",
491 xpMaterial: woodTier
492 }));
493 }
494 return recipes;
495}
496
497/** Cook recipes for every fish species (oven + fireplace). */
498export function fishingCookRecipes ()
499{
500 return FISH_SPECIES_ORDER.map((speciesId) =>
501 {
502 const ids = FISH_ITEM_IDS[speciesId];
503 const species = FISH_SPECIES[speciesId];
504 return Object.freeze({
505 recipeId: `cook-${species.key}`,
506 craftGroup: "cook-fish",
507 craftGroupLabel: "Fish",
508 stationIds: [CraftingStationId.oven, CraftingStationId.fireplace],
509 output: { itemId: ids.cooked, quantity: 1 },
510 inputs: [{ itemId: ids.raw, quantity: 1 }],
511 minSkillLevel: 1,
512 skillId: "cooking",
513 xpMaterial: CLOTH_TIER_ORDER[species.tier - 1] ?? ClothTier.cotton,
514 burntOutput: { itemId: ids.burnt, quantity: 1 }
515 });
516 });
517}
518
519/** Fishing roll difficulty from bait tier rank. */
520export function fishingDifficulty (baitTierRank)
521{
522 const rank = Math.max(1, baitTierRank | 0);
523 return Math.max((rank - 1) * 10, 1);
524}
525
526export function fishingExhaustDurationMs (fishTierRank)
527{
528 return Math.max(1, fishTierRank | 0) * 10_000;
529}
shared/definitions/gathering.js +23 −0
@@ -246,6 +246,29 @@ export function resolveWoodcuttingAxe ({ inventorySlots, equipmentSlots, skills,
246 246 return { ok: true, tool: usable[0] };
247 247 }
248 248
249 /**
250 * Best fishing tool (net or rod) the player can use.
251 * Prefers highest-tier usable rod; falls back to net.
252 * @returns {{ ok: true, tool: object, kind: string } | { ok: false, reason: string }}
253 */
254 export function resolveFishingTool ({ inventorySlots, equipmentSlots, skills })
255 {
256 const fishingLevel = skillLevel(skills, SkillId.fishing);
257 const rods = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.fishingRod)
258 .filter((tool) => canEquipItem(skills, tool.def).ok)
259 .filter((tool) => (fishingLevel | 0) >= tierMineSkillLevel(tool.tier))
260 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
261 if (rods.length)
262 { return { ok: true, tool: rods[0], kind: EquipmentKind.fishingRod }; }
263
264 const nets = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.fishingNet)
265 .filter((tool) => canEquipItem(skills, tool.def).ok);
266 if (nets.length)
267 { return { ok: true, tool: nets[0], kind: EquipmentKind.fishingNet }; }
268
269 return { ok: false, reason: "You need a fishing net or rod." };
270 }
271
249 272 /**
250 273 * Best plant clippers for herbalism nodes (flowers). Cotton needs no tool.
251 274 * @returns {{ ok: true, tool: object|null } | { ok: false, reason: string }}
@@ -246,6 +246,29 @@ export function resolveWoodcuttingAxe ({ inventorySlots, equipmentSlots, skills,
246 return { ok: true, tool: usable[0] };
246 return { ok: true, tool: usable[0] };
247}
247}
248
248
249/**
250 * Best fishing tool (net or rod) the player can use.
251 * Prefers highest-tier usable rod; falls back to net.
252 * @returns {{ ok: true, tool: object, kind: string } | { ok: false, reason: string }}
253 */
254export function resolveFishingTool ({ inventorySlots, equipmentSlots, skills })
255{
256 const fishingLevel = skillLevel(skills, SkillId.fishing);
257 const rods = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.fishingRod)
258 .filter((tool) => canEquipItem(skills, tool.def).ok)
259 .filter((tool) => (fishingLevel | 0) >= tierMineSkillLevel(tool.tier))
260 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
261 if (rods.length)
262 { return { ok: true, tool: rods[0], kind: EquipmentKind.fishingRod }; }
263
264 const nets = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.fishingNet)
265 .filter((tool) => canEquipItem(skills, tool.def).ok);
266 if (nets.length)
267 { return { ok: true, tool: nets[0], kind: EquipmentKind.fishingNet }; }
268
269 return { ok: false, reason: "You need a fishing net or rod." };
270}
271
249/**
272/**
250 * Best plant clippers for herbalism nodes (flowers). Cotton needs no tool.
273 * Best plant clippers for herbalism nodes (flowers). Cotton needs no tool.
251 * @returns {{ ok: true, tool: object|null } | { ok: false, reason: string }}
274 * @returns {{ ok: true, tool: object|null } | { ok: false, reason: string }}
shared/definitions/items.js +8 −0
@@ -16,6 +16,7 @@ import { HERB_ITEM_DEFINITIONS, HerbItemId } from "./herbs.js";
16 16 import { RANGED_ITEM_DEFINITIONS, RangedItemId } from "./rangedItems.js";
17 17 import { POTION_MAX_STACK } from "./alchemy.js";
18 18 import { SpellbookItemId, SPELLBOOK_ITEM_DEFINITIONS } from "./spellItems.js";
19 import { FISH_ITEM_DEFINITIONS, FishingToolItemId } from "./fishItems.js";
19 20
20 21 export const ItemId = Object.freeze({
21 22 paper: 1,
@@ -38,6 +39,7 @@ export const ItemId = Object.freeze({
38 39 ...SpellbookItemId,
39 40 ...MetalItemId,
40 41 ...WoodItemId,
42 ...FishingToolItemId,
41 43 ...ArmourItemId,
42 44 ...ClothItemId,
43 45 ...LeatherItemId,
@@ -276,6 +278,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
276 278 ...HERB_ITEM_DEFINITIONS,
277 279 ...RANGED_ITEM_DEFINITIONS,
278 280 ...SPELLBOOK_ITEM_DEFINITIONS,
281 ...FISH_ITEM_DEFINITIONS,
279 282 [DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
280 283 [DyeItemId.dye]: DYE_ITEM_DEFINITION
281 284 });
@@ -330,6 +333,11 @@ export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
330 333 }
331 334 if (stack?.itemId === ItemId.recipePaper && stack.instance?.displayName)
332 335 { return stack.instance.displayName; }
336 if (stack?.itemId === CraftingItemId.tinderbox && stack.instance?.kind === "tinderbox")
337 {
338 const charges = Math.max(0, stack.instance.charges | 0);
339 return `${def.displayName} (${charges})`;
340 }
333 341 return def.displayName ?? "Item";
334 342 }
335 343
@@ -16,6 +16,7 @@ import { HERB_ITEM_DEFINITIONS, HerbItemId } from "./herbs.js";
16import { RANGED_ITEM_DEFINITIONS, RangedItemId } from "./rangedItems.js";
16import { RANGED_ITEM_DEFINITIONS, RangedItemId } from "./rangedItems.js";
17import { POTION_MAX_STACK } from "./alchemy.js";
17import { POTION_MAX_STACK } from "./alchemy.js";
18import { SpellbookItemId, SPELLBOOK_ITEM_DEFINITIONS } from "./spellItems.js";
18import { SpellbookItemId, SPELLBOOK_ITEM_DEFINITIONS } from "./spellItems.js";
19import { FISH_ITEM_DEFINITIONS, FishingToolItemId } from "./fishItems.js";
19
20
20export const ItemId = Object.freeze({
21export const ItemId = Object.freeze({
21 paper: 1,
22 paper: 1,
@@ -38,6 +39,7 @@ export const ItemId = Object.freeze({
38 ...SpellbookItemId,
39 ...SpellbookItemId,
39 ...MetalItemId,
40 ...MetalItemId,
40 ...WoodItemId,
41 ...WoodItemId,
42 ...FishingToolItemId,
41 ...ArmourItemId,
43 ...ArmourItemId,
42 ...ClothItemId,
44 ...ClothItemId,
43 ...LeatherItemId,
45 ...LeatherItemId,
@@ -276,6 +278,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
276 ...HERB_ITEM_DEFINITIONS,
278 ...HERB_ITEM_DEFINITIONS,
277 ...RANGED_ITEM_DEFINITIONS,
279 ...RANGED_ITEM_DEFINITIONS,
278 ...SPELLBOOK_ITEM_DEFINITIONS,
280 ...SPELLBOOK_ITEM_DEFINITIONS,
281 ...FISH_ITEM_DEFINITIONS,
279 [DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
282 [DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
280 [DyeItemId.dye]: DYE_ITEM_DEFINITION
283 [DyeItemId.dye]: DYE_ITEM_DEFINITION
281});
284});
@@ -330,6 +333,11 @@ export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
330 }
333 }
331 if (stack?.itemId === ItemId.recipePaper && stack.instance?.displayName)
334 if (stack?.itemId === ItemId.recipePaper && stack.instance?.displayName)
332 { return stack.instance.displayName; }
335 { return stack.instance.displayName; }
336 if (stack?.itemId === CraftingItemId.tinderbox && stack.instance?.kind === "tinderbox")
337 {
338 const charges = Math.max(0, stack.instance.charges | 0);
339 return `${def.displayName} (${charges})`;
340 }
333 return def.displayName ?? "Item";
341 return def.displayName ?? "Item";
334}
342}
335
343
shared/definitions/mobs.js +3 −1
@@ -1,6 +1,7 @@
1 1 import { spriteImageName } from "./tileSprites.js";
2 2 import { centralExchangeStaffCount } from "../market/exchange.js";
3 3 import { LeatherItemId } from "./leatherItems.js";
4 import { CraftingItemId } from "./craftingItems.js";
4 5 import { RangedItemId } from "./rangedItems.js";
5 6 import { ArmourItemId } from "./armourItems.js";
6 7 import { WoodItemId } from "./woodItems.js";
@@ -43,7 +44,8 @@ export const MOB_DEFINITIONS = Object.freeze({
43 44 attackSkill: 2,
44 45 attackCooldownMs: 1000,
45 46 drops: Object.freeze([
46 { itemId: LeatherItemId.softLeather, chance: 1 }
47 { itemId: LeatherItemId.softLeather, chance: 1 },
48 { itemId: CraftingItemId.rawMeat, chance: 1 }
47 49 ]),
48 50 sells: Object.freeze([]),
49 51 dialogue: Object.freeze([]),
@@ -1,6 +1,7 @@
1import { spriteImageName } from "./tileSprites.js";
1import { spriteImageName } from "./tileSprites.js";
2import { centralExchangeStaffCount } from "../market/exchange.js";
2import { centralExchangeStaffCount } from "../market/exchange.js";
3import { LeatherItemId } from "./leatherItems.js";
3import { LeatherItemId } from "./leatherItems.js";
4import { CraftingItemId } from "./craftingItems.js";
4import { RangedItemId } from "./rangedItems.js";
5import { RangedItemId } from "./rangedItems.js";
5import { ArmourItemId } from "./armourItems.js";
6import { ArmourItemId } from "./armourItems.js";
6import { WoodItemId } from "./woodItems.js";
7import { WoodItemId } from "./woodItems.js";
@@ -43,7 +44,8 @@ export const MOB_DEFINITIONS = Object.freeze({
43 attackSkill: 2,
44 attackSkill: 2,
44 attackCooldownMs: 1000,
45 attackCooldownMs: 1000,
45 drops: Object.freeze([
46 drops: Object.freeze([
46 { itemId: LeatherItemId.softLeather, chance: 1 }
47 { itemId: LeatherItemId.softLeather, chance: 1 },
48 { itemId: CraftingItemId.rawMeat, chance: 1 }
47 ]),
49 ]),
48 sells: Object.freeze([]),
50 sells: Object.freeze([]),
49 dialogue: Object.freeze([]),
51 dialogue: Object.freeze([]),
shared/definitions/skills.js +3 −0
@@ -20,6 +20,7 @@ export const SkillId = Object.freeze({
20 20 leatherworking: "leatherworking",
21 21 tailoring: "tailoring",
22 22 cooking: "cooking",
23 firestarting: "firestarting",
23 24 herbalism: "herbalism",
24 25 alchemy: "alchemy"
25 26 });
@@ -47,6 +48,7 @@ export const ALL_SKILL_IDS = Object.freeze([
47 48 SkillId.leatherworking,
48 49 SkillId.tailoring,
49 50 SkillId.cooking,
51 SkillId.firestarting,
50 52 SkillId.herbalism,
51 53 SkillId.alchemy
52 54 ]);
@@ -73,6 +75,7 @@ export const SKILL_DEFINITIONS = Object.freeze({
73 75 [SkillId.leatherworking]: Object.freeze({ skillId: SkillId.leatherworking, displayName: "Leatherworking" }),
74 76 [SkillId.tailoring]: Object.freeze({ skillId: SkillId.tailoring, displayName: "Tailoring" }),
75 77 [SkillId.cooking]: Object.freeze({ skillId: SkillId.cooking, displayName: "Cooking" }),
78 [SkillId.firestarting]: Object.freeze({ skillId: SkillId.firestarting, displayName: "Firestarting" }),
76 79 [SkillId.herbalism]: Object.freeze({ skillId: SkillId.herbalism, displayName: "Herbalism" }),
77 80 [SkillId.alchemy]: Object.freeze({ skillId: SkillId.alchemy, displayName: "Alchemy" })
78 81 });
@@ -20,6 +20,7 @@ export const SkillId = Object.freeze({
20 leatherworking: "leatherworking",
20 leatherworking: "leatherworking",
21 tailoring: "tailoring",
21 tailoring: "tailoring",
22 cooking: "cooking",
22 cooking: "cooking",
23 firestarting: "firestarting",
23 herbalism: "herbalism",
24 herbalism: "herbalism",
24 alchemy: "alchemy"
25 alchemy: "alchemy"
25});
26});
@@ -47,6 +48,7 @@ export const ALL_SKILL_IDS = Object.freeze([
47 SkillId.leatherworking,
48 SkillId.leatherworking,
48 SkillId.tailoring,
49 SkillId.tailoring,
49 SkillId.cooking,
50 SkillId.cooking,
51 SkillId.firestarting,
50 SkillId.herbalism,
52 SkillId.herbalism,
51 SkillId.alchemy
53 SkillId.alchemy
52]);
54]);
@@ -73,6 +75,7 @@ export const SKILL_DEFINITIONS = Object.freeze({
73 [SkillId.leatherworking]: Object.freeze({ skillId: SkillId.leatherworking, displayName: "Leatherworking" }),
75 [SkillId.leatherworking]: Object.freeze({ skillId: SkillId.leatherworking, displayName: "Leatherworking" }),
74 [SkillId.tailoring]: Object.freeze({ skillId: SkillId.tailoring, displayName: "Tailoring" }),
76 [SkillId.tailoring]: Object.freeze({ skillId: SkillId.tailoring, displayName: "Tailoring" }),
75 [SkillId.cooking]: Object.freeze({ skillId: SkillId.cooking, displayName: "Cooking" }),
77 [SkillId.cooking]: Object.freeze({ skillId: SkillId.cooking, displayName: "Cooking" }),
78 [SkillId.firestarting]: Object.freeze({ skillId: SkillId.firestarting, displayName: "Firestarting" }),
76 [SkillId.herbalism]: Object.freeze({ skillId: SkillId.herbalism, displayName: "Herbalism" }),
79 [SkillId.herbalism]: Object.freeze({ skillId: SkillId.herbalism, displayName: "Herbalism" }),
77 [SkillId.alchemy]: Object.freeze({ skillId: SkillId.alchemy, displayName: "Alchemy" })
80 [SkillId.alchemy]: Object.freeze({ skillId: SkillId.alchemy, displayName: "Alchemy" })
78});
81});
shared/definitions/tiles.js +51 −1
@@ -63,7 +63,10 @@ export const BlockType = Object.freeze({
63 63 heartwoodTree: 27,
64 64 elderTree: 28,
65 65 leatherworkingTable: 29,
66 doorway: 30
66 doorway: 30,
67 campfire: 31,
68 oven: 32,
69 fishingSpot: 33
67 70 });
68 71
69 72 export const GROUND_DEFINITIONS = Object.freeze({
@@ -251,6 +254,51 @@ export const BLOCK_DEFINITIONS = Object.freeze({
251 254 craftingStationId: "furnace",
252 255 outdoor: false
253 256 }),
257 [BlockType.campfire]: Object.freeze({
258 id: BlockType.campfire,
259 key: "campfire",
260 displayName: "Campfire",
261 passable: true,
262 blocksLight: false,
263 blocksRangedAttacks: false,
264 lightRangeTiles: 4,
265 frames: 1,
266 framesPerRow: 1,
267 animationSpeed: 0,
268 craftingStationId: "fireplace",
269 /** State is wood tier id; tinted like logs. Bloom companion is fire only. */
270 tintFromTier: true,
271 outdoor: true
272 }),
273 [BlockType.oven]: Object.freeze({
274 id: BlockType.oven,
275 key: "oven",
276 displayName: "Oven",
277 passable: false,
278 blocksLight: false,
279 lightRangeTiles: 2,
280 frames: 1,
281 framesPerRow: 1,
282 animationSpeed: 0,
283 craftingStationId: "oven",
284 outdoor: false
285 }),
286 [BlockType.fishingSpot]: Object.freeze({
287 id: BlockType.fishingSpot,
288 key: "fishing-spot",
289 displayName: "Fishing spot",
290 passable: true,
291 blocksLight: false,
292 blocksRangedAttacks: false,
293 lightRangeTiles: 0,
294 /** Ripple / splash strip (temp art; 3 frames). */
295 frames: 3,
296 framesPerRow: 3,
297 animationSpeed: 0.18,
298 outdoor: true,
299 /** Requires water / deepWater under the tile (editor + server). */
300 requiresWater: true
301 }),
254 302 [BlockType.anvil]: Object.freeze({
255 303 id: BlockType.anvil,
256 304 key: "anvil",
@@ -501,6 +549,8 @@ export function resourceNodeDisplayName (block)
501 549 {
502 550 if (!block)
503 551 { return null; }
552 if (block.typeId === BlockType.fishingSpot && block.state !== "exhausted")
553 { return "Fishing spot"; }
504 554 if (block.typeId === BlockType.boulder)
505 555 { return oreBoulderDisplayName(block.state); }
506 556 if (isChopableTreeBlock(block))
@@ -63,7 +63,10 @@ export const BlockType = Object.freeze({
63 heartwoodTree: 27,
63 heartwoodTree: 27,
64 elderTree: 28,
64 elderTree: 28,
65 leatherworkingTable: 29,
65 leatherworkingTable: 29,
66 doorway: 30
66 doorway: 30,
67 campfire: 31,
68 oven: 32,
69 fishingSpot: 33
67});
70});
68
71
69export const GROUND_DEFINITIONS = Object.freeze({
72export const GROUND_DEFINITIONS = Object.freeze({
@@ -251,6 +254,51 @@ export const BLOCK_DEFINITIONS = Object.freeze({
251 craftingStationId: "furnace",
254 craftingStationId: "furnace",
252 outdoor: false
255 outdoor: false
253 }),
256 }),
257 [BlockType.campfire]: Object.freeze({
258 id: BlockType.campfire,
259 key: "campfire",
260 displayName: "Campfire",
261 passable: true,
262 blocksLight: false,
263 blocksRangedAttacks: false,
264 lightRangeTiles: 4,
265 frames: 1,
266 framesPerRow: 1,
267 animationSpeed: 0,
268 craftingStationId: "fireplace",
269 /** State is wood tier id; tinted like logs. Bloom companion is fire only. */
270 tintFromTier: true,
271 outdoor: true
272 }),
273 [BlockType.oven]: Object.freeze({
274 id: BlockType.oven,
275 key: "oven",
276 displayName: "Oven",
277 passable: false,
278 blocksLight: false,
279 lightRangeTiles: 2,
280 frames: 1,
281 framesPerRow: 1,
282 animationSpeed: 0,
283 craftingStationId: "oven",
284 outdoor: false
285 }),
286 [BlockType.fishingSpot]: Object.freeze({
287 id: BlockType.fishingSpot,
288 key: "fishing-spot",
289 displayName: "Fishing spot",
290 passable: true,
291 blocksLight: false,
292 blocksRangedAttacks: false,
293 lightRangeTiles: 0,
294 /** Ripple / splash strip (temp art; 3 frames). */
295 frames: 3,
296 framesPerRow: 3,
297 animationSpeed: 0.18,
298 outdoor: true,
299 /** Requires water / deepWater under the tile (editor + server). */
300 requiresWater: true
301 }),
254 [BlockType.anvil]: Object.freeze({
302 [BlockType.anvil]: Object.freeze({
255 id: BlockType.anvil,
303 id: BlockType.anvil,
256 key: "anvil",
304 key: "anvil",
@@ -501,6 +549,8 @@ export function resourceNodeDisplayName (block)
501{
549{
502 if (!block)
550 if (!block)
503 { return null; }
551 { return null; }
552 if (block.typeId === BlockType.fishingSpot && block.state !== "exhausted")
553 { return "Fishing spot"; }
504 if (block.typeId === BlockType.boulder)
554 if (block.typeId === BlockType.boulder)
505 { return oreBoulderDisplayName(block.state); }
555 { return oreBoulderDisplayName(block.state); }
506 if (isChopableTreeBlock(block))
556 if (isChopableTreeBlock(block))
shared/definitions/woodItems.js +58 −5
@@ -1,16 +1,18 @@
1 1 import {
2 2 WoodTier,
3 WOOD_TIER_ORDER
3 WOOD_TIER_ORDER,
4 MATERIAL_DISPLAY_NAME
4 5 } from "./materialTiers.js";
5 6 import {
6 7 ItemFamilyId,
7 8 buildFamilyDefinitionMap,
8 9 itemIdForFamilyTier
9 10 } from "./tierFamilies.js";
11 import { ItemCategory } from "./itemCategories.js";
10 12
11 13 /**
12 * Wood logs and handles.
13 * Shared magenta base sprites: iconKey wood, states log / handle.
14 * Wood logs, handles, and ash.
15 * Shared magenta base sprites: iconKey wood (log/handle), ash (ash).
14 16 * pineLog reuses former CraftingItemId.log (9).
15 17 */
16 18 export const WoodItemId = Object.freeze({
@@ -33,7 +35,14 @@ export const WoodItemId = Object.freeze({
33 35 ebonyQuarterstaff: 246,
34 36 lignumQuarterstaff: 247,
35 37 heartwoodQuarterstaff: 248,
36 elderQuarterstaff: 249
38 elderQuarterstaff: 249,
39 pineAsh: 281,
40 birchAsh: 282,
41 oakAsh: 283,
42 ebonyAsh: 284,
43 lignumAsh: 285,
44 heartwoodAsh: 286,
45 elderAsh: 287
37 46 });
38 47
39 48 const LOG_IDS = Object.freeze({
@@ -66,9 +75,20 @@ const QUARTERSTAFF_IDS = Object.freeze({
66 75 [WoodTier.elder]: WoodItemId.elderQuarterstaff
67 76 });
68 77
78 const ASH_IDS = Object.freeze({
79 [WoodTier.pine]: WoodItemId.pineAsh,
80 [WoodTier.birch]: WoodItemId.birchAsh,
81 [WoodTier.oak]: WoodItemId.oakAsh,
82 [WoodTier.ebony]: WoodItemId.ebonyAsh,
83 [WoodTier.lignum]: WoodItemId.lignumAsh,
84 [WoodTier.heartwood]: WoodItemId.heartwoodAsh,
85 [WoodTier.elder]: WoodItemId.elderAsh
86 });
87
69 88 export const LOG_ITEM_BY_WOOD = LOG_IDS;
70 89 export const HANDLE_ITEM_BY_WOOD = HANDLE_IDS;
71 90 export const QUARTERSTAFF_ITEM_BY_WOOD = QUARTERSTAFF_IDS;
91 export const ASH_ITEM_BY_WOOD = ASH_IDS;
72 92
73 93 export function logItemIdForWood (woodTier)
74 94 {
@@ -85,9 +105,42 @@ export function quarterstaffItemIdForWood (woodTier)
85 105 return itemIdForFamilyTier(QUARTERSTAFF_IDS, woodTier);
86 106 }
87 107
108 export function ashItemIdForWood (woodTier)
109 {
110 return itemIdForFamilyTier(ASH_IDS, woodTier);
111 }
112
113 function ashDefinitions ()
114 {
115 const out = {};
116 for (const woodTier of WOOD_TIER_ORDER)
117 {
118 const itemId = ASH_IDS[woodTier];
119 const name = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
120 out[itemId] = Object.freeze({
121 itemId,
122 key: `${woodTier}-ash`,
123 displayName: `${name} ash`,
124 description: `Fine grey ash left when ${name.toLowerCase()} wood burns out.`,
125 seedValue: 1,
126 stackable: true,
127 maxStackSize: 99,
128 uniqueInstance: false,
129 category: ItemCategory.ingredient,
130 iconKey: "ash",
131 defaultState: "ash",
132 tier: woodTier,
133 tintFromTier: "ash",
134 npcShopAllowed: true
135 });
136 }
137 return out;
138 }
139
88 140 /** Full defs for wood family (merged into ITEM_DEFINITIONS). */
89 141 export const WOOD_ITEM_DEFINITIONS = Object.freeze({
90 142 ...buildFamilyDefinitionMap(ItemFamilyId.log, LOG_IDS),
91 143 ...buildFamilyDefinitionMap(ItemFamilyId.handle, HANDLE_IDS),
92 ...buildFamilyDefinitionMap(ItemFamilyId.quarterstaff, QUARTERSTAFF_IDS)
144 ...buildFamilyDefinitionMap(ItemFamilyId.quarterstaff, QUARTERSTAFF_IDS),
145 ...ashDefinitions()
93 146 });
@@ -1,16 +1,18 @@
1import {
1import {
2 WoodTier,
2 WoodTier,
3 WOOD_TIER_ORDER
3 WOOD_TIER_ORDER,
4 MATERIAL_DISPLAY_NAME
4} from "./materialTiers.js";
5} from "./materialTiers.js";
5import {
6import {
6 ItemFamilyId,
7 ItemFamilyId,
7 buildFamilyDefinitionMap,
8 buildFamilyDefinitionMap,
8 itemIdForFamilyTier
9 itemIdForFamilyTier
9} from "./tierFamilies.js";
10} from "./tierFamilies.js";
11import { ItemCategory } from "./itemCategories.js";
10
12
11/**
13/**
12 * Wood logs and handles.
14 * Wood logs, handles, and ash.
13 * Shared magenta base sprites: iconKey wood, states log / handle.
15 * Shared magenta base sprites: iconKey wood (log/handle), ash (ash).
14 * pineLog reuses former CraftingItemId.log (9).
16 * pineLog reuses former CraftingItemId.log (9).
15 */
17 */
16export const WoodItemId = Object.freeze({
18export const WoodItemId = Object.freeze({
@@ -33,7 +35,14 @@ export const WoodItemId = Object.freeze({
33 ebonyQuarterstaff: 246,
35 ebonyQuarterstaff: 246,
34 lignumQuarterstaff: 247,
36 lignumQuarterstaff: 247,
35 heartwoodQuarterstaff: 248,
37 heartwoodQuarterstaff: 248,
36 elderQuarterstaff: 249
38 elderQuarterstaff: 249,
39 pineAsh: 281,
40 birchAsh: 282,
41 oakAsh: 283,
42 ebonyAsh: 284,
43 lignumAsh: 285,
44 heartwoodAsh: 286,
45 elderAsh: 287
37});
46});
38
47
39const LOG_IDS = Object.freeze({
48const LOG_IDS = Object.freeze({
@@ -66,9 +75,20 @@ const QUARTERSTAFF_IDS = Object.freeze({
66 [WoodTier.elder]: WoodItemId.elderQuarterstaff
75 [WoodTier.elder]: WoodItemId.elderQuarterstaff
67});
76});
68
77
78const ASH_IDS = Object.freeze({
79 [WoodTier.pine]: WoodItemId.pineAsh,
80 [WoodTier.birch]: WoodItemId.birchAsh,
81 [WoodTier.oak]: WoodItemId.oakAsh,
82 [WoodTier.ebony]: WoodItemId.ebonyAsh,
83 [WoodTier.lignum]: WoodItemId.lignumAsh,
84 [WoodTier.heartwood]: WoodItemId.heartwoodAsh,
85 [WoodTier.elder]: WoodItemId.elderAsh
86});
87
69export const LOG_ITEM_BY_WOOD = LOG_IDS;
88export const LOG_ITEM_BY_WOOD = LOG_IDS;
70export const HANDLE_ITEM_BY_WOOD = HANDLE_IDS;
89export const HANDLE_ITEM_BY_WOOD = HANDLE_IDS;
71export const QUARTERSTAFF_ITEM_BY_WOOD = QUARTERSTAFF_IDS;
90export const QUARTERSTAFF_ITEM_BY_WOOD = QUARTERSTAFF_IDS;
91export const ASH_ITEM_BY_WOOD = ASH_IDS;
72
92
73export function logItemIdForWood (woodTier)
93export function logItemIdForWood (woodTier)
74{
94{
@@ -85,9 +105,42 @@ export function quarterstaffItemIdForWood (woodTier)
85 return itemIdForFamilyTier(QUARTERSTAFF_IDS, woodTier);
105 return itemIdForFamilyTier(QUARTERSTAFF_IDS, woodTier);
86}
106}
87
107
108export function ashItemIdForWood (woodTier)
109{
110 return itemIdForFamilyTier(ASH_IDS, woodTier);
111}
112
113function ashDefinitions ()
114{
115 const out = {};
116 for (const woodTier of WOOD_TIER_ORDER)
117 {
118 const itemId = ASH_IDS[woodTier];
119 const name = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
120 out[itemId] = Object.freeze({
121 itemId,
122 key: `${woodTier}-ash`,
123 displayName: `${name} ash`,
124 description: `Fine grey ash left when ${name.toLowerCase()} wood burns out.`,
125 seedValue: 1,
126 stackable: true,
127 maxStackSize: 99,
128 uniqueInstance: false,
129 category: ItemCategory.ingredient,
130 iconKey: "ash",
131 defaultState: "ash",
132 tier: woodTier,
133 tintFromTier: "ash",
134 npcShopAllowed: true
135 });
136 }
137 return out;
138}
139
88/** Full defs for wood family (merged into ITEM_DEFINITIONS). */
140/** Full defs for wood family (merged into ITEM_DEFINITIONS). */
89export const WOOD_ITEM_DEFINITIONS = Object.freeze({
141export const WOOD_ITEM_DEFINITIONS = Object.freeze({
90 ...buildFamilyDefinitionMap(ItemFamilyId.log, LOG_IDS),
142 ...buildFamilyDefinitionMap(ItemFamilyId.log, LOG_IDS),
91 ...buildFamilyDefinitionMap(ItemFamilyId.handle, HANDLE_IDS),
143 ...buildFamilyDefinitionMap(ItemFamilyId.handle, HANDLE_IDS),
92 ...buildFamilyDefinitionMap(ItemFamilyId.quarterstaff, QUARTERSTAFF_IDS)
144 ...buildFamilyDefinitionMap(ItemFamilyId.quarterstaff, QUARTERSTAFF_IDS),
145 ...ashDefinitions()
93});
146});
shared/protocol/constants.js +2 −0
@@ -179,6 +179,8 @@ export const MessageType = Object.freeze({
179 179 eatItem: "EAT_ITEM",
180 180 drinkItem: "DRINK_ITEM",
181 181 startCraft: "START_CRAFT",
182 startFire: "START_FIRE",
183 startFish: "START_FISH",
182 184 cancelCraft: "CANCEL_CRAFT",
183 185 craftResult: "CRAFT_RESULT",
184 186 openCauldron: "OPEN_CAULDRON",
@@ -179,6 +179,8 @@ export const MessageType = Object.freeze({
179 eatItem: "EAT_ITEM",
179 eatItem: "EAT_ITEM",
180 drinkItem: "DRINK_ITEM",
180 drinkItem: "DRINK_ITEM",
181 startCraft: "START_CRAFT",
181 startCraft: "START_CRAFT",
182 startFire: "START_FIRE",
183 startFish: "START_FISH",
182 cancelCraft: "CANCEL_CRAFT",
184 cancelCraft: "CANCEL_CRAFT",
183 craftResult: "CRAFT_RESULT",
185 craftResult: "CRAFT_RESULT",
184 openCauldron: "OPEN_CAULDRON",
186 openCauldron: "OPEN_CAULDRON",
shared/render/tint.js +18 −0
@@ -158,6 +158,18 @@ export function tierTintColor (tier, { ore = false } = {})
158 158 return normalizeRgb(materialTintColor(tier, { ore }));
159 159 }
160 160
161 /** Halfway between very dark grey and the wood tier colour (shared ash sprite). */
162 export function ashTintColor (woodTier)
163 {
164 const wood = tierTintColor(woodTier);
165 const dark = { r: 0.12, g: 0.12, b: 0.12 };
166 return {
167 r: (dark.r + wood.r) * 0.5,
168 g: (dark.g + wood.g) * 0.5,
169 b: (dark.b + wood.b) * 0.5
170 };
171 }
172
161 173 /**
162 174 * Resolve tint for an inventory/ground stack or item def.
163 175 * Priority: potion instance.color → def.tint → tintFromTier + tier (ore items use ore overrides).
@@ -180,6 +192,8 @@ export function resolveItemTint (stackOrDef, def = null)
180 192 { return normalizeRgb(definition.tint); }
181 193 if (definition?.dualTintFromTier)
182 194 { return null; }
195 if (definition?.tintFromTier === "ash" && definition.tier)
196 { return ashTintColor(definition.tier); }
183 197 const tier = resolveTintTier(definition);
184 198 if (tier)
185 199 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
@@ -199,6 +213,8 @@ export function resolveEquipTint (itemIdOrDef, instance = null)
199 213 { return normalizeRgb(definition.tint); }
200 214 if (definition?.dualTintFromTier)
201 215 { return null; }
216 if (definition?.tintFromTier === "ash" && definition.tier)
217 { return ashTintColor(definition.tier); }
202 218 const tier = resolveTintTier(definition);
203 219 if (tier)
204 220 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
@@ -214,6 +230,8 @@ function resolveTintTier (definition)
214 230 {
215 231 if (!definition)
216 232 { return null; }
233 if (definition.tintFromTier === "ash")
234 { return null; }
217 235 if (typeof definition.tintFromTier === "string")
218 236 { return definition.tintFromTier; }
219 237 if (definition.tintFromTier === true)
@@ -158,6 +158,18 @@ export function tierTintColor (tier, { ore = false } = {})
158 return normalizeRgb(materialTintColor(tier, { ore }));
158 return normalizeRgb(materialTintColor(tier, { ore }));
159}
159}
160
160
161/** Halfway between very dark grey and the wood tier colour (shared ash sprite). */
162export function ashTintColor (woodTier)
163{
164 const wood = tierTintColor(woodTier);
165 const dark = { r: 0.12, g: 0.12, b: 0.12 };
166 return {
167 r: (dark.r + wood.r) * 0.5,
168 g: (dark.g + wood.g) * 0.5,
169 b: (dark.b + wood.b) * 0.5
170 };
171}
172
161/**
173/**
162 * Resolve tint for an inventory/ground stack or item def.
174 * Resolve tint for an inventory/ground stack or item def.
163 * Priority: potion instance.color → def.tint → tintFromTier + tier (ore items use ore overrides).
175 * Priority: potion instance.color → def.tint → tintFromTier + tier (ore items use ore overrides).
@@ -180,6 +192,8 @@ export function resolveItemTint (stackOrDef, def = null)
180 { return normalizeRgb(definition.tint); }
192 { return normalizeRgb(definition.tint); }
181 if (definition?.dualTintFromTier)
193 if (definition?.dualTintFromTier)
182 { return null; }
194 { return null; }
195 if (definition?.tintFromTier === "ash" && definition.tier)
196 { return ashTintColor(definition.tier); }
183 const tier = resolveTintTier(definition);
197 const tier = resolveTintTier(definition);
184 if (tier)
198 if (tier)
185 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
199 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
@@ -199,6 +213,8 @@ export function resolveEquipTint (itemIdOrDef, instance = null)
199 { return normalizeRgb(definition.tint); }
213 { return normalizeRgb(definition.tint); }
200 if (definition?.dualTintFromTier)
214 if (definition?.dualTintFromTier)
201 { return null; }
215 { return null; }
216 if (definition?.tintFromTier === "ash" && definition.tier)
217 { return ashTintColor(definition.tier); }
202 const tier = resolveTintTier(definition);
218 const tier = resolveTintTier(definition);
203 if (tier)
219 if (tier)
204 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
220 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
@@ -214,6 +230,8 @@ function resolveTintTier (definition)
214{
230{
215 if (!definition)
231 if (!definition)
216 { return null; }
232 { return null; }
233 if (definition.tintFromTier === "ash")
234 { return null; }
217 if (typeof definition.tintFromTier === "string")
235 if (typeof definition.tintFromTier === "string")
218 { return definition.tintFromTier; }
236 { return definition.tintFromTier; }
219 if (definition.tintFromTier === true)
237 if (definition.tintFromTier === true)