Add mining, furnace smelting, stamina, and ore exhaustion.
Players mine tinted ore boulders with pickaxes, smelt at furnaces, and drain stamina while running; nodes exhaust then respawn by tier, with simulation tests covering mine and craft flows.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -3,8 +3,10 @@ import {
3
3
GROUND_DEFINITIONS,
4
4
BLOCK_DEFINITIONS,
5
5
GroundType,
6
BlockType,
6
7
normalizeGround,
7
normalizeBlock
8
normalizeBlock,
9
listPlaceableBlockPaletteEntries
8
10
} from "/shared/definitions/tiles.js";
9
11
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
10
12
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
@@ -55,6 +57,13 @@ function selectedToolLabel ()
55
57
const layer = tool.kind === "ground" ? "ground" : "block";
56
58
const states = statesForType(catalog, layer, def.key);
57
59
const state = resolveState(states, tool.state);
60
if (tool.kind === "block" && def.id === BlockType.boulder)
61
{
62
const entry = listPlaceableBlockPaletteEntries(catalog)
63
.find((row) => row.typeId === def.id && row.state === state);
64
if (entry)
65
{ return entry.displayName; }
66
}
58
67
if (states.length > 1)
59
68
{ return `${def.displayName} (${state})`; }
60
69
return def.displayName;
@@ -77,7 +86,7 @@ function selectTool (next)
77
86
tool = {
78
87
kind: next.kind,
79
88
typeId: next.typeId,
80
state: defaultStateForType(catalog, layer, def.key)
89
state: next.state ?? defaultStateForType(catalog, layer, def.key)
81
90
};
82
91
}
83
92
@@ -419,7 +428,19 @@ async function main ()
419
428
420
429
paletteModal = initPaletteModal({
421
430
catalog,
422
imageUrlFor: (name) => imageUrlByName.get(name) ?? null,
431
imageUrlFor (name)
432
{
433
const sprite = game.images[name];
434
const html = sprite?.g_image;
435
if (html && typeof html.toDataURL === "function")
436
{
437
try
438
{ return html.toDataURL("image/png"); }
439
catch (_)
440
{ /* fall through */ }
441
}
442
return imageUrlByName.get(name) ?? null;
443
},
423
444
onSelect (next)
424
445
{
425
446
selectTool(next);
@@ -3,8 +3,10 @@ import {3
GROUND_DEFINITIONS,3
GROUND_DEFINITIONS,4
BLOCK_DEFINITIONS,4
BLOCK_DEFINITIONS,5
GroundType,5
GroundType,6
BlockType,6
normalizeGround,7
normalizeGround,7
normalizeBlock8
normalizeBlock,9
listPlaceableBlockPaletteEntries8
} from "/shared/definitions/tiles.js";10
} from "/shared/definitions/tiles.js";9
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";11
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";10
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";12
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";@@ -55,6 +57,13 @@ function selectedToolLabel ()55
const layer = tool.kind === "ground" ? "ground" : "block";57
const layer = tool.kind === "ground" ? "ground" : "block";56
const states = statesForType(catalog, layer, def.key);58
const states = statesForType(catalog, layer, def.key);57
const state = resolveState(states, tool.state);59
const state = resolveState(states, tool.state);60
if (tool.kind === "block" && def.id === BlockType.boulder)61
{62
const entry = listPlaceableBlockPaletteEntries(catalog)63
.find((row) => row.typeId === def.id && row.state === state);64
if (entry)65
{ return entry.displayName; }66
}58
if (states.length > 1)67
if (states.length > 1)59
{ return `${def.displayName} (${state})`; }68
{ return `${def.displayName} (${state})`; }60
return def.displayName;69
return def.displayName;@@ -77,7 +86,7 @@ function selectTool (next)77
tool = {86
tool = {78
kind: next.kind,87
kind: next.kind,79
typeId: next.typeId,88
typeId: next.typeId,80
state: defaultStateForType(catalog, layer, def.key)89
state: next.state ?? defaultStateForType(catalog, layer, def.key)81
};90
};82
}91
}83
92
@@ -419,7 +428,19 @@ async function main ()419
428
420
paletteModal = initPaletteModal({429
paletteModal = initPaletteModal({421
catalog,430
catalog,422
imageUrlFor: (name) => imageUrlByName.get(name) ?? null,431
imageUrlFor (name)432
{433
const sprite = game.images[name];434
const html = sprite?.g_image;435
if (html && typeof html.toDataURL === "function")436
{437
try438
{ return html.toDataURL("image/png"); }439
catch (_)440
{ /* fall through */ }441
}442
return imageUrlByName.get(name) ?? null;443
},423
onSelect (next)444
onSelect (next)424
{445
{425
selectTool(next);446
selectTool(next);@@ -1,4 +1,4 @@
1
import { listPlaceableGrounds, listPlaceableBlocks } from "/shared/definitions/tiles.js";
1
import { listPlaceableGrounds, listPlaceableBlockPaletteEntries } from "/shared/definitions/tiles.js";
2
2
import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";
3
3
import { defaultStateForType, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4
4
@@ -71,19 +71,18 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
71
71
}
72
72
else if (activeTab === "blocks")
73
73
{
74
for (const def of listPlaceableBlocks())
74
for (const entry of listPlaceableBlockPaletteEntries(catalog))
75
75
{
76
const state = defaultStateForType(catalog, "block", def.key);
77
const name = spriteImageName("block", def.key, resolveState(
78
catalog.blocks?.[def.key]?.states ?? [],
79
state
80
));
81
76
grid.append(tileCard({
82
label: def.displayName,
83
url: imageUrlFor?.(name),
77
label: entry.displayName,
78
url: imageUrlFor?.(entry.spriteName),
84
79
onClick ()
85
80
{
86
onSelect({ kind: "block", typeId: def.id });
81
onSelect({
82
kind: "block",
83
typeId: entry.typeId,
84
state: entry.state
85
});
87
86
show(false);
88
87
}
89
88
}));
@@ -1,4 +1,4 @@1
import { listPlaceableGrounds, listPlaceableBlocks } from "/shared/definitions/tiles.js";1
import { listPlaceableGrounds, listPlaceableBlockPaletteEntries } from "/shared/definitions/tiles.js";2
import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";2
import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";3
import { defaultStateForType, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";3
import { defaultStateForType, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";4
4
@@ -71,19 +71,18 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })71
}71
}72
else if (activeTab === "blocks")72
else if (activeTab === "blocks")73
{73
{74
for (const def of listPlaceableBlocks())74
for (const entry of listPlaceableBlockPaletteEntries(catalog))75
{75
{76
const state = defaultStateForType(catalog, "block", def.key);77
const name = spriteImageName("block", def.key, resolveState(78
catalog.blocks?.[def.key]?.states ?? [],79
state80
));81
grid.append(tileCard({76
grid.append(tileCard({82
label: def.displayName,77
label: entry.displayName,83
url: imageUrlFor?.(name),78
url: imageUrlFor?.(entry.spriteName),84
onClick ()79
onClick ()85
{80
{86
onSelect({ kind: "block", typeId: def.id });81
onSelect({82
kind: "block",83
typeId: entry.typeId,84
state: entry.state85
});87
show(false);86
show(false);88
}87
}89
}));88
}));@@ -1,4 +1,8 @@
1
import { itemAssetPathForStack } from "/shared/definitions/items.js";
2
import { applyItemIcon } from "../render/potionIcon.js";
3
1
4
const BUBBLE_MS = 8000;
5
const ITEM_BUBBLE_MS = 4000;
2
6
3
7
export function initChat ({ socket, MessageType, getSettings })
4
8
{
@@ -6,6 +10,7 @@ export function initChat ({ socket, MessageType, getSettings })
6
10
const input = document.getElementById("chat-input");
7
11
const layer = document.getElementById("chat-bubbles");
8
12
const bubbles = new Map();
13
const itemBubbles = new Map();
9
14
let open = false;
10
15
11
16
function maxChars ()
@@ -79,6 +84,20 @@ export function initChat ({ socket, MessageType, getSettings })
79
84
{ openBar(); }
80
85
}, true);
81
86
87
function positionBubble (bubble, view, rect)
88
{
89
const entity = view.entities.get(bubble.entityId);
90
const anchor = entity ? view.nametagAnchor(entity) : null;
91
if (!anchor)
92
{
93
bubble.element.hidden = true;
94
return;
95
}
96
bubble.element.hidden = false;
97
bubble.element.style.left = `${rect.left + anchor.x}px`;
98
bubble.element.style.top = `${rect.top + anchor.y - 36}px`;
99
}
100
82
101
return {
83
102
isOpen: () => open,
84
103
isBlocking ()
@@ -96,6 +115,7 @@ export function initChat ({ socket, MessageType, getSettings })
96
115
close();
97
116
layer.replaceChildren();
98
117
bubbles.clear();
118
itemBubbles.clear();
99
119
},
100
120
showBubble (message)
101
121
{
@@ -104,7 +124,7 @@ export function initChat ({ socket, MessageType, getSettings })
104
124
let bubble = bubbles.get(message.entityId);
105
125
if (!bubble)
106
126
{
107
bubble = { element: document.createElement("div"), until: 0 };
127
bubble = { element: document.createElement("div"), until: 0, entityId: message.entityId };
108
128
bubble.element.className = "chat-bubble";
109
129
layer.append(bubble.element);
110
130
bubbles.set(message.entityId, bubble);
@@ -114,6 +134,35 @@ export function initChat ({ socket, MessageType, getSettings })
114
134
bubble.element.style.opacity = String(readability);
115
135
bubble.until = Date.now() + BUBBLE_MS;
116
136
},
137
showItemBubble (message)
138
{
139
if (message?.itemId == null || message?.entityId == null)
140
{ return; }
141
let bubble = itemBubbles.get(message.entityId);
142
if (!bubble)
143
{
144
bubble = {
145
element: document.createElement("div"),
146
until: 0,
147
entityId: message.entityId
148
};
149
bubble.element.className = "item-bubble";
150
const img = document.createElement("img");
151
img.alt = "";
152
bubble.element.append(img);
153
layer.append(bubble.element);
154
itemBubbles.set(message.entityId, bubble);
155
}
156
const stack = {
157
itemId: message.itemId,
158
quantity: Math.max(1, message.quantity | 0 || 1)
159
};
160
const img = bubble.element.querySelector("img");
161
applyItemIcon(img, stack, itemAssetPathForStack(stack));
162
const readability = Math.min(1, Math.max(0, Number(message.readability ?? 1)));
163
bubble.element.style.opacity = String(readability);
164
bubble.until = Date.now() + ITEM_BUBBLE_MS;
165
},
117
166
syncSettings ()
118
167
{
119
168
input.maxLength = maxChars();
@@ -127,24 +176,18 @@ export function initChat ({ socket, MessageType, getSettings })
127
176
if (!canvas)
128
177
{ return; }
129
178
const rect = canvas.getBoundingClientRect();
130
for (const [entityId, bubble] of [...bubbles.entries()])
179
for (const map of [bubbles, itemBubbles])
131
180
{
132
if (now >= bubble.until)
133
{
134
bubble.element.remove();
135
bubbles.delete(entityId);
136
continue;
137
}
138
const entity = view.entities.get(entityId);
139
const anchor = entity ? view.nametagAnchor(entity) : null;
140
if (!anchor)
181
for (const [entityId, bubble] of [...map.entries()])
141
182
{
142
bubble.element.hidden = true;
143
continue;
183
if (now >= bubble.until)
184
{
185
bubble.element.remove();
186
map.delete(entityId);
187
continue;
188
}
189
positionBubble(bubble, view, rect);
144
190
}
145
bubble.element.hidden = false;
146
bubble.element.style.left = `${rect.left + anchor.x}px`;
147
bubble.element.style.top = `${rect.top + anchor.y - 36}px`;
148
191
}
149
192
}
150
193
};
@@ -1,4 +1,8 @@1
import { itemAssetPathForStack } from "/shared/definitions/items.js";2
import { applyItemIcon } from "../render/potionIcon.js";3
1
const BUBBLE_MS = 8000;4
const BUBBLE_MS = 8000;5
const ITEM_BUBBLE_MS = 4000;2
6
3
export function initChat ({ socket, MessageType, getSettings })7
export function initChat ({ socket, MessageType, getSettings })4
{8
{@@ -6,6 +10,7 @@ export function initChat ({ socket, MessageType, getSettings })6
const input = document.getElementById("chat-input");10
const input = document.getElementById("chat-input");7
const layer = document.getElementById("chat-bubbles");11
const layer = document.getElementById("chat-bubbles");8
const bubbles = new Map();12
const bubbles = new Map();13
const itemBubbles = new Map();9
let open = false;14
let open = false;10
15
11
function maxChars ()16
function maxChars ()@@ -79,6 +84,20 @@ export function initChat ({ socket, MessageType, getSettings })79
{ openBar(); }84
{ openBar(); }80
}, true);85
}, true);81
86
87
function positionBubble (bubble, view, rect)88
{89
const entity = view.entities.get(bubble.entityId);90
const anchor = entity ? view.nametagAnchor(entity) : null;91
if (!anchor)92
{93
bubble.element.hidden = true;94
return;95
}96
bubble.element.hidden = false;97
bubble.element.style.left = `${rect.left + anchor.x}px`;98
bubble.element.style.top = `${rect.top + anchor.y - 36}px`;99
}100
82
return {101
return {83
isOpen: () => open,102
isOpen: () => open,84
isBlocking ()103
isBlocking ()@@ -96,6 +115,7 @@ export function initChat ({ socket, MessageType, getSettings })96
close();115
close();97
layer.replaceChildren();116
layer.replaceChildren();98
bubbles.clear();117
bubbles.clear();118
itemBubbles.clear();99
},119
},100
showBubble (message)120
showBubble (message)101
{121
{@@ -104,7 +124,7 @@ export function initChat ({ socket, MessageType, getSettings })104
let bubble = bubbles.get(message.entityId);124
let bubble = bubbles.get(message.entityId);105
if (!bubble)125
if (!bubble)106
{126
{107
bubble = { element: document.createElement("div"), until: 0 };127
bubble = { element: document.createElement("div"), until: 0, entityId: message.entityId };108
bubble.element.className = "chat-bubble";128
bubble.element.className = "chat-bubble";109
layer.append(bubble.element);129
layer.append(bubble.element);110
bubbles.set(message.entityId, bubble);130
bubbles.set(message.entityId, bubble);@@ -114,6 +134,35 @@ export function initChat ({ socket, MessageType, getSettings })114
bubble.element.style.opacity = String(readability);134
bubble.element.style.opacity = String(readability);115
bubble.until = Date.now() + BUBBLE_MS;135
bubble.until = Date.now() + BUBBLE_MS;116
},136
},137
showItemBubble (message)138
{139
if (message?.itemId == null || message?.entityId == null)140
{ return; }141
let bubble = itemBubbles.get(message.entityId);142
if (!bubble)143
{144
bubble = {145
element: document.createElement("div"),146
until: 0,147
entityId: message.entityId148
};149
bubble.element.className = "item-bubble";150
const img = document.createElement("img");151
img.alt = "";152
bubble.element.append(img);153
layer.append(bubble.element);154
itemBubbles.set(message.entityId, bubble);155
}156
const stack = {157
itemId: message.itemId,158
quantity: Math.max(1, message.quantity | 0 || 1)159
};160
const img = bubble.element.querySelector("img");161
applyItemIcon(img, stack, itemAssetPathForStack(stack));162
const readability = Math.min(1, Math.max(0, Number(message.readability ?? 1)));163
bubble.element.style.opacity = String(readability);164
bubble.until = Date.now() + ITEM_BUBBLE_MS;165
},117
syncSettings ()166
syncSettings ()118
{167
{119
input.maxLength = maxChars();168
input.maxLength = maxChars();@@ -127,24 +176,18 @@ export function initChat ({ socket, MessageType, getSettings })127
if (!canvas)176
if (!canvas)128
{ return; }177
{ return; }129
const rect = canvas.getBoundingClientRect();178
const rect = canvas.getBoundingClientRect();130
for (const [entityId, bubble] of [...bubbles.entries()])179
for (const map of [bubbles, itemBubbles])131
{180
{132
if (now >= bubble.until)181
for (const [entityId, bubble] of [...map.entries()])133
{134
bubble.element.remove();135
bubbles.delete(entityId);136
continue;137
}138
const entity = view.entities.get(entityId);139
const anchor = entity ? view.nametagAnchor(entity) : null;140
if (!anchor)141
{182
{142
bubble.element.hidden = true;183
if (now >= bubble.until)143
continue;184
{185
bubble.element.remove();186
map.delete(entityId);187
continue;188
}189
positionBubble(bubble, view, rect);144
}190
}145
bubble.element.hidden = false;146
bubble.element.style.left = `${rect.left + anchor.x}px`;147
bubble.element.style.top = `${rect.top + anchor.y - 36}px`;148
}191
}149
}192
}150
};193
};@@ -12,6 +12,7 @@ import {
12
12
hasRecipeInputs,
13
13
recipesForStation
14
14
} from "/shared/crafting/recipes.js";
15
import { applyItemIcon } from "../render/potionIcon.js";
15
16
16
17
export function initCrafting ({
17
18
socket,
@@ -86,8 +87,8 @@ export function initCrafting ({
86
87
{ cell.classList.add("selected"); }
87
88
88
89
const img = document.createElement("img");
89
img.src = itemAssetPathForStack(stack);
90
90
img.alt = def?.displayName ?? "Item";
91
applyItemIcon(img, stack, itemAssetPathForStack(stack));
91
92
92
93
const label = document.createElement("span");
93
94
label.className = "craft-recipe-name";
@@ -121,7 +122,7 @@ export function initCrafting ({
121
122
itemId: recipe.output.itemId,
122
123
quantity: Math.max(1, recipe.output.quantity | 0 || 1)
123
124
};
124
outputImg.src = itemAssetPathForStack(outputStack);
125
applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
125
126
outputImg.alt = itemDisplayName(outputStack);
126
127
const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
127
128
outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
@@ -147,8 +148,8 @@ export function initCrafting ({
147
148
{ row.classList.add("short"); }
148
149
149
150
const img = document.createElement("img");
150
img.src = itemAssetPathForStack(stack);
151
151
img.alt = itemDisplayName(stack);
152
applyItemIcon(img, stack, itemAssetPathForStack(stack));
152
153
153
154
const text = document.createElement("span");
154
155
text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
@@ -12,6 +12,7 @@ import {12
hasRecipeInputs,12
hasRecipeInputs,13
recipesForStation13
recipesForStation14
} from "/shared/crafting/recipes.js";14
} from "/shared/crafting/recipes.js";15
import { applyItemIcon } from "../render/potionIcon.js";15
16
16
export function initCrafting ({17
export function initCrafting ({17
socket,18
socket,@@ -86,8 +87,8 @@ export function initCrafting ({86
{ cell.classList.add("selected"); }87
{ cell.classList.add("selected"); }87
88
88
const img = document.createElement("img");89
const img = document.createElement("img");89
img.src = itemAssetPathForStack(stack);90
img.alt = def?.displayName ?? "Item";90
img.alt = def?.displayName ?? "Item";91
applyItemIcon(img, stack, itemAssetPathForStack(stack));91
92
92
const label = document.createElement("span");93
const label = document.createElement("span");93
label.className = "craft-recipe-name";94
label.className = "craft-recipe-name";@@ -121,7 +122,7 @@ export function initCrafting ({121
itemId: recipe.output.itemId,122
itemId: recipe.output.itemId,122
quantity: Math.max(1, recipe.output.quantity | 0 || 1)123
quantity: Math.max(1, recipe.output.quantity | 0 || 1)123
};124
};124
outputImg.src = itemAssetPathForStack(outputStack);125
applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));125
outputImg.alt = itemDisplayName(outputStack);126
outputImg.alt = itemDisplayName(outputStack);126
const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";127
const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";127
outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;128
outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;@@ -147,8 +148,8 @@ export function initCrafting ({147
{ row.classList.add("short"); }148
{ row.classList.add("short"); }148
149
149
const img = document.createElement("img");150
const img = document.createElement("img");150
img.src = itemAssetPathForStack(stack);151
img.alt = itemDisplayName(stack);151
img.alt = itemDisplayName(stack);152
applyItemIcon(img, stack, itemAssetPathForStack(stack));152
153
153
const text = document.createElement("span");154
const text = document.createElement("span");154
text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;155
text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;@@ -9,9 +9,11 @@ import { initInventory } from "./inventory.js";
9
9
import { initSkills } from "./skills.js";
10
10
import { initCrafting } from "./crafting.js";
11
11
import { initAlchemy } from "./alchemy.js";
12
import { initStamina } from "./stamina.js";
12
13
import { initContextMenu } from "./contextMenu.js";
13
14
import { initDeath } from "./death.js";
14
15
import { CraftingStationId } from "/shared/definitions/craftingStations.js";
16
import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
15
17
import { formatQuantity } from "/shared/items/formatQuantity.js";
16
18
17
19
const game = new Game();
@@ -34,10 +36,11 @@ let inventory;
34
36
let skills;
35
37
let crafting;
36
38
let alchemy;
39
let staminaUi;
37
40
let contextMenu;
38
41
let death;
39
42
let pendingPickup = null;
40
/** @type {{ kind: "bank" | "cauldron", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
43
/** @type {{ kind: "bank" | "cauldron" | "furnace" | "mine", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
41
44
let pendingInteract = null;
42
45
/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
43
46
let leftClickConsumed = false;
@@ -150,6 +153,28 @@ function requestOpenCauldron (tileX, tileY)
150
153
{ approachAdjacentTile(tileX, tileY); }
151
154
}
152
155
156
function requestOpenFurnace (tileX, tileY)
157
{
158
clearAllPendingActions();
159
pendingInteract = { kind: "furnace", tileX, tileY };
160
const local = view?.entities.get(view.localEntityId);
161
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
162
{ flushPendingInteract(); }
163
else
164
{ approachAdjacentTile(tileX, tileY); }
165
}
166
167
function requestMine (tileX, tileY)
168
{
169
clearAllPendingActions();
170
pendingInteract = { kind: "mine", tileX, tileY };
171
const local = view?.entities.get(view.localEntityId);
172
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
173
{ flushPendingInteract(); }
174
else
175
{ approachAdjacentTile(tileX, tileY); }
176
}
177
153
178
function requestTalk (targetEntityId)
154
179
{
155
180
clearPendingPickup();
@@ -193,6 +218,28 @@ function flushPendingInteract ()
193
218
return;
194
219
}
195
220
221
if (pendingInteract.kind === "furnace")
222
{
223
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
224
{ return; }
225
socket.send({ type: MessageType.openFurnace });
226
clearPendingInteract();
227
return;
228
}
229
230
if (pendingInteract.kind === "mine")
231
{
232
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
233
{ return; }
234
socket.send({
235
type: MessageType.mine,
236
tileX: pendingInteract.tileX,
237
tileY: pendingInteract.tileY
238
});
239
clearPendingInteract();
240
return;
241
}
242
196
243
if (pendingInteract.kind === "talk")
197
244
{
198
245
const target = view.entities.get(pendingInteract.targetEntityId);
@@ -300,6 +347,10 @@ function handleLeftClick (mouseX, mouseY)
300
347
{ requestOpenBank(tile.tileX, tile.tileY); }
301
348
else if (isCauldronTile(view, tile.tileX, tile.tileY))
302
349
{ requestOpenCauldron(tile.tileX, tile.tileY); }
350
else if (isFurnaceTile(view, tile.tileX, tile.tileY))
351
{ requestOpenFurnace(tile.tileX, tile.tileY); }
352
else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
353
{ requestMine(tile.tileX, tile.tileY); }
303
354
else
304
355
{
305
356
clearAllPendingActions();
@@ -392,6 +443,22 @@ function handleRightClick (event, mouseX, mouseY)
392
443
});
393
444
}
394
445
446
if (isFurnaceTile(view, tile.tileX, tile.tileY))
447
{
448
items.push({
449
label: "Smelt",
450
onSelect: () => requestOpenFurnace(tile.tileX, tile.tileY)
451
});
452
}
453
454
if (isOreBoulderTile(view, tile.tileX, tile.tileY))
455
{
456
items.push({
457
label: "Mine",
458
onSelect: () => requestMine(tile.tileX, tile.tileY)
459
});
460
}
461
395
462
contextMenu.show(event.clientX, event.clientY, items);
396
463
}
397
464
@@ -421,6 +488,9 @@ function startPlay (payload)
421
488
document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
422
489
gait = payload.gait ?? GAIT.walk;
423
490
document.getElementById("gait").textContent = gait;
491
staminaUi?.show();
492
if (payload.stamina != null)
493
{ staminaUi?.apply(payload.stamina); }
424
494
if (!scene)
425
495
{
426
496
scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
@@ -445,9 +515,16 @@ function startPlay (payload)
445
515
}
446
516
if (GameInput.isPressed(82) && !uiBlocked())
447
517
{
448
gait = gait === GAIT.run ? GAIT.walk : GAIT.run;
449
socket.send({ type: MessageType.setGait, gait });
450
document.getElementById("gait").textContent = gait;
518
const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
519
if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
520
{ return; }
521
socket.send({ type: MessageType.setGait, gait: next });
522
// Walk always applies; run waits for authoritative STAMINA (may reject if empty).
523
if (next === GAIT.walk)
524
{
525
gait = next;
526
document.getElementById("gait").textContent = gait;
527
}
451
528
}
452
529
if (playing && !death?.isBlocking())
453
530
{
@@ -546,6 +623,7 @@ async function main ()
546
623
return inventory?.getInventorySlots?.() ?? [];
547
624
}
548
625
});
626
staminaUi = initStamina();
549
627
chat = initChat({
550
628
socket: { send (payload) { socket.send(payload); } },
551
629
MessageType,
@@ -578,6 +656,18 @@ async function main ()
578
656
case MessageType.chunkSnapshot:
579
657
view?.applySnapshot(message);
580
658
break;
659
case MessageType.chunkDelta:
660
for (const tile of message.tiles ?? [])
661
{
662
view?.updateAuthoredTile(
663
message.chunkX,
664
message.chunkY,
665
tile.localX,
666
tile.localY,
667
{ ground: tile.ground, block: tile.block, light: tile.light }
668
);
669
}
670
break;
581
671
case MessageType.unsubscribeChunk:
582
672
view?.removeChunk(message.chunkX, message.chunkY);
583
673
break;
@@ -613,6 +703,14 @@ async function main ()
613
703
skills?.render(message.skills);
614
704
crafting?.refresh();
615
705
break;
706
case MessageType.stamina:
707
staminaUi?.apply(message);
708
if (message.gait)
709
{
710
gait = message.gait;
711
document.getElementById("gait").textContent = gait;
712
}
713
break;
616
714
case MessageType.bankSnapshot:
617
715
inventory?.handleBank(message);
618
716
break;
@@ -648,6 +746,20 @@ async function main ()
648
746
case MessageType.combatSwing:
649
747
view?.spawnCombatSwing(message);
650
748
break;
749
case MessageType.gatherSwing:
750
case MessageType.tileShove:
751
view?.spawnGatherSwing(message);
752
break;
753
case MessageType.stationOpen:
754
if (message.stationId)
755
{ crafting?.openStation(message.stationId); }
756
break;
757
case MessageType.itemBubble:
758
chat?.showItemBubble(message);
759
break;
760
case MessageType.gatherComplete:
761
crafting?.refresh();
762
break;
651
763
case MessageType.combatHit:
652
764
view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
653
765
view?.flashDamage(message.targetId);
@@ -661,6 +773,13 @@ async function main ()
661
773
case MessageType.playerRespawned:
662
774
death?.hide();
663
775
view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
776
if (message.stamina != null || message.maxStamina != null)
777
{
778
staminaUi?.apply({
779
current: message.stamina ?? staminaUi.getCurrent?.(),
780
max: message.maxStamina ?? staminaUi.getMax?.()
781
});
782
}
664
783
break;
665
784
case MessageType.error:
666
785
showError(message.message);
@@ -696,6 +815,7 @@ function returnToMenu (reason = "")
696
815
inventory?.reset();
697
816
crafting?.reset();
698
817
alchemy?.reset();
818
staminaUi?.hide();
699
819
skills?.hide();
700
820
contextMenu?.hide();
701
821
death?.reset();
@@ -747,7 +867,23 @@ function isCauldronTile (view, tileX, tileY)
747
867
return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
748
868
}
749
869
870
function isFurnaceTile (view, tileX, tileY)
871
{
872
return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
873
}
874
875
function isOreBoulderTile (view, tileX, tileY)
876
{
877
const block = blockAt(view, tileX, tileY);
878
return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
879
}
880
750
881
function blockTypeAt (view, tileX, tileY)
882
{
883
return blockAt(view, tileX, tileY)?.typeId ?? null;
884
}
885
886
function blockAt (view, tileX, tileY)
751
887
{
752
888
const chunkX = Math.floor(tileX / CHUNK_SIZE);
753
889
const chunkY = Math.floor(tileY / CHUNK_SIZE);
@@ -756,7 +892,7 @@ function blockTypeAt (view, tileX, tileY)
756
892
{ return null; }
757
893
const localX = tileX - chunkX * CHUNK_SIZE;
758
894
const localY = tileY - chunkY * CHUNK_SIZE;
759
return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId ?? null;
895
return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
760
896
}
761
897
762
898
function chebyshev (ax, ay, bx, by)
@@ -9,9 +9,11 @@ import { initInventory } from "./inventory.js";9
import { initSkills } from "./skills.js";9
import { initSkills } from "./skills.js";10
import { initCrafting } from "./crafting.js";10
import { initCrafting } from "./crafting.js";11
import { initAlchemy } from "./alchemy.js";11
import { initAlchemy } from "./alchemy.js";12
import { initStamina } from "./stamina.js";12
import { initContextMenu } from "./contextMenu.js";13
import { initContextMenu } from "./contextMenu.js";13
import { initDeath } from "./death.js";14
import { initDeath } from "./death.js";14
import { CraftingStationId } from "/shared/definitions/craftingStations.js";15
import { CraftingStationId } from "/shared/definitions/craftingStations.js";16
import { isOreBoulderState } from "/shared/definitions/materialTiers.js";15
import { formatQuantity } from "/shared/items/formatQuantity.js";17
import { formatQuantity } from "/shared/items/formatQuantity.js";16
18
17
const game = new Game();19
const game = new Game();@@ -34,10 +36,11 @@ let inventory;34
let skills;36
let skills;35
let crafting;37
let crafting;36
let alchemy;38
let alchemy;39
let staminaUi;37
let contextMenu;40
let contextMenu;38
let death;41
let death;39
let pendingPickup = null;42
let pendingPickup = null;40
/** @type {{ kind: "bank" | "cauldron", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */43
/** @type {{ kind: "bank" | "cauldron" | "furnace" | "mine", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */41
let pendingInteract = null;44
let pendingInteract = null;42
/** Framework can report mousePressed for two frames; latch so one physical click is one command. */45
/** Framework can report mousePressed for two frames; latch so one physical click is one command. */43
let leftClickConsumed = false;46
let leftClickConsumed = false;@@ -150,6 +153,28 @@ function requestOpenCauldron (tileX, tileY)150
{ approachAdjacentTile(tileX, tileY); }153
{ approachAdjacentTile(tileX, tileY); }151
}154
}152
155
156
function requestOpenFurnace (tileX, tileY)157
{158
clearAllPendingActions();159
pendingInteract = { kind: "furnace", tileX, tileY };160
const local = view?.entities.get(view.localEntityId);161
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)162
{ flushPendingInteract(); }163
else164
{ approachAdjacentTile(tileX, tileY); }165
}166
167
function requestMine (tileX, tileY)168
{169
clearAllPendingActions();170
pendingInteract = { kind: "mine", tileX, tileY };171
const local = view?.entities.get(view.localEntityId);172
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)173
{ flushPendingInteract(); }174
else175
{ approachAdjacentTile(tileX, tileY); }176
}177
153
function requestTalk (targetEntityId)178
function requestTalk (targetEntityId)154
{179
{155
clearPendingPickup();180
clearPendingPickup();@@ -193,6 +218,28 @@ function flushPendingInteract ()193
return;218
return;194
}219
}195
220
221
if (pendingInteract.kind === "furnace")222
{223
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)224
{ return; }225
socket.send({ type: MessageType.openFurnace });226
clearPendingInteract();227
return;228
}229
230
if (pendingInteract.kind === "mine")231
{232
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)233
{ return; }234
socket.send({235
type: MessageType.mine,236
tileX: pendingInteract.tileX,237
tileY: pendingInteract.tileY238
});239
clearPendingInteract();240
return;241
}242
196
if (pendingInteract.kind === "talk")243
if (pendingInteract.kind === "talk")197
{244
{198
const target = view.entities.get(pendingInteract.targetEntityId);245
const target = view.entities.get(pendingInteract.targetEntityId);@@ -300,6 +347,10 @@ function handleLeftClick (mouseX, mouseY)300
{ requestOpenBank(tile.tileX, tile.tileY); }347
{ requestOpenBank(tile.tileX, tile.tileY); }301
else if (isCauldronTile(view, tile.tileX, tile.tileY))348
else if (isCauldronTile(view, tile.tileX, tile.tileY))302
{ requestOpenCauldron(tile.tileX, tile.tileY); }349
{ requestOpenCauldron(tile.tileX, tile.tileY); }350
else if (isFurnaceTile(view, tile.tileX, tile.tileY))351
{ requestOpenFurnace(tile.tileX, tile.tileY); }352
else if (isOreBoulderTile(view, tile.tileX, tile.tileY))353
{ requestMine(tile.tileX, tile.tileY); }303
else354
else304
{355
{305
clearAllPendingActions();356
clearAllPendingActions();@@ -392,6 +443,22 @@ function handleRightClick (event, mouseX, mouseY)392
});443
});393
}444
}394
445
446
if (isFurnaceTile(view, tile.tileX, tile.tileY))447
{448
items.push({449
label: "Smelt",450
onSelect: () => requestOpenFurnace(tile.tileX, tile.tileY)451
});452
}453
454
if (isOreBoulderTile(view, tile.tileX, tile.tileY))455
{456
items.push({457
label: "Mine",458
onSelect: () => requestMine(tile.tileX, tile.tileY)459
});460
}461
395
contextMenu.show(event.clientX, event.clientY, items);462
contextMenu.show(event.clientX, event.clientY, items);396
}463
}397
464
@@ -421,6 +488,9 @@ function startPlay (payload)421
document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;488
document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;422
gait = payload.gait ?? GAIT.walk;489
gait = payload.gait ?? GAIT.walk;423
document.getElementById("gait").textContent = gait;490
document.getElementById("gait").textContent = gait;491
staminaUi?.show();492
if (payload.stamina != null)493
{ staminaUi?.apply(payload.stamina); }424
if (!scene)494
if (!scene)425
{495
{426
scene = new Scene(0, 0, window.innerWidth, window.innerHeight);496
scene = new Scene(0, 0, window.innerWidth, window.innerHeight);@@ -445,9 +515,16 @@ function startPlay (payload)445
}515
}446
if (GameInput.isPressed(82) && !uiBlocked())516
if (GameInput.isPressed(82) && !uiBlocked())447
{517
{448
gait = gait === GAIT.run ? GAIT.walk : GAIT.run;518
const next = gait === GAIT.run ? GAIT.walk : GAIT.run;449
socket.send({ type: MessageType.setGait, gait });519
if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)450
document.getElementById("gait").textContent = gait;520
{ return; }521
socket.send({ type: MessageType.setGait, gait: next });522
// Walk always applies; run waits for authoritative STAMINA (may reject if empty).523
if (next === GAIT.walk)524
{525
gait = next;526
document.getElementById("gait").textContent = gait;527
}451
}528
}452
if (playing && !death?.isBlocking())529
if (playing && !death?.isBlocking())453
{530
{@@ -546,6 +623,7 @@ async function main ()546
return inventory?.getInventorySlots?.() ?? [];623
return inventory?.getInventorySlots?.() ?? [];547
}624
}548
});625
});626
staminaUi = initStamina();549
chat = initChat({627
chat = initChat({550
socket: { send (payload) { socket.send(payload); } },628
socket: { send (payload) { socket.send(payload); } },551
MessageType,629
MessageType,@@ -578,6 +656,18 @@ async function main ()578
case MessageType.chunkSnapshot:656
case MessageType.chunkSnapshot:579
view?.applySnapshot(message);657
view?.applySnapshot(message);580
break;658
break;659
case MessageType.chunkDelta:660
for (const tile of message.tiles ?? [])661
{662
view?.updateAuthoredTile(663
message.chunkX,664
message.chunkY,665
tile.localX,666
tile.localY,667
{ ground: tile.ground, block: tile.block, light: tile.light }668
);669
}670
break;581
case MessageType.unsubscribeChunk:671
case MessageType.unsubscribeChunk:582
view?.removeChunk(message.chunkX, message.chunkY);672
view?.removeChunk(message.chunkX, message.chunkY);583
break;673
break;@@ -613,6 +703,14 @@ async function main ()613
skills?.render(message.skills);703
skills?.render(message.skills);614
crafting?.refresh();704
crafting?.refresh();615
break;705
break;706
case MessageType.stamina:707
staminaUi?.apply(message);708
if (message.gait)709
{710
gait = message.gait;711
document.getElementById("gait").textContent = gait;712
}713
break;616
case MessageType.bankSnapshot:714
case MessageType.bankSnapshot:617
inventory?.handleBank(message);715
inventory?.handleBank(message);618
break;716
break;@@ -648,6 +746,20 @@ async function main ()648
case MessageType.combatSwing:746
case MessageType.combatSwing:649
view?.spawnCombatSwing(message);747
view?.spawnCombatSwing(message);650
break;748
break;749
case MessageType.gatherSwing:750
case MessageType.tileShove:751
view?.spawnGatherSwing(message);752
break;753
case MessageType.stationOpen:754
if (message.stationId)755
{ crafting?.openStation(message.stationId); }756
break;757
case MessageType.itemBubble:758
chat?.showItemBubble(message);759
break;760
case MessageType.gatherComplete:761
crafting?.refresh();762
break;651
case MessageType.combatHit:763
case MessageType.combatHit:652
view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);764
view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);653
view?.flashDamage(message.targetId);765
view?.flashDamage(message.targetId);@@ -661,6 +773,13 @@ async function main ()661
case MessageType.playerRespawned:773
case MessageType.playerRespawned:662
death?.hide();774
death?.hide();663
view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);775
view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);776
if (message.stamina != null || message.maxStamina != null)777
{778
staminaUi?.apply({779
current: message.stamina ?? staminaUi.getCurrent?.(),780
max: message.maxStamina ?? staminaUi.getMax?.()781
});782
}664
break;783
break;665
case MessageType.error:784
case MessageType.error:666
showError(message.message);785
showError(message.message);@@ -696,6 +815,7 @@ function returnToMenu (reason = "")696
inventory?.reset();815
inventory?.reset();697
crafting?.reset();816
crafting?.reset();698
alchemy?.reset();817
alchemy?.reset();818
staminaUi?.hide();699
skills?.hide();819
skills?.hide();700
contextMenu?.hide();820
contextMenu?.hide();701
death?.reset();821
death?.reset();@@ -747,7 +867,23 @@ function isCauldronTile (view, tileX, tileY)747
return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;867
return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;748
}868
}749
869
870
function isFurnaceTile (view, tileX, tileY)871
{872
return blockTypeAt(view, tileX, tileY) === BlockType.furnace;873
}874
875
function isOreBoulderTile (view, tileX, tileY)876
{877
const block = blockAt(view, tileX, tileY);878
return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);879
}880
750
function blockTypeAt (view, tileX, tileY)881
function blockTypeAt (view, tileX, tileY)882
{883
return blockAt(view, tileX, tileY)?.typeId ?? null;884
}885
886
function blockAt (view, tileX, tileY)751
{887
{752
const chunkX = Math.floor(tileX / CHUNK_SIZE);888
const chunkX = Math.floor(tileX / CHUNK_SIZE);753
const chunkY = Math.floor(tileY / CHUNK_SIZE);889
const chunkY = Math.floor(tileY / CHUNK_SIZE);@@ -756,7 +892,7 @@ function blockTypeAt (view, tileX, tileY)756
{ return null; }892
{ return null; }757
const localX = tileX - chunkX * CHUNK_SIZE;893
const localX = tileX - chunkX * CHUNK_SIZE;758
const localY = tileY - chunkY * CHUNK_SIZE;894
const localY = tileY - chunkY * CHUNK_SIZE;759
return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId ?? null;895
return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;760
}896
}761
897
762
function chebyshev (ax, ay, bx, by)898
function chebyshev (ax, ay, bx, by)@@ -0,0 +1,50 @@
1
export function initStamina ()
2
{
3
let bar = document.getElementById("stamina-bar");
4
if (!bar)
5
{
6
bar = document.createElement("div");
7
bar.id = "stamina-bar";
8
bar.hidden = true;
9
bar.innerHTML = '<div id="stamina-bar-fill"></div><span id="stamina-bar-label" class="stamina-bar-label"></span>';
10
document.body.append(bar);
11
}
12
const fill = document.getElementById("stamina-bar-fill");
13
const label = document.getElementById("stamina-bar-label");
14
15
let current = 1;
16
let max = 1;
17
18
function render ()
19
{
20
const ratio = max > 0 ? Math.min(1, Math.max(0, current / max)) : 0;
21
fill.style.transform = `scaleY(${ratio})`;
22
label.textContent = `${Math.ceil(current)}/${max | 0}`;
23
bar.classList.toggle("empty", current <= 0);
24
bar.classList.toggle("low", current > 0 && current / max <= 0.25);
25
}
26
27
return {
28
show ()
29
{
30
bar.hidden = false;
31
render();
32
},
33
hide ()
34
{
35
bar.hidden = true;
36
},
37
apply (message)
38
{
39
if (message?.max != null)
40
{ max = Math.max(1, message.max | 0); }
41
if (message?.current != null)
42
{ current = Math.max(0, Number(message.current) || 0); }
43
render();
44
},
45
getCurrent ()
46
{ return current; },
47
getMax ()
48
{ return max; }
49
};
50
}
@@ -0,0 +1,50 @@1
export function initStamina ()2
{3
let bar = document.getElementById("stamina-bar");4
if (!bar)5
{6
bar = document.createElement("div");7
bar.id = "stamina-bar";8
bar.hidden = true;9
bar.innerHTML = '<div id="stamina-bar-fill"></div><span id="stamina-bar-label" class="stamina-bar-label"></span>';10
document.body.append(bar);11
}12
const fill = document.getElementById("stamina-bar-fill");13
const label = document.getElementById("stamina-bar-label");14
15
let current = 1;16
let max = 1;17
18
function render ()19
{20
const ratio = max > 0 ? Math.min(1, Math.max(0, current / max)) : 0;21
fill.style.transform = `scaleY(${ratio})`;22
label.textContent = `${Math.ceil(current)}/${max | 0}`;23
bar.classList.toggle("empty", current <= 0);24
bar.classList.toggle("low", current > 0 && current / max <= 0.25);25
}26
27
return {28
show ()29
{30
bar.hidden = false;31
render();32
},33
hide ()34
{35
bar.hidden = true;36
},37
apply (message)38
{39
if (message?.max != null)40
{ max = Math.max(1, message.max | 0); }41
if (message?.current != null)42
{ current = Math.max(0, Number(message.current) || 0); }43
render();44
},45
getCurrent ()46
{ return current; },47
getMax ()48
{ return max; }49
};50
}@@ -1,4 +1,5 @@
1
1
import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2
import { applyMagentaTintToImageData } from "/shared/render/tint.js";
2
3
3
4
export const UTILITY_IMAGES = [
4
5
{ name: "night-shade", url: shadeDataUrl("#000000") },
@@ -44,8 +45,11 @@ function loadOneImage (game, imageData)
44
45
const img = new Image();
45
46
img.onload = () =>
46
47
{
48
const source = imageData.tint
49
? tintedHtmlImage(img, imageData.tint)
50
: img;
47
51
const finalImage = new image(
48
img,
52
source,
49
53
imageData.subImgTotal,
50
54
imageData.perRow,
51
55
imageData.loop,
@@ -63,6 +67,20 @@ function loadOneImage (game, imageData)
63
67
});
64
68
}
65
69
70
function tintedHtmlImage (sourceImg, tintRgb)
71
{
72
const canvas = document.createElement("canvas");
73
canvas.width = sourceImg.naturalWidth || sourceImg.width;
74
canvas.height = sourceImg.naturalHeight || sourceImg.height;
75
const ctx = canvas.getContext("2d");
76
ctx.imageSmoothingEnabled = false;
77
ctx.drawImage(sourceImg, 0, 0);
78
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
79
applyMagentaTintToImageData(imageData, tintRgb);
80
ctx.putImageData(imageData, 0, 0);
81
return canvas;
82
}
83
66
84
export function applySpriteSheets (images, catalog)
67
85
{
68
86
for (const entry of catalog?.images ?? [])
@@ -1,4 +1,5 @@1
import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";1
import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";2
import { applyMagentaTintToImageData } from "/shared/render/tint.js";2
3
3
export const UTILITY_IMAGES = [4
export const UTILITY_IMAGES = [4
{ name: "night-shade", url: shadeDataUrl("#000000") },5
{ name: "night-shade", url: shadeDataUrl("#000000") },@@ -44,8 +45,11 @@ function loadOneImage (game, imageData)44
const img = new Image();45
const img = new Image();45
img.onload = () =>46
img.onload = () =>46
{47
{48
const source = imageData.tint49
? tintedHtmlImage(img, imageData.tint)50
: img;47
const finalImage = new image(51
const finalImage = new image(48
img,52
source,49
imageData.subImgTotal,53
imageData.subImgTotal,50
imageData.perRow,54
imageData.perRow,51
imageData.loop,55
imageData.loop,@@ -63,6 +67,20 @@ function loadOneImage (game, imageData)63
});67
});64
}68
}65
69
70
function tintedHtmlImage (sourceImg, tintRgb)71
{72
const canvas = document.createElement("canvas");73
canvas.width = sourceImg.naturalWidth || sourceImg.width;74
canvas.height = sourceImg.naturalHeight || sourceImg.height;75
const ctx = canvas.getContext("2d");76
ctx.imageSmoothingEnabled = false;77
ctx.drawImage(sourceImg, 0, 0);78
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);79
applyMagentaTintToImageData(imageData, tintRgb);80
ctx.putImageData(imageData, 0, 0);81
return canvas;82
}83
66
export function applySpriteSheets (images, catalog)84
export function applySpriteSheets (images, catalog)67
{85
{68
for (const entry of catalog?.images ?? [])86
for (const entry of catalog?.images ?? [])@@ -613,14 +613,7 @@ export class WorldView
613
613
const target = this.entities.get(payload.targetId);
614
614
if (!attacker || !target)
615
615
{ return; }
616
attacker.shove = {
617
startVisualX: attacker.visualX,
618
startVisualY: attacker.visualY,
619
targetVisualX: target.visualX,
620
targetVisualY: target.visualY,
621
started: performance.now(),
622
durationMs: SHOVE_MS
623
};
616
this.#applyShove(attacker, target.visualX, target.visualY);
624
617
const midX = (attacker.visualX + target.visualX) / 2;
625
618
const midY = (attacker.visualY + target.visualY) / 2;
626
619
const sortY = Math.max(attacker.visualY, target.visualY) + 0.02;
@@ -642,6 +635,28 @@ export class WorldView
642
635
});
643
636
}
644
637
638
/** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
639
spawnGatherSwing (payload)
640
{
641
const attacker = this.entities.get(payload.attackerId);
642
if (!attacker)
643
{ return; }
644
const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
645
this.#applyShove(attacker, pivot.x, pivot.y);
646
}
647
648
#applyShove (entity, targetVisualX, targetVisualY)
649
{
650
entity.shove = {
651
startVisualX: entity.visualX,
652
startVisualY: entity.visualY,
653
targetVisualX,
654
targetVisualY,
655
started: performance.now(),
656
durationMs: SHOVE_MS
657
};
658
}
659
645
660
/** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
646
661
spawnPhysicalProjectileFx (payload)
647
662
{
@@ -613,14 +613,7 @@ export class WorldView613
const target = this.entities.get(payload.targetId);613
const target = this.entities.get(payload.targetId);614
if (!attacker || !target)614
if (!attacker || !target)615
{ return; }615
{ return; }616
attacker.shove = {616
this.#applyShove(attacker, target.visualX, target.visualY);617
startVisualX: attacker.visualX,618
startVisualY: attacker.visualY,619
targetVisualX: target.visualX,620
targetVisualY: target.visualY,621
started: performance.now(),622
durationMs: SHOVE_MS623
};624
const midX = (attacker.visualX + target.visualX) / 2;617
const midX = (attacker.visualX + target.visualX) / 2;625
const midY = (attacker.visualY + target.visualY) / 2;618
const midY = (attacker.visualY + target.visualY) / 2;626
const sortY = Math.max(attacker.visualY, target.visualY) + 0.02;619
const sortY = Math.max(attacker.visualY, target.visualY) + 0.02;@@ -642,6 +635,28 @@ export class WorldView642
});635
});643
}636
}644
637
638
/** Mining / gathering lunge toward a tile — shove only, no swipe FX. */639
spawnGatherSwing (payload)640
{641
const attacker = this.entities.get(payload.attackerId);642
if (!attacker)643
{ return; }644
const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());645
this.#applyShove(attacker, pivot.x, pivot.y);646
}647
648
#applyShove (entity, targetVisualX, targetVisualY)649
{650
entity.shove = {651
startVisualX: entity.visualX,652
startVisualY: entity.visualY,653
targetVisualX,654
targetVisualY,655
started: performance.now(),656
durationMs: SHOVE_MS657
};658
}659
645
/** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */660
/** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */646
spawnPhysicalProjectileFx (payload)661
spawnPhysicalProjectileFx (payload)647
{662
{@@ -800,6 +800,55 @@ a { color: #d4c48a; }
800
800
background: rgba(12, 14, 18, 0.92);
801
801
}
802
802
803
#stamina-bar {
804
position: fixed;
805
z-index: 4;
806
right: 1rem;
807
bottom: 1.25rem;
808
width: 14px;
809
height: 120px;
810
padding: 3px;
811
box-sizing: border-box;
812
background: rgba(12, 14, 18, 0.82);
813
border: 1px solid #3a4250;
814
display: flex;
815
flex-direction: column;
816
justify-content: flex-end;
817
align-items: stretch;
818
}
819
820
#stamina-bar[hidden] {
821
display: none !important;
822
}
823
824
#stamina-bar-fill {
825
flex: 1;
826
width: 100%;
827
transform-origin: bottom center;
828
transform: scaleY(1);
829
background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%);
830
border-radius: 1px;
831
transition: transform 80ms linear;
832
}
833
834
#stamina-bar.empty #stamina-bar-fill {
835
background: #4a3030;
836
}
837
838
#stamina-bar.low #stamina-bar-fill {
839
background: linear-gradient(180deg, #d4c48a 0%, #a08040 100%);
840
}
841
842
.stamina-bar-label {
843
position: absolute;
844
right: calc(100% + 0.4rem);
845
bottom: 0;
846
font-size: 0.75rem;
847
color: #9aa3b2;
848
white-space: nowrap;
849
pointer-events: none;
850
}
851
803
852
#damage-numbers {
804
853
position: fixed;
805
854
inset: 0;
@@ -839,3 +888,27 @@ a { color: #d4c48a; }
839
888
.chat-bubble[hidden] {
840
889
display: none !important;
841
890
}
891
892
.item-bubble {
893
position: fixed;
894
z-index: 4;
895
pointer-events: none;
896
transform: translate(-50%, -100%) scale(0.5);
897
transform-origin: bottom center;
898
background: rgba(16, 18, 24, 0.92);
899
border: 1px solid #3a4250;
900
border-radius: 8px;
901
padding: 0.35rem;
902
line-height: 0;
903
}
904
905
.item-bubble img {
906
display: block;
907
width: 32px;
908
height: 32px;
909
image-rendering: pixelated;
910
}
911
912
.item-bubble[hidden] {
913
display: none !important;
914
}
@@ -800,6 +800,55 @@ a { color: #d4c48a; }800
background: rgba(12, 14, 18, 0.92);800
background: rgba(12, 14, 18, 0.92);801
}801
}802
802
803
#stamina-bar {804
position: fixed;805
z-index: 4;806
right: 1rem;807
bottom: 1.25rem;808
width: 14px;809
height: 120px;810
padding: 3px;811
box-sizing: border-box;812
background: rgba(12, 14, 18, 0.82);813
border: 1px solid #3a4250;814
display: flex;815
flex-direction: column;816
justify-content: flex-end;817
align-items: stretch;818
}819
820
#stamina-bar[hidden] {821
display: none !important;822
}823
824
#stamina-bar-fill {825
flex: 1;826
width: 100%;827
transform-origin: bottom center;828
transform: scaleY(1);829
background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%);830
border-radius: 1px;831
transition: transform 80ms linear;832
}833
834
#stamina-bar.empty #stamina-bar-fill {835
background: #4a3030;836
}837
838
#stamina-bar.low #stamina-bar-fill {839
background: linear-gradient(180deg, #d4c48a 0%, #a08040 100%);840
}841
842
.stamina-bar-label {843
position: absolute;844
right: calc(100% + 0.4rem);845
bottom: 0;846
font-size: 0.75rem;847
color: #9aa3b2;848
white-space: nowrap;849
pointer-events: none;850
}851
803
#damage-numbers {852
#damage-numbers {804
position: fixed;853
position: fixed;805
inset: 0;854
inset: 0;@@ -839,3 +888,27 @@ a { color: #d4c48a; }839
.chat-bubble[hidden] {888
.chat-bubble[hidden] {840
display: none !important;889
display: none !important;841
}890
}891
892
.item-bubble {893
position: fixed;894
z-index: 4;895
pointer-events: none;896
transform: translate(-50%, -100%) scale(0.5);897
transform-origin: bottom center;898
background: rgba(16, 18, 24, 0.92);899
border: 1px solid #3a4250;900
border-radius: 8px;901
padding: 0.35rem;902
line-height: 0;903
}904
905
.item-bubble img {906
display: block;907
width: 32px;908
height: 32px;909
image-rendering: pixelated;910
}911
912
.item-bubble[hidden] {913
display: none !important;914
}@@ -228,65 +228,35 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
228
228
## Equipment tiers and worn stat bonuses
229
229
230
230
**Status:** partial
231
**Spec:** Metal gear exists in six material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**. Bronze has no extra gate (min relevant skill 1). Every higher tier requires a minimum level of the item's **relevant skill** (weapons → their hit skill e.g. Sword fighting; metal armour & shields → Defence; bows → Archery; wizard cloth & staves → Magic; gathering tools → Woodcutting / Mining / Fishing). Tier min levels and per-tier stat bonuses live in `shared/definitions/materialTiers.js`. Worn items add flat bonuses to **effective** combat stats (not base skill XP): metal weapons & clubs → Strength; metal armour & shields → Defence; bows → Dexterity; wizard cloth → Magic; staves → Mind; leather armour → Dexterity (Agility); cloth armour → Defence. Item defs carry `equipment.tier`, `equipment.kind`, optional `equipment.bonus` override, and `attack.attackType`. Equip checks enforce min skill; combat rolls use `shared/equipment/stats.js`.
232
233
**Shared sprites + magenta tint:** Draw one base sprite per shape (sword, ore, bar, …). Tintable pixels use **magenta** (`R == B` and `G < R`); lightness is `R` (e.g. `(50,0,50)` dark … `(255,0,255)` bright); `G > 0` desaturates toward white. Non-magenta pixels stay as-is. World/UI apply `TIER_TINT_COLOR` (or potion `instance.color`) then darkness. See `shared/render/tint.js`.
234
235
**TODO:** full tiered item catalog (all metals, bows, shields, wizard sets, leather, tools); more shared base art; client tooltip showing reqs/bonuses.
236
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/equipmentKinds.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `shared/definitions/items.js`, `client/src/render/worldView.js` (tint lit shader), `client/src/render/potionIcon.js`, `server/src/items/bags.js`, `server/src/combat/service.js`, tests in `server/tests/equipment.test.js`, `server/tests/tint.test.js`
231
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. Coal is a gather material (dark gray tint, iron-tier mine gate) with no bar of its own.
232
**Shared sprites + magenta tint:** one base sprite per shape (ore, bar, pickaxe, boulder-ore); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint.
233
**TODO:** full combat gear catalog; woodcutting wood tiers; tooltips.
234
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
237
235
238
236
## Gathering, crafting, and production skills
239
237
240
**Status:** not implemented
241
**Spec:** Skill IDs exist for **Woodcutting**, **Mining**, **Fishing**, **Smithing**, **Crafting**, **Leatherworking**, **Tailoring**, **Cooking**, **Herbalism**, and **Alchemy**. **Axes** (Woodcutting) and **pickaxes** (Mining) are tools, not melee weapons — tier sets min Woodcutting/Mining to equip; better tools gather faster. **Plant clippers** (Herbalism) mirror that pattern for herb nodes (gather mechanics later). **Fishing rods** and **nets** use Fishing. **Smithing** crafts metal items (min Smithing per recipe). **Crafting** makes misc items (e.g. arrows from smithed tips). **Leatherworking** makes leather armour (Dexterity bonus, not Defence). **Tailoring** makes cloth armour; separate **wizard cloth** tiers grant Magic bonus. **Cooking** prepares raw food at ovens and campfires (see **Crafting stations**). **Alchemy** brews potions at a **Cauldron** (see **Alchemy / cauldron**). Gathering attempts always succeed when in range; non-cooking crafts always succeed when skill ≥ recipe min. Resources have a **minimum tier** (tool tier must meet or exceed). **Leather** needs no tool — drops from certain mobs. **TODO:** resource nodes (trees, ores, fish spots, herb nodes), gather commands, recipe data files, tool/item sprites, gather speed formula, mob leather drops, sheep shearing. Craft UI is specified under **Crafting stations**.
242
**Code:** `shared/definitions/skills.js` (skill IDs + panel entries), `shared/definitions/equipmentKinds.js` (`plantClippers`), `shared/definitions/alchemy.js`
238
**Status:** partial (mining + smelting live)
239
**Spec:** **Mining:** LMB/RMB on ore boulder (states `bronze-ore` … `dragon-ore`, `coal`). Requires equipped pickaxe with tool rank ≥ resource rank and Mining ≥ mine gate. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX. Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × material rank`, then restores its ore state via runtime `CHUNK_DELTA`. **Smelting:** furnace block opens craft UI; recipes 1 ore → 1 bar except **steel** = 1 iron ore + 1 coal. Smithing XP on success. Server-authoritative `START_CRAFT` / timer. Woodcutting / fishing / other stations later.
240
**Code:** `shared/definitions/gathering.js`, `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`
243
241
244
242
## Crafting stations
245
243
246
**Status:** UI shell + item/recipe scaffolding; server crafting not implemented
247
**Spec:** Recipes run at a **station** adjacent to or under the player (exact interaction radius TBD). Station IDs and linked skills live in `shared/definitions/craftingStations.js`.
248
249
| Station | Role | Skill |
250
| --- | --- | --- |
251
| **Furnace** | Smelt gathered **ore → bars** | Smithing |
252
| **Spinning wheel** | **Wool → thread** (wool from shorn sheep — sheep/WIP) | Tailoring |
253
| **Loom** | Weave **cloth clothing** | Tailoring |
254
| **Anvil** | Smith **metal items** from bars | Smithing |
255
| **Leatherworking station** | Craft **leather** goods | Leatherworking |
256
| **Crafting bench** | General **Crafting** (e.g. arrows + tips) | Crafting |
257
| **Oven** | Cook **raw meat** | Cooking |
258
| **Fireplace (campfire)** | Same cooking as oven | Cooking |
259
260
**Cooking:** Requires Cooking ≥ recipe minimum or the attempt can **burn** the food (lost). **Oven** uses a lower burn chance than **fireplace** for the same recipe/skill gap.
244
**Status:** partial (furnace smelting live; UI shell for others)
245
**Spec:** Furnace block (placeholder sprite) + adjacency craft panel. Recipes in `stationRecipes.js`. Server craft timer = `CRAFT_DURATION_MS` (2s). Other stations still UI/dev only (`__craftDev`).
246
**TODO:** anvil smithing recipes, oven/campfire burn, spinning wheel once sheep exist.
247
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
261
248
262
**Fireplace (portable):** Drop a **log** on the ground; **right-click the log → Start Fire** while carrying a **tinderbox** in inventory (consumes tinderbox use TBD). Creates a shared **campfire** on that tile for **10 minutes** (`FIREPLACE_DURATION_MS`). Any player may cook at it. **At most one fireplace per tile.** Fixed **oven** blocks are separate placeables (editor/content later).
263
264
**Station UI (shared across all stations):** Opening a station shows a **recipe grid** on the left — each cell is the output **item icon** with **display name** underneath. Clicking a recipe selects it; the **detail pane on the right** repeats the icon and name, lists **required materials** (icon + quantity per input), and a **Craft** button. Crafting is blocked unless the server confirms room for the product: `canCraftFitInventory()` simulates **consuming inputs first**, then inserting the output, so freed slots from spent materials count toward space (`shared/crafting/recipes.js`). While crafting, a **2 s** progress bar runs (`CRAFT_DURATION_MS`) for every recipe regardless of item. Only one craft at a time per player; closing the panel cancels in-progress craft (sends `CANCEL_CRAFT`). Cooking stations use the same shell; burn failure is an outcome after the timer, not a separate UI.
265
266
**Item scaffolding:** Reserved IDs and stub definitions for gathering/crafting content live in `shared/definitions/craftingItems.js` (`CraftingItemId`, `CRAFTING_ITEM_STUBS` merged into `ITEM_DEFINITIONS`). Replace stubs with full defs (sprites, equipment, tiers) as rules land. Recipe rows go in `shared/crafting/stationRecipes.js` (`CRAFT_RECIPES`); filter with `recipesForStation()`.
267
268
**Dev:** In the browser console, `__craftDev()` opens the crafting bench UI; pass any `CraftingStationId` string for other stations.
249
## Stamina and running
269
250
270
**TODO:** station block/entity types and sprites, real recipe tables per station, open/close from world interaction, server craft command + timer + adjacency checks, Cooking burn formula, log/tinderbox behaviour, campfire ground entity lifecycle & replication, spinning wheel wool input once sheep exist.
271
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/craftingItems.js`, `shared/definitions/itemCategories.js`, `shared/crafting/recipes.js`, `shared/crafting/stationRecipes.js`, `client/src/play/crafting.js`, `client/ui/play.css` (#craft-panel)
251
**Status:** full
252
**Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking / idle with walk gait regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows a vertical stamina bar bottom-right.
253
**Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
272
254
273
255
## Alchemy / cauldron
274
256
275
257
**Status:** partial (scaffolding)
276
**Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs (and other ingredients) at a **Cauldron** block (`BlockType.cauldron`, editor placeable). Nonstandard UI: four reserve slots above the vessel, ↓ insert arrows under each slot, **Stir / Heat / Cool** actions, **Bottle**, **Clear** (also auto-clears after bottle), and **Save Recipe** after a successful brew when the player has blank **paper**.
277
278
Slots register item+quantity without consuming until insert; insert consumes the reserved amount into the brew and records an `insert` step. Recipes list ≤4 unique ingredients as **ratios** (double inputs → double output if bottles allow; excess brew is lost without enough **glass bottles**). Steps must match; wrong order/ratios or Alchemy level below the recipe minimum yields an **Unstable Potion** chosen by hashing the step transcript (same mistakes → same failure potion). Unstable effects are stubs (slow, damage, blind, queasy). Success + paper → Save Recipe writes a unique **recipe paper** (read like a letter: ratios, steps, Alchemy level). Potions of the same type/effect stack to **16**. Shared potion art: clear bottle (= empty bottle) + fill levels 1–5 with **magenta** liquid pixels; liquid is recolored per potion `color` via the shared magenta tint path (inventory canvas; world ground items use the tint+darkness lit shader).
279
280
Example scaffold recipe: **Green draught** — heat → insert green herb → stir → insert apple → cool → Bottle (ratios 2 green herb : 1 apple).
281
282
**TODO:** more recipes, drink/effect application, herb nodes + Herbalism XP, more clipper tiers, polish cauldron art.
283
**Code:** `shared/definitions/alchemy.js`, `shared/alchemy/recipes.js`, `shared/definitions/items.js`, `shared/definitions/tiles.js` (`cauldron`), `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, `client/src/render/potionIcon.js`, `client/src/render/worldView.js` (potion shader), tests in `server/tests/alchemy.test.js`
284
285
## Stamina and running
286
287
**Status:** not implemented
288
**Spec:** **Stamina** skill sets max stamina (= skill level). Each stamina point equals **one second of running**. Running consumes stamina; running awards Stamina XP. Walking does not consume stamina. **TODO:** stamina component sync, run gate when empty, regen rules, Stamina XP on run ticks, client stamina bar.
289
**Code:** `shared/definitions/skills.js` (`playerMaxStamina` helper only)
258
**Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs at a **Cauldron** block. Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules.
259
**Code:** `shared/definitions/alchemy.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`
290
260
291
261
## Inventory, items, equipment, ground drops
292
262
@@ -228,65 +228,35 @@ Each entry is a short note on behaviour and where the code lives. Update this fi228
## Equipment tiers and worn stat bonuses228
## Equipment tiers and worn stat bonuses229
229
230
**Status:** partial 230
**Status:** partial 231
**Spec:** Metal gear exists in six material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**. Bronze has no extra gate (min relevant skill 1). Every higher tier requires a minimum level of the item's **relevant skill** (weapons → their hit skill e.g. Sword fighting; metal armour & shields → Defence; bows → Archery; wizard cloth & staves → Magic; gathering tools → Woodcutting / Mining / Fishing). Tier min levels and per-tier stat bonuses live in `shared/definitions/materialTiers.js`. Worn items add flat bonuses to **effective** combat stats (not base skill XP): metal weapons & clubs → Strength; metal armour & shields → Defence; bows → Dexterity; wizard cloth → Magic; staves → Mind; leather armour → Dexterity (Agility); cloth armour → Defence. Item defs carry `equipment.tier`, `equipment.kind`, optional `equipment.bonus` override, and `attack.attackType`. Equip checks enforce min skill; combat rolls use `shared/equipment/stats.js`.231
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. Coal is a gather material (dark gray tint, iron-tier mine gate) with no bar of its own. 232
232
**Shared sprites + magenta tint:** one base sprite per shape (ore, bar, pickaxe, boulder-ore); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. 233
**Shared sprites + magenta tint:** Draw one base sprite per shape (sword, ore, bar, …). Tintable pixels use **magenta** (`R == B` and `G < R`); lightness is `R` (e.g. `(50,0,50)` dark … `(255,0,255)` bright); `G > 0` desaturates toward white. Non-magenta pixels stay as-is. World/UI apply `TIER_TINT_COLOR` (or potion `instance.color`) then darkness. See `shared/render/tint.js`.233
**TODO:** full combat gear catalog; woodcutting wood tiers; tooltips. 234
234
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`235
**TODO:** full tiered item catalog (all metals, bows, shields, wizard sets, leather, tools); more shared base art; client tooltip showing reqs/bonuses. 236
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/equipmentKinds.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `shared/definitions/items.js`, `client/src/render/worldView.js` (tint lit shader), `client/src/render/potionIcon.js`, `server/src/items/bags.js`, `server/src/combat/service.js`, tests in `server/tests/equipment.test.js`, `server/tests/tint.test.js`237
235
238
## Gathering, crafting, and production skills236
## Gathering, crafting, and production skills239
237
240
**Status:** not implemented 238
**Status:** partial (mining + smelting live) 241
**Spec:** Skill IDs exist for **Woodcutting**, **Mining**, **Fishing**, **Smithing**, **Crafting**, **Leatherworking**, **Tailoring**, **Cooking**, **Herbalism**, and **Alchemy**. **Axes** (Woodcutting) and **pickaxes** (Mining) are tools, not melee weapons — tier sets min Woodcutting/Mining to equip; better tools gather faster. **Plant clippers** (Herbalism) mirror that pattern for herb nodes (gather mechanics later). **Fishing rods** and **nets** use Fishing. **Smithing** crafts metal items (min Smithing per recipe). **Crafting** makes misc items (e.g. arrows from smithed tips). **Leatherworking** makes leather armour (Dexterity bonus, not Defence). **Tailoring** makes cloth armour; separate **wizard cloth** tiers grant Magic bonus. **Cooking** prepares raw food at ovens and campfires (see **Crafting stations**). **Alchemy** brews potions at a **Cauldron** (see **Alchemy / cauldron**). Gathering attempts always succeed when in range; non-cooking crafts always succeed when skill ≥ recipe min. Resources have a **minimum tier** (tool tier must meet or exceed). **Leather** needs no tool — drops from certain mobs. **TODO:** resource nodes (trees, ores, fish spots, herb nodes), gather commands, recipe data files, tool/item sprites, gather speed formula, mob leather drops, sheep shearing. Craft UI is specified under **Crafting stations**. 239
**Spec:** **Mining:** LMB/RMB on ore boulder (states `bronze-ore` … `dragon-ore`, `coal`). Requires equipped pickaxe with tool rank ≥ resource rank and Mining ≥ mine gate. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX. Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × material rank`, then restores its ore state via runtime `CHUNK_DELTA`. **Smelting:** furnace block opens craft UI; recipes 1 ore → 1 bar except **steel** = 1 iron ore + 1 coal. Smithing XP on success. Server-authoritative `START_CRAFT` / timer. Woodcutting / fishing / other stations later.242
**Code:** `shared/definitions/skills.js` (skill IDs + panel entries), `shared/definitions/equipmentKinds.js` (`plantClippers`), `shared/definitions/alchemy.js`240
**Code:** `shared/definitions/gathering.js`, `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`243
241
244
## Crafting stations242
## Crafting stations245
243
246
**Status:** UI shell + item/recipe scaffolding; server crafting not implemented 244
**Status:** partial (furnace smelting live; UI shell for others) 247
**Spec:** Recipes run at a **station** adjacent to or under the player (exact interaction radius TBD). Station IDs and linked skills live in `shared/definitions/craftingStations.js`.245
**Spec:** Furnace block (placeholder sprite) + adjacency craft panel. Recipes in `stationRecipes.js`. Server craft timer = `CRAFT_DURATION_MS` (2s). Other stations still UI/dev only (`__craftDev`). 248
246
**TODO:** anvil smithing recipes, oven/campfire burn, spinning wheel once sheep exist. 249
| Station | Role | Skill |247
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace`), `server/src/crafting/service.js`, `client/src/play/crafting.js`250
| --- | --- | --- |251
| **Furnace** | Smelt gathered **ore → bars** | Smithing |252
| **Spinning wheel** | **Wool → thread** (wool from shorn sheep — sheep/WIP) | Tailoring |253
| **Loom** | Weave **cloth clothing** | Tailoring |254
| **Anvil** | Smith **metal items** from bars | Smithing |255
| **Leatherworking station** | Craft **leather** goods | Leatherworking |256
| **Crafting bench** | General **Crafting** (e.g. arrows + tips) | Crafting |257
| **Oven** | Cook **raw meat** | Cooking |258
| **Fireplace (campfire)** | Same cooking as oven | Cooking |259
260
**Cooking:** Requires Cooking ≥ recipe minimum or the attempt can **burn** the food (lost). **Oven** uses a lower burn chance than **fireplace** for the same recipe/skill gap.261
248
262
**Fireplace (portable):** Drop a **log** on the ground; **right-click the log → Start Fire** while carrying a **tinderbox** in inventory (consumes tinderbox use TBD). Creates a shared **campfire** on that tile for **10 minutes** (`FIREPLACE_DURATION_MS`). Any player may cook at it. **At most one fireplace per tile.** Fixed **oven** blocks are separate placeables (editor/content later).249
## Stamina and running263
264
**Station UI (shared across all stations):** Opening a station shows a **recipe grid** on the left — each cell is the output **item icon** with **display name** underneath. Clicking a recipe selects it; the **detail pane on the right** repeats the icon and name, lists **required materials** (icon + quantity per input), and a **Craft** button. Crafting is blocked unless the server confirms room for the product: `canCraftFitInventory()` simulates **consuming inputs first**, then inserting the output, so freed slots from spent materials count toward space (`shared/crafting/recipes.js`). While crafting, a **2 s** progress bar runs (`CRAFT_DURATION_MS`) for every recipe regardless of item. Only one craft at a time per player; closing the panel cancels in-progress craft (sends `CANCEL_CRAFT`). Cooking stations use the same shell; burn failure is an outcome after the timer, not a separate UI.265
266
**Item scaffolding:** Reserved IDs and stub definitions for gathering/crafting content live in `shared/definitions/craftingItems.js` (`CraftingItemId`, `CRAFTING_ITEM_STUBS` merged into `ITEM_DEFINITIONS`). Replace stubs with full defs (sprites, equipment, tiers) as rules land. Recipe rows go in `shared/crafting/stationRecipes.js` (`CRAFT_RECIPES`); filter with `recipesForStation()`.267
268
**Dev:** In the browser console, `__craftDev()` opens the crafting bench UI; pass any `CraftingStationId` string for other stations.269
250
270
**TODO:** station block/entity types and sprites, real recipe tables per station, open/close from world interaction, server craft command + timer + adjacency checks, Cooking burn formula, log/tinderbox behaviour, campfire ground entity lifecycle & replication, spinning wheel wool input once sheep exist. 251
**Status:** full 271
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/craftingItems.js`, `shared/definitions/itemCategories.js`, `shared/crafting/recipes.js`, `shared/crafting/stationRecipes.js`, `client/src/play/crafting.js`, `client/ui/play.css` (#craft-panel)252
**Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking / idle with walk gait regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows a vertical stamina bar bottom-right. 253
**Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`272
254
273
## Alchemy / cauldron255
## Alchemy / cauldron274
256
275
**Status:** partial (scaffolding) 257
**Status:** partial (scaffolding) 276
**Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs (and other ingredients) at a **Cauldron** block (`BlockType.cauldron`, editor placeable). Nonstandard UI: four reserve slots above the vessel, ↓ insert arrows under each slot, **Stir / Heat / Cool** actions, **Bottle**, **Clear** (also auto-clears after bottle), and **Save Recipe** after a successful brew when the player has blank **paper**.258
**Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs at a **Cauldron** block. Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules. 277
259
**Code:** `shared/definitions/alchemy.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`278
Slots register item+quantity without consuming until insert; insert consumes the reserved amount into the brew and records an `insert` step. Recipes list ≤4 unique ingredients as **ratios** (double inputs → double output if bottles allow; excess brew is lost without enough **glass bottles**). Steps must match; wrong order/ratios or Alchemy level below the recipe minimum yields an **Unstable Potion** chosen by hashing the step transcript (same mistakes → same failure potion). Unstable effects are stubs (slow, damage, blind, queasy). Success + paper → Save Recipe writes a unique **recipe paper** (read like a letter: ratios, steps, Alchemy level). Potions of the same type/effect stack to **16**. Shared potion art: clear bottle (= empty bottle) + fill levels 1–5 with **magenta** liquid pixels; liquid is recolored per potion `color` via the shared magenta tint path (inventory canvas; world ground items use the tint+darkness lit shader).279
280
Example scaffold recipe: **Green draught** — heat → insert green herb → stir → insert apple → cool → Bottle (ratios 2 green herb : 1 apple).281
282
**TODO:** more recipes, drink/effect application, herb nodes + Herbalism XP, more clipper tiers, polish cauldron art. 283
**Code:** `shared/definitions/alchemy.js`, `shared/alchemy/recipes.js`, `shared/definitions/items.js`, `shared/definitions/tiles.js` (`cauldron`), `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, `client/src/render/potionIcon.js`, `client/src/render/worldView.js` (potion shader), tests in `server/tests/alchemy.test.js`284
285
## Stamina and running286
287
**Status:** not implemented 288
**Spec:** **Stamina** skill sets max stamina (= skill level). Each stamina point equals **one second of running**. Running consumes stamina; running awards Stamina XP. Walking does not consume stamina. **TODO:** stamina component sync, run gate when empty, regen rules, Stamina XP on run ticks, client stamina bar. 289
**Code:** `shared/definitions/skills.js` (`playerMaxStamina` helper only)290
260
291
## Inventory, items, equipment, ground drops261
## Inventory, items, equipment, ground drops292
262
@@ -20,6 +20,7 @@ import {
20
20
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
21
21
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22
22
import { randomUUID } from "node:crypto";
23
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
23
24
24
25
/**
25
26
* Cauldron sessions live on the worker world (per character while the UI is open).
@@ -142,13 +143,14 @@ export function handleAlchemyCommand (world, sessionId, command)
142
143
143
144
function openCauldron (world, sessionId, command)
144
145
{
145
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
146
const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
146
147
requireNearCauldron(world, handle);
147
148
const sessions = ensureSessions(world);
148
149
const existing = sessions.get(command.characterId) ?? emptySession();
149
150
sessions.set(command.characterId, existing);
151
const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
150
152
return {
151
events: [],
153
events: shove ? [shove] : [],
152
154
private: bagView(world.ecs, handle),
153
155
cauldron: true,
154
156
cauldronState: sessionView(existing)
@@ -20,6 +20,7 @@ import {20
import { tileToChunk, tileToLocal } from "../world/coordinates.js";20
import { tileToChunk, tileToLocal } from "../world/coordinates.js";21
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";21
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";22
import { randomUUID } from "node:crypto";22
import { randomUUID } from "node:crypto";23
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";23
24
24
/**25
/**25
* Cauldron sessions live on the worker world (per character while the UI is open).26
* Cauldron sessions live on the worker world (per character while the UI is open).@@ -142,13 +143,14 @@ export function handleAlchemyCommand (world, sessionId, command)142
143
143
function openCauldron (world, sessionId, command)144
function openCauldron (world, sessionId, command)144
{145
{145
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);146
const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);146
requireNearCauldron(world, handle);147
requireNearCauldron(world, handle);147
const sessions = ensureSessions(world);148
const sessions = ensureSessions(world);148
const existing = sessions.get(command.characterId) ?? emptySession();149
const existing = sessions.get(command.characterId) ?? emptySession();149
sessions.set(command.characterId, existing);150
sessions.set(command.characterId, existing);151
const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);150
return {152
return {151
events: [],153
events: shove ? [shove] : [],152
private: bagView(world.ecs, handle),154
private: bagView(world.ecs, handle),153
cauldron: true,155
cauldron: true,154
cauldronState: sessionView(existing)156
cauldronState: sessionView(existing)@@ -3,6 +3,11 @@ import { extname, join } from "node:path";
3
3
import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
4
4
import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
5
5
import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
6
import {
7
ORE_BEARING_MATERIALS,
8
oreBoulderState,
9
materialTintColor
10
} from "../../../shared/definitions/materialTiers.js";
6
11
import {
7
12
bloomImageName,
8
13
equipBloomImageName,
@@ -134,18 +139,46 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
134
139
for (const def of Object.values(definitions))
135
140
{
136
141
const folder = join(layerDir, def.key);
137
const { states, blooms, equips, equipBlooms } = listVisualStates(folder);
138
if (states.length === 0)
142
const { states: fileStates, blooms, equips, equipBlooms } = listVisualStates(folder);
143
if (fileStates.length === 0)
139
144
{ throw new Error(`No PNG states in ${folder}`); }
140
145
141
146
const frames = Math.max(1, def.frames ?? 1);
142
147
const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
143
148
const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
149
let states = [...fileStates];
150
const imagesForType = [];
151
152
if (layer === "block" && def.key === "boulder")
153
{
154
states = states.filter((state) => state !== "boulder-ore");
155
if (!states.includes("boulder"))
156
{ states.unshift("boulder"); }
157
for (const material of ORE_BEARING_MATERIALS)
158
{
159
const state = oreBoulderState(material);
160
if (!states.includes(state))
161
{ states.push(state); }
162
const tint = materialTintColor(material);
163
imagesForType.push({
164
name: spriteImageName(layer, def.key, state),
165
url: `/assets/${urlFolder}/${def.key}/boulder-ore.png`,
166
subImgTotal: frames,
167
perRow: framesPerRow,
168
loop: animationSpeed > 0,
169
animationSpeed,
170
tint: { r: tint.r, g: tint.g, b: tint.b }
171
});
172
}
173
}
174
144
175
types[def.key] = {
145
176
key: def.key,
146
177
typeId: def.id,
147
178
states,
148
defaultState: states[0],
179
defaultState: def.key === "boulder" && states.includes("boulder")
180
? "boulder"
181
: states[0],
149
182
blooms,
150
183
equips,
151
184
equipBlooms,
@@ -155,6 +188,8 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
155
188
};
156
189
for (const state of states)
157
190
{
191
if (imagesForType.some((entry) => entry.name === spriteImageName(layer, def.key, state)))
192
{ continue; }
158
193
const sheet = {
159
194
subImgTotal: frames,
160
195
perRow: framesPerRow,
@@ -191,6 +226,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
191
226
});
192
227
}
193
228
}
229
images.push(...imagesForType);
194
230
}
195
231
return { types, images };
196
232
}
@@ -3,6 +3,11 @@ import { extname, join } from "node:path";3
import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";3
import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";4
import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";4
import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";5
import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";5
import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";6
import {7
ORE_BEARING_MATERIALS,8
oreBoulderState,9
materialTintColor10
} from "../../../shared/definitions/materialTiers.js";6
import {11
import {7
bloomImageName,12
bloomImageName,8
equipBloomImageName,13
equipBloomImageName,@@ -134,18 +139,46 @@ function scanLayer (layerDir, definitions, layer, urlFolder)134
for (const def of Object.values(definitions))139
for (const def of Object.values(definitions))135
{140
{136
const folder = join(layerDir, def.key);141
const folder = join(layerDir, def.key);137
const { states, blooms, equips, equipBlooms } = listVisualStates(folder);142
const { states: fileStates, blooms, equips, equipBlooms } = listVisualStates(folder);138
if (states.length === 0)143
if (fileStates.length === 0)139
{ throw new Error(`No PNG states in ${folder}`); }144
{ throw new Error(`No PNG states in ${folder}`); }140
145
141
const frames = Math.max(1, def.frames ?? 1);146
const frames = Math.max(1, def.frames ?? 1);142
const framesPerRow = Math.max(1, def.framesPerRow ?? 1);147
const framesPerRow = Math.max(1, def.framesPerRow ?? 1);143
const animationSpeed = Math.max(0, def.animationSpeed ?? 0);148
const animationSpeed = Math.max(0, def.animationSpeed ?? 0);149
let states = [...fileStates];150
const imagesForType = [];151
152
if (layer === "block" && def.key === "boulder")153
{154
states = states.filter((state) => state !== "boulder-ore");155
if (!states.includes("boulder"))156
{ states.unshift("boulder"); }157
for (const material of ORE_BEARING_MATERIALS)158
{159
const state = oreBoulderState(material);160
if (!states.includes(state))161
{ states.push(state); }162
const tint = materialTintColor(material);163
imagesForType.push({164
name: spriteImageName(layer, def.key, state),165
url: `/assets/${urlFolder}/${def.key}/boulder-ore.png`,166
subImgTotal: frames,167
perRow: framesPerRow,168
loop: animationSpeed > 0,169
animationSpeed,170
tint: { r: tint.r, g: tint.g, b: tint.b }171
});172
}173
}174
144
types[def.key] = {175
types[def.key] = {145
key: def.key,176
key: def.key,146
typeId: def.id,177
typeId: def.id,147
states,178
states,148
defaultState: states[0],179
defaultState: def.key === "boulder" && states.includes("boulder")180
? "boulder"181
: states[0],149
blooms,182
blooms,150
equips,183
equips,151
equipBlooms,184
equipBlooms,@@ -155,6 +188,8 @@ function scanLayer (layerDir, definitions, layer, urlFolder)155
};188
};156
for (const state of states)189
for (const state of states)157
{190
{191
if (imagesForType.some((entry) => entry.name === spriteImageName(layer, def.key, state)))192
{ continue; }158
const sheet = {193
const sheet = {159
subImgTotal: frames,194
subImgTotal: frames,160
perRow: framesPerRow,195
perRow: framesPerRow,@@ -191,6 +226,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)191
});226
});192
}227
}193
}228
}229
images.push(...imagesForType);194
}230
}195
return { types, images };231
return { types, images };196
}232
}@@ -49,3 +49,45 @@ export function broadcastSpeech (sessions, simulation, speakerSession, rawText)
49
49
}
50
50
}
51
51
}
52
53
/**
54
* Product icon above the crafter's head. Same proximity opacity as chat,
55
* but no text and no letter obfuscation.
56
*/
57
export function broadcastItemBubble (sessions, simulation, speakerEntityId, itemId, quantity = 1)
58
{
59
const speakerPos = simulation.positionOf(speakerEntityId);
60
if (!speakerPos || itemId == null)
61
{ return; }
62
63
const messageId = nextMessageId++;
64
const createdAt = Date.now();
65
for (const other of sessions.values())
66
{
67
if (!other.entityId)
68
{ continue; }
69
let readability = 1;
70
if (other.entityId !== speakerEntityId)
71
{
72
const listenerPos = simulation.positionOf(other.entityId);
73
if (!listenerPos)
74
{ continue; }
75
const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY);
76
readability = speechReadability(distance, CHUNK_SIZE);
77
if (readability <= 0)
78
{ continue; }
79
}
80
if (other.socket.readyState === 1)
81
{
82
other.socket.send(JSON.stringify({
83
type: MessageType.itemBubble,
84
messageId,
85
entityId: speakerEntityId,
86
itemId,
87
quantity: Math.max(1, quantity | 0 || 1),
88
readability,
89
createdAt
90
}));
91
}
92
}
93
}
@@ -49,3 +49,45 @@ export function broadcastSpeech (sessions, simulation, speakerSession, rawText)49
}49
}50
}50
}51
}51
}52
53
/**54
* Product icon above the crafter's head. Same proximity opacity as chat,55
* but no text and no letter obfuscation.56
*/57
export function broadcastItemBubble (sessions, simulation, speakerEntityId, itemId, quantity = 1)58
{59
const speakerPos = simulation.positionOf(speakerEntityId);60
if (!speakerPos || itemId == null)61
{ return; }62
63
const messageId = nextMessageId++;64
const createdAt = Date.now();65
for (const other of sessions.values())66
{67
if (!other.entityId)68
{ continue; }69
let readability = 1;70
if (other.entityId !== speakerEntityId)71
{72
const listenerPos = simulation.positionOf(other.entityId);73
if (!listenerPos)74
{ continue; }75
const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY);76
readability = speechReadability(distance, CHUNK_SIZE);77
if (readability <= 0)78
{ continue; }79
}80
if (other.socket.readyState === 1)81
{82
other.socket.send(JSON.stringify({83
type: MessageType.itemBubble,84
messageId,85
entityId: speakerEntityId,86
itemId,87
quantity: Math.max(1, quantity | 0 || 1),88
readability,89
createdAt90
}));91
}92
}93
}@@ -0,0 +1,322 @@
1
import { Component } from "../ecs/components.js";
2
import { BlockType } from "../../../shared/definitions/tiles.js";
3
import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
4
import { itemDefinition } from "../../../shared/definitions/items.js";
5
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6
import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7
import {
8
recipeDefinition,
9
canStartCraft,
10
canCraftFitInventory,
11
hasRecipeInputs
12
} from "../../../shared/crafting/recipes.js";
13
import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
14
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
15
import { smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
16
import { bagView } from "../items/bags.js";
17
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
18
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
19
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
20
21
function userError (message)
22
{
23
const error = new Error(message);
24
error.userFacing = true;
25
return error;
26
}
27
28
function ensureCraftSessions (world)
29
{
30
if (!world.craftSessions)
31
{ world.craftSessions = new Map(); }
32
return world.craftSessions;
33
}
34
35
function nearStationBlock (world, tileX, tileY, blockType)
36
{
37
for (let dy = -1; dy <= 1; dy++)
38
{
39
for (let dx = -1; dx <= 1; dx++)
40
{
41
const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
42
const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
43
if (data.blocks[index]?.typeId === blockType)
44
{ return true; }
45
}
46
}
47
return false;
48
}
49
50
function stationBlockType (stationId)
51
{
52
if (stationId === CraftingStationId.furnace)
53
{ return BlockType.furnace; }
54
return null;
55
}
56
57
function takeInputs (slots, inputs)
58
{
59
let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
60
for (const input of inputs ?? [])
61
{
62
let remaining = Math.max(0, stackQuantity(input.quantity));
63
if (!remaining)
64
{ continue; }
65
for (let i = 0; i < next.length && remaining > 0; i++)
66
{
67
if (!next[i] || next[i].itemId !== input.itemId)
68
{ continue; }
69
const taken = takeFromSlot(next, i, remaining);
70
if (!taken.ok)
71
{ continue; }
72
next = taken.slots;
73
remaining -= stackQuantity(taken.taken?.quantity);
74
}
75
if (remaining > 0)
76
{ return { ok: false, slots }; }
77
}
78
return { ok: true, slots: next };
79
}
80
81
export function startCraft (world, sessionId, characterId, stationId, recipeId, now)
82
{
83
const entityId = world.characterEntities.get(characterId);
84
if (entityId == null)
85
{ throw userError("Character is not in the world."); }
86
const handle = world.ecs.handleOf(entityId);
87
const identity = world.ecs.get(handle, Component.networkIdentity);
88
if (!identity || identity.sessionId !== sessionId)
89
{ throw userError("Character is not in the world."); }
90
if (world.ecs.has(handle, Component.dead))
91
{ throw userError("You are dead."); }
92
93
const stationDef = craftingStationDefinition(stationId);
94
if (!stationDef)
95
{ throw userError("Unknown crafting station."); }
96
const recipe = recipeDefinition(recipeId);
97
if (!recipe)
98
{ throw userError("Unknown recipe."); }
99
const stationIds = Array.isArray(recipe.stationIds)
100
? recipe.stationIds
101
: [recipe.stationId];
102
if (!stationIds.includes(stationId))
103
{ throw userError("That recipe cannot be made here."); }
104
105
const position = world.ecs.get(handle, Component.position);
106
const blockType = stationBlockType(stationId);
107
if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
108
{ throw userError("You need to stand next to the station."); }
109
110
const inventory = world.ecs.get(handle, Component.inventory);
111
const skills = world.ecs.get(handle, Component.skills);
112
const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
113
if (!canStartCraft(inventory?.slots ?? [], recipe, level))
114
{
115
if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
116
{ throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
117
if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
118
{ throw userError("Missing materials."); }
119
throw userError("Not enough bag space for the result.");
120
}
121
122
const sessions = ensureCraftSessions(world);
123
sessions.set(characterId, {
124
sessionId,
125
stationId,
126
recipeId,
127
finishesAt: now + CRAFT_DURATION_MS
128
});
129
const events = [];
130
if (blockType)
131
{
132
const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
133
if (shove)
134
{ events.push(shove); }
135
}
136
events.push({
137
type: "item-bubble",
138
entityId,
139
itemId: recipe.output.itemId,
140
quantity: Math.max(1, recipe.output.quantity | 0 || 1)
141
});
142
return { events };
143
}
144
145
export function openStation (world, sessionId, characterId, stationId)
146
{
147
const entityId = world.characterEntities.get(characterId);
148
if (entityId == null)
149
{ throw userError("Character is not in the world."); }
150
const handle = world.ecs.handleOf(entityId);
151
const identity = world.ecs.get(handle, Component.networkIdentity);
152
if (!identity || identity.sessionId !== sessionId)
153
{ throw userError("Character is not in the world."); }
154
if (world.ecs.has(handle, Component.dead))
155
{ throw userError("You are dead."); }
156
157
const stationDef = craftingStationDefinition(stationId);
158
if (!stationDef)
159
{ throw userError("Unknown crafting station."); }
160
const blockType = stationBlockType(stationId);
161
const position = world.ecs.get(handle, Component.position);
162
if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
163
{ throw userError("You need to stand next to the station."); }
164
165
const events = [];
166
if (blockType)
167
{
168
const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
169
if (shove)
170
{ events.push(shove); }
171
}
172
events.push({
173
type: "station-open",
174
sessionId,
175
characterId,
176
stationId
177
});
178
return { events };
179
}
180
181
export function cancelCraft (world, characterId)
182
{
183
ensureCraftSessions(world).delete(characterId);
184
return { events: [] };
185
}
186
187
export function stepCrafting (world, now)
188
{
189
const sessions = ensureCraftSessions(world);
190
const events = [];
191
const privates = [];
192
for (const [characterId, session] of [...sessions.entries()])
193
{
194
if (now < session.finishesAt)
195
{ continue; }
196
sessions.delete(characterId);
197
const entityId = world.characterEntities.get(characterId);
198
if (entityId == null)
199
{
200
events.push({
201
type: "craft-result",
202
sessionId: session.sessionId,
203
recipeId: session.recipeId,
204
ok: false,
205
error: "Character left the world."
206
});
207
continue;
208
}
209
const handle = world.ecs.handleOf(entityId);
210
if (world.ecs.has(handle, Component.dead))
211
{
212
events.push({
213
type: "craft-result",
214
sessionId: session.sessionId,
215
recipeId: session.recipeId,
216
ok: false,
217
error: "You are dead."
218
});
219
continue;
220
}
221
222
const recipe = recipeDefinition(session.recipeId);
223
const stationDef = craftingStationDefinition(session.stationId);
224
const inventory = world.ecs.get(handle, Component.inventory);
225
const skills = world.ecs.get(handle, Component.skills);
226
const position = world.ecs.get(handle, Component.position);
227
const blockType = stationBlockType(session.stationId);
228
const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
229
230
if (!recipe || !stationDef || !inventory
231
|| (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
232
|| !canCraftFitInventory(inventory.slots, recipe)
233
|| (level | 0) < (recipe.minSkillLevel | 0 || 1))
234
{
235
events.push({
236
type: "craft-result",
237
sessionId: session.sessionId,
238
recipeId: session.recipeId,
239
ok: false,
240
error: "Could not finish crafting."
241
});
242
continue;
243
}
244
245
const taken = takeInputs(inventory.slots, recipe.inputs);
246
if (!taken.ok)
247
{
248
events.push({
249
type: "craft-result",
250
sessionId: session.sessionId,
251
recipeId: session.recipeId,
252
ok: false,
253
error: "Missing materials."
254
});
255
continue;
256
}
257
const outDef = itemDefinition(recipe.output.itemId);
258
const added = insertStack(taken.slots, {
259
itemId: recipe.output.itemId,
260
quantity: Math.max(1, recipe.output.quantity | 0 || 1)
261
}, outDef);
262
if (!added.ok || added.remainder > 0)
263
{
264
events.push({
265
type: "craft-result",
266
sessionId: session.sessionId,
267
recipeId: session.recipeId,
268
ok: false,
269
error: "Not enough bag space for the result."
270
});
271
continue;
272
}
273
inventory.slots = added.slots;
274
275
let skillsChanged = false;
276
if (skills?.xp && recipe.xpMaterial && stationDef.skillId === SkillId.smithing)
277
{
278
if (addSkillXp(skills, SkillId.smithing, smeltingXpForMaterial(recipe.xpMaterial)))
279
{ skillsChanged = true; }
280
}
281
282
privates.push({ characterId, bag: bagView(world.ecs, handle) });
283
if (skillsChanged)
284
{
285
events.push({
286
type: "skills-updated",
287
characterId,
288
skills: publicSkillsView(skills),
289
stored: storedSkillXp(skills)
290
});
291
}
292
events.push({
293
type: "craft-result",
294
sessionId: session.sessionId,
295
recipeId: session.recipeId,
296
ok: true
297
});
298
}
299
return { events, privates };
300
}
301
302
export function handleCraftCommand (world, sessionId, command, now)
303
{
304
switch (command.type)
305
{
306
case "open-station":
307
return openStation(world, sessionId, command.characterId, command.stationId);
308
case "start-craft":
309
return startCraft(
310
world,
311
sessionId,
312
command.characterId,
313
command.stationId,
314
command.recipeId,
315
now
316
);
317
case "cancel-craft":
318
return cancelCraft(world, command.characterId);
319
default:
320
return null;
321
}
322
}
@@ -0,0 +1,322 @@1
import { Component } from "../ecs/components.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";3
import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";4
import { itemDefinition } from "../../../shared/definitions/items.js";5
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";6
import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";7
import {8
recipeDefinition,9
canStartCraft,10
canCraftFitInventory,11
hasRecipeInputs12
} from "../../../shared/crafting/recipes.js";13
import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";14
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";15
import { smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";16
import { bagView } from "../items/bags.js";17
import { tileToChunk, tileToLocal } from "../world/coordinates.js";18
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";19
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";20
21
function userError (message)22
{23
const error = new Error(message);24
error.userFacing = true;25
return error;26
}27
28
function ensureCraftSessions (world)29
{30
if (!world.craftSessions)31
{ world.craftSessions = new Map(); }32
return world.craftSessions;33
}34
35
function nearStationBlock (world, tileX, tileY, blockType)36
{37
for (let dy = -1; dy <= 1; dy++)38
{39
for (let dx = -1; dx <= 1; dx++)40
{41
const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));42
const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);43
if (data.blocks[index]?.typeId === blockType)44
{ return true; }45
}46
}47
return false;48
}49
50
function stationBlockType (stationId)51
{52
if (stationId === CraftingStationId.furnace)53
{ return BlockType.furnace; }54
return null;55
}56
57
function takeInputs (slots, inputs)58
{59
let next = slots.map((slot) => (slot ? structuredClone(slot) : null));60
for (const input of inputs ?? [])61
{62
let remaining = Math.max(0, stackQuantity(input.quantity));63
if (!remaining)64
{ continue; }65
for (let i = 0; i < next.length && remaining > 0; i++)66
{67
if (!next[i] || next[i].itemId !== input.itemId)68
{ continue; }69
const taken = takeFromSlot(next, i, remaining);70
if (!taken.ok)71
{ continue; }72
next = taken.slots;73
remaining -= stackQuantity(taken.taken?.quantity);74
}75
if (remaining > 0)76
{ return { ok: false, slots }; }77
}78
return { ok: true, slots: next };79
}80
81
export function startCraft (world, sessionId, characterId, stationId, recipeId, now)82
{83
const entityId = world.characterEntities.get(characterId);84
if (entityId == null)85
{ throw userError("Character is not in the world."); }86
const handle = world.ecs.handleOf(entityId);87
const identity = world.ecs.get(handle, Component.networkIdentity);88
if (!identity || identity.sessionId !== sessionId)89
{ throw userError("Character is not in the world."); }90
if (world.ecs.has(handle, Component.dead))91
{ throw userError("You are dead."); }92
93
const stationDef = craftingStationDefinition(stationId);94
if (!stationDef)95
{ throw userError("Unknown crafting station."); }96
const recipe = recipeDefinition(recipeId);97
if (!recipe)98
{ throw userError("Unknown recipe."); }99
const stationIds = Array.isArray(recipe.stationIds)100
? recipe.stationIds101
: [recipe.stationId];102
if (!stationIds.includes(stationId))103
{ throw userError("That recipe cannot be made here."); }104
105
const position = world.ecs.get(handle, Component.position);106
const blockType = stationBlockType(stationId);107
if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))108
{ throw userError("You need to stand next to the station."); }109
110
const inventory = world.ecs.get(handle, Component.inventory);111
const skills = world.ecs.get(handle, Component.skills);112
const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);113
if (!canStartCraft(inventory?.slots ?? [], recipe, level))114
{115
if ((level | 0) < (recipe.minSkillLevel | 0 || 1))116
{ throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }117
if (!hasRecipeInputs(inventory?.slots ?? [], recipe))118
{ throw userError("Missing materials."); }119
throw userError("Not enough bag space for the result.");120
}121
122
const sessions = ensureCraftSessions(world);123
sessions.set(characterId, {124
sessionId,125
stationId,126
recipeId,127
finishesAt: now + CRAFT_DURATION_MS128
});129
const events = [];130
if (blockType)131
{132
const shove = tileShoveTowardBlock(world, handle, entityId, blockType);133
if (shove)134
{ events.push(shove); }135
}136
events.push({137
type: "item-bubble",138
entityId,139
itemId: recipe.output.itemId,140
quantity: Math.max(1, recipe.output.quantity | 0 || 1)141
});142
return { events };143
}144
145
export function openStation (world, sessionId, characterId, stationId)146
{147
const entityId = world.characterEntities.get(characterId);148
if (entityId == null)149
{ throw userError("Character is not in the world."); }150
const handle = world.ecs.handleOf(entityId);151
const identity = world.ecs.get(handle, Component.networkIdentity);152
if (!identity || identity.sessionId !== sessionId)153
{ throw userError("Character is not in the world."); }154
if (world.ecs.has(handle, Component.dead))155
{ throw userError("You are dead."); }156
157
const stationDef = craftingStationDefinition(stationId);158
if (!stationDef)159
{ throw userError("Unknown crafting station."); }160
const blockType = stationBlockType(stationId);161
const position = world.ecs.get(handle, Component.position);162
if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))163
{ throw userError("You need to stand next to the station."); }164
165
const events = [];166
if (blockType)167
{168
const shove = tileShoveTowardBlock(world, handle, entityId, blockType);169
if (shove)170
{ events.push(shove); }171
}172
events.push({173
type: "station-open",174
sessionId,175
characterId,176
stationId177
});178
return { events };179
}180
181
export function cancelCraft (world, characterId)182
{183
ensureCraftSessions(world).delete(characterId);184
return { events: [] };185
}186
187
export function stepCrafting (world, now)188
{189
const sessions = ensureCraftSessions(world);190
const events = [];191
const privates = [];192
for (const [characterId, session] of [...sessions.entries()])193
{194
if (now < session.finishesAt)195
{ continue; }196
sessions.delete(characterId);197
const entityId = world.characterEntities.get(characterId);198
if (entityId == null)199
{200
events.push({201
type: "craft-result",202
sessionId: session.sessionId,203
recipeId: session.recipeId,204
ok: false,205
error: "Character left the world."206
});207
continue;208
}209
const handle = world.ecs.handleOf(entityId);210
if (world.ecs.has(handle, Component.dead))211
{212
events.push({213
type: "craft-result",214
sessionId: session.sessionId,215
recipeId: session.recipeId,216
ok: false,217
error: "You are dead."218
});219
continue;220
}221
222
const recipe = recipeDefinition(session.recipeId);223
const stationDef = craftingStationDefinition(session.stationId);224
const inventory = world.ecs.get(handle, Component.inventory);225
const skills = world.ecs.get(handle, Component.skills);226
const position = world.ecs.get(handle, Component.position);227
const blockType = stationBlockType(session.stationId);228
const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);229
230
if (!recipe || !stationDef || !inventory231
|| (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))232
|| !canCraftFitInventory(inventory.slots, recipe)233
|| (level | 0) < (recipe.minSkillLevel | 0 || 1))234
{235
events.push({236
type: "craft-result",237
sessionId: session.sessionId,238
recipeId: session.recipeId,239
ok: false,240
error: "Could not finish crafting."241
});242
continue;243
}244
245
const taken = takeInputs(inventory.slots, recipe.inputs);246
if (!taken.ok)247
{248
events.push({249
type: "craft-result",250
sessionId: session.sessionId,251
recipeId: session.recipeId,252
ok: false,253
error: "Missing materials."254
});255
continue;256
}257
const outDef = itemDefinition(recipe.output.itemId);258
const added = insertStack(taken.slots, {259
itemId: recipe.output.itemId,260
quantity: Math.max(1, recipe.output.quantity | 0 || 1)261
}, outDef);262
if (!added.ok || added.remainder > 0)263
{264
events.push({265
type: "craft-result",266
sessionId: session.sessionId,267
recipeId: session.recipeId,268
ok: false,269
error: "Not enough bag space for the result."270
});271
continue;272
}273
inventory.slots = added.slots;274
275
let skillsChanged = false;276
if (skills?.xp && recipe.xpMaterial && stationDef.skillId === SkillId.smithing)277
{278
if (addSkillXp(skills, SkillId.smithing, smeltingXpForMaterial(recipe.xpMaterial)))279
{ skillsChanged = true; }280
}281
282
privates.push({ characterId, bag: bagView(world.ecs, handle) });283
if (skillsChanged)284
{285
events.push({286
type: "skills-updated",287
characterId,288
skills: publicSkillsView(skills),289
stored: storedSkillXp(skills)290
});291
}292
events.push({293
type: "craft-result",294
sessionId: session.sessionId,295
recipeId: session.recipeId,296
ok: true297
});298
}299
return { events, privates };300
}301
302
export function handleCraftCommand (world, sessionId, command, now)303
{304
switch (command.type)305
{306
case "open-station":307
return openStation(world, sessionId, command.characterId, command.stationId);308
case "start-craft":309
return startCraft(310
world,311
sessionId,312
command.characterId,313
command.stationId,314
command.recipeId,315
now316
);317
case "cancel-craft":318
return cancelCraft(world, command.characterId);319
default:320
return null;321
}322
}@@ -18,5 +18,6 @@ export const Component = Object.freeze({
18
18
skills: "skills",
19
19
follow: "follow",
20
20
dead: "dead",
21
stamina: "stamina"
21
stamina: "stamina",
22
gather: "gather"
22
23
});
@@ -18,5 +18,6 @@ export const Component = Object.freeze({18
skills: "skills",18
skills: "skills",19
follow: "follow",19
follow: "follow",20
dead: "dead",20
dead: "dead",21
stamina: "stamina"21
stamina: "stamina",22
gather: "gather"22
});23
});@@ -2,7 +2,8 @@ import { WebSocketServer } from "ws";
2
2
import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3
3
import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4
4
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5
import { broadcastSpeech } from "../chat/speech.js";
5
import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
6
import { CraftingStationId } from "../../../shared/definitions/craftingStations.js";
6
7
import { publicSkillsView } from "../../../shared/skills/state.js";
7
8
8
9
let nextSessionId = 1;
@@ -199,6 +200,46 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
199
200
characterId: session.characterId
200
201
});
201
202
break;
203
case MessageType.openFurnace:
204
requirePlaying(session);
205
simulation.enqueue(session.id, {
206
type: "open-station",
207
characterId: session.characterId,
208
stationId: CraftingStationId.furnace
209
});
210
break;
211
case MessageType.mine:
212
requirePlaying(session);
213
simulation.enqueue(session.id, {
214
type: "mine",
215
characterId: session.characterId,
216
tileX: message.tileX | 0,
217
tileY: message.tileY | 0
218
});
219
break;
220
case MessageType.cancelGather:
221
requirePlaying(session);
222
simulation.enqueue(session.id, {
223
type: "cancel-gather",
224
characterId: session.characterId
225
});
226
break;
227
case MessageType.startCraft:
228
requirePlaying(session);
229
simulation.enqueue(session.id, {
230
type: "start-craft",
231
characterId: session.characterId,
232
stationId: message.stationId,
233
recipeId: message.recipeId
234
});
235
break;
236
case MessageType.cancelCraft:
237
requirePlaying(session);
238
simulation.enqueue(session.id, {
239
type: "cancel-craft",
240
characterId: session.characterId
241
});
242
break;
202
243
case MessageType.cauldronSetSlot:
203
244
requirePlaying(session);
204
245
simulation.enqueue(session.id, {
@@ -503,6 +544,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
503
544
const skills = simulation.skillsOf(session.entityId);
504
545
if (skills)
505
546
{ send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
547
const stamina = simulation.staminaOf(session.entityId);
548
if (stamina)
549
{
550
send(session, {
551
type: MessageType.stamina,
552
current: stamina.current,
553
max: stamina.max,
554
gait: stamina.gait
555
});
556
}
506
557
if (character.is_dead)
507
558
{
508
559
send(session, {
@@ -672,6 +723,19 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
672
723
send(session, { type: MessageType.skills, skills: event.skills ?? [] });
673
724
continue;
674
725
}
726
if (event.type === "stamina")
727
{
728
const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
729
if (!session)
730
{ continue; }
731
send(session, {
732
type: MessageType.stamina,
733
current: event.current,
734
max: event.max,
735
gait: event.gait
736
});
737
continue;
738
}
675
739
if (event.type === "pigeon-delivered")
676
740
{
677
741
for (const session of sessions.values())
@@ -721,7 +785,72 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
721
785
}
722
786
continue;
723
787
}
724
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")
788
if (event.type === "craft-result")
789
{
790
const session = sessions.get(event.sessionId);
791
if (session)
792
{
793
send(session, {
794
type: MessageType.craftResult,
795
recipeId: event.recipeId,
796
ok: !!event.ok,
797
error: event.error ?? null,
798
burned: !!event.burned
799
});
800
}
801
continue;
802
}
803
if (event.type === "station-open")
804
{
805
const session = sessions.get(event.sessionId);
806
if (session)
807
{
808
send(session, {
809
type: MessageType.stationOpen,
810
stationId: event.stationId
811
});
812
}
813
continue;
814
}
815
if (event.type === "item-bubble")
816
{
817
broadcastItemBubble(
818
sessions,
819
simulation,
820
event.entityId,
821
event.itemId,
822
event.quantity
823
);
824
continue;
825
}
826
if (event.type === "gather-swing" || event.type === "tile-shove")
827
{
828
publishEntity({
829
...event,
830
type: event.type
831
});
832
continue;
833
}
834
if (event.type === "chunk-delta")
835
{
836
publishEntity(event);
837
continue;
838
}
839
if (event.type === "gather-complete")
840
{
841
const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
842
if (session)
843
{
844
send(session, {
845
type: MessageType.gatherComplete,
846
kind: event.kind,
847
materialId: event.materialId,
848
itemId: event.itemId
849
});
850
}
851
continue;
852
}
853
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta")
725
854
{ publishEntity(event); }
726
855
}
727
856
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -812,6 +941,36 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
812
941
});
813
942
continue;
814
943
}
944
if (event.type === "gather-swing" || event.type === "tile-shove")
945
{
946
if (!seesTo && !seesFrom)
947
{ continue; }
948
send(session, {
949
type: MessageType.tileShove,
950
attackerId: event.attackerId,
951
tileX: event.tileX,
952
tileY: event.tileY,
953
fromTileX: event.fromTileX,
954
fromTileY: event.fromTileY
955
});
956
continue;
957
}
958
if (event.type === "chunk-delta")
959
{
960
if (!seesTo)
961
{ continue; }
962
send(session, {
963
type: MessageType.chunkDelta,
964
chunkX: event.chunkX,
965
chunkY: event.chunkY,
966
tiles: [{
967
localX: event.localX,
968
localY: event.localY,
969
block: event.block
970
}]
971
});
972
continue;
973
}
815
974
if (event.type !== "entity-move")
816
975
{ continue; }
817
976
if (seesTo)
@@ -2,7 +2,8 @@ import { WebSocketServer } from "ws";2
import { MessageType, GAIT } from "../../../shared/protocol/constants.js";2
import { MessageType, GAIT } from "../../../shared/protocol/constants.js";3
import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";3
import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";4
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";4
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";5
import { broadcastSpeech } from "../chat/speech.js";5
import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";6
import { CraftingStationId } from "../../../shared/definitions/craftingStations.js";6
import { publicSkillsView } from "../../../shared/skills/state.js";7
import { publicSkillsView } from "../../../shared/skills/state.js";7
8
8
let nextSessionId = 1;9
let nextSessionId = 1;@@ -199,6 +200,46 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,199
characterId: session.characterId200
characterId: session.characterId200
});201
});201
break;202
break;203
case MessageType.openFurnace:204
requirePlaying(session);205
simulation.enqueue(session.id, {206
type: "open-station",207
characterId: session.characterId,208
stationId: CraftingStationId.furnace209
});210
break;211
case MessageType.mine:212
requirePlaying(session);213
simulation.enqueue(session.id, {214
type: "mine",215
characterId: session.characterId,216
tileX: message.tileX | 0,217
tileY: message.tileY | 0218
});219
break;220
case MessageType.cancelGather:221
requirePlaying(session);222
simulation.enqueue(session.id, {223
type: "cancel-gather",224
characterId: session.characterId225
});226
break;227
case MessageType.startCraft:228
requirePlaying(session);229
simulation.enqueue(session.id, {230
type: "start-craft",231
characterId: session.characterId,232
stationId: message.stationId,233
recipeId: message.recipeId234
});235
break;236
case MessageType.cancelCraft:237
requirePlaying(session);238
simulation.enqueue(session.id, {239
type: "cancel-craft",240
characterId: session.characterId241
});242
break;202
case MessageType.cauldronSetSlot:243
case MessageType.cauldronSetSlot:203
requirePlaying(session);244
requirePlaying(session);204
simulation.enqueue(session.id, {245
simulation.enqueue(session.id, {@@ -503,6 +544,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,503
const skills = simulation.skillsOf(session.entityId);544
const skills = simulation.skillsOf(session.entityId);504
if (skills)545
if (skills)505
{ send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }546
{ send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }547
const stamina = simulation.staminaOf(session.entityId);548
if (stamina)549
{550
send(session, {551
type: MessageType.stamina,552
current: stamina.current,553
max: stamina.max,554
gait: stamina.gait555
});556
}506
if (character.is_dead)557
if (character.is_dead)507
{558
{508
send(session, {559
send(session, {@@ -672,6 +723,19 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,672
send(session, { type: MessageType.skills, skills: event.skills ?? [] });723
send(session, { type: MessageType.skills, skills: event.skills ?? [] });673
continue;724
continue;674
}725
}726
if (event.type === "stamina")727
{728
const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);729
if (!session)730
{ continue; }731
send(session, {732
type: MessageType.stamina,733
current: event.current,734
max: event.max,735
gait: event.gait736
});737
continue;738
}675
if (event.type === "pigeon-delivered")739
if (event.type === "pigeon-delivered")676
{740
{677
for (const session of sessions.values())741
for (const session of sessions.values())@@ -721,7 +785,72 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,721
}785
}722
continue;786
continue;723
}787
}724
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")788
if (event.type === "craft-result")789
{790
const session = sessions.get(event.sessionId);791
if (session)792
{793
send(session, {794
type: MessageType.craftResult,795
recipeId: event.recipeId,796
ok: !!event.ok,797
error: event.error ?? null,798
burned: !!event.burned799
});800
}801
continue;802
}803
if (event.type === "station-open")804
{805
const session = sessions.get(event.sessionId);806
if (session)807
{808
send(session, {809
type: MessageType.stationOpen,810
stationId: event.stationId811
});812
}813
continue;814
}815
if (event.type === "item-bubble")816
{817
broadcastItemBubble(818
sessions,819
simulation,820
event.entityId,821
event.itemId,822
event.quantity823
);824
continue;825
}826
if (event.type === "gather-swing" || event.type === "tile-shove")827
{828
publishEntity({829
...event,830
type: event.type831
});832
continue;833
}834
if (event.type === "chunk-delta")835
{836
publishEntity(event);837
continue;838
}839
if (event.type === "gather-complete")840
{841
const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);842
if (session)843
{844
send(session, {845
type: MessageType.gatherComplete,846
kind: event.kind,847
materialId: event.materialId,848
itemId: event.itemId849
});850
}851
continue;852
}853
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta")725
{ publishEntity(event); }854
{ publishEntity(event); }726
}855
}727
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)856
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)@@ -812,6 +941,36 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,812
});941
});813
continue;942
continue;814
}943
}944
if (event.type === "gather-swing" || event.type === "tile-shove")945
{946
if (!seesTo && !seesFrom)947
{ continue; }948
send(session, {949
type: MessageType.tileShove,950
attackerId: event.attackerId,951
tileX: event.tileX,952
tileY: event.tileY,953
fromTileX: event.fromTileX,954
fromTileY: event.fromTileY955
});956
continue;957
}958
if (event.type === "chunk-delta")959
{960
if (!seesTo)961
{ continue; }962
send(session, {963
type: MessageType.chunkDelta,964
chunkX: event.chunkX,965
chunkY: event.chunkY,966
tiles: [{967
localX: event.localX,968
localY: event.localY,969
block: event.block970
}]971
});972
continue;973
}815
if (event.type !== "entity-move")974
if (event.type !== "entity-move")816
{ continue; }975
{ continue; }817
if (seesTo)976
if (seesTo)@@ -0,0 +1,325 @@
1
import { Component } from "../ecs/components.js";
2
import { BlockType } from "../../../shared/definitions/tiles.js";
3
import { itemDefinition } from "../../../shared/definitions/items.js";
4
import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
5
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6
import {
7
materialFromOreBoulderState,
8
canMineMaterial,
9
oreItemIdForMaterial,
10
miningDurationMs,
11
miningXpForMaterial,
12
oreExhaustDurationMs,
13
oreBoulderState,
14
EXHAUSTED_ORE_BOULDER_STATE
15
} from "../../../shared/definitions/gathering.js";
16
import { insertStack } from "../../../shared/items/inventory.js";
17
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
18
import { bagView } from "../items/bags.js";
19
import { chebyshev, clearEngage } from "../combat/service.js";
20
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
21
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22
23
const GATHER_SWING_INTERVAL_MS = 900;
24
25
function userError (message)
26
{
27
const error = new Error(message);
28
error.userFacing = true;
29
return error;
30
}
31
32
function ensureOreRespawns (world)
33
{
34
if (!world.oreRespawns)
35
{ world.oreRespawns = new Map(); }
36
return world.oreRespawns;
37
}
38
39
function blockAt (world, tileX, tileY)
40
{
41
const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
42
return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
43
}
44
45
function setBoulderState (world, tileX, tileY, state)
46
{
47
const chunkX = tileToChunk(tileX);
48
const chunkY = tileToChunk(tileY);
49
const localX = tileToLocal(tileX);
50
const localY = tileToLocal(tileY);
51
const data = world.chunkData(chunkX, chunkY);
52
const index = localY * CHUNK_SIZE + localX;
53
const prev = data?.blocks?.[index];
54
if (!prev || prev.typeId !== BlockType.boulder)
55
{ return null; }
56
const block = { typeId: prev.typeId, state, config: prev.config ?? null };
57
data.blocks[index] = block;
58
return {
59
type: "chunk-delta",
60
chunkX,
61
chunkY,
62
tileX,
63
tileY,
64
localX,
65
localY,
66
block
67
};
68
}
69
70
function equippedPickaxe (ecs, handle)
71
{
72
const equipment = ecs.get(handle, Component.equipment);
73
const stack = equipment?.slots?.weapon;
74
if (!stack?.itemId)
75
{ return null; }
76
const def = itemDefinition(stack.itemId);
77
if (def?.equipment?.kind !== EquipmentKind.pickaxeTool)
78
{ return null; }
79
return { stack, def, tier: def.equipment.tier };
80
}
81
82
function clearGather (ecs, handle)
83
{
84
if (ecs.has(handle, Component.gather))
85
{ ecs.remove(handle, Component.gather); }
86
}
87
88
export function cancelGather (ecs, handle)
89
{
90
clearGather(ecs, handle);
91
}
92
93
/** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
94
export function clearOreRespawnsForChunk (world, chunkX, chunkY)
95
{
96
const respawns = world.oreRespawns;
97
if (!respawns?.size)
98
{ return; }
99
for (const key of [...respawns.keys()])
100
{
101
const [tileX, tileY] = key.split(",").map(Number);
102
if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
103
{ respawns.delete(key); }
104
}
105
}
106
107
/**
108
* Restore exhausted ore boulders whose timers have elapsed.
109
*/
110
export function stepOreRespawns (world, now)
111
{
112
const respawns = world.oreRespawns;
113
if (!respawns?.size)
114
{ return { events: [] }; }
115
const events = [];
116
for (const [key, entry] of [...respawns.entries()])
117
{
118
if (now < entry.respawnsAt)
119
{ continue; }
120
respawns.delete(key);
121
const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId));
122
if (delta)
123
{ events.push(delta); }
124
}
125
return { events };
126
}
127
128
/**
129
* Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.
130
*/
131
export function startMine (world, sessionId, characterId, tileX, tileY, now)
132
{
133
const entityId = world.characterEntities.get(characterId);
134
if (entityId == null)
135
{ throw userError("Character is not in the world."); }
136
const handle = world.ecs.handleOf(entityId);
137
const identity = world.ecs.get(handle, Component.networkIdentity);
138
if (!identity || identity.sessionId !== sessionId)
139
{ throw userError("Character is not in the world."); }
140
if (world.ecs.has(handle, Component.dead))
141
{ throw userError("You are dead."); }
142
143
const position = world.ecs.get(handle, Component.position);
144
if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
145
{ throw userError("You need to stand next to the rock."); }
146
147
const block = blockAt(world, tileX, tileY);
148
if (!block || block.typeId !== BlockType.boulder)
149
{ throw userError("There is nothing to mine there."); }
150
const materialId = materialFromOreBoulderState(block.state);
151
if (!materialId)
152
{ throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE
153
? "That rock is exhausted."
154
: "That rock has no ore."); }
155
156
const pickaxe = equippedPickaxe(world.ecs, handle);
157
if (!pickaxe)
158
{ throw userError("Equip a pickaxe to mine."); }
159
160
const skills = world.ecs.get(handle, Component.skills);
161
const miningLevel = skillLevel(skills, SkillId.mining);
162
const gate = canMineMaterial(miningLevel, pickaxe.tier, materialId);
163
if (!gate.ok)
164
{ throw userError(gate.reason); }
165
166
const durationMs = miningDurationMs(materialId, pickaxe.tier);
167
clearEngage(world.ecs, entityId);
168
const path = world.ecs.get(handle, Component.path);
169
if (path)
170
{ path.tiles = []; }
171
world.ecs.add(handle, Component.gather, {
172
kind: "mining",
173
tileX,
174
tileY,
175
materialId,
176
startedAt: now,
177
finishesAt: now + durationMs,
178
nextSwingAt: now
179
});
180
181
return {
182
events: [{
183
type: "gather-swing",
184
attackerId: entityId,
185
tileX,
186
tileY,
187
fromTileX: position.tileX,
188
fromTileY: position.tileY,
189
swipe: false
190
}]
191
};
192
}
193
194
export function stepGather (world, now)
195
{
196
const events = [];
197
const privates = [];
198
const respawnEvents = stepOreRespawns(world, now);
199
events.push(...respawnEvents.events);
200
201
for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
202
{
203
const { handle, gather, position, character, entityId } = entity;
204
if (world.ecs.has(handle, Component.dead))
205
{
206
clearGather(world.ecs, handle);
207
continue;
208
}
209
if (chebyshev(position.tileX, position.tileY, gather.tileX, gather.tileY) > 1)
210
{
211
clearGather(world.ecs, handle);
212
continue;
213
}
214
const block = blockAt(world, gather.tileX, gather.tileY);
215
if (!block || block.typeId !== BlockType.boulder
216
|| materialFromOreBoulderState(block.state) !== gather.materialId)
217
{
218
clearGather(world.ecs, handle);
219
continue;
220
}
221
222
if (now >= gather.nextSwingAt && now < gather.finishesAt)
223
{
224
gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
225
events.push({
226
type: "gather-swing",
227
attackerId: entityId,
228
tileX: gather.tileX,
229
tileY: gather.tileY,
230
fromTileX: position.tileX,
231
fromTileY: position.tileY,
232
swipe: false
233
});
234
}
235
236
if (now < gather.finishesAt)
237
{ continue; }
238
239
const oreItemId = oreItemIdForMaterial(gather.materialId);
240
const def = itemDefinition(oreItemId);
241
const inventory = world.ecs.get(handle, Component.inventory);
242
if (!oreItemId || !def || !inventory)
243
{
244
clearGather(world.ecs, handle);
245
continue;
246
}
247
const inserted = insertStack(inventory.slots, { itemId: oreItemId, quantity: 1 }, def);
248
if (!inserted.ok || inserted.remainder > 0)
249
{
250
clearGather(world.ecs, handle);
251
events.push({
252
type: "command-error",
253
sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
254
message: "Your inventory is full."
255
});
256
continue;
257
}
258
inventory.slots = inserted.slots;
259
260
const skills = world.ecs.get(handle, Component.skills);
261
let skillsChanged = false;
262
if (skills?.xp && addSkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)))
263
{ skillsChanged = true; }
264
265
const exhausted = setBoulderState(
266
world,
267
gather.tileX,
268
gather.tileY,
269
EXHAUSTED_ORE_BOULDER_STATE
270
);
271
if (exhausted)
272
{
273
events.push(exhausted);
274
ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
275
tileX: gather.tileX,
276
tileY: gather.tileY,
277
materialId: gather.materialId,
278
respawnsAt: now + oreExhaustDurationMs(gather.materialId)
279
});
280
}
281
282
clearGather(world.ecs, handle);
283
privates.push({
284
characterId: character.characterId,
285
bag: bagView(world.ecs, handle)
286
});
287
if (skillsChanged)
288
{
289
events.push({
290
type: "skills-updated",
291
characterId: character.characterId,
292
skills: publicSkillsView(skills),
293
stored: storedSkillXp(skills)
294
});
295
}
296
events.push({
297
type: "gather-complete",
298
characterId: character.characterId,
299
kind: "mining",
300
materialId: gather.materialId,
301
itemId: oreItemId
302
});
303
}
304
return { events, privates };
305
}
306
307
export function handleGatherCommand (world, sessionId, command, now)
308
{
309
switch (command.type)
310
{
311
case "mine":
312
return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
313
case "cancel-gather":
314
{
315
const entityId = world.characterEntities.get(command.characterId);
316
if (entityId == null)
317
{ return { events: [] }; }
318
const handle = world.ecs.handleOf(entityId);
319
clearGather(world.ecs, handle);
320
return { events: [] };
321
}
322
default:
323
return null;
324
}
325
}
@@ -0,0 +1,325 @@1
import { Component } from "../ecs/components.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";3
import { itemDefinition } from "../../../shared/definitions/items.js";4
import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";5
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";6
import {7
materialFromOreBoulderState,8
canMineMaterial,9
oreItemIdForMaterial,10
miningDurationMs,11
miningXpForMaterial,12
oreExhaustDurationMs,13
oreBoulderState,14
EXHAUSTED_ORE_BOULDER_STATE15
} from "../../../shared/definitions/gathering.js";16
import { insertStack } from "../../../shared/items/inventory.js";17
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";18
import { bagView } from "../items/bags.js";19
import { chebyshev, clearEngage } from "../combat/service.js";20
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";21
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";22
23
const GATHER_SWING_INTERVAL_MS = 900;24
25
function userError (message)26
{27
const error = new Error(message);28
error.userFacing = true;29
return error;30
}31
32
function ensureOreRespawns (world)33
{34
if (!world.oreRespawns)35
{ world.oreRespawns = new Map(); }36
return world.oreRespawns;37
}38
39
function blockAt (world, tileX, tileY)40
{41
const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));42
return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;43
}44
45
function setBoulderState (world, tileX, tileY, state)46
{47
const chunkX = tileToChunk(tileX);48
const chunkY = tileToChunk(tileY);49
const localX = tileToLocal(tileX);50
const localY = tileToLocal(tileY);51
const data = world.chunkData(chunkX, chunkY);52
const index = localY * CHUNK_SIZE + localX;53
const prev = data?.blocks?.[index];54
if (!prev || prev.typeId !== BlockType.boulder)55
{ return null; }56
const block = { typeId: prev.typeId, state, config: prev.config ?? null };57
data.blocks[index] = block;58
return {59
type: "chunk-delta",60
chunkX,61
chunkY,62
tileX,63
tileY,64
localX,65
localY,66
block67
};68
}69
70
function equippedPickaxe (ecs, handle)71
{72
const equipment = ecs.get(handle, Component.equipment);73
const stack = equipment?.slots?.weapon;74
if (!stack?.itemId)75
{ return null; }76
const def = itemDefinition(stack.itemId);77
if (def?.equipment?.kind !== EquipmentKind.pickaxeTool)78
{ return null; }79
return { stack, def, tier: def.equipment.tier };80
}81
82
function clearGather (ecs, handle)83
{84
if (ecs.has(handle, Component.gather))85
{ ecs.remove(handle, Component.gather); }86
}87
88
export function cancelGather (ecs, handle)89
{90
clearGather(ecs, handle);91
}92
93
/** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */94
export function clearOreRespawnsForChunk (world, chunkX, chunkY)95
{96
const respawns = world.oreRespawns;97
if (!respawns?.size)98
{ return; }99
for (const key of [...respawns.keys()])100
{101
const [tileX, tileY] = key.split(",").map(Number);102
if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)103
{ respawns.delete(key); }104
}105
}106
107
/**108
* Restore exhausted ore boulders whose timers have elapsed.109
*/110
export function stepOreRespawns (world, now)111
{112
const respawns = world.oreRespawns;113
if (!respawns?.size)114
{ return { events: [] }; }115
const events = [];116
for (const [key, entry] of [...respawns.entries()])117
{118
if (now < entry.respawnsAt)119
{ continue; }120
respawns.delete(key);121
const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId));122
if (delta)123
{ events.push(delta); }124
}125
return { events };126
}127
128
/**129
* Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.130
*/131
export function startMine (world, sessionId, characterId, tileX, tileY, now)132
{133
const entityId = world.characterEntities.get(characterId);134
if (entityId == null)135
{ throw userError("Character is not in the world."); }136
const handle = world.ecs.handleOf(entityId);137
const identity = world.ecs.get(handle, Component.networkIdentity);138
if (!identity || identity.sessionId !== sessionId)139
{ throw userError("Character is not in the world."); }140
if (world.ecs.has(handle, Component.dead))141
{ throw userError("You are dead."); }142
143
const position = world.ecs.get(handle, Component.position);144
if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)145
{ throw userError("You need to stand next to the rock."); }146
147
const block = blockAt(world, tileX, tileY);148
if (!block || block.typeId !== BlockType.boulder)149
{ throw userError("There is nothing to mine there."); }150
const materialId = materialFromOreBoulderState(block.state);151
if (!materialId)152
{ throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE153
? "That rock is exhausted."154
: "That rock has no ore."); }155
156
const pickaxe = equippedPickaxe(world.ecs, handle);157
if (!pickaxe)158
{ throw userError("Equip a pickaxe to mine."); }159
160
const skills = world.ecs.get(handle, Component.skills);161
const miningLevel = skillLevel(skills, SkillId.mining);162
const gate = canMineMaterial(miningLevel, pickaxe.tier, materialId);163
if (!gate.ok)164
{ throw userError(gate.reason); }165
166
const durationMs = miningDurationMs(materialId, pickaxe.tier);167
clearEngage(world.ecs, entityId);168
const path = world.ecs.get(handle, Component.path);169
if (path)170
{ path.tiles = []; }171
world.ecs.add(handle, Component.gather, {172
kind: "mining",173
tileX,174
tileY,175
materialId,176
startedAt: now,177
finishesAt: now + durationMs,178
nextSwingAt: now179
});180
181
return {182
events: [{183
type: "gather-swing",184
attackerId: entityId,185
tileX,186
tileY,187
fromTileX: position.tileX,188
fromTileY: position.tileY,189
swipe: false190
}]191
};192
}193
194
export function stepGather (world, now)195
{196
const events = [];197
const privates = [];198
const respawnEvents = stepOreRespawns(world, now);199
events.push(...respawnEvents.events);200
201
for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))202
{203
const { handle, gather, position, character, entityId } = entity;204
if (world.ecs.has(handle, Component.dead))205
{206
clearGather(world.ecs, handle);207
continue;208
}209
if (chebyshev(position.tileX, position.tileY, gather.tileX, gather.tileY) > 1)210
{211
clearGather(world.ecs, handle);212
continue;213
}214
const block = blockAt(world, gather.tileX, gather.tileY);215
if (!block || block.typeId !== BlockType.boulder216
|| materialFromOreBoulderState(block.state) !== gather.materialId)217
{218
clearGather(world.ecs, handle);219
continue;220
}221
222
if (now >= gather.nextSwingAt && now < gather.finishesAt)223
{224
gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;225
events.push({226
type: "gather-swing",227
attackerId: entityId,228
tileX: gather.tileX,229
tileY: gather.tileY,230
fromTileX: position.tileX,231
fromTileY: position.tileY,232
swipe: false233
});234
}235
236
if (now < gather.finishesAt)237
{ continue; }238
239
const oreItemId = oreItemIdForMaterial(gather.materialId);240
const def = itemDefinition(oreItemId);241
const inventory = world.ecs.get(handle, Component.inventory);242
if (!oreItemId || !def || !inventory)243
{244
clearGather(world.ecs, handle);245
continue;246
}247
const inserted = insertStack(inventory.slots, { itemId: oreItemId, quantity: 1 }, def);248
if (!inserted.ok || inserted.remainder > 0)249
{250
clearGather(world.ecs, handle);251
events.push({252
type: "command-error",253
sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,254
message: "Your inventory is full."255
});256
continue;257
}258
inventory.slots = inserted.slots;259
260
const skills = world.ecs.get(handle, Component.skills);261
let skillsChanged = false;262
if (skills?.xp && addSkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)))263
{ skillsChanged = true; }264
265
const exhausted = setBoulderState(266
world,267
gather.tileX,268
gather.tileY,269
EXHAUSTED_ORE_BOULDER_STATE270
);271
if (exhausted)272
{273
events.push(exhausted);274
ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {275
tileX: gather.tileX,276
tileY: gather.tileY,277
materialId: gather.materialId,278
respawnsAt: now + oreExhaustDurationMs(gather.materialId)279
});280
}281
282
clearGather(world.ecs, handle);283
privates.push({284
characterId: character.characterId,285
bag: bagView(world.ecs, handle)286
});287
if (skillsChanged)288
{289
events.push({290
type: "skills-updated",291
characterId: character.characterId,292
skills: publicSkillsView(skills),293
stored: storedSkillXp(skills)294
});295
}296
events.push({297
type: "gather-complete",298
characterId: character.characterId,299
kind: "mining",300
materialId: gather.materialId,301
itemId: oreItemId302
});303
}304
return { events, privates };305
}306
307
export function handleGatherCommand (world, sessionId, command, now)308
{309
switch (command.type)310
{311
case "mine":312
return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);313
case "cancel-gather":314
{315
const entityId = world.characterEntities.get(command.characterId);316
if (entityId == null)317
{ return { events: [] }; }318
const handle = world.ecs.handleOf(entityId);319
clearGather(world.ecs, handle);320
return { events: [] };321
}322
default:323
return null;324
}325
}@@ -22,6 +22,7 @@ import {
22
22
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
23
23
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
24
24
import { randomUUID } from "node:crypto";
25
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
25
26
26
27
export function publicGroundItem (item)
27
28
{
@@ -351,11 +352,16 @@ function eatItem (world, sessionId, command)
351
352
352
353
function openBank (world, sessionId, command)
353
354
{
354
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
355
const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
355
356
const position = world.ecs.get(handle, Component.position);
356
357
if (!nearBank(world, position.tileX, position.tileY))
357
358
{ throw userError("Stand next to a bank."); }
358
return { events: [], private: bagView(world.ecs, handle), bank: true };
359
const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank);
360
return {
361
events: shove ? [shove] : [],
362
private: bagView(world.ecs, handle),
363
bank: true
364
};
359
365
}
360
366
361
367
function bankMove (world, sessionId, command, fromKey, toKey)
@@ -22,6 +22,7 @@ import {22
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";22
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";23
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";23
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";24
import { randomUUID } from "node:crypto";24
import { randomUUID } from "node:crypto";25
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";25
26
26
export function publicGroundItem (item)27
export function publicGroundItem (item)27
{28
{@@ -351,11 +352,16 @@ function eatItem (world, sessionId, command)351
352
352
function openBank (world, sessionId, command)353
function openBank (world, sessionId, command)353
{354
{354
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);355
const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);355
const position = world.ecs.get(handle, Component.position);356
const position = world.ecs.get(handle, Component.position);356
if (!nearBank(world, position.tileX, position.tileY))357
if (!nearBank(world, position.tileX, position.tileY))357
{ throw userError("Stand next to a bank."); }358
{ throw userError("Stand next to a bank."); }358
return { events: [], private: bagView(world.ecs, handle), bank: true };359
const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank);360
return {361
events: shove ? [shove] : [],362
private: bagView(world.ecs, handle),363
bank: true364
};359
}365
}360
366
361
function bankMove (world, sessionId, command, fromKey, toKey)367
function bankMove (world, sessionId, command, fromKey, toKey)@@ -7,6 +7,14 @@ const FOLLOW_BREAK_TILES = CHUNK_SIZE;
7
7
const FOLLOW_ALWAYS_RUN_TILES = 3;
8
8
const FOLLOW_TRAIL_MAX = CHUNK_SIZE * 2;
9
9
10
function canEntityRun (ecs, handle)
11
{
12
const stamina = ecs.get(handle, Component.stamina);
13
if (!stamina)
14
{ return true; }
15
return Number(stamina.current) > 0;
16
}
17
10
18
export function clearFollow (ecs, entityId)
11
19
{
12
20
const handle = ecs.handleOf(entityId);
@@ -94,10 +102,15 @@ export function stepFollow (world)
94
102
continue;
95
103
}
96
104
105
const canRun = canEntityRun(world.ecs, entity.handle);
97
106
if (dist > FOLLOW_ALWAYS_RUN_TILES)
98
{ entity.movement.gait = GAIT.run; }
107
{ entity.movement.gait = canRun ? GAIT.run : GAIT.walk; }
99
108
else if (dist > 1)
100
{ entity.movement.gait = target.gait === GAIT.run ? GAIT.run : GAIT.walk; }
109
{
110
entity.movement.gait = canRun && target.gait === GAIT.run
111
? GAIT.run
112
: GAIT.walk;
113
}
101
114
102
115
if (!Array.isArray(follow.trail))
103
116
{ follow.trail = []; }
@@ -7,6 +7,14 @@ const FOLLOW_BREAK_TILES = CHUNK_SIZE;7
const FOLLOW_ALWAYS_RUN_TILES = 3;7
const FOLLOW_ALWAYS_RUN_TILES = 3;8
const FOLLOW_TRAIL_MAX = CHUNK_SIZE * 2;8
const FOLLOW_TRAIL_MAX = CHUNK_SIZE * 2;9
9
10
function canEntityRun (ecs, handle)11
{12
const stamina = ecs.get(handle, Component.stamina);13
if (!stamina)14
{ return true; }15
return Number(stamina.current) > 0;16
}17
10
export function clearFollow (ecs, entityId)18
export function clearFollow (ecs, entityId)11
{19
{12
const handle = ecs.handleOf(entityId);20
const handle = ecs.handleOf(entityId);@@ -94,10 +102,15 @@ export function stepFollow (world)94
continue;102
continue;95
}103
}96
104
105
const canRun = canEntityRun(world.ecs, entity.handle);97
if (dist > FOLLOW_ALWAYS_RUN_TILES)106
if (dist > FOLLOW_ALWAYS_RUN_TILES)98
{ entity.movement.gait = GAIT.run; }107
{ entity.movement.gait = canRun ? GAIT.run : GAIT.walk; }99
else if (dist > 1)108
else if (dist > 1)100
{ entity.movement.gait = target.gait === GAIT.run ? GAIT.run : GAIT.walk; }109
{110
entity.movement.gait = canRun && target.gait === GAIT.run111
? GAIT.run112
: GAIT.walk;113
}101
114
102
if (!Array.isArray(follow.trail))115
if (!Array.isArray(follow.trail))103
{ follow.trail = []; }116
{ follow.trail = []; }@@ -27,6 +27,7 @@ export const WorkerMessage = Object.freeze({
27
27
setGroundItems: "setGroundItems",
28
28
stepSpawners: "stepSpawners",
29
29
stepSystems: "stepSystems",
30
inspectStamina: "inspectStamina",
30
31
remoteCombatEngage: "remoteCombatEngage",
31
32
applyRemoteMelee: "applyRemoteMelee",
32
33
applyCombatHitXp: "applyCombatHitXp",
@@ -27,6 +27,7 @@ export const WorkerMessage = Object.freeze({27
setGroundItems: "setGroundItems",27
setGroundItems: "setGroundItems",28
stepSpawners: "stepSpawners",28
stepSpawners: "stepSpawners",29
stepSystems: "stepSystems",29
stepSystems: "stepSystems",30
inspectStamina: "inspectStamina",30
remoteCombatEngage: "remoteCombatEngage",31
remoteCombatEngage: "remoteCombatEngage",31
applyRemoteMelee: "applyRemoteMelee",32
applyRemoteMelee: "applyRemoteMelee",32
applyCombatHitXp: "applyCombatHitXp",33
applyCombatHitXp: "applyCombatHitXp",@@ -163,7 +163,7 @@ export class Simulation
163
163
const remoteMelee = [];
164
164
for (const worker of this.workers)
165
165
{
166
const result = worker.call({ type: WorkerMessage.stepSystems, now });
166
const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });
167
167
for (const event of result?.events ?? [])
168
168
{
169
169
if (event.type === "remote-melee-resolve")
@@ -177,6 +177,15 @@ export class Simulation
177
177
{ this.#forget(event.entityId); }
178
178
if (event.type === "skills-updated")
179
179
{ this.#applySkillsUpdated(event); }
180
if (event.type === "inventory" && event.characterId)
181
{
182
this.#saveBagFromView(event.characterId, {
183
inventory: event.inventory,
184
equipment: event.equipment,
185
vault: event.vault,
186
vaultReserved: event.vaultReserved
187
});
188
}
180
189
if (event.type === "player-died")
181
190
{
182
191
events.push(...this.#applyPlayerDeath(event));
@@ -212,8 +221,11 @@ export class Simulation
212
221
{
213
222
if (event.type === "entity-move")
214
223
{ this.#applyMoveToDirectory(event); }
224
if (event.type === "skills-updated")
225
{ this.#applySkillsUpdated(event); }
215
226
this.#persistGroundEvent(event);
216
events.push(event);
227
if (event.type !== "skills-updated")
228
{ events.push(event); }
217
229
}
218
230
for (const request of result?.transferRequests ?? [])
219
231
{ transfers.push({ ...request, fromWorkerId: worker.workerId }); }
@@ -308,7 +320,7 @@ export class Simulation
308
320
reserved: bag.vaultReserved ?? []
309
321
},
310
322
health: { current: isDead ? 0 : maxHealth, max: maxHealth },
311
stamina: { current: maxStamina, max: maxStamina },
323
stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
312
324
combat: { targetEntityId: null, nextSwingAt: 0 },
313
325
skills,
314
326
};
@@ -468,6 +480,17 @@ export class Simulation
468
480
});
469
481
}
470
482
483
staminaOf (entityId)
484
{
485
const record = this.directory.get(entityId);
486
if (!record)
487
{ return null; }
488
return this.workers[record.workerId].call({
489
type: WorkerMessage.inspectStamina,
490
entityId
491
});
492
}
493
471
494
pushInventory (characterId, bag)
472
495
{
473
496
this.pendingPrivate.push({
@@ -163,7 +163,7 @@ export class Simulation163
const remoteMelee = [];163
const remoteMelee = [];164
for (const worker of this.workers)164
for (const worker of this.workers)165
{165
{166
const result = worker.call({ type: WorkerMessage.stepSystems, now });166
const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });167
for (const event of result?.events ?? [])167
for (const event of result?.events ?? [])168
{168
{169
if (event.type === "remote-melee-resolve")169
if (event.type === "remote-melee-resolve")@@ -177,6 +177,15 @@ export class Simulation177
{ this.#forget(event.entityId); }177
{ this.#forget(event.entityId); }178
if (event.type === "skills-updated")178
if (event.type === "skills-updated")179
{ this.#applySkillsUpdated(event); }179
{ this.#applySkillsUpdated(event); }180
if (event.type === "inventory" && event.characterId)181
{182
this.#saveBagFromView(event.characterId, {183
inventory: event.inventory,184
equipment: event.equipment,185
vault: event.vault,186
vaultReserved: event.vaultReserved187
});188
}180
if (event.type === "player-died")189
if (event.type === "player-died")181
{190
{182
events.push(...this.#applyPlayerDeath(event));191
events.push(...this.#applyPlayerDeath(event));@@ -212,8 +221,11 @@ export class Simulation212
{221
{213
if (event.type === "entity-move")222
if (event.type === "entity-move")214
{ this.#applyMoveToDirectory(event); }223
{ this.#applyMoveToDirectory(event); }224
if (event.type === "skills-updated")225
{ this.#applySkillsUpdated(event); }215
this.#persistGroundEvent(event);226
this.#persistGroundEvent(event);216
events.push(event);227
if (event.type !== "skills-updated")228
{ events.push(event); }217
}229
}218
for (const request of result?.transferRequests ?? [])230
for (const request of result?.transferRequests ?? [])219
{ transfers.push({ ...request, fromWorkerId: worker.workerId }); }231
{ transfers.push({ ...request, fromWorkerId: worker.workerId }); }@@ -308,7 +320,7 @@ export class Simulation308
reserved: bag.vaultReserved ?? []320
reserved: bag.vaultReserved ?? []309
},321
},310
health: { current: isDead ? 0 : maxHealth, max: maxHealth },322
health: { current: isDead ? 0 : maxHealth, max: maxHealth },311
stamina: { current: maxStamina, max: maxStamina },323
stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },312
combat: { targetEntityId: null, nextSwingAt: 0 },324
combat: { targetEntityId: null, nextSwingAt: 0 },313
skills,325
skills,314
};326
};@@ -468,6 +480,17 @@ export class Simulation468
});480
});469
}481
}470
482
483
staminaOf (entityId)484
{485
const record = this.directory.get(entityId);486
if (!record)487
{ return null; }488
return this.workers[record.workerId].call({489
type: WorkerMessage.inspectStamina,490
entityId491
});492
}493
471
pushInventory (characterId, bag)494
pushInventory (characterId, bag)472
{495
{473
this.pendingPrivate.push({496
this.pendingPrivate.push({@@ -0,0 +1,49 @@
1
import { Component } from "../ecs/components.js";
2
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
3
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
4
5
/** Find a neighbouring (or same) tile with the given block type. Prefer non-self when possible. */
6
export function findAdjacentBlockTile (world, tileX, tileY, blockType)
7
{
8
let fallback = null;
9
for (let dy = -1; dy <= 1; dy++)
10
{
11
for (let dx = -1; dx <= 1; dx++)
12
{
13
const x = tileX + dx;
14
const y = tileY + dy;
15
const data = world.chunkData(tileToChunk(x), tileToChunk(y));
16
const index = tileToLocal(y) * CHUNK_SIZE + tileToLocal(x);
17
if (data.blocks[index]?.typeId !== blockType)
18
{ continue; }
19
if (dx !== 0 || dy !== 0)
20
{ return { tileX: x, tileY: y }; }
21
fallback = { tileX: x, tileY: y };
22
}
23
}
24
return fallback;
25
}
26
27
/** Shove the actor toward a world tile (bank, furnace, mine, craft, …). */
28
export function tileShoveEvent (entityId, fromTileX, fromTileY, tileX, tileY)
29
{
30
return {
31
type: "tile-shove",
32
attackerId: entityId,
33
fromTileX,
34
fromTileY,
35
tileX,
36
tileY
37
};
38
}
39
40
export function tileShoveTowardBlock (world, handle, entityId, blockType)
41
{
42
const position = world.ecs.get(handle, Component.position);
43
if (!position)
44
{ return null; }
45
const target = findAdjacentBlockTile(world, position.tileX, position.tileY, blockType);
46
if (!target)
47
{ return null; }
48
return tileShoveEvent(entityId, position.tileX, position.tileY, target.tileX, target.tileY);
49
}
@@ -0,0 +1,49 @@1
import { Component } from "../ecs/components.js";2
import { tileToChunk, tileToLocal } from "../world/coordinates.js";3
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";4
5
/** Find a neighbouring (or same) tile with the given block type. Prefer non-self when possible. */6
export function findAdjacentBlockTile (world, tileX, tileY, blockType)7
{8
let fallback = null;9
for (let dy = -1; dy <= 1; dy++)10
{11
for (let dx = -1; dx <= 1; dx++)12
{13
const x = tileX + dx;14
const y = tileY + dy;15
const data = world.chunkData(tileToChunk(x), tileToChunk(y));16
const index = tileToLocal(y) * CHUNK_SIZE + tileToLocal(x);17
if (data.blocks[index]?.typeId !== blockType)18
{ continue; }19
if (dx !== 0 || dy !== 0)20
{ return { tileX: x, tileY: y }; }21
fallback = { tileX: x, tileY: y };22
}23
}24
return fallback;25
}26
27
/** Shove the actor toward a world tile (bank, furnace, mine, craft, …). */28
export function tileShoveEvent (entityId, fromTileX, fromTileY, tileX, tileY)29
{30
return {31
type: "tile-shove",32
attackerId: entityId,33
fromTileX,34
fromTileY,35
tileX,36
tileY37
};38
}39
40
export function tileShoveTowardBlock (world, handle, entityId, blockType)41
{42
const position = world.ecs.get(handle, Component.position);43
if (!position)44
{ return null; }45
const target = findAdjacentBlockTile(world, position.tileX, position.tileY, blockType);46
if (!target)47
{ return null; }48
return tileShoveEvent(entityId, position.tileX, position.tileY, target.tileX, target.tileY);49
}@@ -31,6 +31,13 @@ import {
31
31
setGroundItemsForRegion
32
32
} from "../items/bags.js";
33
33
import { handleAlchemyCommand } from "../alchemy/service.js";
34
import {
35
handleGatherCommand,
36
stepGather,
37
cancelGather,
38
clearOreRespawnsForChunk
39
} from "../gathering/service.js";
40
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
34
41
import {
35
42
applyRemoteMeleeSwing,
36
43
clearEngage,
@@ -40,7 +47,15 @@ import {
40
47
resolveCombatTarget,
41
48
stepCombat
42
49
} from "../combat/service.js";
43
import { awardCombatHitXp } from "../skills/service.js";
50
import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
51
import { SkillId } from "../../../shared/definitions/skills.js";
52
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
53
import {
54
STAMINA_REGEN_PER_SECOND,
55
STAMINA_XP_PER_POINT_SPENT,
56
staminaCostPerRunStep,
57
publicStaminaView
58
} from "../../../shared/stamina/rules.js";
44
59
import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
45
60
import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
46
61
@@ -59,6 +74,7 @@ export class WorkerWorld
59
74
this.frozen = new Set();
60
75
this.groundItems = new Map();
61
76
this.groundByTile = new Map();
77
this.oreRespawns = new Map();
62
78
this.settings = { ...DEFAULT_WORLD_SETTINGS };
63
79
this.activeRevisionId = 1;
64
80
}
@@ -92,7 +108,7 @@ export class WorkerWorld
92
108
case WorkerMessage.stepMovement:
93
109
return this.#stepMovement(message.now);
94
110
case WorkerMessage.stepSystems:
95
return this.#stepSystems(message.now);
111
return this.#stepSystems(message.now, message.dt ?? (1 / 20));
96
112
case WorkerMessage.stepSpawners:
97
113
return { spawnRequests: collectSpawnRequests(this) };
98
114
case WorkerMessage.setGroundItems:
@@ -102,6 +118,8 @@ export class WorkerWorld
102
118
return this.#inspectBag(message.entityId);
103
119
case WorkerMessage.inspectSkills:
104
120
return this.#inspectSkills(message.entityId);
121
case WorkerMessage.inspectStamina:
122
return this.#inspectStamina(message.entityId);
105
123
case WorkerMessage.applyBag:
106
124
return this.#applyBag(message.entityId, message.bag);
107
125
case WorkerMessage.updateFlight:
@@ -181,6 +199,7 @@ export class WorkerWorld
181
199
this.ownedRegions.add(regionKey(message.regionX, message.regionY));
182
200
for (const chunk of message.chunks ?? [])
183
201
{
202
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
184
203
this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
185
204
data: cloneChunkData(chunk.data),
186
205
simulating: false,
@@ -196,6 +215,7 @@ export class WorkerWorld
196
215
{
197
216
const key = chunkKey(chunk.chunkX, chunk.chunkY);
198
217
const existing = this.chunks.get(key);
218
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
199
219
this.chunks.set(key, {
200
220
data: cloneChunkData(chunk.data),
201
221
simulating: existing?.simulating ?? false,
@@ -225,7 +245,10 @@ export class WorkerWorld
225
245
if (chunk.replica)
226
246
{ continue; }
227
247
if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
228
{ this.chunks.delete(key); }
248
{
249
clearOreRespawnsForChunk(this, chunkX, chunkY);
250
this.chunks.delete(key);
251
}
229
252
}
230
253
this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
231
254
return { dropped, groundItems };
@@ -354,8 +377,7 @@ export class WorkerWorld
354
377
this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
355
378
return { events: [] };
356
379
case "set-gait":
357
this.#setGait(sessionId, command.characterId, command.gait);
358
return { events: [] };
380
return this.#setGait(sessionId, command.characterId, command.gait);
359
381
case "attack":
360
382
return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
361
383
case "cancel-attack":
@@ -368,6 +390,12 @@ export class WorkerWorld
368
390
return this.#cancelFollow(sessionId, command.characterId);
369
391
default:
370
392
{
393
const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
394
if (gather)
395
{ return gather; }
396
const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
397
if (craft)
398
{ return craft; }
371
399
const alchemy = handleAlchemyCommand(this, sessionId, command);
372
400
if (alchemy)
373
401
{ return alchemy; }
@@ -495,6 +523,21 @@ export class WorkerWorld
495
523
return skills;
496
524
}
497
525
526
#inspectStamina (entityId)
527
{
528
const handle = this.ecs.handleOf(entityId);
529
if (handle == null)
530
{ return null; }
531
const stamina = this.ecs.get(handle, Component.stamina);
532
const movement = this.ecs.get(handle, Component.movement);
533
if (!stamina)
534
{ return null; }
535
return {
536
...publicStaminaView(stamina),
537
gait: movement?.gait ?? GAIT.walk
538
};
539
}
540
498
541
#applyBag (entityId, bag)
499
542
{
500
543
const handle = this.ecs.handleOf(entityId);
@@ -566,6 +609,7 @@ export class WorkerWorld
566
609
{ return; }
567
610
clearEngage(this.ecs, entityId);
568
611
clearFollow(this.ecs, entityId);
612
cancelGather(this.ecs, handle);
569
613
const position = this.ecs.get(handle, Component.position);
570
614
const movement = this.ecs.get(handle, Component.movement);
571
615
let path = this.ecs.get(handle, Component.path);
@@ -611,6 +655,7 @@ export class WorkerWorld
611
655
if (!this.ecs.get(handle, Component.combat))
612
656
{ this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
613
657
clearFollow(this.ecs, entityId);
658
cancelGather(this.ecs, handle);
614
659
engageTarget(this.ecs, entityId, targetEntityId, now);
615
660
if (target.local)
616
661
{
@@ -755,7 +800,99 @@ export class WorkerWorld
755
800
throw error;
756
801
}
757
802
const { handle } = this.#requireOwnedEntity(sessionId, characterId);
758
this.ecs.get(handle, Component.movement).gait = gait;
803
const movement = this.ecs.get(handle, Component.movement);
804
const stamina = this.ecs.get(handle, Component.stamina);
805
if (gait === GAIT.run && !(Number(stamina?.current) > 0))
806
{
807
const error = new Error("You are too exhausted to run.");
808
error.userFacing = true;
809
throw error;
810
}
811
movement.gait = gait;
812
const character = this.ecs.get(handle, Component.character);
813
return {
814
events: character
815
? [this.#staminaEvent(handle, character.characterId, movement.gait)]
816
: []
817
};
818
}
819
820
#staminaEvent (handle, characterId, gait = null)
821
{
822
const stamina = this.ecs.get(handle, Component.stamina);
823
const movement = this.ecs.get(handle, Component.movement);
824
return {
825
type: "stamina",
826
characterId,
827
...publicStaminaView(stamina),
828
gait: gait ?? movement?.gait ?? GAIT.walk
829
};
830
}
831
832
#consumeRunStamina (handle, events)
833
{
834
const character = this.ecs.get(handle, Component.character);
835
if (!character)
836
{ return; }
837
let stamina = this.ecs.get(handle, Component.stamina);
838
if (!stamina)
839
{
840
stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 });
841
}
842
const skills = this.ecs.get(handle, Component.skills);
843
syncPlayerStamina(this.ecs, handle);
844
const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond);
845
stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost);
846
stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost;
847
let skillsChanged = false;
848
while (stamina.xpDebt >= 1 && skills?.xp)
849
{
850
stamina.xpDebt -= 1;
851
if (addSkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT))
852
{
853
skillsChanged = true;
854
syncPlayerStamina(this.ecs, handle);
855
}
856
}
857
const movement = this.ecs.get(handle, Component.movement);
858
if (stamina.current <= 0 && movement)
859
{
860
stamina.current = 0;
861
movement.gait = GAIT.walk;
862
}
863
events.push(this.#staminaEvent(handle, character.characterId));
864
if (skillsChanged)
865
{
866
events.push({
867
type: "skills-updated",
868
characterId: character.characterId,
869
skills: publicSkillsView(skills),
870
stored: storedSkillXp(skills)
871
});
872
}
873
}
874
875
#regenStamina (dt, events)
876
{
877
if (!(dt > 0))
878
{ return; }
879
for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement))
880
{
881
const { handle, character, stamina, movement } = entity;
882
if (this.ecs.has(handle, Component.dead))
883
{ continue; }
884
if (movement.gait === GAIT.run)
885
{ continue; }
886
syncPlayerStamina(this.ecs, handle);
887
const before = Number(stamina.current) || 0;
888
if (before >= stamina.max)
889
{ continue; }
890
stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND);
891
const after = Number(stamina.current) || 0;
892
// Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
893
if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
894
{ events.push(this.#staminaEvent(handle, character.characterId)); }
895
}
759
896
}
760
897
761
898
#requireOwnedEntity (sessionId, characterId)
@@ -784,10 +921,11 @@ export class WorkerWorld
784
921
return { handle, entityId };
785
922
}
786
923
787
#stepSystems (now = Date.now())
924
#stepSystems (now = Date.now(), dt = 1 / 20)
788
925
{
789
926
const events = [];
790
927
const transferRequests = [];
928
this.#regenStamina(dt, events);
791
929
const flight = stepFreeFlight(this, now);
792
930
for (const event of flight)
793
931
{
@@ -810,6 +948,26 @@ export class WorkerWorld
810
948
}
811
949
events.push(...stepCombat(this, now));
812
950
stepFollow(this);
951
const gather = stepGather(this, now);
952
events.push(...gather.events);
953
for (const entry of gather.privates ?? [])
954
{
955
events.push({
956
type: "inventory",
957
characterId: entry.characterId,
958
...entry.bag
959
});
960
}
961
const craft = stepCrafting(this, now);
962
events.push(...craft.events);
963
for (const entry of craft.privates ?? [])
964
{
965
events.push({
966
type: "inventory",
967
characterId: entry.characterId,
968
...entry.bag
969
});
970
}
813
971
return { events, transferRequests };
814
972
}
815
973
@@ -833,6 +991,9 @@ export class WorkerWorld
833
991
if (!this.chunkIsSimulating(position.tileX, position.tileY))
834
992
{ continue; }
835
993
994
const stamina = this.ecs.get(handle, Component.stamina);
995
if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))
996
{ movement.gait = GAIT.walk; }
836
997
const isWalk = movement.gait !== GAIT.run;
837
998
if (isWalk)
838
999
{
@@ -890,6 +1051,8 @@ export class WorkerWorld
890
1051
{ this.#occupy(entityId, position.tileX, position.tileY); }
891
1052
recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
892
1053
consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1054
if (!isWalk)
1055
{ this.#consumeRunStamina(handle, events); }
893
1056
events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
894
1057
}
895
1058
return { events, transferRequests };
@@ -31,6 +31,13 @@ import {31
setGroundItemsForRegion31
setGroundItemsForRegion32
} from "../items/bags.js";32
} from "../items/bags.js";33
import { handleAlchemyCommand } from "../alchemy/service.js";33
import { handleAlchemyCommand } from "../alchemy/service.js";34
import {35
handleGatherCommand,36
stepGather,37
cancelGather,38
clearOreRespawnsForChunk39
} from "../gathering/service.js";40
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";34
import {41
import {35
applyRemoteMeleeSwing,42
applyRemoteMeleeSwing,36
clearEngage,43
clearEngage,@@ -40,7 +47,15 @@ import {40
resolveCombatTarget,47
resolveCombatTarget,41
stepCombat48
stepCombat42
} from "../combat/service.js";49
} from "../combat/service.js";43
import { awardCombatHitXp } from "../skills/service.js";50
import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";51
import { SkillId } from "../../../shared/definitions/skills.js";52
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";53
import {54
STAMINA_REGEN_PER_SECOND,55
STAMINA_XP_PER_POINT_SPENT,56
staminaCostPerRunStep,57
publicStaminaView58
} from "../../../shared/stamina/rules.js";44
import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";59
import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";45
import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";60
import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";46
61
@@ -59,6 +74,7 @@ export class WorkerWorld59
this.frozen = new Set();74
this.frozen = new Set();60
this.groundItems = new Map();75
this.groundItems = new Map();61
this.groundByTile = new Map();76
this.groundByTile = new Map();77
this.oreRespawns = new Map();62
this.settings = { ...DEFAULT_WORLD_SETTINGS };78
this.settings = { ...DEFAULT_WORLD_SETTINGS };63
this.activeRevisionId = 1;79
this.activeRevisionId = 1;64
}80
}@@ -92,7 +108,7 @@ export class WorkerWorld92
case WorkerMessage.stepMovement:108
case WorkerMessage.stepMovement:93
return this.#stepMovement(message.now);109
return this.#stepMovement(message.now);94
case WorkerMessage.stepSystems:110
case WorkerMessage.stepSystems:95
return this.#stepSystems(message.now);111
return this.#stepSystems(message.now, message.dt ?? (1 / 20));96
case WorkerMessage.stepSpawners:112
case WorkerMessage.stepSpawners:97
return { spawnRequests: collectSpawnRequests(this) };113
return { spawnRequests: collectSpawnRequests(this) };98
case WorkerMessage.setGroundItems:114
case WorkerMessage.setGroundItems:@@ -102,6 +118,8 @@ export class WorkerWorld102
return this.#inspectBag(message.entityId);118
return this.#inspectBag(message.entityId);103
case WorkerMessage.inspectSkills:119
case WorkerMessage.inspectSkills:104
return this.#inspectSkills(message.entityId);120
return this.#inspectSkills(message.entityId);121
case WorkerMessage.inspectStamina:122
return this.#inspectStamina(message.entityId);105
case WorkerMessage.applyBag:123
case WorkerMessage.applyBag:106
return this.#applyBag(message.entityId, message.bag);124
return this.#applyBag(message.entityId, message.bag);107
case WorkerMessage.updateFlight:125
case WorkerMessage.updateFlight:@@ -181,6 +199,7 @@ export class WorkerWorld181
this.ownedRegions.add(regionKey(message.regionX, message.regionY));199
this.ownedRegions.add(regionKey(message.regionX, message.regionY));182
for (const chunk of message.chunks ?? [])200
for (const chunk of message.chunks ?? [])183
{201
{202
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);184
this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {203
this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {185
data: cloneChunkData(chunk.data),204
data: cloneChunkData(chunk.data),186
simulating: false,205
simulating: false,@@ -196,6 +215,7 @@ export class WorkerWorld196
{215
{197
const key = chunkKey(chunk.chunkX, chunk.chunkY);216
const key = chunkKey(chunk.chunkX, chunk.chunkY);198
const existing = this.chunks.get(key);217
const existing = this.chunks.get(key);218
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);199
this.chunks.set(key, {219
this.chunks.set(key, {200
data: cloneChunkData(chunk.data),220
data: cloneChunkData(chunk.data),201
simulating: existing?.simulating ?? false,221
simulating: existing?.simulating ?? false,@@ -225,7 +245,10 @@ export class WorkerWorld225
if (chunk.replica)245
if (chunk.replica)226
{ continue; }246
{ continue; }227
if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)247
if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)228
{ this.chunks.delete(key); }248
{249
clearOreRespawnsForChunk(this, chunkX, chunkY);250
this.chunks.delete(key);251
}229
}252
}230
this.ownedRegions.delete(regionKey(message.regionX, message.regionY));253
this.ownedRegions.delete(regionKey(message.regionX, message.regionY));231
return { dropped, groundItems };254
return { dropped, groundItems };@@ -354,8 +377,7 @@ export class WorkerWorld354
this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);377
this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);355
return { events: [] };378
return { events: [] };356
case "set-gait":379
case "set-gait":357
this.#setGait(sessionId, command.characterId, command.gait);380
return this.#setGait(sessionId, command.characterId, command.gait);358
return { events: [] };359
case "attack":381
case "attack":360
return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());382
return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());361
case "cancel-attack":383
case "cancel-attack":@@ -368,6 +390,12 @@ export class WorkerWorld368
return this.#cancelFollow(sessionId, command.characterId);390
return this.#cancelFollow(sessionId, command.characterId);369
default:391
default:370
{392
{393
const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());394
if (gather)395
{ return gather; }396
const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());397
if (craft)398
{ return craft; }371
const alchemy = handleAlchemyCommand(this, sessionId, command);399
const alchemy = handleAlchemyCommand(this, sessionId, command);372
if (alchemy)400
if (alchemy)373
{ return alchemy; }401
{ return alchemy; }@@ -495,6 +523,21 @@ export class WorkerWorld495
return skills;523
return skills;496
}524
}497
525
526
#inspectStamina (entityId)527
{528
const handle = this.ecs.handleOf(entityId);529
if (handle == null)530
{ return null; }531
const stamina = this.ecs.get(handle, Component.stamina);532
const movement = this.ecs.get(handle, Component.movement);533
if (!stamina)534
{ return null; }535
return {536
...publicStaminaView(stamina),537
gait: movement?.gait ?? GAIT.walk538
};539
}540
498
#applyBag (entityId, bag)541
#applyBag (entityId, bag)499
{542
{500
const handle = this.ecs.handleOf(entityId);543
const handle = this.ecs.handleOf(entityId);@@ -566,6 +609,7 @@ export class WorkerWorld566
{ return; }609
{ return; }567
clearEngage(this.ecs, entityId);610
clearEngage(this.ecs, entityId);568
clearFollow(this.ecs, entityId);611
clearFollow(this.ecs, entityId);612
cancelGather(this.ecs, handle);569
const position = this.ecs.get(handle, Component.position);613
const position = this.ecs.get(handle, Component.position);570
const movement = this.ecs.get(handle, Component.movement);614
const movement = this.ecs.get(handle, Component.movement);571
let path = this.ecs.get(handle, Component.path);615
let path = this.ecs.get(handle, Component.path);@@ -611,6 +655,7 @@ export class WorkerWorld611
if (!this.ecs.get(handle, Component.combat))655
if (!this.ecs.get(handle, Component.combat))612
{ this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }656
{ this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }613
clearFollow(this.ecs, entityId);657
clearFollow(this.ecs, entityId);658
cancelGather(this.ecs, handle);614
engageTarget(this.ecs, entityId, targetEntityId, now);659
engageTarget(this.ecs, entityId, targetEntityId, now);615
if (target.local)660
if (target.local)616
{661
{@@ -755,7 +800,99 @@ export class WorkerWorld755
throw error;800
throw error;756
}801
}757
const { handle } = this.#requireOwnedEntity(sessionId, characterId);802
const { handle } = this.#requireOwnedEntity(sessionId, characterId);758
this.ecs.get(handle, Component.movement).gait = gait;803
const movement = this.ecs.get(handle, Component.movement);804
const stamina = this.ecs.get(handle, Component.stamina);805
if (gait === GAIT.run && !(Number(stamina?.current) > 0))806
{807
const error = new Error("You are too exhausted to run.");808
error.userFacing = true;809
throw error;810
}811
movement.gait = gait;812
const character = this.ecs.get(handle, Component.character);813
return {814
events: character815
? [this.#staminaEvent(handle, character.characterId, movement.gait)]816
: []817
};818
}819
820
#staminaEvent (handle, characterId, gait = null)821
{822
const stamina = this.ecs.get(handle, Component.stamina);823
const movement = this.ecs.get(handle, Component.movement);824
return {825
type: "stamina",826
characterId,827
...publicStaminaView(stamina),828
gait: gait ?? movement?.gait ?? GAIT.walk829
};830
}831
832
#consumeRunStamina (handle, events)833
{834
const character = this.ecs.get(handle, Component.character);835
if (!character)836
{ return; }837
let stamina = this.ecs.get(handle, Component.stamina);838
if (!stamina)839
{840
stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 });841
}842
const skills = this.ecs.get(handle, Component.skills);843
syncPlayerStamina(this.ecs, handle);844
const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond);845
stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost);846
stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost;847
let skillsChanged = false;848
while (stamina.xpDebt >= 1 && skills?.xp)849
{850
stamina.xpDebt -= 1;851
if (addSkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT))852
{853
skillsChanged = true;854
syncPlayerStamina(this.ecs, handle);855
}856
}857
const movement = this.ecs.get(handle, Component.movement);858
if (stamina.current <= 0 && movement)859
{860
stamina.current = 0;861
movement.gait = GAIT.walk;862
}863
events.push(this.#staminaEvent(handle, character.characterId));864
if (skillsChanged)865
{866
events.push({867
type: "skills-updated",868
characterId: character.characterId,869
skills: publicSkillsView(skills),870
stored: storedSkillXp(skills)871
});872
}873
}874
875
#regenStamina (dt, events)876
{877
if (!(dt > 0))878
{ return; }879
for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement))880
{881
const { handle, character, stamina, movement } = entity;882
if (this.ecs.has(handle, Component.dead))883
{ continue; }884
if (movement.gait === GAIT.run)885
{ continue; }886
syncPlayerStamina(this.ecs, handle);887
const before = Number(stamina.current) || 0;888
if (before >= stamina.max)889
{ continue; }890
stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND);891
const after = Number(stamina.current) || 0;892
// Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.893
if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))894
{ events.push(this.#staminaEvent(handle, character.characterId)); }895
}759
}896
}760
897
761
#requireOwnedEntity (sessionId, characterId)898
#requireOwnedEntity (sessionId, characterId)@@ -784,10 +921,11 @@ export class WorkerWorld784
return { handle, entityId };921
return { handle, entityId };785
}922
}786
923
787
#stepSystems (now = Date.now())924
#stepSystems (now = Date.now(), dt = 1 / 20)788
{925
{789
const events = [];926
const events = [];790
const transferRequests = [];927
const transferRequests = [];928
this.#regenStamina(dt, events);791
const flight = stepFreeFlight(this, now);929
const flight = stepFreeFlight(this, now);792
for (const event of flight)930
for (const event of flight)793
{931
{@@ -810,6 +948,26 @@ export class WorkerWorld810
}948
}811
events.push(...stepCombat(this, now));949
events.push(...stepCombat(this, now));812
stepFollow(this);950
stepFollow(this);951
const gather = stepGather(this, now);952
events.push(...gather.events);953
for (const entry of gather.privates ?? [])954
{955
events.push({956
type: "inventory",957
characterId: entry.characterId,958
...entry.bag959
});960
}961
const craft = stepCrafting(this, now);962
events.push(...craft.events);963
for (const entry of craft.privates ?? [])964
{965
events.push({966
type: "inventory",967
characterId: entry.characterId,968
...entry.bag969
});970
}813
return { events, transferRequests };971
return { events, transferRequests };814
}972
}815
973
@@ -833,6 +991,9 @@ export class WorkerWorld833
if (!this.chunkIsSimulating(position.tileX, position.tileY))991
if (!this.chunkIsSimulating(position.tileX, position.tileY))834
{ continue; }992
{ continue; }835
993
994
const stamina = this.ecs.get(handle, Component.stamina);995
if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))996
{ movement.gait = GAIT.walk; }836
const isWalk = movement.gait !== GAIT.run;997
const isWalk = movement.gait !== GAIT.run;837
if (isWalk)998
if (isWalk)838
{999
{@@ -890,6 +1051,8 @@ export class WorkerWorld890
{ this.#occupy(entityId, position.tileX, position.tileY); }1051
{ this.#occupy(entityId, position.tileX, position.tileY); }891
recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);1052
recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);892
consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);1053
consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);1054
if (!isWalk)1055
{ this.#consumeRunStamina(handle, events); }893
events.push(this.#moveEvent(entityId, fromTileX, fromTileY));1056
events.push(this.#moveEvent(entityId, fromTileX, fromTileY));894
}1057
}895
return { events, transferRequests };1058
return { events, transferRequests };@@ -1,5 +1,5 @@
1
1
import { Component } from "../ecs/components.js";
2
import { SkillId, playerMaxHealth } from "../../../shared/definitions/skills.js";
2
import { SkillId, playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
3
3
import { combatHitXpPerSkill } from "../../../shared/skills/progression.js";
4
4
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
5
5
@@ -17,6 +17,20 @@ export function syncPlayerHealth (ecs, handle)
17
17
health.current = Math.min(health.current | 0, max);
18
18
}
19
19
20
export function syncPlayerStamina (ecs, handle)
21
{
22
const character = ecs.get(handle, Component.character);
23
if (!character)
24
{ return; }
25
const skills = ecs.get(handle, Component.skills);
26
const stamina = ecs.get(handle, Component.stamina);
27
if (!skills || !stamina)
28
{ return; }
29
const max = playerMaxStamina(skills);
30
stamina.max = max;
31
stamina.current = Math.min(Number(stamina.current) || 0, max);
32
}
33
20
34
export function awardCombatHitXp (ecs, attackerHandle, profile)
21
35
{
22
36
const skills = ecs.get(attackerHandle, Component.skills);
@@ -1,5 +1,5 @@1
import { Component } from "../ecs/components.js";1
import { Component } from "../ecs/components.js";2
import { SkillId, playerMaxHealth } from "../../../shared/definitions/skills.js";2
import { SkillId, playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";3
import { combatHitXpPerSkill } from "../../../shared/skills/progression.js";3
import { combatHitXpPerSkill } from "../../../shared/skills/progression.js";4
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";4
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";5
5
@@ -17,6 +17,20 @@ export function syncPlayerHealth (ecs, handle)17
health.current = Math.min(health.current | 0, max);17
health.current = Math.min(health.current | 0, max);18
}18
}19
19
20
export function syncPlayerStamina (ecs, handle)21
{22
const character = ecs.get(handle, Component.character);23
if (!character)24
{ return; }25
const skills = ecs.get(handle, Component.skills);26
const stamina = ecs.get(handle, Component.stamina);27
if (!skills || !stamina)28
{ return; }29
const max = playerMaxStamina(skills);30
stamina.max = max;31
stamina.current = Math.min(Number(stamina.current) || 0, max);32
}33
20
export function awardCombatHitXp (ecs, attackerHandle, profile)34
export function awardCombatHitXp (ecs, attackerHandle, profile)21
{35
{22
const skills = ecs.get(attackerHandle, Component.skills);36
const skills = ecs.get(attackerHandle, Component.skills);@@ -0,0 +1,250 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { BlockType, blockDefinition } from "../../shared/definitions/tiles.js";
4
import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/craftingStations.js";
5
import { ItemId } from "../../shared/definitions/items.js";
6
import { SkillId } from "../../shared/definitions/skills.js";
7
import { MaterialTier, tierSmeltSkillLevel } from "../../shared/definitions/materialTiers.js";
8
import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
9
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
10
import { totalXpForLevel } from "../../shared/skills/progression.js";
11
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
12
import { Component } from "../src/ecs/components.js";
13
14
function countItem (slots, itemId)
15
{
16
return (slots ?? []).reduce((sum, slot) =>
17
{
18
if (slot?.itemId === itemId)
19
{ return sum + (slot.quantity | 0); }
20
return sum;
21
}, 0);
22
}
23
24
function placeFurnace (worker, tileX, tileY)
25
{
26
const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
27
const localX = tileX % 16;
28
const localY = tileY % 16;
29
data.blocks[localY * 16 + localX] = {
30
typeId: BlockType.furnace,
31
state: "furnace",
32
config: null
33
};
34
}
35
36
function setSkillLevel (worker, playerId, skillId, level)
37
{
38
const handle = worker.world.ecs.handleOf(playerId);
39
const skills = worker.world.ecs.get(handle, Component.skills);
40
skills.xp[skillId] = totalXpForLevel(level);
41
}
42
43
function giveInventory (harness, playerId, items)
44
{
45
const inventory = emptySlots();
46
items.forEach((stack, index) =>
47
{
48
inventory[index] = { itemId: stack.itemId, quantity: stack.quantity };
49
});
50
harness.simulation.applyBag(playerId, {
51
inventory,
52
equipment: emptyEquipment(),
53
vault: [],
54
vaultReserved: []
55
});
56
}
57
58
function advanceMs (harness, ms)
59
{
60
const ticks = Math.ceil(ms / 50) + 3;
61
for (let i = 0; i < ticks; i++)
62
{
63
harness.advance(50);
64
harness.simulation.step();
65
}
66
}
67
68
test("furnace block and steel recipe exist", () =>
69
{
70
assert.equal(blockDefinition(BlockType.furnace)?.key, "furnace");
71
const recipes = recipesForStation(CraftingStationId.furnace);
72
const steel = recipes.find((recipe) => recipe.recipeId === "smelt-steel");
73
assert.ok(steel);
74
assert.deepEqual(steel.inputs.map((row) => row.itemId).sort(), [
75
ItemId.coal,
76
ItemId.ironOre
77
].sort());
78
assert.equal(steel.output.itemId, ItemId.steelBar);
79
assert.equal(recipeDefinition("smelt-bronze")?.minSkillLevel, tierSmeltSkillLevel(MaterialTier.bronze));
80
});
81
82
test("open furnace near station emits shove and station-open", () =>
83
{
84
const harness = makeSimulation({ workerCount: 1 });
85
try
86
{
87
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
88
const playerId = harness.simulation.spawnCharacter(1, character);
89
const record = harness.simulation.entityRecord(playerId);
90
const worker = harness.simulation.workers[record.workerId];
91
placeFurnace(worker, 9, 8);
92
93
harness.simulation.enqueue(1, {
94
type: "open-station",
95
characterId: character.character_id,
96
stationId: CraftingStationId.furnace
97
});
98
const result = harness.simulation.step();
99
assert.ok(result.events.some((event) => event.type === "tile-shove"));
100
assert.ok(result.events.some((event) =>
101
event.type === "station-open" && event.stationId === CraftingStationId.furnace));
102
}
103
finally
104
{ harness.close(); }
105
});
106
107
test("smelting bronze consumes ore, grants bar and Smithing XP", () =>
108
{
109
const harness = makeSimulation({ workerCount: 1 });
110
try
111
{
112
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
113
const playerId = harness.simulation.spawnCharacter(1, character);
114
const record = harness.simulation.entityRecord(playerId);
115
const worker = harness.simulation.workers[record.workerId];
116
placeFurnace(worker, 9, 8);
117
giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);
118
119
harness.simulation.enqueue(1, {
120
type: "start-craft",
121
characterId: character.character_id,
122
stationId: CraftingStationId.furnace,
123
recipeId: "smelt-bronze"
124
});
125
const start = harness.simulation.step();
126
assert.ok(start.events.some((event) => event.type === "tile-shove"));
127
assert.ok(start.events.some((event) =>
128
event.type === "item-bubble" && event.itemId === ItemId.bronzeBar));
129
130
const smithingBefore = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
131
advanceMs(harness, CRAFT_DURATION_MS);
132
133
const bag = harness.simulation.bagOf(playerId);
134
assert.equal(countItem(bag.inventory, ItemId.bronzeOre), 0);
135
assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 1);
136
const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
137
assert.ok(smithingAfter > smithingBefore);
138
}
139
finally
140
{ harness.close(); }
141
});
142
143
test("smelting steel requires iron ore and coal", () =>
144
{
145
const harness = makeSimulation({ workerCount: 1 });
146
try
147
{
148
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
149
const playerId = harness.simulation.spawnCharacter(1, character);
150
const record = harness.simulation.entityRecord(playerId);
151
const worker = harness.simulation.workers[record.workerId];
152
placeFurnace(worker, 9, 8);
153
setSkillLevel(worker, playerId, SkillId.smithing, tierSmeltSkillLevel(MaterialTier.steel));
154
giveInventory(harness, playerId, [
155
{ itemId: ItemId.ironOre, quantity: 1 },
156
{ itemId: ItemId.coal, quantity: 1 }
157
]);
158
159
harness.simulation.enqueue(1, {
160
type: "start-craft",
161
characterId: character.character_id,
162
stationId: CraftingStationId.furnace,
163
recipeId: "smelt-steel"
164
});
165
harness.simulation.step();
166
advanceMs(harness, CRAFT_DURATION_MS);
167
168
const bag = harness.simulation.bagOf(playerId);
169
assert.equal(countItem(bag.inventory, ItemId.ironOre), 0);
170
assert.equal(countItem(bag.inventory, ItemId.coal), 0);
171
assert.equal(countItem(bag.inventory, ItemId.steelBar), 1);
172
}
173
finally
174
{ harness.close(); }
175
});
176
177
test("craft rejects missing materials", () =>
178
{
179
const harness = makeSimulation({ workerCount: 1 });
180
try
181
{
182
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
183
const playerId = harness.simulation.spawnCharacter(1, character);
184
const record = harness.simulation.entityRecord(playerId);
185
const worker = harness.simulation.workers[record.workerId];
186
placeFurnace(worker, 9, 8);
187
giveInventory(harness, playerId, []);
188
189
harness.simulation.enqueue(1, {
190
type: "start-craft",
191
characterId: character.character_id,
192
stationId: CraftingStationId.furnace,
193
recipeId: "smelt-bronze"
194
});
195
const result = harness.simulation.step();
196
assert.ok(result.events.some((event) =>
197
event.type === "command-error" && /missing|materials/i.test(event.message ?? "")));
198
}
199
finally
200
{ harness.close(); }
201
});
202
203
test("craft rejects low Smithing for iron bars", () =>
204
{
205
const harness = makeSimulation({ workerCount: 1 });
206
try
207
{
208
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
209
const playerId = harness.simulation.spawnCharacter(1, character);
210
const record = harness.simulation.entityRecord(playerId);
211
const worker = harness.simulation.workers[record.workerId];
212
placeFurnace(worker, 9, 8);
213
giveInventory(harness, playerId, [{ itemId: ItemId.ironOre, quantity: 1 }]);
214
215
harness.simulation.enqueue(1, {
216
type: "start-craft",
217
characterId: character.character_id,
218
stationId: CraftingStationId.furnace,
219
recipeId: "smelt-iron"
220
});
221
const result = harness.simulation.step();
222
assert.ok(result.events.some((event) =>
223
event.type === "command-error" && /smithing|requires/i.test(event.message ?? "")));
224
}
225
finally
226
{ harness.close(); }
227
});
228
229
test("craft rejects furnace recipes when not next to a furnace", () =>
230
{
231
const harness = makeSimulation({ workerCount: 1 });
232
try
233
{
234
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
235
const playerId = harness.simulation.spawnCharacter(1, character);
236
giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);
237
238
harness.simulation.enqueue(1, {
239
type: "start-craft",
240
characterId: character.character_id,
241
stationId: CraftingStationId.furnace,
242
recipeId: "smelt-bronze"
243
});
244
const result = harness.simulation.step();
245
assert.ok(result.events.some((event) =>
246
event.type === "command-error" && /station|next to/i.test(event.message ?? "")));
247
}
248
finally
249
{ harness.close(); }
250
});
@@ -0,0 +1,250 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { BlockType, blockDefinition } from "../../shared/definitions/tiles.js";4
import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/craftingStations.js";5
import { ItemId } from "../../shared/definitions/items.js";6
import { SkillId } from "../../shared/definitions/skills.js";7
import { MaterialTier, tierSmeltSkillLevel } from "../../shared/definitions/materialTiers.js";8
import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";9
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";10
import { totalXpForLevel } from "../../shared/skills/progression.js";11
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";12
import { Component } from "../src/ecs/components.js";13
14
function countItem (slots, itemId)15
{16
return (slots ?? []).reduce((sum, slot) =>17
{18
if (slot?.itemId === itemId)19
{ return sum + (slot.quantity | 0); }20
return sum;21
}, 0);22
}23
24
function placeFurnace (worker, tileX, tileY)25
{26
const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));27
const localX = tileX % 16;28
const localY = tileY % 16;29
data.blocks[localY * 16 + localX] = {30
typeId: BlockType.furnace,31
state: "furnace",32
config: null33
};34
}35
36
function setSkillLevel (worker, playerId, skillId, level)37
{38
const handle = worker.world.ecs.handleOf(playerId);39
const skills = worker.world.ecs.get(handle, Component.skills);40
skills.xp[skillId] = totalXpForLevel(level);41
}42
43
function giveInventory (harness, playerId, items)44
{45
const inventory = emptySlots();46
items.forEach((stack, index) =>47
{48
inventory[index] = { itemId: stack.itemId, quantity: stack.quantity };49
});50
harness.simulation.applyBag(playerId, {51
inventory,52
equipment: emptyEquipment(),53
vault: [],54
vaultReserved: []55
});56
}57
58
function advanceMs (harness, ms)59
{60
const ticks = Math.ceil(ms / 50) + 3;61
for (let i = 0; i < ticks; i++)62
{63
harness.advance(50);64
harness.simulation.step();65
}66
}67
68
test("furnace block and steel recipe exist", () =>69
{70
assert.equal(blockDefinition(BlockType.furnace)?.key, "furnace");71
const recipes = recipesForStation(CraftingStationId.furnace);72
const steel = recipes.find((recipe) => recipe.recipeId === "smelt-steel");73
assert.ok(steel);74
assert.deepEqual(steel.inputs.map((row) => row.itemId).sort(), [75
ItemId.coal,76
ItemId.ironOre77
].sort());78
assert.equal(steel.output.itemId, ItemId.steelBar);79
assert.equal(recipeDefinition("smelt-bronze")?.minSkillLevel, tierSmeltSkillLevel(MaterialTier.bronze));80
});81
82
test("open furnace near station emits shove and station-open", () =>83
{84
const harness = makeSimulation({ workerCount: 1 });85
try86
{87
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });88
const playerId = harness.simulation.spawnCharacter(1, character);89
const record = harness.simulation.entityRecord(playerId);90
const worker = harness.simulation.workers[record.workerId];91
placeFurnace(worker, 9, 8);92
93
harness.simulation.enqueue(1, {94
type: "open-station",95
characterId: character.character_id,96
stationId: CraftingStationId.furnace97
});98
const result = harness.simulation.step();99
assert.ok(result.events.some((event) => event.type === "tile-shove"));100
assert.ok(result.events.some((event) =>101
event.type === "station-open" && event.stationId === CraftingStationId.furnace));102
}103
finally104
{ harness.close(); }105
});106
107
test("smelting bronze consumes ore, grants bar and Smithing XP", () =>108
{109
const harness = makeSimulation({ workerCount: 1 });110
try111
{112
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });113
const playerId = harness.simulation.spawnCharacter(1, character);114
const record = harness.simulation.entityRecord(playerId);115
const worker = harness.simulation.workers[record.workerId];116
placeFurnace(worker, 9, 8);117
giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);118
119
harness.simulation.enqueue(1, {120
type: "start-craft",121
characterId: character.character_id,122
stationId: CraftingStationId.furnace,123
recipeId: "smelt-bronze"124
});125
const start = harness.simulation.step();126
assert.ok(start.events.some((event) => event.type === "tile-shove"));127
assert.ok(start.events.some((event) =>128
event.type === "item-bubble" && event.itemId === ItemId.bronzeBar));129
130
const smithingBefore = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;131
advanceMs(harness, CRAFT_DURATION_MS);132
133
const bag = harness.simulation.bagOf(playerId);134
assert.equal(countItem(bag.inventory, ItemId.bronzeOre), 0);135
assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 1);136
const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;137
assert.ok(smithingAfter > smithingBefore);138
}139
finally140
{ harness.close(); }141
});142
143
test("smelting steel requires iron ore and coal", () =>144
{145
const harness = makeSimulation({ workerCount: 1 });146
try147
{148
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });149
const playerId = harness.simulation.spawnCharacter(1, character);150
const record = harness.simulation.entityRecord(playerId);151
const worker = harness.simulation.workers[record.workerId];152
placeFurnace(worker, 9, 8);153
setSkillLevel(worker, playerId, SkillId.smithing, tierSmeltSkillLevel(MaterialTier.steel));154
giveInventory(harness, playerId, [155
{ itemId: ItemId.ironOre, quantity: 1 },156
{ itemId: ItemId.coal, quantity: 1 }157
]);158
159
harness.simulation.enqueue(1, {160
type: "start-craft",161
characterId: character.character_id,162
stationId: CraftingStationId.furnace,163
recipeId: "smelt-steel"164
});165
harness.simulation.step();166
advanceMs(harness, CRAFT_DURATION_MS);167
168
const bag = harness.simulation.bagOf(playerId);169
assert.equal(countItem(bag.inventory, ItemId.ironOre), 0);170
assert.equal(countItem(bag.inventory, ItemId.coal), 0);171
assert.equal(countItem(bag.inventory, ItemId.steelBar), 1);172
}173
finally174
{ harness.close(); }175
});176
177
test("craft rejects missing materials", () =>178
{179
const harness = makeSimulation({ workerCount: 1 });180
try181
{182
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });183
const playerId = harness.simulation.spawnCharacter(1, character);184
const record = harness.simulation.entityRecord(playerId);185
const worker = harness.simulation.workers[record.workerId];186
placeFurnace(worker, 9, 8);187
giveInventory(harness, playerId, []);188
189
harness.simulation.enqueue(1, {190
type: "start-craft",191
characterId: character.character_id,192
stationId: CraftingStationId.furnace,193
recipeId: "smelt-bronze"194
});195
const result = harness.simulation.step();196
assert.ok(result.events.some((event) =>197
event.type === "command-error" && /missing|materials/i.test(event.message ?? "")));198
}199
finally200
{ harness.close(); }201
});202
203
test("craft rejects low Smithing for iron bars", () =>204
{205
const harness = makeSimulation({ workerCount: 1 });206
try207
{208
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });209
const playerId = harness.simulation.spawnCharacter(1, character);210
const record = harness.simulation.entityRecord(playerId);211
const worker = harness.simulation.workers[record.workerId];212
placeFurnace(worker, 9, 8);213
giveInventory(harness, playerId, [{ itemId: ItemId.ironOre, quantity: 1 }]);214
215
harness.simulation.enqueue(1, {216
type: "start-craft",217
characterId: character.character_id,218
stationId: CraftingStationId.furnace,219
recipeId: "smelt-iron"220
});221
const result = harness.simulation.step();222
assert.ok(result.events.some((event) =>223
event.type === "command-error" && /smithing|requires/i.test(event.message ?? "")));224
}225
finally226
{ harness.close(); }227
});228
229
test("craft rejects furnace recipes when not next to a furnace", () =>230
{231
const harness = makeSimulation({ workerCount: 1 });232
try233
{234
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });235
const playerId = harness.simulation.spawnCharacter(1, character);236
giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);237
238
harness.simulation.enqueue(1, {239
type: "start-craft",240
characterId: character.character_id,241
stationId: CraftingStationId.furnace,242
recipeId: "smelt-bronze"243
});244
const result = harness.simulation.step();245
assert.ok(result.events.some((event) =>246
event.type === "command-error" && /station|next to/i.test(event.message ?? "")));247
}248
finally249
{ harness.close(); }250
});@@ -0,0 +1,283 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import {
4
MaterialTier,
5
GatherMaterialId,
6
tierMinSkillLevel,
7
tierMineSkillLevel,
8
tierSmeltSkillLevel,
9
tierRank,
10
miningDurationMs,
11
oreExhaustDurationMs,
12
oreBoulderState,
13
materialFromOreBoulderState,
14
EXHAUSTED_ORE_BOULDER_STATE
15
} from "../../shared/definitions/materialTiers.js";
16
import {
17
canMineMaterial,
18
oreItemIdForMaterial
19
} from "../../shared/definitions/gathering.js";
20
import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
21
import { SkillId } from "../../shared/definitions/skills.js";
22
import { canEquipItem } from "../../shared/equipment/stats.js";
23
import { normalizePlayerSkills } from "../../shared/skills/state.js";
24
import { totalXpForLevel } from "../../shared/skills/progression.js";
25
import { BlockType, blockDefinition } from "../../shared/definitions/tiles.js";
26
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
27
import { Component } from "../src/ecs/components.js";
28
29
function countItem (slots, itemId)
30
{
31
return (slots ?? []).reduce((sum, slot) =>
32
{
33
if (slot?.itemId === itemId)
34
{ return sum + (slot.quantity | 0); }
35
return sum;
36
}, 0);
37
}
38
39
function placeOre (worker, tileX, tileY, state)
40
{
41
const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
42
const localX = tileX % 16;
43
const localY = tileY % 16;
44
const index = localY * 16 + localX;
45
data.blocks[index] = { typeId: BlockType.boulder, state, config: null };
46
return { data, index };
47
}
48
49
function equipPickaxe (worker, playerId, itemId)
50
{
51
const handle = worker.world.ecs.handleOf(playerId);
52
const equipment = worker.world.ecs.get(handle, Component.equipment);
53
equipment.slots[EQUIPMENT_SLOT.weapon] = { itemId, quantity: 1 };
54
}
55
56
function setSkillLevel (worker, playerId, skillId, level)
57
{
58
const handle = worker.world.ecs.handleOf(playerId);
59
const skills = worker.world.ecs.get(handle, Component.skills);
60
skills.xp[skillId] = totalXpForLevel(level);
61
}
62
63
function advanceMs (harness, ms)
64
{
65
const ticks = Math.ceil(ms / 50) + 3;
66
for (let i = 0; i < ticks; i++)
67
{
68
harness.advance(50);
69
harness.simulation.step();
70
}
71
}
72
73
test("tier skill gates: equip / mine / smelt", () =>
74
{
75
assert.equal(tierMinSkillLevel(MaterialTier.bronze), 1);
76
assert.equal(tierMinSkillLevel(MaterialTier.mithril), 35);
77
assert.equal(tierMinSkillLevel(MaterialTier.dragon), 90);
78
assert.equal(tierMineSkillLevel(MaterialTier.iron), 5);
79
assert.equal(tierMineSkillLevel(MaterialTier.mithril), 18);
80
assert.equal(tierSmeltSkillLevel(MaterialTier.iron), 8);
81
assert.equal(tierSmeltSkillLevel(MaterialTier.steel), 15);
82
assert.equal(tierRank(MaterialTier.dragon), 7);
83
});
84
85
test("mining duration uses resource and tool ranks", () =>
86
{
87
assert.equal(miningDurationMs(MaterialTier.bronze, MaterialTier.bronze), 5000);
88
assert.equal(miningDurationMs(MaterialTier.iron, MaterialTier.bronze), 13000);
89
assert.ok(miningDurationMs(MaterialTier.bronze, MaterialTier.dragon) >= 500);
90
});
91
92
test("ore exhaust duration is 10s times material rank", () =>
93
{
94
assert.equal(oreExhaustDurationMs(MaterialTier.bronze), 10_000);
95
assert.equal(oreExhaustDurationMs(MaterialTier.iron), 20_000);
96
assert.equal(oreExhaustDurationMs(GatherMaterialId.coal), 20_000);
97
assert.equal(oreExhaustDurationMs(MaterialTier.dragon), 70_000);
98
});
99
100
test("ore boulder states map to materials", () =>
101
{
102
assert.equal(materialFromOreBoulderState("bronze-ore"), MaterialTier.bronze);
103
assert.equal(materialFromOreBoulderState("coal"), GatherMaterialId.coal);
104
assert.equal(materialFromOreBoulderState("boulder"), null);
105
assert.equal(oreBoulderState(MaterialTier.mithril), "mithril-ore");
106
});
107
108
test("boulder block exists", () =>
109
{
110
assert.equal(blockDefinition(BlockType.boulder)?.key, "boulder");
111
});
112
113
test("iron pickaxe requires Mining 10", () =>
114
{
115
const skills = normalizePlayerSkills(null);
116
assert.equal(canEquipItem(skills, itemDefinition(ItemId.ironPickaxe)).ok, false);
117
skills.xp[SkillId.mining] = totalXpForLevel(10);
118
assert.equal(canEquipItem(skills, itemDefinition(ItemId.ironPickaxe)).ok, true);
119
assert.equal(canEquipItem(skills, itemDefinition(ItemId.bronzePickaxe)).ok, true);
120
});
121
122
test("canMineMaterial enforces skill and tool tier", () =>
123
{
124
assert.equal(canMineMaterial(1, MaterialTier.bronze, MaterialTier.iron).ok, false);
125
assert.equal(canMineMaterial(5, MaterialTier.bronze, MaterialTier.iron).ok, false);
126
assert.equal(canMineMaterial(5, MaterialTier.iron, MaterialTier.iron).ok, true);
127
});
128
129
test("mining without a pickaxe is rejected", () =>
130
{
131
const harness = makeSimulation({ workerCount: 1 });
132
try
133
{
134
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
135
const playerId = harness.simulation.spawnCharacter(1, character);
136
const record = harness.simulation.entityRecord(playerId);
137
const worker = harness.simulation.workers[record.workerId];
138
placeOre(worker, 9, 8, "bronze-ore");
139
140
harness.simulation.enqueue(1, {
141
type: "mine",
142
characterId: character.character_id,
143
tileX: 9,
144
tileY: 8
145
});
146
const result = harness.simulation.step();
147
assert.ok(result.events.some((event) =>
148
event.type === "command-error" && /pickaxe/i.test(event.message ?? "")));
149
}
150
finally
151
{ harness.close(); }
152
});
153
154
test("plain boulder cannot be mined", () =>
155
{
156
const harness = makeSimulation({ workerCount: 1 });
157
try
158
{
159
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
160
const playerId = harness.simulation.spawnCharacter(1, character);
161
const record = harness.simulation.entityRecord(playerId);
162
const worker = harness.simulation.workers[record.workerId];
163
equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
164
placeOre(worker, 9, 8, EXHAUSTED_ORE_BOULDER_STATE);
165
166
harness.simulation.enqueue(1, {
167
type: "mine",
168
characterId: character.character_id,
169
tileX: 9,
170
tileY: 8
171
});
172
const result = harness.simulation.step();
173
assert.ok(result.events.some((event) =>
174
event.type === "command-error"
175
&& (/no ore|exhausted/i.test(event.message ?? ""))));
176
}
177
finally
178
{ harness.close(); }
179
});
180
181
test("weak pickaxe cannot mine higher-tier ore", () =>
182
{
183
const harness = makeSimulation({ workerCount: 1 });
184
try
185
{
186
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
187
const playerId = harness.simulation.spawnCharacter(1, character);
188
const record = harness.simulation.entityRecord(playerId);
189
const worker = harness.simulation.workers[record.workerId];
190
equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
191
setSkillLevel(worker, playerId, SkillId.mining, 10);
192
placeOre(worker, 9, 8, "iron-ore");
193
194
harness.simulation.enqueue(1, {
195
type: "mine",
196
characterId: character.character_id,
197
tileX: 9,
198
tileY: 8
199
});
200
const result = harness.simulation.step();
201
assert.ok(result.events.some((event) =>
202
event.type === "command-error" && /too weak|pickaxe/i.test(event.message ?? "")));
203
}
204
finally
205
{ harness.close(); }
206
});
207
208
test("mining grants ore and Mining XP then exhausts and respawns the node", () =>
209
{
210
const harness = makeSimulation({ workerCount: 1 });
211
try
212
{
213
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
214
const playerId = harness.simulation.spawnCharacter(1, character);
215
const record = harness.simulation.entityRecord(playerId);
216
const worker = harness.simulation.workers[record.workerId];
217
equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
218
const { data, index } = placeOre(worker, 9, 8, "bronze-ore");
219
220
harness.simulation.enqueue(1, {
221
type: "mine",
222
characterId: character.character_id,
223
tileX: 9,
224
tileY: 8
225
});
226
const start = harness.simulation.step();
227
assert.ok(start.events.some((event) => event.type === "gather-swing" || event.type === "tile-shove"));
228
229
advanceMs(harness, miningDurationMs(MaterialTier.bronze, MaterialTier.bronze));
230
231
const bag = harness.simulation.bagOf(playerId);
232
assert.ok(countItem(bag.inventory, ItemId.bronzeOre) >= 1);
233
const skills = harness.stateDb.getSkills(character.character_id);
234
assert.ok(skills.xp.mining > 0);
235
assert.equal(oreItemIdForMaterial(MaterialTier.bronze), ItemId.bronzeOre);
236
assert.equal(data.blocks[index].state, EXHAUSTED_ORE_BOULDER_STATE);
237
238
harness.simulation.enqueue(1, {
239
type: "mine",
240
characterId: character.character_id,
241
tileX: 9,
242
tileY: 8
243
});
244
const exhaustedResult = harness.simulation.step();
245
assert.ok(exhaustedResult.events.some((event) =>
246
event.type === "command-error" && /exhausted/i.test(event.message ?? "")));
247
248
advanceMs(harness, oreExhaustDurationMs(MaterialTier.bronze));
249
assert.equal(data.blocks[index].state, "bronze-ore");
250
}
251
finally
252
{ harness.close(); }
253
});
254
255
test("coal mining yields coal and exhausts the node", () =>
256
{
257
const harness = makeSimulation({ workerCount: 1 });
258
try
259
{
260
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
261
const playerId = harness.simulation.spawnCharacter(1, character);
262
const record = harness.simulation.entityRecord(playerId);
263
const worker = harness.simulation.workers[record.workerId];
264
setSkillLevel(worker, playerId, SkillId.mining, 10);
265
equipPickaxe(worker, playerId, ItemId.ironPickaxe);
266
const { data, index } = placeOre(worker, 9, 8, "coal");
267
268
harness.simulation.enqueue(1, {
269
type: "mine",
270
characterId: character.character_id,
271
tileX: 9,
272
tileY: 8
273
});
274
harness.simulation.step();
275
advanceMs(harness, miningDurationMs(GatherMaterialId.coal, MaterialTier.iron));
276
277
const bag = harness.simulation.bagOf(playerId);
278
assert.ok(countItem(bag.inventory, ItemId.coal) >= 1);
279
assert.equal(data.blocks[index].state, EXHAUSTED_ORE_BOULDER_STATE);
280
}
281
finally
282
{ harness.close(); }
283
});
@@ -0,0 +1,283 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import {4
MaterialTier,5
GatherMaterialId,6
tierMinSkillLevel,7
tierMineSkillLevel,8
tierSmeltSkillLevel,9
tierRank,10
miningDurationMs,11
oreExhaustDurationMs,12
oreBoulderState,13
materialFromOreBoulderState,14
EXHAUSTED_ORE_BOULDER_STATE15
} from "../../shared/definitions/materialTiers.js";16
import {17
canMineMaterial,18
oreItemIdForMaterial19
} from "../../shared/definitions/gathering.js";20
import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";21
import { SkillId } from "../../shared/definitions/skills.js";22
import { canEquipItem } from "../../shared/equipment/stats.js";23
import { normalizePlayerSkills } from "../../shared/skills/state.js";24
import { totalXpForLevel } from "../../shared/skills/progression.js";25
import { BlockType, blockDefinition } from "../../shared/definitions/tiles.js";26
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";27
import { Component } from "../src/ecs/components.js";28
29
function countItem (slots, itemId)30
{31
return (slots ?? []).reduce((sum, slot) =>32
{33
if (slot?.itemId === itemId)34
{ return sum + (slot.quantity | 0); }35
return sum;36
}, 0);37
}38
39
function placeOre (worker, tileX, tileY, state)40
{41
const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));42
const localX = tileX % 16;43
const localY = tileY % 16;44
const index = localY * 16 + localX;45
data.blocks[index] = { typeId: BlockType.boulder, state, config: null };46
return { data, index };47
}48
49
function equipPickaxe (worker, playerId, itemId)50
{51
const handle = worker.world.ecs.handleOf(playerId);52
const equipment = worker.world.ecs.get(handle, Component.equipment);53
equipment.slots[EQUIPMENT_SLOT.weapon] = { itemId, quantity: 1 };54
}55
56
function setSkillLevel (worker, playerId, skillId, level)57
{58
const handle = worker.world.ecs.handleOf(playerId);59
const skills = worker.world.ecs.get(handle, Component.skills);60
skills.xp[skillId] = totalXpForLevel(level);61
}62
63
function advanceMs (harness, ms)64
{65
const ticks = Math.ceil(ms / 50) + 3;66
for (let i = 0; i < ticks; i++)67
{68
harness.advance(50);69
harness.simulation.step();70
}71
}72
73
test("tier skill gates: equip / mine / smelt", () =>74
{75
assert.equal(tierMinSkillLevel(MaterialTier.bronze), 1);76
assert.equal(tierMinSkillLevel(MaterialTier.mithril), 35);77
assert.equal(tierMinSkillLevel(MaterialTier.dragon), 90);78
assert.equal(tierMineSkillLevel(MaterialTier.iron), 5);79
assert.equal(tierMineSkillLevel(MaterialTier.mithril), 18);80
assert.equal(tierSmeltSkillLevel(MaterialTier.iron), 8);81
assert.equal(tierSmeltSkillLevel(MaterialTier.steel), 15);82
assert.equal(tierRank(MaterialTier.dragon), 7);83
});84
85
test("mining duration uses resource and tool ranks", () =>86
{87
assert.equal(miningDurationMs(MaterialTier.bronze, MaterialTier.bronze), 5000);88
assert.equal(miningDurationMs(MaterialTier.iron, MaterialTier.bronze), 13000);89
assert.ok(miningDurationMs(MaterialTier.bronze, MaterialTier.dragon) >= 500);90
});91
92
test("ore exhaust duration is 10s times material rank", () =>93
{94
assert.equal(oreExhaustDurationMs(MaterialTier.bronze), 10_000);95
assert.equal(oreExhaustDurationMs(MaterialTier.iron), 20_000);96
assert.equal(oreExhaustDurationMs(GatherMaterialId.coal), 20_000);97
assert.equal(oreExhaustDurationMs(MaterialTier.dragon), 70_000);98
});99
100
test("ore boulder states map to materials", () =>101
{102
assert.equal(materialFromOreBoulderState("bronze-ore"), MaterialTier.bronze);103
assert.equal(materialFromOreBoulderState("coal"), GatherMaterialId.coal);104
assert.equal(materialFromOreBoulderState("boulder"), null);105
assert.equal(oreBoulderState(MaterialTier.mithril), "mithril-ore");106
});107
108
test("boulder block exists", () =>109
{110
assert.equal(blockDefinition(BlockType.boulder)?.key, "boulder");111
});112
113
test("iron pickaxe requires Mining 10", () =>114
{115
const skills = normalizePlayerSkills(null);116
assert.equal(canEquipItem(skills, itemDefinition(ItemId.ironPickaxe)).ok, false);117
skills.xp[SkillId.mining] = totalXpForLevel(10);118
assert.equal(canEquipItem(skills, itemDefinition(ItemId.ironPickaxe)).ok, true);119
assert.equal(canEquipItem(skills, itemDefinition(ItemId.bronzePickaxe)).ok, true);120
});121
122
test("canMineMaterial enforces skill and tool tier", () =>123
{124
assert.equal(canMineMaterial(1, MaterialTier.bronze, MaterialTier.iron).ok, false);125
assert.equal(canMineMaterial(5, MaterialTier.bronze, MaterialTier.iron).ok, false);126
assert.equal(canMineMaterial(5, MaterialTier.iron, MaterialTier.iron).ok, true);127
});128
129
test("mining without a pickaxe is rejected", () =>130
{131
const harness = makeSimulation({ workerCount: 1 });132
try133
{134
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });135
const playerId = harness.simulation.spawnCharacter(1, character);136
const record = harness.simulation.entityRecord(playerId);137
const worker = harness.simulation.workers[record.workerId];138
placeOre(worker, 9, 8, "bronze-ore");139
140
harness.simulation.enqueue(1, {141
type: "mine",142
characterId: character.character_id,143
tileX: 9,144
tileY: 8145
});146
const result = harness.simulation.step();147
assert.ok(result.events.some((event) =>148
event.type === "command-error" && /pickaxe/i.test(event.message ?? "")));149
}150
finally151
{ harness.close(); }152
});153
154
test("plain boulder cannot be mined", () =>155
{156
const harness = makeSimulation({ workerCount: 1 });157
try158
{159
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });160
const playerId = harness.simulation.spawnCharacter(1, character);161
const record = harness.simulation.entityRecord(playerId);162
const worker = harness.simulation.workers[record.workerId];163
equipPickaxe(worker, playerId, ItemId.bronzePickaxe);164
placeOre(worker, 9, 8, EXHAUSTED_ORE_BOULDER_STATE);165
166
harness.simulation.enqueue(1, {167
type: "mine",168
characterId: character.character_id,169
tileX: 9,170
tileY: 8171
});172
const result = harness.simulation.step();173
assert.ok(result.events.some((event) =>174
event.type === "command-error"175
&& (/no ore|exhausted/i.test(event.message ?? ""))));176
}177
finally178
{ harness.close(); }179
});180
181
test("weak pickaxe cannot mine higher-tier ore", () =>182
{183
const harness = makeSimulation({ workerCount: 1 });184
try185
{186
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });187
const playerId = harness.simulation.spawnCharacter(1, character);188
const record = harness.simulation.entityRecord(playerId);189
const worker = harness.simulation.workers[record.workerId];190
equipPickaxe(worker, playerId, ItemId.bronzePickaxe);191
setSkillLevel(worker, playerId, SkillId.mining, 10);192
placeOre(worker, 9, 8, "iron-ore");193
194
harness.simulation.enqueue(1, {195
type: "mine",196
characterId: character.character_id,197
tileX: 9,198
tileY: 8199
});200
const result = harness.simulation.step();201
assert.ok(result.events.some((event) =>202
event.type === "command-error" && /too weak|pickaxe/i.test(event.message ?? "")));203
}204
finally205
{ harness.close(); }206
});207
208
test("mining grants ore and Mining XP then exhausts and respawns the node", () =>209
{210
const harness = makeSimulation({ workerCount: 1 });211
try212
{213
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });214
const playerId = harness.simulation.spawnCharacter(1, character);215
const record = harness.simulation.entityRecord(playerId);216
const worker = harness.simulation.workers[record.workerId];217
equipPickaxe(worker, playerId, ItemId.bronzePickaxe);218
const { data, index } = placeOre(worker, 9, 8, "bronze-ore");219
220
harness.simulation.enqueue(1, {221
type: "mine",222
characterId: character.character_id,223
tileX: 9,224
tileY: 8225
});226
const start = harness.simulation.step();227
assert.ok(start.events.some((event) => event.type === "gather-swing" || event.type === "tile-shove"));228
229
advanceMs(harness, miningDurationMs(MaterialTier.bronze, MaterialTier.bronze));230
231
const bag = harness.simulation.bagOf(playerId);232
assert.ok(countItem(bag.inventory, ItemId.bronzeOre) >= 1);233
const skills = harness.stateDb.getSkills(character.character_id);234
assert.ok(skills.xp.mining > 0);235
assert.equal(oreItemIdForMaterial(MaterialTier.bronze), ItemId.bronzeOre);236
assert.equal(data.blocks[index].state, EXHAUSTED_ORE_BOULDER_STATE);237
238
harness.simulation.enqueue(1, {239
type: "mine",240
characterId: character.character_id,241
tileX: 9,242
tileY: 8243
});244
const exhaustedResult = harness.simulation.step();245
assert.ok(exhaustedResult.events.some((event) =>246
event.type === "command-error" && /exhausted/i.test(event.message ?? "")));247
248
advanceMs(harness, oreExhaustDurationMs(MaterialTier.bronze));249
assert.equal(data.blocks[index].state, "bronze-ore");250
}251
finally252
{ harness.close(); }253
});254
255
test("coal mining yields coal and exhausts the node", () =>256
{257
const harness = makeSimulation({ workerCount: 1 });258
try259
{260
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });261
const playerId = harness.simulation.spawnCharacter(1, character);262
const record = harness.simulation.entityRecord(playerId);263
const worker = harness.simulation.workers[record.workerId];264
setSkillLevel(worker, playerId, SkillId.mining, 10);265
equipPickaxe(worker, playerId, ItemId.ironPickaxe);266
const { data, index } = placeOre(worker, 9, 8, "coal");267
268
harness.simulation.enqueue(1, {269
type: "mine",270
characterId: character.character_id,271
tileX: 9,272
tileY: 8273
});274
harness.simulation.step();275
advanceMs(harness, miningDurationMs(GatherMaterialId.coal, MaterialTier.iron));276
277
const bag = harness.simulation.bagOf(playerId);278
assert.ok(countItem(bag.inventory, ItemId.coal) >= 1);279
assert.equal(data.blocks[index].state, EXHAUSTED_ORE_BOULDER_STATE);280
}281
finally282
{ harness.close(); }283
});@@ -28,8 +28,9 @@ test("enforceMinimumSkillLevels raises Health to 10 and leaves higher XP alone",
28
28
assert.equal(enforceMinimumSkillLevels(low), true);
29
29
assert.equal(skillLevel(low, SkillId.health), 10);
30
30
assert.equal(skillLevel(low, SkillId.strength), 1);
31
assert.equal(skillLevel(low, SkillId.stamina), 5);
31
32
32
const high = { xp: { health: totalXpForLevel(12), strength: totalXpForLevel(5) } };
33
const high = { xp: { health: totalXpForLevel(12), strength: totalXpForLevel(5), stamina: totalXpForLevel(5) } };
33
34
assert.equal(enforceMinimumSkillLevels(high), false);
34
35
assert.equal(skillLevel(high, SkillId.health), 12);
35
36
assert.equal(skillLevel(high, SkillId.strength), 5);
@@ -49,6 +50,7 @@ test("login floors under-minimum skills and persists them", () =>
49
50
assert.equal(skillLevel(stored, SkillId.health), 10);
50
51
assert.equal(skillLevel(stored, SkillId.strength), 1);
51
52
assert.equal(skillLevel(stored, SkillId.defence), 1);
53
assert.equal(skillLevel(stored, SkillId.stamina), 5);
52
54
}
53
55
finally
54
56
{ harness.close(); }
@@ -28,8 +28,9 @@ test("enforceMinimumSkillLevels raises Health to 10 and leaves higher XP alone",28
assert.equal(enforceMinimumSkillLevels(low), true);28
assert.equal(enforceMinimumSkillLevels(low), true);29
assert.equal(skillLevel(low, SkillId.health), 10);29
assert.equal(skillLevel(low, SkillId.health), 10);30
assert.equal(skillLevel(low, SkillId.strength), 1);30
assert.equal(skillLevel(low, SkillId.strength), 1);31
assert.equal(skillLevel(low, SkillId.stamina), 5);31
32
32
const high = { xp: { health: totalXpForLevel(12), strength: totalXpForLevel(5) } };33
const high = { xp: { health: totalXpForLevel(12), strength: totalXpForLevel(5), stamina: totalXpForLevel(5) } };33
assert.equal(enforceMinimumSkillLevels(high), false);34
assert.equal(enforceMinimumSkillLevels(high), false);34
assert.equal(skillLevel(high, SkillId.health), 12);35
assert.equal(skillLevel(high, SkillId.health), 12);35
assert.equal(skillLevel(high, SkillId.strength), 5);36
assert.equal(skillLevel(high, SkillId.strength), 5);@@ -49,6 +50,7 @@ test("login floors under-minimum skills and persists them", () =>49
assert.equal(skillLevel(stored, SkillId.health), 10);50
assert.equal(skillLevel(stored, SkillId.health), 10);50
assert.equal(skillLevel(stored, SkillId.strength), 1);51
assert.equal(skillLevel(stored, SkillId.strength), 1);51
assert.equal(skillLevel(stored, SkillId.defence), 1);52
assert.equal(skillLevel(stored, SkillId.defence), 1);53
assert.equal(skillLevel(stored, SkillId.stamina), 5);52
}54
}53
finally55
finally54
{ harness.close(); }56
{ harness.close(); }@@ -0,0 +1,164 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { GAIT } from "../../shared/protocol/constants.js";
4
import { SkillId, skillLevel } from "../../shared/definitions/skills.js";
5
import { totalXpForLevel } from "../../shared/skills/progression.js";
6
import {
7
staminaCostPerRunStep,
8
STAMINA_REGEN_PER_SECOND
9
} from "../../shared/stamina/rules.js";
10
import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
11
12
function workerOf (simulation, entityId)
13
{
14
const record = simulation.entityRecord(entityId);
15
assert.ok(record);
16
return simulation.workers[record.workerId];
17
}
18
19
function componentsOf (simulation, entityId)
20
{
21
const worker = workerOf(simulation, entityId);
22
const handle = worker.world.ecs.handleOf(entityId);
23
assert.ok(handle != null);
24
return worker.world.ecs.componentsOf(handle);
25
}
26
27
function setStaminaXp (harness, characterId, level)
28
{
29
const skills = harness.stateDb.getSkills(characterId);
30
skills.xp.stamina = totalXpForLevel(level);
31
harness.stateDb.saveSkills(characterId, skills);
32
}
33
34
test("staminaCostPerRunStep drains one point per second of continuous running", () =>
35
{
36
assert.equal(staminaCostPerRunStep(2), 0.25);
37
assert.equal(staminaCostPerRunStep(1), 0.5);
38
});
39
40
test("set-gait to run is rejected when stamina is empty", () =>
41
{
42
const harness = makeSimulation({ workerCount: 1 });
43
try
44
{
45
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
46
const playerId = harness.simulation.spawnCharacter(1, character);
47
const comps = componentsOf(harness.simulation, playerId);
48
comps.stamina.current = 0;
49
50
harness.simulation.enqueue(1, {
51
type: "set-gait",
52
characterId: character.character_id,
53
gait: GAIT.run
54
});
55
const result = harness.simulation.step();
56
assert.ok(result.events.some((event) =>
57
event.type === "command-error" && /exhausted/i.test(event.message)
58
));
59
assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);
60
}
61
finally
62
{ harness.close(); }
63
});
64
65
test("running drains stamina, awards XP, and forces walk at zero", () =>
66
{
67
const harness = makeSimulation({ workerCount: 1 });
68
try
69
{
70
const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
71
setStaminaXp(harness, character.character_id, 6);
72
const playerId = harness.simulation.spawnCharacter(1, character);
73
assert.equal(harness.simulation.staminaOf(playerId).max, 6);
74
// Drain a short bar so the test finishes quickly.
75
componentsOf(harness.simulation, playerId).stamina.current = 2;
76
77
harness.simulation.enqueue(1, {
78
type: "set-gait",
79
characterId: character.character_id,
80
gait: GAIT.run
81
});
82
harness.simulation.enqueue(1, {
83
type: "move-to",
84
characterId: character.character_id,
85
tileX: 30,
86
tileY: 8
87
});
88
89
const xpBefore = harness.stateDb.getSkills(character.character_id).xp.stamina;
90
let forcedWalk = false;
91
for (let i = 0; i < 120; i++)
92
{
93
harness.advance(50);
94
const events = harness.simulation.step().events;
95
const stamina = harness.simulation.staminaOf(playerId);
96
if (events.some((event) => event.type === "stamina" && event.gait === GAIT.walk && event.current <= 0))
97
{ forcedWalk = true; }
98
if (stamina.current <= 0)
99
{
100
assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);
101
forcedWalk = true;
102
break;
103
}
104
}
105
assert.equal(forcedWalk, true);
106
assert.ok(harness.simulation.staminaOf(playerId).current <= 0);
107
assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);
108
109
const xpAfter = harness.stateDb.getSkills(character.character_id).xp.stamina;
110
assert.ok(xpAfter > xpBefore, "running should award Stamina XP");
111
assert.equal(skillLevel({ xp: { stamina: xpAfter } }, SkillId.stamina) >= 6, true);
112
}
113
finally
114
{ harness.close(); }
115
});
116
117
test("walking regenerates stamina over time", () =>
118
{
119
const harness = makeSimulation({ workerCount: 1 });
120
try
121
{
122
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
123
setStaminaXp(harness, character.character_id, 3);
124
const playerId = harness.simulation.spawnCharacter(1, character);
125
const comps = componentsOf(harness.simulation, playerId);
126
comps.stamina.current = 0;
127
comps.movement.gait = GAIT.walk;
128
129
const seconds = 2.2;
130
const ticks = Math.ceil(seconds * 20);
131
for (let i = 0; i < ticks; i++)
132
{
133
harness.advance(50);
134
harness.simulation.step();
135
}
136
const stamina = harness.simulation.staminaOf(playerId);
137
assert.ok(
138
stamina.current >= seconds * STAMINA_REGEN_PER_SECOND - 0.2,
139
`expected ~${seconds} regen, got ${stamina.current}`
140
);
141
assert.ok(stamina.current <= 3);
142
}
143
finally
144
{ harness.close(); }
145
});
146
147
test("running does not regenerate stamina", () =>
148
{
149
const harness = makeSimulation({ workerCount: 1 });
150
try
151
{
152
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
153
setStaminaXp(harness, character.character_id, 5);
154
const playerId = harness.simulation.spawnCharacter(1, character);
155
const comps = componentsOf(harness.simulation, playerId);
156
comps.stamina.current = 2;
157
comps.movement.gait = GAIT.run;
158
159
stepTimes(harness.simulation, 40);
160
assert.ok(harness.simulation.staminaOf(playerId).current <= 2.01);
161
}
162
finally
163
{ harness.close(); }
164
});
@@ -0,0 +1,164 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { GAIT } from "../../shared/protocol/constants.js";4
import { SkillId, skillLevel } from "../../shared/definitions/skills.js";5
import { totalXpForLevel } from "../../shared/skills/progression.js";6
import {7
staminaCostPerRunStep,8
STAMINA_REGEN_PER_SECOND9
} from "../../shared/stamina/rules.js";10
import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";11
12
function workerOf (simulation, entityId)13
{14
const record = simulation.entityRecord(entityId);15
assert.ok(record);16
return simulation.workers[record.workerId];17
}18
19
function componentsOf (simulation, entityId)20
{21
const worker = workerOf(simulation, entityId);22
const handle = worker.world.ecs.handleOf(entityId);23
assert.ok(handle != null);24
return worker.world.ecs.componentsOf(handle);25
}26
27
function setStaminaXp (harness, characterId, level)28
{29
const skills = harness.stateDb.getSkills(characterId);30
skills.xp.stamina = totalXpForLevel(level);31
harness.stateDb.saveSkills(characterId, skills);32
}33
34
test("staminaCostPerRunStep drains one point per second of continuous running", () =>35
{36
assert.equal(staminaCostPerRunStep(2), 0.25);37
assert.equal(staminaCostPerRunStep(1), 0.5);38
});39
40
test("set-gait to run is rejected when stamina is empty", () =>41
{42
const harness = makeSimulation({ workerCount: 1 });43
try44
{45
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });46
const playerId = harness.simulation.spawnCharacter(1, character);47
const comps = componentsOf(harness.simulation, playerId);48
comps.stamina.current = 0;49
50
harness.simulation.enqueue(1, {51
type: "set-gait",52
characterId: character.character_id,53
gait: GAIT.run54
});55
const result = harness.simulation.step();56
assert.ok(result.events.some((event) =>57
event.type === "command-error" && /exhausted/i.test(event.message)58
));59
assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);60
}61
finally62
{ harness.close(); }63
});64
65
test("running drains stamina, awards XP, and forces walk at zero", () =>66
{67
const harness = makeSimulation({ workerCount: 1 });68
try69
{70
const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });71
setStaminaXp(harness, character.character_id, 6);72
const playerId = harness.simulation.spawnCharacter(1, character);73
assert.equal(harness.simulation.staminaOf(playerId).max, 6);74
// Drain a short bar so the test finishes quickly.75
componentsOf(harness.simulation, playerId).stamina.current = 2;76
77
harness.simulation.enqueue(1, {78
type: "set-gait",79
characterId: character.character_id,80
gait: GAIT.run81
});82
harness.simulation.enqueue(1, {83
type: "move-to",84
characterId: character.character_id,85
tileX: 30,86
tileY: 887
});88
89
const xpBefore = harness.stateDb.getSkills(character.character_id).xp.stamina;90
let forcedWalk = false;91
for (let i = 0; i < 120; i++)92
{93
harness.advance(50);94
const events = harness.simulation.step().events;95
const stamina = harness.simulation.staminaOf(playerId);96
if (events.some((event) => event.type === "stamina" && event.gait === GAIT.walk && event.current <= 0))97
{ forcedWalk = true; }98
if (stamina.current <= 0)99
{100
assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);101
forcedWalk = true;102
break;103
}104
}105
assert.equal(forcedWalk, true);106
assert.ok(harness.simulation.staminaOf(playerId).current <= 0);107
assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);108
109
const xpAfter = harness.stateDb.getSkills(character.character_id).xp.stamina;110
assert.ok(xpAfter > xpBefore, "running should award Stamina XP");111
assert.equal(skillLevel({ xp: { stamina: xpAfter } }, SkillId.stamina) >= 6, true);112
}113
finally114
{ harness.close(); }115
});116
117
test("walking regenerates stamina over time", () =>118
{119
const harness = makeSimulation({ workerCount: 1 });120
try121
{122
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });123
setStaminaXp(harness, character.character_id, 3);124
const playerId = harness.simulation.spawnCharacter(1, character);125
const comps = componentsOf(harness.simulation, playerId);126
comps.stamina.current = 0;127
comps.movement.gait = GAIT.walk;128
129
const seconds = 2.2;130
const ticks = Math.ceil(seconds * 20);131
for (let i = 0; i < ticks; i++)132
{133
harness.advance(50);134
harness.simulation.step();135
}136
const stamina = harness.simulation.staminaOf(playerId);137
assert.ok(138
stamina.current >= seconds * STAMINA_REGEN_PER_SECOND - 0.2,139
`expected ~${seconds} regen, got ${stamina.current}`140
);141
assert.ok(stamina.current <= 3);142
}143
finally144
{ harness.close(); }145
});146
147
test("running does not regenerate stamina", () =>148
{149
const harness = makeSimulation({ workerCount: 1 });150
try151
{152
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });153
setStaminaXp(harness, character.character_id, 5);154
const playerId = harness.simulation.spawnCharacter(1, character);155
const comps = componentsOf(harness.simulation, playerId);156
comps.stamina.current = 2;157
comps.movement.gait = GAIT.run;158
159
stepTimes(harness.simulation, 40);160
assert.ok(harness.simulation.staminaOf(playerId).current <= 2.01);161
}162
finally163
{ harness.close(); }164
});