BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

service.js 34.5 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 dimensionId: normalizeDimensionId(item.dimensionId ?? OVERWORLD_ID),
924 stack: debarkedStack,
925 now,
926 source: "debark",
927 droppedByCharacterId: character.characterId,
928 groundItemId: reuseGroundItemId
929 });
930 events.push(...placedDebarked.events);
931
932 const placedBark = placeOrMergeGroundStack(world, {
933 tileX,
934 tileY,
935 dimensionId: normalizeDimensionId(item.dimensionId ?? OVERWORLD_ID),
936 stack: attachOrigins({
937 itemId: gather.barkItemId,
938 quantity: 1,
939 origins: [{ origin, quantity: 1 }]
940 }),
941 now,
942 source: "debark",
943 droppedByCharacterId: character.characterId
944 });
945 events.push(...placedBark.events);
946
947 const skills = world.ecs.get(handle, Component.skills);
948 let skillsChanged = false;
949 const levelUps = [];
950 if (skills?.xp)
951 {
952 const result = applySkillXp(
953 skills,
954 SkillId.woodworking,
955 woodworkingXpForDebark(gather.woodTier),
956 world.ecs.get(handle, Component.equipment)
957 );
958 if (result.changed)
959 { skillsChanged = true; }
960 if (result.levelUp)
961 { levelUps.push(result.levelUp); }
962 }
963
964 clearGather(world.ecs, handle);
965 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
966 events.push({
967 type: "gather-complete",
968 characterId: character.characterId,
969 kind: "debark",
970 woodTier: gather.woodTier,
971 itemId: gather.barkItemId
972 });
973}
974
975function completePlant (world, handle, entityId, character, gather, events, privates, now)
976{
977 const inventory = world.ecs.get(handle, Component.inventory);
978 if (!inventory)
979 {
980 clearGather(world.ecs, handle);
981 return;
982 }
983
984 let itemId = null;
985 let instance = null;
986 if (gather.plantKind === "flower")
987 {
988 itemId = ItemId.flower;
989 const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID);
990 const live = blockAt(world, gather.tileX, gather.tileY, dim);
991 const colorId = gather.flowerColorId
992 ?? flowerColorIdFromBlockState(live?.state)
993 ?? randomFlowerColorId();
994 instance = flowerItemInstance(colorId);
995 }
996 else if (gather.plantKind === "cotton")
997 {
998 itemId = rawClothItemId(ClothTier.cotton);
999 }
1000 else if (gather.plantKind === "flax")
1001 {
1002 itemId = rawClothItemId(ClothTier.linen);
1003 }
1004 else if (gather.plantKind === "silk")
1005 {
1006 itemId = rawClothItemId(ClothTier.silk);
1007 }
1008 else if (gather.plantKind === "herb")
1009 {
1010 const herb = herbDefinition(gather.herbId);
1011 itemId = herb?.itemId ?? null;
1012 }
1013 else
1014 {
1015 clearGather(world.ecs, handle);
1016 return;
1017 }
1018
1019 const def = itemDefinition(itemId);
1020 if (!def)
1021 {
1022 clearGather(world.ecs, handle);
1023 return;
1024 }
1025
1026 const origin = gatherOrigin(GatherOriginVerb.picked, characterDisplayName(world, handle));
1027 const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment))));
1028 const stack = attachOrigins({
1029 itemId,
1030 quantity,
1031 instance,
1032 origins: [{ origin, quantity }]
1033 });
1034 const inserted = insertStack(inventory.slots, stack, def);
1035 if (!inserted.ok || inserted.remainder > 0)
1036 {
1037 clearGather(world.ecs, handle);
1038 events.push({
1039 type: "command-error",
1040 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
1041 message: "Your inventory is full."
1042 });
1043 return;
1044 }
1045 inventory.slots = inserted.slots;
1046
1047 const skills = world.ecs.get(handle, Component.skills);
1048 let skillsChanged = false;
1049 const levelUps = [];
1050 if (skills?.xp)
1051 {
1052 const result = applySkillXp(
1053 skills,
1054 SkillId.herbalism,
1055 herbalismXpForPick(gather.plantKind, gather.herbTier),
1056 world.ecs.get(handle, Component.equipment)
1057 );
1058 if (result.changed)
1059 { skillsChanged = true; }
1060 if (result.levelUp)
1061 { levelUps.push(result.levelUp); }
1062 }
1063
1064 const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID);
1065 const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId, dim);
1066 if (delta)
1067 { events.push(delta); }
1068 ensurePlantRespawns(world).set(respawnTileKey(gather.tileX, gather.tileY, dim), {
1069 tileX: gather.tileX,
1070 tileY: gather.tileY,
1071 dimensionId: dim,
1072 typeId: gather.typeId,
1073 // Colour is chosen when the node refreshes (see stepPlantRespawns).
1074 state: gather.plantKind === "flower"
1075 ? null
1076 : (gather.plantKind === "herb" && isHerbId(gather.herbId)
1077 ? gather.herbId
1078 : defaultPlantState(gather.typeId)),
1079 respawnsAt: now + scaleRegrowDurationMs(PLANT_EXHAUST_MS, now)
1080 });
1081
1082 clearGather(world.ecs, handle);
1083 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
1084 events.push({
1085 type: "gather-complete",
1086 characterId: character.characterId,
1087 kind: "plant",
1088 plantKind: gather.plantKind,
1089 itemId
1090 });
1091}
1092
1093export function stepGather (world, now)
1094{
1095 const events = [];
1096 const privates = [];
1097 events.push(...stepOreRespawns(world, now).events);
1098 events.push(...stepTreeRespawns(world, now).events);
1099 events.push(...stepPlantRespawns(world, now).events);
1100
1101 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
1102 {
1103 const { handle, gather, position, character, entityId } = entity;
1104 if (world.ecs.has(handle, Component.dead))
1105 {
1106 clearGather(world.ecs, handle);
1107 continue;
1108 }
1109 const nearTarget = gather.kind === "debark"
1110 ? nearDebarkTarget(position, gather.tileX, gather.tileY)
1111 : isAdjacentTile(position.tileX, position.tileY, gather.tileX, gather.tileY);
1112 if (!nearTarget)
1113 {
1114 clearGather(world.ecs, handle);
1115 continue;
1116 }
1117 const block = blockAt(
1118 world,
1119 gather.tileX,
1120 gather.tileY,
1121 normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID)
1122 );
1123
1124 if (gather.kind === "mining")
1125 {
1126 if (!block || block.typeId !== BlockType.boulder
1127 || materialFromOreBoulderState(block.state) !== gather.materialId)
1128 {
1129 clearGather(world.ecs, handle);
1130 continue;
1131 }
1132 }
1133 else if (gather.kind === "woodcutting")
1134 {
1135 if (!block || block.typeId !== gather.typeId || !isChopableTreeBlock(block))
1136 {
1137 clearGather(world.ecs, handle);
1138 continue;
1139 }
1140 }
1141 else if (gather.kind === "plant")
1142 {
1143 if (!block || block.typeId !== gather.typeId || !plantGatherForBlock(block))
1144 {
1145 clearGather(world.ecs, handle);
1146 continue;
1147 }
1148 }
1149 else if (gather.kind === "debark")
1150 {
1151 const item = world.groundItems.get(gather.groundItemId);
1152 if (!item?.stack
1153 || (item.stack.itemId | 0) !== (gather.logItemId | 0)
1154 || isLogDebarked(item.stack)
1155 || item.tileX !== gather.tileX
1156 || item.tileY !== gather.tileY)
1157 {
1158 clearGather(world.ecs, handle);
1159 continue;
1160 }
1161 }
1162 else
1163 {
1164 clearGather(world.ecs, handle);
1165 continue;
1166 }
1167
1168 if (now >= gather.nextSwingAt && now < gather.finishesAt)
1169 {
1170 gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
1171 events.push({
1172 type: "gather-swing",
1173 attackerId: entityId,
1174 tileX: gather.tileX,
1175 tileY: gather.tileY,
1176 fromTileX: position.tileX,
1177 fromTileY: position.tileY,
1178 toolItemId: gather.toolItemId ?? null,
1179 swipe: false
1180 });
1181 }
1182
1183 if (now < gather.finishesAt)
1184 { continue; }
1185
1186 if (gather.kind === "mining")
1187 { completeMining(world, handle, entityId, character, gather, events, privates, now); }
1188 else if (gather.kind === "woodcutting")
1189 { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }
1190 else if (gather.kind === "debark")
1191 { completeDebark(world, handle, entityId, character, gather, events, privates, now); }
1192 else
1193 { completePlant(world, handle, entityId, character, gather, events, privates, now); }
1194 }
1195 return { events, privates };
1196}
1197
1198export function handleGatherCommand (world, sessionId, command, now)
1199{
1200 switch (command.type)
1201 {
1202 case "mine":
1203 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1204 case "chop":
1205 return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1206 case "pick":
1207 return startPick(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1208 case "debark-log":
1209 return startDebark(world, sessionId, command.characterId, command.groundItemId | 0, now);
1210 case "cancel-gather":
1211 {
1212 const entityId = world.characterEntities.get(command.characterId);
1213 if (entityId == null)
1214 { return { events: [] }; }
1215 const handle = world.ecs.handleOf(entityId);
1216 clearGather(world.ecs, handle);
1217 return { events: [] };
1218 }
1219 default:
1220 return null;
1221 }
1222}
1223
1224function defaultPlantState (typeId)
1225{
1226 if (typeId === BlockType.herbPlant)
1227 { return "mint"; }
1228 if (typeId === BlockType.flaxPlant)
1229 { return "flax-plant"; }
1230 if (typeId === BlockType.silkCocoon)
1231 { return "silk-cocoon"; }
1232 return "cotton-plant";
1233}