BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

service.js 8.8 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { itemDefinition } from "../../../shared/definitions/items.js";
4import { SkillId } from "../../../shared/definitions/skills.js";
5import {
6 materialFromOreBoulderState,
7 oreItemIdForMaterial,
8 miningDurationMs,
9 miningXpForMaterial,
10 oreExhaustDurationMs,
11 oreBoulderState,
12 EXHAUSTED_ORE_BOULDER_STATE,
13 resolveMiningPickaxe
14} from "../../../shared/definitions/gathering.js";
15import { insertStack } from "../../../shared/items/inventory.js";
16import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
17import { bagView } from "../items/bags.js";
18import { chebyshev, clearEngage } from "../combat/service.js";
19import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
20import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
21
22const GATHER_SWING_INTERVAL_MS = 900;
23
24function userError (message)
25{
26 const error = new Error(message);
27 error.userFacing = true;
28 return error;
29}
30
31function ensureOreRespawns (world)
32{
33 if (!world.oreRespawns)
34 { world.oreRespawns = new Map(); }
35 return world.oreRespawns;
36}
37
38function blockAt (world, tileX, tileY)
39{
40 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
41 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
42}
43
44function setBoulderState (world, tileX, tileY, state)
45{
46 const chunkX = tileToChunk(tileX);
47 const chunkY = tileToChunk(tileY);
48 const localX = tileToLocal(tileX);
49 const localY = tileToLocal(tileY);
50 const data = world.chunkData(chunkX, chunkY);
51 const index = localY * CHUNK_SIZE + localX;
52 const prev = data?.blocks?.[index];
53 if (!prev || prev.typeId !== BlockType.boulder)
54 { return null; }
55 const block = { typeId: prev.typeId, state, config: prev.config ?? null };
56 data.blocks[index] = block;
57 return {
58 type: "chunk-delta",
59 chunkX,
60 chunkY,
61 tileX,
62 tileY,
63 localX,
64 localY,
65 block
66 };
67}
68
69function pickaxeForOre (world, handle, materialId)
70{
71 const inventory = world.ecs.get(handle, Component.inventory);
72 const equipment = world.ecs.get(handle, Component.equipment);
73 const skills = world.ecs.get(handle, Component.skills);
74 return resolveMiningPickaxe({
75 inventorySlots: inventory?.slots,
76 equipmentSlots: equipment?.slots,
77 skills,
78 materialId
79 });
80}
81
82function clearGather (ecs, handle)
83{
84 if (ecs.has(handle, Component.gather))
85 { ecs.remove(handle, Component.gather); }
86}
87
88export function cancelGather (ecs, handle)
89{
90 clearGather(ecs, handle);
91}
92
93/** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
94export 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 */
110export 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 */
131export 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 = pickaxeForOre(world, handle, materialId);
157 if (!pickaxe.ok)
158 { throw userError(pickaxe.reason); }
159
160 const durationMs = miningDurationMs(materialId, pickaxe.tool.tier);
161 clearEngage(world.ecs, entityId);
162 const path = world.ecs.get(handle, Component.path);
163 if (path)
164 { path.tiles = []; }
165 const toolItemId = pickaxe.tool.stack?.itemId ?? null;
166 world.ecs.add(handle, Component.gather, {
167 kind: "mining",
168 tileX,
169 tileY,
170 materialId,
171 toolTier: pickaxe.tool.tier,
172 toolItemId,
173 startedAt: now,
174 finishesAt: now + durationMs,
175 nextSwingAt: now
176 });
177
178 return {
179 events: [{
180 type: "gather-swing",
181 attackerId: entityId,
182 tileX,
183 tileY,
184 fromTileX: position.tileX,
185 fromTileY: position.tileY,
186 toolItemId,
187 swipe: false
188 }]
189 };
190}
191
192export function stepGather (world, now)
193{
194 const events = [];
195 const privates = [];
196 const respawnEvents = stepOreRespawns(world, now);
197 events.push(...respawnEvents.events);
198
199 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
200 {
201 const { handle, gather, position, character, entityId } = entity;
202 if (world.ecs.has(handle, Component.dead))
203 {
204 clearGather(world.ecs, handle);
205 continue;
206 }
207 if (chebyshev(position.tileX, position.tileY, gather.tileX, gather.tileY) > 1)
208 {
209 clearGather(world.ecs, handle);
210 continue;
211 }
212 const block = blockAt(world, gather.tileX, gather.tileY);
213 if (!block || block.typeId !== BlockType.boulder
214 || materialFromOreBoulderState(block.state) !== gather.materialId)
215 {
216 clearGather(world.ecs, handle);
217 continue;
218 }
219
220 if (now >= gather.nextSwingAt && now < gather.finishesAt)
221 {
222 gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
223 events.push({
224 type: "gather-swing",
225 attackerId: entityId,
226 tileX: gather.tileX,
227 tileY: gather.tileY,
228 fromTileX: position.tileX,
229 fromTileY: position.tileY,
230 toolItemId: gather.toolItemId ?? null,
231 swipe: false
232 });
233 }
234
235 if (now < gather.finishesAt)
236 { continue; }
237
238 const oreItemId = oreItemIdForMaterial(gather.materialId);
239 const def = itemDefinition(oreItemId);
240 const inventory = world.ecs.get(handle, Component.inventory);
241 if (!oreItemId || !def || !inventory)
242 {
243 clearGather(world.ecs, handle);
244 continue;
245 }
246 const inserted = insertStack(inventory.slots, { itemId: oreItemId, quantity: 1 }, def);
247 if (!inserted.ok || inserted.remainder > 0)
248 {
249 clearGather(world.ecs, handle);
250 events.push({
251 type: "command-error",
252 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
253 message: "Your inventory is full."
254 });
255 continue;
256 }
257 inventory.slots = inserted.slots;
258
259 const skills = world.ecs.get(handle, Component.skills);
260 let skillsChanged = false;
261 if (skills?.xp && addSkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)))
262 { skillsChanged = true; }
263
264 const exhausted = setBoulderState(
265 world,
266 gather.tileX,
267 gather.tileY,
268 EXHAUSTED_ORE_BOULDER_STATE
269 );
270 if (exhausted)
271 {
272 events.push(exhausted);
273 ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
274 tileX: gather.tileX,
275 tileY: gather.tileY,
276 materialId: gather.materialId,
277 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
278 });
279 }
280
281 clearGather(world.ecs, handle);
282 privates.push({
283 characterId: character.characterId,
284 bag: bagView(world.ecs, handle)
285 });
286 if (skillsChanged)
287 {
288 events.push({
289 type: "skills-updated",
290 characterId: character.characterId,
291 skills: publicSkillsView(skills),
292 stored: storedSkillXp(skills)
293 });
294 }
295 events.push({
296 type: "gather-complete",
297 characterId: character.characterId,
298 kind: "mining",
299 materialId: gather.materialId,
300 itemId: oreItemId
301 });
302 }
303 return { events, privates };
304}
305
306export function handleGatherCommand (world, sessionId, command, now)
307{
308 switch (command.type)
309 {
310 case "mine":
311 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
312 case "cancel-gather":
313 {
314 const entityId = world.characterEntities.get(command.characterId);
315 if (entityId == null)
316 { return { events: [] }; }
317 const handle = world.ecs.handleOf(entityId);
318 clearGather(world.ecs, handle);
319 return { events: [] };
320 }
321 default:
322 return null;
323 }
324}