BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

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