BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

service.js 24.3 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType, woodTierForTreeBlock, isChopableTreeBlock, plantGatherForBlock } from "../../../shared/definitions/tiles.js";
3import { itemDefinition, ItemId } 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 resolvePlantClippers,
16 resolveHerbGather,
17 woodcuttingDurationMs,
18 woodcuttingXpForWood,
19 treeExhaustDurationMs,
20 logItemIdForWoodTier,
21 herbalismDurationMs,
22 herbalismXpForPick,
23 PLANT_EXHAUST_MS
24} from "../../../shared/definitions/gathering.js";
25import { rawClothItemId } from "../../../shared/definitions/clothItems.js";
26import { ClothTier } from "../../../shared/definitions/materialTiers.js";
27import {
28 flowerItemInstance,
29 flowerColorIdFromBlockState,
30 flowerBlockState,
31 flowerColorIdForTile,
32 randomFlowerColorId
33} from "../../../shared/definitions/dyes.js";
34import { herbDefinition, isHerbId } from "../../../shared/definitions/herbs.js";
35import { insertStack } from "../../../shared/items/inventory.js";
36import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
37import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
38import { seasonIdAt, treeStumpStateForSeason, SeasonId } from "../../../shared/world/season.js";
39import { bagView } from "../items/bags.js";
40import { chebyshev, clearEngage } from "../combat/service.js";
41import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
42import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
43
44const GATHER_SWING_INTERVAL_MS = 900;
45
46function userError (message)
47{
48 const error = new Error(message);
49 error.userFacing = true;
50 return error;
51}
52
53function characterDisplayName (world, handle)
54{
55 const appearance = world.ecs.get(handle, Component.appearance);
56 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
57 return name || "someone";
58}
59
60function ensureOreRespawns (world)
61{
62 if (!world.oreRespawns)
63 { world.oreRespawns = new Map(); }
64 return world.oreRespawns;
65}
66
67function ensureTreeRespawns (world)
68{
69 if (!world.treeRespawns)
70 { world.treeRespawns = new Map(); }
71 return world.treeRespawns;
72}
73
74function ensurePlantRespawns (world)
75{
76 if (!world.plantRespawns)
77 { world.plantRespawns = new Map(); }
78 return world.plantRespawns;
79}
80
81function blockAt (world, tileX, tileY)
82{
83 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
84 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
85}
86
87function setBlockState (world, tileX, tileY, typeId, state)
88{
89 const chunkX = tileToChunk(tileX);
90 const chunkY = tileToChunk(tileY);
91 const localX = tileToLocal(tileX);
92 const localY = tileToLocal(tileY);
93 const data = world.chunkData(chunkX, chunkY);
94 const index = localY * CHUNK_SIZE + localX;
95 const prev = data?.blocks?.[index];
96 if (!prev || prev.typeId !== typeId)
97 { return null; }
98 const block = { typeId: prev.typeId, state, config: prev.config ?? null };
99 data.blocks[index] = block;
100 return {
101 type: "chunk-delta",
102 chunkX,
103 chunkY,
104 tileX,
105 tileY,
106 localX,
107 localY,
108 block
109 };
110}
111
112function setBoulderState (world, tileX, tileY, state)
113{
114 return setBlockState(world, tileX, tileY, BlockType.boulder, state);
115}
116
117function setTreeState (world, tileX, tileY, typeId, state)
118{
119 return setBlockState(world, tileX, tileY, typeId, state);
120}
121
122function clearBlock (world, tileX, tileY, typeId)
123{
124 const chunkX = tileToChunk(tileX);
125 const chunkY = tileToChunk(tileY);
126 const localX = tileToLocal(tileX);
127 const localY = tileToLocal(tileY);
128 const data = world.chunkData(chunkX, chunkY);
129 const index = localY * CHUNK_SIZE + localX;
130 const prev = data?.blocks?.[index];
131 if (!prev || prev.typeId !== typeId)
132 { return null; }
133 data.blocks[index] = null;
134 return {
135 type: "chunk-delta",
136 chunkX,
137 chunkY,
138 tileX,
139 tileY,
140 localX,
141 localY,
142 block: null
143 };
144}
145
146function placeBlock (world, tileX, tileY, typeId, state)
147{
148 const chunkX = tileToChunk(tileX);
149 const chunkY = tileToChunk(tileY);
150 const localX = tileToLocal(tileX);
151 const localY = tileToLocal(tileY);
152 const data = world.chunkData(chunkX, chunkY);
153 const index = localY * CHUNK_SIZE + localX;
154 const block = { typeId, state, config: null };
155 data.blocks[index] = block;
156 return {
157 type: "chunk-delta",
158 chunkX,
159 chunkY,
160 tileX,
161 tileY,
162 localX,
163 localY,
164 block
165 };
166}
167
168function pickaxeForOre (world, handle, materialId)
169{
170 const inventory = world.ecs.get(handle, Component.inventory);
171 const equipment = world.ecs.get(handle, Component.equipment);
172 const skills = world.ecs.get(handle, Component.skills);
173 return resolveMiningPickaxe({
174 inventorySlots: inventory?.slots,
175 equipmentSlots: equipment?.slots,
176 skills,
177 materialId
178 });
179}
180
181function axeForWood (world, handle, woodTier)
182{
183 const inventory = world.ecs.get(handle, Component.inventory);
184 const equipment = world.ecs.get(handle, Component.equipment);
185 const skills = world.ecs.get(handle, Component.skills);
186 return resolveWoodcuttingAxe({
187 inventorySlots: inventory?.slots,
188 equipmentSlots: equipment?.slots,
189 skills,
190 woodTier
191 });
192}
193
194function clearGather (ecs, handle)
195{
196 if (ecs.has(handle, Component.gather))
197 { ecs.remove(handle, Component.gather); }
198}
199
200export function cancelGather (ecs, handle)
201{
202 clearGather(ecs, handle);
203}
204
205/** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
206export function clearOreRespawnsForChunk (world, chunkX, chunkY)
207{
208 const respawns = world.oreRespawns;
209 if (!respawns?.size)
210 { return; }
211 for (const key of [...respawns.keys()])
212 {
213 const [tileX, tileY] = key.split(",").map(Number);
214 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
215 { respawns.delete(key); }
216 }
217}
218
219/** Drop scheduled tree respawns when authored chunk data is replaced or unloaded. */
220export function clearTreeRespawnsForChunk (world, chunkX, chunkY)
221{
222 const respawns = world.treeRespawns;
223 if (!respawns?.size)
224 { return; }
225 for (const key of [...respawns.keys()])
226 {
227 const [tileX, tileY] = key.split(",").map(Number);
228 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
229 { respawns.delete(key); }
230 }
231}
232
233export function clearPlantRespawnsForChunk (world, chunkX, chunkY)
234{
235 const respawns = world.plantRespawns;
236 if (!respawns?.size)
237 { return; }
238 for (const key of [...respawns.keys()])
239 {
240 const [tileX, tileY] = key.split(",").map(Number);
241 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
242 { respawns.delete(key); }
243 }
244}
245
246/**
247 * Restore exhausted ore boulders whose timers have elapsed.
248 */
249export function stepOreRespawns (world, now)
250{
251 const respawns = world.oreRespawns;
252 if (!respawns?.size)
253 { return { events: [] }; }
254 const events = [];
255 for (const [key, entry] of [...respawns.entries()])
256 {
257 if (now < entry.respawnsAt)
258 { continue; }
259 respawns.delete(key);
260 const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId));
261 if (delta)
262 { events.push(delta); }
263 }
264 return { events };
265}
266
267/**
268 * Restore exhausted trees whose timers have elapsed (live seasonal look).
269 */
270export function stepTreeRespawns (world, now)
271{
272 const respawns = world.treeRespawns;
273 if (!respawns?.size)
274 { return { events: [] }; }
275 const events = [];
276 for (const [key, entry] of [...respawns.entries()])
277 {
278 if (now < entry.respawnsAt)
279 { continue; }
280 respawns.delete(key);
281 const delta = setTreeState(
282 world,
283 entry.tileX,
284 entry.tileY,
285 entry.typeId,
286 SeasonId.summer
287 );
288 if (delta)
289 { events.push(delta); }
290 }
291 return { events };
292}
293
294export function stepPlantRespawns (world, now)
295{
296 const respawns = world.plantRespawns;
297 if (!respawns?.size)
298 { return { events: [] }; }
299 const events = [];
300 for (const [key, entry] of [...respawns.entries()])
301 {
302 if (now < entry.respawnsAt)
303 { continue; }
304 respawns.delete(key);
305 const existing = blockAt(world, entry.tileX, entry.tileY);
306 if (existing)
307 { continue; }
308 const state = entry.typeId === BlockType.flower
309 ? flowerBlockState(randomFlowerColorId())
310 : (entry.state ?? defaultPlantState(entry.typeId));
311 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state);
312 if (delta)
313 { events.push(delta); }
314 }
315 return { events };
316}
317
318function beginGatherSwing (world, handle, entityId, position, gatherFields, now)
319{
320 clearEngage(world.ecs, entityId);
321 const path = world.ecs.get(handle, Component.path);
322 if (path)
323 { path.tiles = []; }
324 world.ecs.add(handle, Component.gather, {
325 ...gatherFields,
326 startedAt: now,
327 finishesAt: now + gatherFields.durationMs,
328 nextSwingAt: now
329 });
330 return {
331 events: [{
332 type: "gather-swing",
333 attackerId: entityId,
334 tileX: gatherFields.tileX,
335 tileY: gatherFields.tileY,
336 fromTileX: position.tileX,
337 fromTileY: position.tileY,
338 toolItemId: gatherFields.toolItemId ?? null,
339 swipe: false
340 }]
341 };
342}
343
344/**
345 * Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.
346 */
347export function startMine (world, sessionId, characterId, tileX, tileY, now)
348{
349 const entityId = world.characterEntities.get(characterId);
350 if (entityId == null)
351 { throw userError("Character is not in the world."); }
352 const handle = world.ecs.handleOf(entityId);
353 const identity = world.ecs.get(handle, Component.networkIdentity);
354 if (!identity || identity.sessionId !== sessionId)
355 { throw userError("Character is not in the world."); }
356 if (world.ecs.has(handle, Component.dead))
357 { throw userError("You are dead."); }
358
359 const position = world.ecs.get(handle, Component.position);
360 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
361 { throw userError("You need to stand next to the rock."); }
362
363 const block = blockAt(world, tileX, tileY);
364 if (!block || block.typeId !== BlockType.boulder)
365 { throw userError("There is nothing to mine there."); }
366 const materialId = materialFromOreBoulderState(block.state);
367 if (!materialId)
368 {
369 throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE
370 ? "That rock is exhausted."
371 : "That rock has no ore.");
372 }
373
374 const pickaxe = pickaxeForOre(world, handle, materialId);
375 if (!pickaxe.ok)
376 { throw userError(pickaxe.reason); }
377
378 const durationMs = miningDurationMs(materialId, pickaxe.tool.tier);
379 const toolItemId = pickaxe.tool.stack?.itemId ?? null;
380 return beginGatherSwing(world, handle, entityId, position, {
381 kind: "mining",
382 tileX,
383 tileY,
384 materialId,
385 toolTier: pickaxe.tool.tier,
386 toolItemId,
387 durationMs
388 }, now);
389}
390
391/**
392 * Start chopping a tree. Completes via stepGather (stump + log + woodcutting XP).
393 */
394export function startChop (world, sessionId, characterId, tileX, tileY, now)
395{
396 const entityId = world.characterEntities.get(characterId);
397 if (entityId == null)
398 { throw userError("Character is not in the world."); }
399 const handle = world.ecs.handleOf(entityId);
400 const identity = world.ecs.get(handle, Component.networkIdentity);
401 if (!identity || identity.sessionId !== sessionId)
402 { throw userError("Character is not in the world."); }
403 if (world.ecs.has(handle, Component.dead))
404 { throw userError("You are dead."); }
405
406 const position = world.ecs.get(handle, Component.position);
407 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
408 { throw userError("You need to stand next to the tree."); }
409
410 const block = blockAt(world, tileX, tileY);
411 if (!isChopableTreeBlock(block))
412 {
413 throw userError(block && woodTierForTreeBlock(block.typeId) != null
414 ? "That tree is already felled."
415 : "There is nothing to chop there.");
416 }
417 const woodTier = woodTierForTreeBlock(block.typeId);
418 const axe = axeForWood(world, handle, woodTier);
419 if (!axe.ok)
420 { throw userError(axe.reason); }
421
422 const durationMs = woodcuttingDurationMs(woodTier, axe.tool.tier);
423 const toolItemId = axe.tool.stack?.itemId ?? null;
424 return beginGatherSwing(world, handle, entityId, position, {
425 kind: "woodcutting",
426 tileX,
427 tileY,
428 typeId: block.typeId,
429 woodTier,
430 toolTier: axe.tool.tier,
431 toolItemId,
432 durationMs
433 }, now);
434}
435
436/**
437 * Pick a plant node (flower / cotton; no tools required).
438 */
439export function startPick (world, sessionId, characterId, tileX, tileY, now)
440{
441 const entityId = world.characterEntities.get(characterId);
442 if (entityId == null)
443 { throw userError("Character is not in the world."); }
444 const handle = world.ecs.handleOf(entityId);
445 const identity = world.ecs.get(handle, Component.networkIdentity);
446 if (!identity || identity.sessionId !== sessionId)
447 { throw userError("Character is not in the world."); }
448 if (world.ecs.has(handle, Component.dead))
449 { throw userError("You are dead."); }
450
451 const position = world.ecs.get(handle, Component.position);
452 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
453 { throw userError("You need to stand next to the plant."); }
454
455 const block = blockAt(world, tileX, tileY);
456 const plant = plantGatherForBlock(block);
457 if (!plant)
458 { throw userError("There is nothing to pick there."); }
459
460 const inventory = world.ecs.get(handle, Component.inventory);
461 const equipment = world.ecs.get(handle, Component.equipment);
462 const skills = world.ecs.get(handle, Component.skills);
463 const clippers = resolvePlantClippers({
464 inventorySlots: inventory?.slots,
465 equipmentSlots: equipment?.slots,
466 skills,
467 requireTool: !!plant.requiresClippers
468 });
469 if (!clippers.ok)
470 { throw userError(clippers.reason); }
471
472 let herbId = null;
473 let herbTier = null;
474 if (plant.kind === "herb")
475 {
476 const gate = resolveHerbGather({ herbId: block.state, skills });
477 if (!gate.ok)
478 { throw userError(gate.reason); }
479 herbId = gate.herb.herbId;
480 herbTier = gate.herb.tier;
481 }
482
483 const toolTier = clippers.tool?.tier ?? null;
484 const durationMs = herbalismDurationMs(plant.kind, toolTier, herbTier);
485 const toolItemId = clippers.tool?.stack?.itemId ?? null;
486 const prefixEvents = [];
487 let flowerColorId = null;
488 if (plant.kind === "flower")
489 {
490 flowerColorId = flowerColorIdFromBlockState(block.state);
491 if (!flowerColorId)
492 {
493 // Legacy / uncoloured placements: lock a colour before the pick starts.
494 flowerColorId = flowerColorIdForTile(tileX, tileY);
495 const delta = setBlockState(
496 world,
497 tileX,
498 tileY,
499 BlockType.flower,
500 flowerBlockState(flowerColorId)
501 );
502 if (delta)
503 { prefixEvents.push(delta); }
504 }
505 }
506 const started = beginGatherSwing(world, handle, entityId, position, {
507 kind: "plant",
508 plantKind: plant.kind,
509 herbId,
510 herbTier,
511 tileX,
512 tileY,
513 typeId: block.typeId,
514 flowerColorId,
515 toolTier,
516 toolItemId,
517 durationMs
518 }, now);
519 return {
520 ...started,
521 events: [...prefixEvents, ...(started.events ?? [])]
522 };
523}
524
525function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])
526{
527 privates.push({
528 characterId: character.characterId,
529 bag: bagView(world.ecs, handle)
530 });
531 if (skillsChanged)
532 {
533 events.push({
534 type: "skills-updated",
535 entityId,
536 characterId: character.characterId,
537 skills: publicSkillsView(skills),
538 stored: storedSkillXp(skills),
539 levelUps
540 });
541 }
542}
543
544function completeMining (world, handle, entityId, character, gather, events, privates, now)
545{
546 const oreItemId = oreItemIdForMaterial(gather.materialId);
547 const def = itemDefinition(oreItemId);
548 const inventory = world.ecs.get(handle, Component.inventory);
549 if (!oreItemId || !def || !inventory)
550 {
551 clearGather(world.ecs, handle);
552 return;
553 }
554 const origin = gatherOrigin(GatherOriginVerb.mined, characterDisplayName(world, handle));
555 const stack = attachOrigins({
556 itemId: oreItemId,
557 quantity: 1,
558 origins: [{ origin, quantity: 1 }]
559 });
560 const inserted = insertStack(inventory.slots, stack, def);
561 if (!inserted.ok || inserted.remainder > 0)
562 {
563 clearGather(world.ecs, handle);
564 events.push({
565 type: "command-error",
566 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
567 message: "Your inventory is full."
568 });
569 return;
570 }
571 inventory.slots = inserted.slots;
572
573 const skills = world.ecs.get(handle, Component.skills);
574 let skillsChanged = false;
575 const levelUps = [];
576 if (skills?.xp)
577 {
578 const result = applySkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId));
579 if (result.changed)
580 { skillsChanged = true; }
581 if (result.levelUp)
582 { levelUps.push(result.levelUp); }
583 }
584
585 const exhausted = setBoulderState(
586 world,
587 gather.tileX,
588 gather.tileY,
589 EXHAUSTED_ORE_BOULDER_STATE
590 );
591 if (exhausted)
592 {
593 events.push(exhausted);
594 ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
595 tileX: gather.tileX,
596 tileY: gather.tileY,
597 materialId: gather.materialId,
598 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
599 });
600 }
601
602 clearGather(world.ecs, handle);
603 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
604 events.push({
605 type: "gather-complete",
606 characterId: character.characterId,
607 kind: "mining",
608 materialId: gather.materialId,
609 itemId: oreItemId
610 });
611}
612
613function completeWoodcutting (world, handle, entityId, character, gather, events, privates, now)
614{
615 const logItemId = logItemIdForWoodTier(gather.woodTier);
616 const def = itemDefinition(logItemId);
617 const inventory = world.ecs.get(handle, Component.inventory);
618 if (!logItemId || !def || !inventory)
619 {
620 clearGather(world.ecs, handle);
621 return;
622 }
623 const origin = gatherOrigin(GatherOriginVerb.felled, characterDisplayName(world, handle));
624 const stack = attachOrigins({
625 itemId: logItemId,
626 quantity: 1,
627 origins: [{ origin, quantity: 1 }]
628 });
629 const inserted = insertStack(inventory.slots, stack, def);
630 if (!inserted.ok || inserted.remainder > 0)
631 {
632 clearGather(world.ecs, handle);
633 events.push({
634 type: "command-error",
635 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
636 message: "Your inventory is full."
637 });
638 return;
639 }
640 inventory.slots = inserted.slots;
641
642 const skills = world.ecs.get(handle, Component.skills);
643 let skillsChanged = false;
644 const levelUps = [];
645 if (skills?.xp)
646 {
647 const result = applySkillXp(skills, SkillId.woodcutting, woodcuttingXpForWood(gather.woodTier));
648 if (result.changed)
649 { skillsChanged = true; }
650 if (result.levelUp)
651 { levelUps.push(result.levelUp); }
652 }
653
654 const stumpState = treeStumpStateForSeason(seasonIdAt(now));
655 const exhausted = setTreeState(
656 world,
657 gather.tileX,
658 gather.tileY,
659 gather.typeId,
660 stumpState
661 );
662 if (exhausted)
663 {
664 events.push(exhausted);
665 ensureTreeRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
666 tileX: gather.tileX,
667 tileY: gather.tileY,
668 typeId: gather.typeId,
669 woodTier: gather.woodTier,
670 respawnsAt: now + treeExhaustDurationMs(gather.woodTier)
671 });
672 }
673
674 clearGather(world.ecs, handle);
675 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
676 events.push({
677 type: "gather-complete",
678 characterId: character.characterId,
679 kind: "woodcutting",
680 woodTier: gather.woodTier,
681 itemId: logItemId
682 });
683}
684
685function completePlant (world, handle, entityId, character, gather, events, privates, now)
686{
687 const inventory = world.ecs.get(handle, Component.inventory);
688 if (!inventory)
689 {
690 clearGather(world.ecs, handle);
691 return;
692 }
693
694 let itemId = null;
695 let instance = null;
696 if (gather.plantKind === "flower")
697 {
698 itemId = ItemId.flower;
699 const live = blockAt(world, gather.tileX, gather.tileY);
700 const colorId = gather.flowerColorId
701 ?? flowerColorIdFromBlockState(live?.state)
702 ?? randomFlowerColorId();
703 instance = flowerItemInstance(colorId);
704 }
705 else if (gather.plantKind === "cotton")
706 {
707 itemId = rawClothItemId(ClothTier.cotton);
708 }
709 else if (gather.plantKind === "herb")
710 {
711 const herb = herbDefinition(gather.herbId);
712 itemId = herb?.itemId ?? null;
713 }
714 else
715 {
716 clearGather(world.ecs, handle);
717 return;
718 }
719
720 const def = itemDefinition(itemId);
721 if (!def)
722 {
723 clearGather(world.ecs, handle);
724 return;
725 }
726
727 const origin = gatherOrigin(GatherOriginVerb.picked, characterDisplayName(world, handle));
728 const stack = attachOrigins({
729 itemId,
730 quantity: 1,
731 instance,
732 origins: [{ origin, quantity: 1 }]
733 });
734 const inserted = insertStack(inventory.slots, stack, def);
735 if (!inserted.ok || inserted.remainder > 0)
736 {
737 clearGather(world.ecs, handle);
738 events.push({
739 type: "command-error",
740 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
741 message: "Your inventory is full."
742 });
743 return;
744 }
745 inventory.slots = inserted.slots;
746
747 const skills = world.ecs.get(handle, Component.skills);
748 let skillsChanged = false;
749 const levelUps = [];
750 if (skills?.xp)
751 {
752 const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind, gather.herbTier));
753 if (result.changed)
754 { skillsChanged = true; }
755 if (result.levelUp)
756 { levelUps.push(result.levelUp); }
757 }
758
759 const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId);
760 if (delta)
761 { events.push(delta); }
762 ensurePlantRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
763 tileX: gather.tileX,
764 tileY: gather.tileY,
765 typeId: gather.typeId,
766 // Colour is chosen when the node refreshes (see stepPlantRespawns).
767 state: gather.plantKind === "flower"
768 ? null
769 : (gather.plantKind === "herb" && isHerbId(gather.herbId)
770 ? gather.herbId
771 : defaultPlantState(gather.typeId)),
772 respawnsAt: now + PLANT_EXHAUST_MS
773 });
774
775 clearGather(world.ecs, handle);
776 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
777 events.push({
778 type: "gather-complete",
779 characterId: character.characterId,
780 kind: "plant",
781 plantKind: gather.plantKind,
782 itemId
783 });
784}
785
786export function stepGather (world, now)
787{
788 const events = [];
789 const privates = [];
790 events.push(...stepOreRespawns(world, now).events);
791 events.push(...stepTreeRespawns(world, now).events);
792 events.push(...stepPlantRespawns(world, now).events);
793
794 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
795 {
796 const { handle, gather, position, character, entityId } = entity;
797 if (world.ecs.has(handle, Component.dead))
798 {
799 clearGather(world.ecs, handle);
800 continue;
801 }
802 if (chebyshev(position.tileX, position.tileY, gather.tileX, gather.tileY) > 1)
803 {
804 clearGather(world.ecs, handle);
805 continue;
806 }
807 const block = blockAt(world, gather.tileX, gather.tileY);
808
809 if (gather.kind === "mining")
810 {
811 if (!block || block.typeId !== BlockType.boulder
812 || materialFromOreBoulderState(block.state) !== gather.materialId)
813 {
814 clearGather(world.ecs, handle);
815 continue;
816 }
817 }
818 else if (gather.kind === "woodcutting")
819 {
820 if (!block || block.typeId !== gather.typeId || !isChopableTreeBlock(block))
821 {
822 clearGather(world.ecs, handle);
823 continue;
824 }
825 }
826 else if (gather.kind === "plant")
827 {
828 if (!block || block.typeId !== gather.typeId || !plantGatherForBlock(block))
829 {
830 clearGather(world.ecs, handle);
831 continue;
832 }
833 }
834 else
835 {
836 clearGather(world.ecs, handle);
837 continue;
838 }
839
840 if (now >= gather.nextSwingAt && now < gather.finishesAt)
841 {
842 gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
843 events.push({
844 type: "gather-swing",
845 attackerId: entityId,
846 tileX: gather.tileX,
847 tileY: gather.tileY,
848 fromTileX: position.tileX,
849 fromTileY: position.tileY,
850 toolItemId: gather.toolItemId ?? null,
851 swipe: false
852 });
853 }
854
855 if (now < gather.finishesAt)
856 { continue; }
857
858 if (gather.kind === "mining")
859 { completeMining(world, handle, entityId, character, gather, events, privates, now); }
860 else if (gather.kind === "woodcutting")
861 { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }
862 else
863 { completePlant(world, handle, entityId, character, gather, events, privates, now); }
864 }
865 return { events, privates };
866}
867
868export function handleGatherCommand (world, sessionId, command, now)
869{
870 switch (command.type)
871 {
872 case "mine":
873 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
874 case "chop":
875 return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
876 case "pick":
877 return startPick(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
878 case "cancel-gather":
879 {
880 const entityId = world.characterEntities.get(command.characterId);
881 if (entityId == null)
882 { return { events: [] }; }
883 const handle = world.ecs.handleOf(entityId);
884 clearGather(world.ecs, handle);
885 return { events: [] };
886 }
887 default:
888 return null;
889 }
890}
891
892function defaultPlantState (typeId)
893{
894 if (typeId === BlockType.herbPlant)
895 { return "mint"; }
896 return "cotton-plant";
897}