BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

0d794626 History
service.js 31.8 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 woodworkingXpForDebark,
20 treeExhaustDurationMs,
21 logItemIdForWoodTier,
22 herbalismDurationMs,
23 herbalismXpForPick,
24 PLANT_EXHAUST_MS
25} from "../../../shared/definitions/gathering.js";
26import { rawClothItemId } from "../../../shared/definitions/clothItems.js";
27import { ClothTier } from "../../../shared/definitions/materialTiers.js";
28import {
29 flowerItemInstance,
30 flowerColorIdFromBlockState,
31 flowerBlockState,
32 flowerColorIdForTile,
33 randomFlowerColorId
34} from "../../../shared/definitions/dyes.js";
35import { herbDefinition, isHerbId } from "../../../shared/definitions/herbs.js";
36import { insertStack, stackQuantity } from "../../../shared/items/inventory.js";
37import {
38 attachOrigins,
39 GatherOriginVerb,
40 gatherOrigin,
41 craftOrigin,
42 CraftOriginVerb,
43 normalizeOrigins,
44 splitOrigins
45} from "../../../shared/items/origin.js";
46import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
47import
48{
49 gatherDurationMultiplier,
50 harvestYieldMultiplier
51} from "../../../shared/equipment/jewelryEffects.js";
52import {
53 seasonIdAt,
54 treeStumpStateForSeason,
55 SeasonId,
56 scaleRegrowDurationMs
57} from "../../../shared/world/season.js";
58import { bagView, addGroundItem, publicGroundItem } from "../items/bags.js";
59import { clearEngage } from "../combat/service.js";
60import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
61import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
62import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
63import {
64 barkItemIdForWood,
65 debarkedLogInstance,
66 isLogDebarked
67} from "../../../shared/definitions/woodItems.js";
68import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js";
69
70const GATHER_SWING_INTERVAL_MS = 900;
71/** Fixed strip duration — short axe work on a felled log. */
72export const DEBARK_DURATION_MS = 2000;
73
74function userError (message)
75{
76 const error = new Error(message);
77 error.userFacing = true;
78 return error;
79}
80
81function characterDisplayName (world, handle)
82{
83 const appearance = world.ecs.get(handle, Component.appearance);
84 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
85 return name || "someone";
86}
87
88function ensureOreRespawns (world)
89{
90 if (!world.oreRespawns)
91 { world.oreRespawns = new Map(); }
92 return world.oreRespawns;
93}
94
95function ensureTreeRespawns (world)
96{
97 if (!world.treeRespawns)
98 { world.treeRespawns = new Map(); }
99 return world.treeRespawns;
100}
101
102function ensurePlantRespawns (world)
103{
104 if (!world.plantRespawns)
105 { world.plantRespawns = new Map(); }
106 return world.plantRespawns;
107}
108
109function blockAt (world, tileX, tileY)
110{
111 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
112 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
113}
114
115function setBlockState (world, tileX, tileY, typeId, state)
116{
117 const chunkX = tileToChunk(tileX);
118 const chunkY = tileToChunk(tileY);
119 const localX = tileToLocal(tileX);
120 const localY = tileToLocal(tileY);
121 const data = world.chunkData(chunkX, chunkY);
122 const index = localY * CHUNK_SIZE + localX;
123 const prev = data?.blocks?.[index];
124 if (!prev || prev.typeId !== typeId)
125 { return null; }
126 const block = { typeId: prev.typeId, state, config: prev.config ?? null };
127 data.blocks[index] = block;
128 return {
129 type: "chunk-delta",
130 chunkX,
131 chunkY,
132 tileX,
133 tileY,
134 localX,
135 localY,
136 block
137 };
138}
139
140function setBoulderState (world, tileX, tileY, state)
141{
142 return setBlockState(world, tileX, tileY, BlockType.boulder, state);
143}
144
145function setTreeState (world, tileX, tileY, typeId, state)
146{
147 return setBlockState(world, tileX, tileY, typeId, state);
148}
149
150function clearBlock (world, tileX, tileY, typeId)
151{
152 const chunkX = tileToChunk(tileX);
153 const chunkY = tileToChunk(tileY);
154 const localX = tileToLocal(tileX);
155 const localY = tileToLocal(tileY);
156 const data = world.chunkData(chunkX, chunkY);
157 const index = localY * CHUNK_SIZE + localX;
158 const prev = data?.blocks?.[index];
159 if (!prev || prev.typeId !== typeId)
160 { return null; }
161 data.blocks[index] = null;
162 return {
163 type: "chunk-delta",
164 chunkX,
165 chunkY,
166 tileX,
167 tileY,
168 localX,
169 localY,
170 block: null
171 };
172}
173
174function placeBlock (world, tileX, tileY, typeId, state)
175{
176 const chunkX = tileToChunk(tileX);
177 const chunkY = tileToChunk(tileY);
178 const localX = tileToLocal(tileX);
179 const localY = tileToLocal(tileY);
180 const data = world.chunkData(chunkX, chunkY);
181 const index = localY * CHUNK_SIZE + localX;
182 const block = { typeId, state, config: null };
183 data.blocks[index] = block;
184 return {
185 type: "chunk-delta",
186 chunkX,
187 chunkY,
188 tileX,
189 tileY,
190 localX,
191 localY,
192 block
193 };
194}
195
196function pickaxeForOre (world, handle, materialId)
197{
198 const inventory = world.ecs.get(handle, Component.inventory);
199 const equipment = world.ecs.get(handle, Component.equipment);
200 const skills = world.ecs.get(handle, Component.skills);
201 return resolveMiningPickaxe({
202 inventorySlots: inventory?.slots,
203 equipmentSlots: equipment?.slots,
204 skills,
205 materialId
206 });
207}
208
209function axeForWood (world, handle, woodTier)
210{
211 const inventory = world.ecs.get(handle, Component.inventory);
212 const equipment = world.ecs.get(handle, Component.equipment);
213 const skills = world.ecs.get(handle, Component.skills);
214 return resolveWoodcuttingAxe({
215 inventorySlots: inventory?.slots,
216 equipmentSlots: equipment?.slots,
217 skills,
218 woodTier
219 });
220}
221
222function clearGather (ecs, handle)
223{
224 if (ecs.has(handle, Component.gather))
225 { ecs.remove(handle, Component.gather); }
226}
227
228export function cancelGather (ecs, handle)
229{
230 clearGather(ecs, handle);
231}
232
233/** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
234export function clearOreRespawnsForChunk (world, chunkX, chunkY)
235{
236 const respawns = world.oreRespawns;
237 if (!respawns?.size)
238 { return; }
239 for (const key of [...respawns.keys()])
240 {
241 const [tileX, tileY] = key.split(",").map(Number);
242 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
243 { respawns.delete(key); }
244 }
245}
246
247/** Drop scheduled tree respawns when authored chunk data is replaced or unloaded. */
248export function clearTreeRespawnsForChunk (world, chunkX, chunkY)
249{
250 const respawns = world.treeRespawns;
251 if (!respawns?.size)
252 { return; }
253 for (const key of [...respawns.keys()])
254 {
255 const [tileX, tileY] = key.split(",").map(Number);
256 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
257 { respawns.delete(key); }
258 }
259}
260
261export function clearPlantRespawnsForChunk (world, chunkX, chunkY)
262{
263 const respawns = world.plantRespawns;
264 if (!respawns?.size)
265 { return; }
266 for (const key of [...respawns.keys()])
267 {
268 const [tileX, tileY] = key.split(",").map(Number);
269 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
270 { respawns.delete(key); }
271 }
272}
273
274/**
275 * Restore exhausted ore boulders whose timers have elapsed.
276 */
277export function stepOreRespawns (world, now)
278{
279 const respawns = world.oreRespawns;
280 if (!respawns?.size)
281 { return { events: [] }; }
282 const events = [];
283 for (const [key, entry] of [...respawns.entries()])
284 {
285 if (now < entry.respawnsAt)
286 { continue; }
287 respawns.delete(key);
288 const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId));
289 if (delta)
290 { events.push(delta); }
291 }
292 return { events };
293}
294
295/**
296 * Restore exhausted trees whose timers have elapsed (live seasonal look).
297 */
298export function stepTreeRespawns (world, now)
299{
300 const respawns = world.treeRespawns;
301 if (!respawns?.size)
302 { return { events: [] }; }
303 const events = [];
304 for (const [key, entry] of [...respawns.entries()])
305 {
306 if (now < entry.respawnsAt)
307 { continue; }
308 respawns.delete(key);
309 const delta = setTreeState(
310 world,
311 entry.tileX,
312 entry.tileY,
313 entry.typeId,
314 SeasonId.summer
315 );
316 if (delta)
317 { events.push(delta); }
318 }
319 return { events };
320}
321
322export function stepPlantRespawns (world, now)
323{
324 const respawns = world.plantRespawns;
325 if (!respawns?.size)
326 { return { events: [] }; }
327 const events = [];
328 for (const [key, entry] of [...respawns.entries()])
329 {
330 if (now < entry.respawnsAt)
331 { continue; }
332 respawns.delete(key);
333 const existing = blockAt(world, entry.tileX, entry.tileY);
334 if (existing)
335 { continue; }
336 const state = entry.typeId === BlockType.flower
337 ? flowerBlockState(randomFlowerColorId())
338 : (entry.state ?? defaultPlantState(entry.typeId));
339 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state);
340 if (delta)
341 { events.push(delta); }
342 }
343 return { events };
344}
345
346function beginGatherSwing (world, handle, entityId, position, gatherFields, now)
347{
348 clearEngage(world.ecs, entityId);
349 const path = world.ecs.get(handle, Component.path);
350 if (path)
351 { path.tiles = []; }
352 world.ecs.add(handle, Component.gather, {
353 ...gatherFields,
354 startedAt: now,
355 finishesAt: now + gatherFields.durationMs,
356 nextSwingAt: now
357 });
358 return {
359 events: [{
360 type: "gather-swing",
361 attackerId: entityId,
362 tileX: gatherFields.tileX,
363 tileY: gatherFields.tileY,
364 fromTileX: position.tileX,
365 fromTileY: position.tileY,
366 toolItemId: gatherFields.toolItemId ?? null,
367 swipe: false
368 }]
369 };
370}
371
372/**
373 * Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.
374 */
375export function startMine (world, sessionId, characterId, tileX, tileY, now)
376{
377 const entityId = world.characterEntities.get(characterId);
378 if (entityId == null)
379 { throw userError("Character is not in the world."); }
380 const handle = world.ecs.handleOf(entityId);
381 const identity = world.ecs.get(handle, Component.networkIdentity);
382 if (!identity || identity.sessionId !== sessionId)
383 { throw userError("Character is not in the world."); }
384 if (world.ecs.has(handle, Component.dead))
385 { throw userError("You are dead."); }
386
387 const position = world.ecs.get(handle, Component.position);
388 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
389 { throw userError("You need to stand next to the rock."); }
390
391 const block = blockAt(world, tileX, tileY);
392 if (!block || block.typeId !== BlockType.boulder)
393 { throw userError("There is nothing to mine there."); }
394 const materialId = materialFromOreBoulderState(block.state);
395 if (!materialId)
396 {
397 throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE
398 ? "That rock is exhausted."
399 : "That rock has no ore.");
400 }
401
402 const pickaxe = pickaxeForOre(world, handle, materialId);
403 if (!pickaxe.ok)
404 { throw userError(pickaxe.reason); }
405
406 const durationMs = Math.max(
407 1,
408 Math.floor(miningDurationMs(materialId, pickaxe.tool.tier)
409 * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment)))
410 );
411 const toolItemId = pickaxe.tool.stack?.itemId ?? null;
412 return beginGatherSwing(world, handle, entityId, position, {
413 kind: "mining",
414 tileX,
415 tileY,
416 materialId,
417 toolTier: pickaxe.tool.tier,
418 toolItemId,
419 durationMs
420 }, now);
421}
422
423/**
424 * Start chopping a tree. Completes via stepGather (stump + log + woodcutting XP).
425 */
426export function startChop (world, sessionId, characterId, tileX, tileY, now)
427{
428 const entityId = world.characterEntities.get(characterId);
429 if (entityId == null)
430 { throw userError("Character is not in the world."); }
431 const handle = world.ecs.handleOf(entityId);
432 const identity = world.ecs.get(handle, Component.networkIdentity);
433 if (!identity || identity.sessionId !== sessionId)
434 { throw userError("Character is not in the world."); }
435 if (world.ecs.has(handle, Component.dead))
436 { throw userError("You are dead."); }
437
438 const position = world.ecs.get(handle, Component.position);
439 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
440 { throw userError("You need to stand next to the tree."); }
441
442 const block = blockAt(world, tileX, tileY);
443 if (!isChopableTreeBlock(block))
444 {
445 throw userError(block && woodTierForTreeBlock(block.typeId) != null
446 ? "That tree is already felled."
447 : "There is nothing to chop there.");
448 }
449 const woodTier = woodTierForTreeBlock(block.typeId);
450 const axe = axeForWood(world, handle, woodTier);
451 if (!axe.ok)
452 { throw userError(axe.reason); }
453
454 const durationMs = Math.max(
455 1,
456 Math.floor(woodcuttingDurationMs(woodTier, axe.tool.tier)
457 * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment)))
458 );
459 const toolItemId = axe.tool.stack?.itemId ?? null;
460 return beginGatherSwing(world, handle, entityId, position, {
461 kind: "woodcutting",
462 tileX,
463 tileY,
464 typeId: block.typeId,
465 woodTier,
466 toolTier: axe.tool.tier,
467 toolItemId,
468 durationMs
469 }, now);
470}
471
472function woodTierFromLogItemId (itemId)
473{
474 const def = itemDefinition(itemId);
475 if (!def || def.familyId !== ItemFamilyId.log)
476 { return null; }
477 return def.tier ?? null;
478}
479
480function nearDebarkTarget (position, tileX, tileY)
481{
482 return isAdjacentTile(position.tileX, position.tileY, tileX, tileY)
483 || (position.tileX === tileX && position.tileY === tileY);
484}
485
486function publishGroundItem (item)
487{
488 return {
489 type: "ground-item-appear",
490 ...publicGroundItem(item),
491 stack: item.stack,
492 droppedAt: item.droppedAt,
493 source: item.source,
494 droppedByCharacterId: item.droppedByCharacterId,
495 expiresAt: item.expiresAt
496 };
497}
498
499/**
500 * Start stripping bark from a ground log (2s axe swings, then bark + debarked flag).
501 */
502export function startDebark (world, sessionId, characterId, groundItemId, now)
503{
504 const entityId = world.characterEntities.get(characterId);
505 if (entityId == null)
506 { throw userError("Character is not in the world."); }
507 const handle = world.ecs.handleOf(entityId);
508 const identity = world.ecs.get(handle, Component.networkIdentity);
509 if (!identity || identity.sessionId !== sessionId)
510 { throw userError("Character is not in the world."); }
511 if (world.ecs.has(handle, Component.dead))
512 { throw userError("You are dead."); }
513
514 const item = world.groundItems.get(groundItemId);
515 if (!item?.stack)
516 { throw userError("That item is no longer on the ground."); }
517
518 const woodTier = woodTierFromLogItemId(item.stack.itemId);
519 if (!woodTier)
520 { throw userError("That is not a log."); }
521 if (isLogDebarked(item.stack))
522 { throw userError("That log is already stripped of bark."); }
523
524 const position = world.ecs.get(handle, Component.position);
525 if (!nearDebarkTarget(position, item.tileX, item.tileY))
526 { throw userError("Stand next to the log."); }
527
528 const axe = axeForWood(world, handle, woodTier);
529 if (!axe.ok)
530 { throw userError(axe.reason || "You need an axe to strip this bark."); }
531
532 const barkId = barkItemIdForWood(woodTier);
533 if (barkId == null)
534 { throw userError("That bark cannot be stripped."); }
535
536 const toolItemId = axe.tool.stack?.itemId ?? null;
537 return beginGatherSwing(world, handle, entityId, position, {
538 kind: "debark",
539 tileX: item.tileX,
540 tileY: item.tileY,
541 groundItemId,
542 woodTier,
543 logItemId: item.stack.itemId,
544 barkItemId: barkId,
545 toolTier: axe.tool.tier,
546 toolItemId,
547 durationMs: DEBARK_DURATION_MS
548 }, now);
549}
550
551/**
552 * Pick a plant node (flower / cotton; no tools required).
553 */
554export function startPick (world, sessionId, characterId, tileX, tileY, now)
555{
556 const entityId = world.characterEntities.get(characterId);
557 if (entityId == null)
558 { throw userError("Character is not in the world."); }
559 const handle = world.ecs.handleOf(entityId);
560 const identity = world.ecs.get(handle, Component.networkIdentity);
561 if (!identity || identity.sessionId !== sessionId)
562 { throw userError("Character is not in the world."); }
563 if (world.ecs.has(handle, Component.dead))
564 { throw userError("You are dead."); }
565
566 const position = world.ecs.get(handle, Component.position);
567 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
568 { throw userError("You need to stand next to the plant."); }
569
570 const block = blockAt(world, tileX, tileY);
571 const plant = plantGatherForBlock(block);
572 if (!plant)
573 { throw userError("There is nothing to pick there."); }
574
575 const inventory = world.ecs.get(handle, Component.inventory);
576 const equipment = world.ecs.get(handle, Component.equipment);
577 const skills = world.ecs.get(handle, Component.skills);
578 const clippers = resolvePlantClippers({
579 inventorySlots: inventory?.slots,
580 equipmentSlots: equipment?.slots,
581 skills,
582 requireTool: !!plant.requiresClippers,
583 minClothTier: plant.minClothTier ?? null
584 });
585 if (!clippers.ok)
586 { throw userError(clippers.reason); }
587
588 let herbId = null;
589 let herbTier = null;
590 if (plant.kind === "herb")
591 {
592 const gate = resolveHerbGather({ herbId: block.state, skills });
593 if (!gate.ok)
594 { throw userError(gate.reason); }
595 herbId = gate.herb.herbId;
596 herbTier = gate.herb.tier;
597 }
598
599 const toolTier = clippers.tool?.tier ?? null;
600 const durationMs = Math.max(
601 1,
602 Math.floor(herbalismDurationMs(plant.kind, toolTier, herbTier)
603 * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment)))
604 );
605 const toolItemId = clippers.tool?.stack?.itemId ?? null;
606 const prefixEvents = [];
607 let flowerColorId = null;
608 if (plant.kind === "flower")
609 {
610 flowerColorId = flowerColorIdFromBlockState(block.state);
611 if (!flowerColorId)
612 {
613 // Legacy / uncoloured placements: lock a colour before the pick starts.
614 flowerColorId = flowerColorIdForTile(tileX, tileY);
615 const delta = setBlockState(
616 world,
617 tileX,
618 tileY,
619 BlockType.flower,
620 flowerBlockState(flowerColorId)
621 );
622 if (delta)
623 { prefixEvents.push(delta); }
624 }
625 }
626 const started = beginGatherSwing(world, handle, entityId, position, {
627 kind: "plant",
628 plantKind: plant.kind,
629 herbId,
630 herbTier,
631 tileX,
632 tileY,
633 typeId: block.typeId,
634 flowerColorId,
635 toolTier,
636 toolItemId,
637 durationMs
638 }, now);
639 return {
640 ...started,
641 events: [...prefixEvents, ...(started.events ?? [])]
642 };
643}
644
645function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])
646{
647 privates.push({
648 characterId: character.characterId,
649 bag: bagView(world.ecs, handle)
650 });
651 if (skillsChanged)
652 {
653 events.push({
654 type: "skills-updated",
655 entityId,
656 characterId: character.characterId,
657 ...publicSkillsPayload(skills),
658 stored: storedSkillXp(skills),
659 levelUps
660 });
661 }
662}
663
664function completeMining (world, handle, entityId, character, gather, events, privates, now)
665{
666 const oreItemId = oreItemIdForMaterial(gather.materialId);
667 const def = itemDefinition(oreItemId);
668 const inventory = world.ecs.get(handle, Component.inventory);
669 if (!oreItemId || !def || !inventory)
670 {
671 clearGather(world.ecs, handle);
672 return;
673 }
674 const origin = gatherOrigin(GatherOriginVerb.mined, characterDisplayName(world, handle));
675 const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment))));
676 const stack = attachOrigins({
677 itemId: oreItemId,
678 quantity,
679 origins: [{ origin, quantity }]
680 });
681 const inserted = insertStack(inventory.slots, stack, def);
682 if (!inserted.ok || inserted.remainder > 0)
683 {
684 clearGather(world.ecs, handle);
685 events.push({
686 type: "command-error",
687 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
688 message: "Your inventory is full."
689 });
690 return;
691 }
692 inventory.slots = inserted.slots;
693
694 const skills = world.ecs.get(handle, Component.skills);
695 let skillsChanged = false;
696 const levelUps = [];
697 if (skills?.xp)
698 {
699 const result = applySkillXp(
700 skills,
701 SkillId.mining,
702 miningXpForMaterial(gather.materialId),
703 world.ecs.get(handle, Component.equipment)
704 );
705 if (result.changed)
706 { skillsChanged = true; }
707 if (result.levelUp)
708 { levelUps.push(result.levelUp); }
709 }
710
711 const exhausted = setBoulderState(
712 world,
713 gather.tileX,
714 gather.tileY,
715 EXHAUSTED_ORE_BOULDER_STATE
716 );
717 if (exhausted)
718 {
719 events.push(exhausted);
720 ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
721 tileX: gather.tileX,
722 tileY: gather.tileY,
723 materialId: gather.materialId,
724 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
725 });
726 }
727
728 clearGather(world.ecs, handle);
729 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
730 events.push({
731 type: "gather-complete",
732 characterId: character.characterId,
733 kind: "mining",
734 materialId: gather.materialId,
735 itemId: oreItemId
736 });
737}
738
739function completeWoodcutting (world, handle, entityId, character, gather, events, privates, now)
740{
741 const logItemId = logItemIdForWoodTier(gather.woodTier);
742 const def = itemDefinition(logItemId);
743 const inventory = world.ecs.get(handle, Component.inventory);
744 if (!logItemId || !def || !inventory)
745 {
746 clearGather(world.ecs, handle);
747 return;
748 }
749 const origin = gatherOrigin(GatherOriginVerb.felled, characterDisplayName(world, handle));
750 const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment))));
751 const stack = attachOrigins({
752 itemId: logItemId,
753 quantity,
754 origins: [{ origin, quantity }]
755 });
756 const inserted = insertStack(inventory.slots, stack, def);
757 if (!inserted.ok || inserted.remainder > 0)
758 {
759 clearGather(world.ecs, handle);
760 events.push({
761 type: "command-error",
762 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
763 message: "Your inventory is full."
764 });
765 return;
766 }
767 inventory.slots = inserted.slots;
768
769 const skills = world.ecs.get(handle, Component.skills);
770 let skillsChanged = false;
771 const levelUps = [];
772 if (skills?.xp)
773 {
774 const result = applySkillXp(
775 skills,
776 SkillId.woodcutting,
777 woodcuttingXpForWood(gather.woodTier),
778 world.ecs.get(handle, Component.equipment)
779 );
780 if (result.changed)
781 { skillsChanged = true; }
782 if (result.levelUp)
783 { levelUps.push(result.levelUp); }
784 }
785
786 const stumpState = treeStumpStateForSeason(seasonIdAt(now));
787 const exhausted = setTreeState(
788 world,
789 gather.tileX,
790 gather.tileY,
791 gather.typeId,
792 stumpState
793 );
794 if (exhausted)
795 {
796 events.push(exhausted);
797 ensureTreeRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
798 tileX: gather.tileX,
799 tileY: gather.tileY,
800 typeId: gather.typeId,
801 woodTier: gather.woodTier,
802 respawnsAt: now + scaleRegrowDurationMs(treeExhaustDurationMs(gather.woodTier), now)
803 });
804 }
805
806 clearGather(world.ecs, handle);
807 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
808 events.push({
809 type: "gather-complete",
810 characterId: character.characterId,
811 kind: "woodcutting",
812 woodTier: gather.woodTier,
813 itemId: logItemId
814 });
815}
816
817function completeDebark (world, handle, entityId, character, gather, events, privates, now)
818{
819 const item = world.groundItems.get(gather.groundItemId);
820 if (!item?.stack
821 || (item.stack.itemId | 0) !== (gather.logItemId | 0)
822 || isLogDebarked(item.stack)
823 || item.tileX !== gather.tileX
824 || item.tileY !== gather.tileY)
825 {
826 clearGather(world.ecs, handle);
827 return;
828 }
829
830 const qty = stackQuantity(item.stack.quantity);
831 if (qty <= 0)
832 {
833 clearGather(world.ecs, handle);
834 return;
835 }
836
837 const origin = craftOrigin(CraftOriginVerb.made, characterDisplayName(world, handle));
838 const split = splitOrigins(normalizeOrigins(item.stack), 1);
839 const debarkedStack = attachOrigins({
840 itemId: item.stack.itemId,
841 quantity: 1,
842 instance: debarkedLogInstance(),
843 origins: split.taken
844 });
845 const despawnMs = world.settings.groundItemDespawnDurationMs ?? 600_000;
846
847 if (qty === 1)
848 {
849 item.stack = debarkedStack;
850 events.push(publishGroundItem(item));
851 }
852 else
853 {
854 item.stack = {
855 itemId: item.stack.itemId,
856 quantity: qty - 1,
857 instance: item.stack.instance ?? null,
858 origins: split.remain
859 };
860 events.push(publishGroundItem(item));
861
862 const debarkedItem = {
863 groundItemId: (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1),
864 tileX: item.tileX,
865 tileY: item.tileY,
866 stack: debarkedStack,
867 droppedAt: now,
868 expiresAt: now + despawnMs,
869 source: "debark",
870 droppedByCharacterId: character.characterId
871 };
872 addGroundItem(world, debarkedItem);
873 events.push(publishGroundItem(debarkedItem));
874 }
875
876 const barkItem = {
877 groundItemId: (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1),
878 tileX: item.tileX,
879 tileY: item.tileY,
880 stack: attachOrigins({
881 itemId: gather.barkItemId,
882 quantity: 1,
883 origins: [{ origin, quantity: 1 }]
884 }),
885 droppedAt: now,
886 expiresAt: now + despawnMs,
887 source: "debark",
888 droppedByCharacterId: character.characterId
889 };
890 addGroundItem(world, barkItem);
891 events.push(publishGroundItem(barkItem));
892
893 const skills = world.ecs.get(handle, Component.skills);
894 let skillsChanged = false;
895 const levelUps = [];
896 if (skills?.xp)
897 {
898 const result = applySkillXp(
899 skills,
900 SkillId.crafting,
901 woodworkingXpForDebark(gather.woodTier),
902 world.ecs.get(handle, Component.equipment)
903 );
904 if (result.changed)
905 { skillsChanged = true; }
906 if (result.levelUp)
907 { levelUps.push(result.levelUp); }
908 }
909
910 clearGather(world.ecs, handle);
911 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
912 events.push({
913 type: "gather-complete",
914 characterId: character.characterId,
915 kind: "debark",
916 woodTier: gather.woodTier,
917 itemId: gather.barkItemId
918 });
919}
920
921function completePlant (world, handle, entityId, character, gather, events, privates, now)
922{
923 const inventory = world.ecs.get(handle, Component.inventory);
924 if (!inventory)
925 {
926 clearGather(world.ecs, handle);
927 return;
928 }
929
930 let itemId = null;
931 let instance = null;
932 if (gather.plantKind === "flower")
933 {
934 itemId = ItemId.flower;
935 const live = blockAt(world, gather.tileX, gather.tileY);
936 const colorId = gather.flowerColorId
937 ?? flowerColorIdFromBlockState(live?.state)
938 ?? randomFlowerColorId();
939 instance = flowerItemInstance(colorId);
940 }
941 else if (gather.plantKind === "cotton")
942 {
943 itemId = rawClothItemId(ClothTier.cotton);
944 }
945 else if (gather.plantKind === "flax")
946 {
947 itemId = rawClothItemId(ClothTier.linen);
948 }
949 else if (gather.plantKind === "silk")
950 {
951 itemId = rawClothItemId(ClothTier.silk);
952 }
953 else if (gather.plantKind === "herb")
954 {
955 const herb = herbDefinition(gather.herbId);
956 itemId = herb?.itemId ?? null;
957 }
958 else
959 {
960 clearGather(world.ecs, handle);
961 return;
962 }
963
964 const def = itemDefinition(itemId);
965 if (!def)
966 {
967 clearGather(world.ecs, handle);
968 return;
969 }
970
971 const origin = gatherOrigin(GatherOriginVerb.picked, characterDisplayName(world, handle));
972 const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment))));
973 const stack = attachOrigins({
974 itemId,
975 quantity,
976 instance,
977 origins: [{ origin, quantity }]
978 });
979 const inserted = insertStack(inventory.slots, stack, def);
980 if (!inserted.ok || inserted.remainder > 0)
981 {
982 clearGather(world.ecs, handle);
983 events.push({
984 type: "command-error",
985 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
986 message: "Your inventory is full."
987 });
988 return;
989 }
990 inventory.slots = inserted.slots;
991
992 const skills = world.ecs.get(handle, Component.skills);
993 let skillsChanged = false;
994 const levelUps = [];
995 if (skills?.xp)
996 {
997 const result = applySkillXp(
998 skills,
999 SkillId.herbalism,
1000 herbalismXpForPick(gather.plantKind, gather.herbTier),
1001 world.ecs.get(handle, Component.equipment)
1002 );
1003 if (result.changed)
1004 { skillsChanged = true; }
1005 if (result.levelUp)
1006 { levelUps.push(result.levelUp); }
1007 }
1008
1009 const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId);
1010 if (delta)
1011 { events.push(delta); }
1012 ensurePlantRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
1013 tileX: gather.tileX,
1014 tileY: gather.tileY,
1015 typeId: gather.typeId,
1016 // Colour is chosen when the node refreshes (see stepPlantRespawns).
1017 state: gather.plantKind === "flower"
1018 ? null
1019 : (gather.plantKind === "herb" && isHerbId(gather.herbId)
1020 ? gather.herbId
1021 : defaultPlantState(gather.typeId)),
1022 respawnsAt: now + scaleRegrowDurationMs(PLANT_EXHAUST_MS, now)
1023 });
1024
1025 clearGather(world.ecs, handle);
1026 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
1027 events.push({
1028 type: "gather-complete",
1029 characterId: character.characterId,
1030 kind: "plant",
1031 plantKind: gather.plantKind,
1032 itemId
1033 });
1034}
1035
1036export function stepGather (world, now)
1037{
1038 const events = [];
1039 const privates = [];
1040 events.push(...stepOreRespawns(world, now).events);
1041 events.push(...stepTreeRespawns(world, now).events);
1042 events.push(...stepPlantRespawns(world, now).events);
1043
1044 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
1045 {
1046 const { handle, gather, position, character, entityId } = entity;
1047 if (world.ecs.has(handle, Component.dead))
1048 {
1049 clearGather(world.ecs, handle);
1050 continue;
1051 }
1052 const nearTarget = gather.kind === "debark"
1053 ? nearDebarkTarget(position, gather.tileX, gather.tileY)
1054 : isAdjacentTile(position.tileX, position.tileY, gather.tileX, gather.tileY);
1055 if (!nearTarget)
1056 {
1057 clearGather(world.ecs, handle);
1058 continue;
1059 }
1060 const block = blockAt(world, gather.tileX, gather.tileY);
1061
1062 if (gather.kind === "mining")
1063 {
1064 if (!block || block.typeId !== BlockType.boulder
1065 || materialFromOreBoulderState(block.state) !== gather.materialId)
1066 {
1067 clearGather(world.ecs, handle);
1068 continue;
1069 }
1070 }
1071 else if (gather.kind === "woodcutting")
1072 {
1073 if (!block || block.typeId !== gather.typeId || !isChopableTreeBlock(block))
1074 {
1075 clearGather(world.ecs, handle);
1076 continue;
1077 }
1078 }
1079 else if (gather.kind === "plant")
1080 {
1081 if (!block || block.typeId !== gather.typeId || !plantGatherForBlock(block))
1082 {
1083 clearGather(world.ecs, handle);
1084 continue;
1085 }
1086 }
1087 else if (gather.kind === "debark")
1088 {
1089 const item = world.groundItems.get(gather.groundItemId);
1090 if (!item?.stack
1091 || (item.stack.itemId | 0) !== (gather.logItemId | 0)
1092 || isLogDebarked(item.stack)
1093 || item.tileX !== gather.tileX
1094 || item.tileY !== gather.tileY)
1095 {
1096 clearGather(world.ecs, handle);
1097 continue;
1098 }
1099 }
1100 else
1101 {
1102 clearGather(world.ecs, handle);
1103 continue;
1104 }
1105
1106 if (now >= gather.nextSwingAt && now < gather.finishesAt)
1107 {
1108 gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
1109 events.push({
1110 type: "gather-swing",
1111 attackerId: entityId,
1112 tileX: gather.tileX,
1113 tileY: gather.tileY,
1114 fromTileX: position.tileX,
1115 fromTileY: position.tileY,
1116 toolItemId: gather.toolItemId ?? null,
1117 swipe: false
1118 });
1119 }
1120
1121 if (now < gather.finishesAt)
1122 { continue; }
1123
1124 if (gather.kind === "mining")
1125 { completeMining(world, handle, entityId, character, gather, events, privates, now); }
1126 else if (gather.kind === "woodcutting")
1127 { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }
1128 else if (gather.kind === "debark")
1129 { completeDebark(world, handle, entityId, character, gather, events, privates, now); }
1130 else
1131 { completePlant(world, handle, entityId, character, gather, events, privates, now); }
1132 }
1133 return { events, privates };
1134}
1135
1136export function handleGatherCommand (world, sessionId, command, now)
1137{
1138 switch (command.type)
1139 {
1140 case "mine":
1141 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1142 case "chop":
1143 return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1144 case "pick":
1145 return startPick(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1146 case "debark-log":
1147 return startDebark(world, sessionId, command.characterId, command.groundItemId | 0, now);
1148 case "cancel-gather":
1149 {
1150 const entityId = world.characterEntities.get(command.characterId);
1151 if (entityId == null)
1152 { return { events: [] }; }
1153 const handle = world.ecs.handleOf(entityId);
1154 clearGather(world.ecs, handle);
1155 return { events: [] };
1156 }
1157 default:
1158 return null;
1159 }
1160}
1161
1162function defaultPlantState (typeId)
1163{
1164 if (typeId === BlockType.herbPlant)
1165 { return "mint"; }
1166 if (typeId === BlockType.flaxPlant)
1167 { return "flax-plant"; }
1168 if (typeId === BlockType.silkCocoon)
1169 { return "silk-cocoon"; }
1170 return "cotton-plant";
1171}