BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

service.js 16.0 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType, woodTierForTreeBlock, isChopableTreeBlock } 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 resolveWoodcuttingAxe,
15 woodcuttingDurationMs,
16 woodcuttingXpForWood,
17 treeExhaustDurationMs,
18 logItemIdForWoodTier
19} from "../../../shared/definitions/gathering.js";
20import { insertStack } from "../../../shared/items/inventory.js";
21import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
22import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
23import { seasonIdAt, treeStumpStateForSeason, SeasonId } from "../../../shared/world/season.js";
24import { bagView } from "../items/bags.js";
25import { chebyshev, clearEngage } from "../combat/service.js";
26import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
27import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
28
29const GATHER_SWING_INTERVAL_MS = 900;
30
31function userError (message)
32{
33 const error = new Error(message);
34 error.userFacing = true;
35 return error;
36}
37
38function characterDisplayName (world, handle)
39{
40 const appearance = world.ecs.get(handle, Component.appearance);
41 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
42 return name || "someone";
43}
44
45function ensureOreRespawns (world)
46{
47 if (!world.oreRespawns)
48 { world.oreRespawns = new Map(); }
49 return world.oreRespawns;
50}
51
52function ensureTreeRespawns (world)
53{
54 if (!world.treeRespawns)
55 { world.treeRespawns = new Map(); }
56 return world.treeRespawns;
57}
58
59function blockAt (world, tileX, tileY)
60{
61 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
62 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
63}
64
65function setBlockState (world, tileX, tileY, typeId, state)
66{
67 const chunkX = tileToChunk(tileX);
68 const chunkY = tileToChunk(tileY);
69 const localX = tileToLocal(tileX);
70 const localY = tileToLocal(tileY);
71 const data = world.chunkData(chunkX, chunkY);
72 const index = localY * CHUNK_SIZE + localX;
73 const prev = data?.blocks?.[index];
74 if (!prev || prev.typeId !== typeId)
75 { return null; }
76 const block = { typeId: prev.typeId, state, config: prev.config ?? null };
77 data.blocks[index] = block;
78 return {
79 type: "chunk-delta",
80 chunkX,
81 chunkY,
82 tileX,
83 tileY,
84 localX,
85 localY,
86 block
87 };
88}
89
90function setBoulderState (world, tileX, tileY, state)
91{
92 return setBlockState(world, tileX, tileY, BlockType.boulder, state);
93}
94
95function setTreeState (world, tileX, tileY, typeId, state)
96{
97 return setBlockState(world, tileX, tileY, typeId, state);
98}
99
100function pickaxeForOre (world, handle, materialId)
101{
102 const inventory = world.ecs.get(handle, Component.inventory);
103 const equipment = world.ecs.get(handle, Component.equipment);
104 const skills = world.ecs.get(handle, Component.skills);
105 return resolveMiningPickaxe({
106 inventorySlots: inventory?.slots,
107 equipmentSlots: equipment?.slots,
108 skills,
109 materialId
110 });
111}
112
113function axeForWood (world, handle, woodTier)
114{
115 const inventory = world.ecs.get(handle, Component.inventory);
116 const equipment = world.ecs.get(handle, Component.equipment);
117 const skills = world.ecs.get(handle, Component.skills);
118 return resolveWoodcuttingAxe({
119 inventorySlots: inventory?.slots,
120 equipmentSlots: equipment?.slots,
121 skills,
122 woodTier
123 });
124}
125
126function clearGather (ecs, handle)
127{
128 if (ecs.has(handle, Component.gather))
129 { ecs.remove(handle, Component.gather); }
130}
131
132export function cancelGather (ecs, handle)
133{
134 clearGather(ecs, handle);
135}
136
137/** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
138export function clearOreRespawnsForChunk (world, chunkX, chunkY)
139{
140 const respawns = world.oreRespawns;
141 if (!respawns?.size)
142 { return; }
143 for (const key of [...respawns.keys()])
144 {
145 const [tileX, tileY] = key.split(",").map(Number);
146 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
147 { respawns.delete(key); }
148 }
149}
150
151/** Drop scheduled tree respawns when authored chunk data is replaced or unloaded. */
152export function clearTreeRespawnsForChunk (world, chunkX, chunkY)
153{
154 const respawns = world.treeRespawns;
155 if (!respawns?.size)
156 { return; }
157 for (const key of [...respawns.keys()])
158 {
159 const [tileX, tileY] = key.split(",").map(Number);
160 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
161 { respawns.delete(key); }
162 }
163}
164
165/**
166 * Restore exhausted ore boulders whose timers have elapsed.
167 */
168export function stepOreRespawns (world, now)
169{
170 const respawns = world.oreRespawns;
171 if (!respawns?.size)
172 { return { events: [] }; }
173 const events = [];
174 for (const [key, entry] of [...respawns.entries()])
175 {
176 if (now < entry.respawnsAt)
177 { continue; }
178 respawns.delete(key);
179 const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId));
180 if (delta)
181 { events.push(delta); }
182 }
183 return { events };
184}
185
186/**
187 * Restore exhausted trees whose timers have elapsed (live seasonal look).
188 */
189export function stepTreeRespawns (world, now)
190{
191 const respawns = world.treeRespawns;
192 if (!respawns?.size)
193 { return { events: [] }; }
194 const events = [];
195 for (const [key, entry] of [...respawns.entries()])
196 {
197 if (now < entry.respawnsAt)
198 { continue; }
199 respawns.delete(key);
200 const delta = setTreeState(
201 world,
202 entry.tileX,
203 entry.tileY,
204 entry.typeId,
205 SeasonId.summer
206 );
207 if (delta)
208 { events.push(delta); }
209 }
210 return { events };
211}
212
213function beginGatherSwing (world, handle, entityId, position, gatherFields, now)
214{
215 clearEngage(world.ecs, entityId);
216 const path = world.ecs.get(handle, Component.path);
217 if (path)
218 { path.tiles = []; }
219 world.ecs.add(handle, Component.gather, {
220 ...gatherFields,
221 startedAt: now,
222 finishesAt: now + gatherFields.durationMs,
223 nextSwingAt: now
224 });
225 return {
226 events: [{
227 type: "gather-swing",
228 attackerId: entityId,
229 tileX: gatherFields.tileX,
230 tileY: gatherFields.tileY,
231 fromTileX: position.tileX,
232 fromTileY: position.tileY,
233 toolItemId: gatherFields.toolItemId ?? null,
234 swipe: false
235 }]
236 };
237}
238
239/**
240 * Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.
241 */
242export function startMine (world, sessionId, characterId, tileX, tileY, now)
243{
244 const entityId = world.characterEntities.get(characterId);
245 if (entityId == null)
246 { throw userError("Character is not in the world."); }
247 const handle = world.ecs.handleOf(entityId);
248 const identity = world.ecs.get(handle, Component.networkIdentity);
249 if (!identity || identity.sessionId !== sessionId)
250 { throw userError("Character is not in the world."); }
251 if (world.ecs.has(handle, Component.dead))
252 { throw userError("You are dead."); }
253
254 const position = world.ecs.get(handle, Component.position);
255 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
256 { throw userError("You need to stand next to the rock."); }
257
258 const block = blockAt(world, tileX, tileY);
259 if (!block || block.typeId !== BlockType.boulder)
260 { throw userError("There is nothing to mine there."); }
261 const materialId = materialFromOreBoulderState(block.state);
262 if (!materialId)
263 {
264 throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE
265 ? "That rock is exhausted."
266 : "That rock has no ore.");
267 }
268
269 const pickaxe = pickaxeForOre(world, handle, materialId);
270 if (!pickaxe.ok)
271 { throw userError(pickaxe.reason); }
272
273 const durationMs = miningDurationMs(materialId, pickaxe.tool.tier);
274 const toolItemId = pickaxe.tool.stack?.itemId ?? null;
275 return beginGatherSwing(world, handle, entityId, position, {
276 kind: "mining",
277 tileX,
278 tileY,
279 materialId,
280 toolTier: pickaxe.tool.tier,
281 toolItemId,
282 durationMs
283 }, now);
284}
285
286/**
287 * Start chopping a tree. Completes via stepGather (stump + log + woodcutting XP).
288 */
289export function startChop (world, sessionId, characterId, tileX, tileY, now)
290{
291 const entityId = world.characterEntities.get(characterId);
292 if (entityId == null)
293 { throw userError("Character is not in the world."); }
294 const handle = world.ecs.handleOf(entityId);
295 const identity = world.ecs.get(handle, Component.networkIdentity);
296 if (!identity || identity.sessionId !== sessionId)
297 { throw userError("Character is not in the world."); }
298 if (world.ecs.has(handle, Component.dead))
299 { throw userError("You are dead."); }
300
301 const position = world.ecs.get(handle, Component.position);
302 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
303 { throw userError("You need to stand next to the tree."); }
304
305 const block = blockAt(world, tileX, tileY);
306 if (!isChopableTreeBlock(block))
307 {
308 throw userError(block && woodTierForTreeBlock(block.typeId) != null
309 ? "That tree is already felled."
310 : "There is nothing to chop there.");
311 }
312 const woodTier = woodTierForTreeBlock(block.typeId);
313 const axe = axeForWood(world, handle, woodTier);
314 if (!axe.ok)
315 { throw userError(axe.reason); }
316
317 const durationMs = woodcuttingDurationMs(woodTier, axe.tool.tier);
318 const toolItemId = axe.tool.stack?.itemId ?? null;
319 return beginGatherSwing(world, handle, entityId, position, {
320 kind: "woodcutting",
321 tileX,
322 tileY,
323 typeId: block.typeId,
324 woodTier,
325 toolTier: axe.tool.tier,
326 toolItemId,
327 durationMs
328 }, now);
329}
330
331function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])
332{
333 privates.push({
334 characterId: character.characterId,
335 bag: bagView(world.ecs, handle)
336 });
337 if (skillsChanged)
338 {
339 events.push({
340 type: "skills-updated",
341 entityId,
342 characterId: character.characterId,
343 skills: publicSkillsView(skills),
344 stored: storedSkillXp(skills),
345 levelUps
346 });
347 }
348}
349
350function completeMining (world, handle, entityId, character, gather, events, privates, now)
351{
352 const oreItemId = oreItemIdForMaterial(gather.materialId);
353 const def = itemDefinition(oreItemId);
354 const inventory = world.ecs.get(handle, Component.inventory);
355 if (!oreItemId || !def || !inventory)
356 {
357 clearGather(world.ecs, handle);
358 return;
359 }
360 const origin = gatherOrigin(GatherOriginVerb.mined, characterDisplayName(world, handle));
361 const stack = attachOrigins({
362 itemId: oreItemId,
363 quantity: 1,
364 origins: [{ origin, quantity: 1 }]
365 });
366 const inserted = insertStack(inventory.slots, stack, def);
367 if (!inserted.ok || inserted.remainder > 0)
368 {
369 clearGather(world.ecs, handle);
370 events.push({
371 type: "command-error",
372 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
373 message: "Your inventory is full."
374 });
375 return;
376 }
377 inventory.slots = inserted.slots;
378
379 const skills = world.ecs.get(handle, Component.skills);
380 let skillsChanged = false;
381 const levelUps = [];
382 if (skills?.xp)
383 {
384 const result = applySkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId));
385 if (result.changed)
386 { skillsChanged = true; }
387 if (result.levelUp)
388 { levelUps.push(result.levelUp); }
389 }
390
391 const exhausted = setBoulderState(
392 world,
393 gather.tileX,
394 gather.tileY,
395 EXHAUSTED_ORE_BOULDER_STATE
396 );
397 if (exhausted)
398 {
399 events.push(exhausted);
400 ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
401 tileX: gather.tileX,
402 tileY: gather.tileY,
403 materialId: gather.materialId,
404 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
405 });
406 }
407
408 clearGather(world.ecs, handle);
409 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
410 events.push({
411 type: "gather-complete",
412 characterId: character.characterId,
413 kind: "mining",
414 materialId: gather.materialId,
415 itemId: oreItemId
416 });
417}
418
419function completeWoodcutting (world, handle, entityId, character, gather, events, privates, now)
420{
421 const logItemId = logItemIdForWoodTier(gather.woodTier);
422 const def = itemDefinition(logItemId);
423 const inventory = world.ecs.get(handle, Component.inventory);
424 if (!logItemId || !def || !inventory)
425 {
426 clearGather(world.ecs, handle);
427 return;
428 }
429 const origin = gatherOrigin(GatherOriginVerb.felled, characterDisplayName(world, handle));
430 const stack = attachOrigins({
431 itemId: logItemId,
432 quantity: 1,
433 origins: [{ origin, quantity: 1 }]
434 });
435 const inserted = insertStack(inventory.slots, stack, def);
436 if (!inserted.ok || inserted.remainder > 0)
437 {
438 clearGather(world.ecs, handle);
439 events.push({
440 type: "command-error",
441 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
442 message: "Your inventory is full."
443 });
444 return;
445 }
446 inventory.slots = inserted.slots;
447
448 const skills = world.ecs.get(handle, Component.skills);
449 let skillsChanged = false;
450 const levelUps = [];
451 if (skills?.xp)
452 {
453 const result = applySkillXp(skills, SkillId.woodcutting, woodcuttingXpForWood(gather.woodTier));
454 if (result.changed)
455 { skillsChanged = true; }
456 if (result.levelUp)
457 { levelUps.push(result.levelUp); }
458 }
459
460 const stumpState = treeStumpStateForSeason(seasonIdAt(now));
461 const exhausted = setTreeState(
462 world,
463 gather.tileX,
464 gather.tileY,
465 gather.typeId,
466 stumpState
467 );
468 if (exhausted)
469 {
470 events.push(exhausted);
471 ensureTreeRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
472 tileX: gather.tileX,
473 tileY: gather.tileY,
474 typeId: gather.typeId,
475 woodTier: gather.woodTier,
476 respawnsAt: now + treeExhaustDurationMs(gather.woodTier)
477 });
478 }
479
480 clearGather(world.ecs, handle);
481 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
482 events.push({
483 type: "gather-complete",
484 characterId: character.characterId,
485 kind: "woodcutting",
486 woodTier: gather.woodTier,
487 itemId: logItemId
488 });
489}
490
491export function stepGather (world, now)
492{
493 const events = [];
494 const privates = [];
495 events.push(...stepOreRespawns(world, now).events);
496 events.push(...stepTreeRespawns(world, now).events);
497
498 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
499 {
500 const { handle, gather, position, character, entityId } = entity;
501 if (world.ecs.has(handle, Component.dead))
502 {
503 clearGather(world.ecs, handle);
504 continue;
505 }
506 if (chebyshev(position.tileX, position.tileY, gather.tileX, gather.tileY) > 1)
507 {
508 clearGather(world.ecs, handle);
509 continue;
510 }
511 const block = blockAt(world, gather.tileX, gather.tileY);
512
513 if (gather.kind === "mining")
514 {
515 if (!block || block.typeId !== BlockType.boulder
516 || materialFromOreBoulderState(block.state) !== gather.materialId)
517 {
518 clearGather(world.ecs, handle);
519 continue;
520 }
521 }
522 else if (gather.kind === "woodcutting")
523 {
524 if (!block || block.typeId !== gather.typeId || !isChopableTreeBlock(block))
525 {
526 clearGather(world.ecs, handle);
527 continue;
528 }
529 }
530 else
531 {
532 clearGather(world.ecs, handle);
533 continue;
534 }
535
536 if (now >= gather.nextSwingAt && now < gather.finishesAt)
537 {
538 gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
539 events.push({
540 type: "gather-swing",
541 attackerId: entityId,
542 tileX: gather.tileX,
543 tileY: gather.tileY,
544 fromTileX: position.tileX,
545 fromTileY: position.tileY,
546 toolItemId: gather.toolItemId ?? null,
547 swipe: false
548 });
549 }
550
551 if (now < gather.finishesAt)
552 { continue; }
553
554 if (gather.kind === "mining")
555 { completeMining(world, handle, entityId, character, gather, events, privates, now); }
556 else
557 { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }
558 }
559 return { events, privates };
560}
561
562export function handleGatherCommand (world, sessionId, command, now)
563{
564 switch (command.type)
565 {
566 case "mine":
567 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
568 case "chop":
569 return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
570 case "cancel-gather":
571 {
572 const entityId = world.characterEntities.get(command.characterId);
573 if (entityId == null)
574 { return { events: [] }; }
575 const handle = world.ecs.handleOf(entityId);
576 clearGather(world.ecs, handle);
577 return { events: [] };
578 }
579 default:
580 return null;
581 }
582}