import { Component } from "../ecs/components.js"; import { BlockType, woodTierForTreeBlock, isChopableTreeBlock, plantGatherForBlock } from "../../../shared/definitions/tiles.js"; import { itemDefinition, ItemId } from "../../../shared/definitions/items.js"; import { SkillId } from "../../../shared/definitions/skills.js"; import { materialFromOreBoulderState, oreItemIdForMaterial, miningDurationMs, miningXpForMaterial, oreExhaustDurationMs, oreBoulderState, EXHAUSTED_ORE_BOULDER_STATE, resolveMiningPickaxe, resolveWoodcuttingAxe, resolvePlantClippers, resolveHerbGather, woodcuttingDurationMs, woodcuttingXpForWood, woodworkingXpForDebark, treeExhaustDurationMs, logItemIdForWoodTier, herbalismDurationMs, herbalismXpForPick, PLANT_EXHAUST_MS } from "../../../shared/definitions/gathering.js"; import { rawClothItemId } from "../../../shared/definitions/clothItems.js"; import { ClothTier, metalTierForHerbTier } from "../../../shared/definitions/materialTiers.js"; import { flowerItemInstance, flowerColorIdFromBlockState, flowerBlockState, flowerColorIdForTile, randomFlowerColorId } from "../../../shared/definitions/dyes.js"; import { herbDefinition, isHerbId } from "../../../shared/definitions/herbs.js"; import { insertStack, stackQuantity } from "../../../shared/items/inventory.js"; import { attachOrigins, GatherOriginVerb, gatherOrigin, craftOrigin, CraftOriginVerb, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js"; import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js"; import { gatherDurationMultiplier, harvestYieldMultiplier } from "../../../shared/equipment/jewelryEffects.js"; import { seasonIdAt, treeStumpStateForSeason, SeasonId, scaleRegrowDurationMs } from "../../../shared/world/season.js"; import { bagView, placeOrMergeGroundStack, publicGroundItem, removeGroundItem } from "../items/bags.js"; import { clearEngage } from "../combat/service.js"; import { isAdjacentTile } from "../../../shared/navigation/adjacency.js"; import { tileToChunk, tileToLocal } from "../world/coordinates.js"; import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; import { barkItemIdForWood, debarkedLogInstance, isLogDebarked } from "../../../shared/definitions/woodItems.js"; import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js"; const GATHER_SWING_INTERVAL_MS = 900; /** Fixed strip duration — short axe work on a felled log. */ export const DEBARK_DURATION_MS = 2000; function respawnTileKey (tileX, tileY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); return `${dim}:${tileX},${tileY}`; } function parseRespawnTileKey (key) { const raw = String(key ?? ""); const colon = raw.indexOf(":"); if (colon < 0) { const [tileX, tileY] = raw.split(",").map(Number); return { dimensionId: OVERWORLD_ID, tileX, tileY }; } return { dimensionId: normalizeDimensionId(raw.slice(0, colon)), tileX: Number(raw.slice(colon + 1).split(",")[0]), tileY: Number(raw.slice(colon + 1).split(",")[1]) }; } function userError (message) { const error = new Error(message); error.userFacing = true; return error; } function characterDisplayName (world, handle) { const appearance = world.ecs.get(handle, Component.appearance); const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim(); return name || "someone"; } function ensureOreRespawns (world) { if (!world.oreRespawns) { world.oreRespawns = new Map(); } return world.oreRespawns; } function ensureTreeRespawns (world) { if (!world.treeRespawns) { world.treeRespawns = new Map(); } return world.treeRespawns; } function ensurePlantRespawns (world) { if (!world.plantRespawns) { world.plantRespawns = new Map(); } return world.plantRespawns; } function blockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim); return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null; } function setBlockState (world, tileX, tileY, typeId, state, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); const localX = tileToLocal(tileX); const localY = tileToLocal(tileY); const data = world.chunkData(chunkX, chunkY, dim); const index = localY * CHUNK_SIZE + localX; const prev = data?.blocks?.[index]; if (!prev || prev.typeId !== typeId) { return null; } const block = { typeId: prev.typeId, state, config: prev.config ?? null }; data.blocks[index] = block; return { type: "chunk-delta", chunkX, chunkY, dimensionId: dim, tileX, tileY, localX, localY, block }; } function setBoulderState (world, tileX, tileY, state, dimensionId = OVERWORLD_ID) { return setBlockState(world, tileX, tileY, BlockType.boulder, state, dimensionId); } function setTreeState (world, tileX, tileY, typeId, state, dimensionId = OVERWORLD_ID) { return setBlockState(world, tileX, tileY, typeId, state, dimensionId); } function clearBlock (world, tileX, tileY, typeId, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); const localX = tileToLocal(tileX); const localY = tileToLocal(tileY); const data = world.chunkData(chunkX, chunkY, dim); const index = localY * CHUNK_SIZE + localX; const prev = data?.blocks?.[index]; if (!prev || prev.typeId !== typeId) { return null; } data.blocks[index] = null; return { type: "chunk-delta", chunkX, chunkY, dimensionId: dim, tileX, tileY, localX, localY, block: null }; } function placeBlock (world, tileX, tileY, typeId, state, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); const localX = tileToLocal(tileX); const localY = tileToLocal(tileY); const data = world.chunkData(chunkX, chunkY, dim); const index = localY * CHUNK_SIZE + localX; const block = { typeId, state, config: null }; data.blocks[index] = block; return { type: "chunk-delta", chunkX, chunkY, dimensionId: dim, tileX, tileY, localX, localY, block }; } function pickaxeForOre (world, handle, materialId) { const inventory = world.ecs.get(handle, Component.inventory); const equipment = world.ecs.get(handle, Component.equipment); const skills = world.ecs.get(handle, Component.skills); return resolveMiningPickaxe({ inventorySlots: inventory?.slots, equipmentSlots: equipment?.slots, skills, materialId }); } function axeForWood (world, handle, woodTier) { const inventory = world.ecs.get(handle, Component.inventory); const equipment = world.ecs.get(handle, Component.equipment); const skills = world.ecs.get(handle, Component.skills); return resolveWoodcuttingAxe({ inventorySlots: inventory?.slots, equipmentSlots: equipment?.slots, skills, woodTier }); } function clearGather (ecs, handle) { if (ecs.has(handle, Component.gather)) { ecs.remove(handle, Component.gather); } } export function cancelGather (ecs, handle) { clearGather(ecs, handle); } /** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */ export function clearOreRespawnsForChunk (world, chunkX, chunkY, dimensionId = null) { const respawns = world.oreRespawns; if (!respawns?.size) { return; } const dimFilter = dimensionId != null ? normalizeDimensionId(dimensionId) : null; for (const key of [...respawns.keys()]) { const { dimensionId: keyDim, tileX, tileY } = parseRespawnTileKey(key); if (dimFilter != null && keyDim !== dimFilter) { continue; } if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY) { respawns.delete(key); } } } /** Drop scheduled tree respawns when authored chunk data is replaced or unloaded. */ export function clearTreeRespawnsForChunk (world, chunkX, chunkY, dimensionId = null) { const respawns = world.treeRespawns; if (!respawns?.size) { return; } const dimFilter = dimensionId != null ? normalizeDimensionId(dimensionId) : null; for (const key of [...respawns.keys()]) { const { dimensionId: keyDim, tileX, tileY } = parseRespawnTileKey(key); if (dimFilter != null && keyDim !== dimFilter) { continue; } if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY) { respawns.delete(key); } } } export function clearPlantRespawnsForChunk (world, chunkX, chunkY, dimensionId = null) { const respawns = world.plantRespawns; if (!respawns?.size) { return; } const dimFilter = dimensionId != null ? normalizeDimensionId(dimensionId) : null; for (const key of [...respawns.keys()]) { const { dimensionId: keyDim, tileX, tileY } = parseRespawnTileKey(key); if (dimFilter != null && keyDim !== dimFilter) { continue; } if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY) { respawns.delete(key); } } } /** * Restore exhausted ore boulders whose timers have elapsed. */ export function stepOreRespawns (world, now) { const respawns = world.oreRespawns; if (!respawns?.size) { return { events: [] }; } const events = []; for (const [key, entry] of [...respawns.entries()]) { if (now < entry.respawnsAt) { continue; } respawns.delete(key); const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID); const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId), dim); if (delta) { events.push(delta); } } return { events }; } /** * Restore exhausted trees whose timers have elapsed (live seasonal look). */ export function stepTreeRespawns (world, now) { const respawns = world.treeRespawns; if (!respawns?.size) { return { events: [] }; } const events = []; for (const [key, entry] of [...respawns.entries()]) { if (now < entry.respawnsAt) { continue; } respawns.delete(key); const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID); const delta = setTreeState( world, entry.tileX, entry.tileY, entry.typeId, SeasonId.summer, dim ); if (delta) { events.push(delta); } } return { events }; } export function stepPlantRespawns (world, now) { const respawns = world.plantRespawns; if (!respawns?.size) { return { events: [] }; } const events = []; for (const [key, entry] of [...respawns.entries()]) { if (now < entry.respawnsAt) { continue; } respawns.delete(key); const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID); const existing = blockAt(world, entry.tileX, entry.tileY, dim); if (existing) { continue; } const state = entry.typeId === BlockType.flower ? flowerBlockState(randomFlowerColorId()) : (entry.state ?? defaultPlantState(entry.typeId)); const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state, dim); if (delta) { events.push(delta); } } return { events }; } function beginGatherSwing (world, handle, entityId, position, gatherFields, now) { clearEngage(world.ecs, entityId); const path = world.ecs.get(handle, Component.path); if (path) { path.tiles = []; } world.ecs.add(handle, Component.gather, { ...gatherFields, dimensionId: normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID), startedAt: now, finishesAt: now + gatherFields.durationMs, nextSwingAt: now }); return { events: [{ type: "gather-swing", attackerId: entityId, tileX: gatherFields.tileX, tileY: gatherFields.tileY, fromTileX: position.tileX, fromTileY: position.tileY, toolItemId: gatherFields.toolItemId ?? null, swipe: false, dimensionId: normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID) }] }; } /** * Start mining an ore boulder. Returns events / private bag updates when complete via stepGather. */ export function startMine (world, sessionId, characterId, tileX, tileY, now) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { throw userError("Character is not in the world."); } const handle = world.ecs.handleOf(entityId); const identity = world.ecs.get(handle, Component.networkIdentity); if (!identity || identity.sessionId !== sessionId) { throw userError("Character is not in the world."); } if (world.ecs.has(handle, Component.dead)) { throw userError("You are dead."); } const position = world.ecs.get(handle, Component.position); if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY)) { throw userError("You need to stand next to the rock."); } const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); const block = blockAt(world, tileX, tileY, dim); if (!block || block.typeId !== BlockType.boulder) { throw userError("There is nothing to mine there."); } const materialId = materialFromOreBoulderState(block.state); if (!materialId) { throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE ? "That rock is exhausted." : "That rock has no ore."); } const pickaxe = pickaxeForOre(world, handle, materialId); if (!pickaxe.ok) { throw userError(pickaxe.reason); } const durationMs = Math.max( 1, Math.floor(miningDurationMs(materialId, pickaxe.tool.tier) * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment))) ); const toolItemId = pickaxe.tool.stack?.itemId ?? null; return beginGatherSwing(world, handle, entityId, position, { kind: "mining", tileX, tileY, materialId, toolTier: pickaxe.tool.tier, toolItemId, durationMs }, now); } /** * Start chopping a tree. Completes via stepGather (stump + log + woodcutting XP). */ export function startChop (world, sessionId, characterId, tileX, tileY, now) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { throw userError("Character is not in the world."); } const handle = world.ecs.handleOf(entityId); const identity = world.ecs.get(handle, Component.networkIdentity); if (!identity || identity.sessionId !== sessionId) { throw userError("Character is not in the world."); } if (world.ecs.has(handle, Component.dead)) { throw userError("You are dead."); } const position = world.ecs.get(handle, Component.position); if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY)) { throw userError("You need to stand next to the tree."); } const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); const block = blockAt(world, tileX, tileY, dim); if (!isChopableTreeBlock(block)) { throw userError(block && woodTierForTreeBlock(block.typeId) != null ? "That tree is already felled." : "There is nothing to chop there."); } const woodTier = woodTierForTreeBlock(block.typeId); const axe = axeForWood(world, handle, woodTier); if (!axe.ok) { throw userError(axe.reason); } const durationMs = Math.max( 1, Math.floor(woodcuttingDurationMs(woodTier, axe.tool.tier) * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment))) ); const toolItemId = axe.tool.stack?.itemId ?? null; return beginGatherSwing(world, handle, entityId, position, { kind: "woodcutting", tileX, tileY, typeId: block.typeId, woodTier, toolTier: axe.tool.tier, toolItemId, durationMs }, now); } function woodTierFromLogItemId (itemId) { const def = itemDefinition(itemId); if (!def || def.familyId !== ItemFamilyId.log) { return null; } return def.tier ?? null; } function nearDebarkTarget (position, tileX, tileY) { return isAdjacentTile(position.tileX, position.tileY, tileX, tileY) || (position.tileX === tileX && position.tileY === tileY); } function publishGroundItem (item) { return { type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }; } /** * Start stripping bark from a ground log (2s axe swings, then bark + debarked flag). */ export function startDebark (world, sessionId, characterId, groundItemId, now) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { throw userError("Character is not in the world."); } const handle = world.ecs.handleOf(entityId); const identity = world.ecs.get(handle, Component.networkIdentity); if (!identity || identity.sessionId !== sessionId) { throw userError("Character is not in the world."); } if (world.ecs.has(handle, Component.dead)) { throw userError("You are dead."); } const item = world.groundItems.get(groundItemId); if (!item?.stack) { throw userError("That item is no longer on the ground."); } const woodTier = woodTierFromLogItemId(item.stack.itemId); if (!woodTier) { throw userError("That is not a log."); } if (isLogDebarked(item.stack)) { throw userError("That log is already stripped of bark."); } const position = world.ecs.get(handle, Component.position); if (!nearDebarkTarget(position, item.tileX, item.tileY)) { throw userError("Stand next to the log."); } const axe = axeForWood(world, handle, woodTier); if (!axe.ok) { throw userError(axe.reason || "You need an axe to strip this bark."); } const barkId = barkItemIdForWood(woodTier); if (barkId == null) { throw userError("That bark cannot be stripped."); } const toolItemId = axe.tool.stack?.itemId ?? null; return beginGatherSwing(world, handle, entityId, position, { kind: "debark", tileX: item.tileX, tileY: item.tileY, groundItemId, woodTier, logItemId: item.stack.itemId, barkItemId: barkId, toolTier: axe.tool.tier, toolItemId, durationMs: DEBARK_DURATION_MS }, now); } /** * Pick a plant node (flower / cotton; no tools required). */ export function startPick (world, sessionId, characterId, tileX, tileY, now) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { throw userError("Character is not in the world."); } const handle = world.ecs.handleOf(entityId); const identity = world.ecs.get(handle, Component.networkIdentity); if (!identity || identity.sessionId !== sessionId) { throw userError("Character is not in the world."); } if (world.ecs.has(handle, Component.dead)) { throw userError("You are dead."); } const position = world.ecs.get(handle, Component.position); if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY)) { throw userError("You need to stand next to the plant."); } const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); const block = blockAt(world, tileX, tileY, dim); const plant = plantGatherForBlock(block); if (!plant) { throw userError("There is nothing to pick there."); } const inventory = world.ecs.get(handle, Component.inventory); const equipment = world.ecs.get(handle, Component.equipment); const skills = world.ecs.get(handle, Component.skills); let herbId = null; let herbTier = null; let minMetalTier = null; if (plant.kind === "herb") { const gate = resolveHerbGather({ herbId: block.state, skills }); if (!gate.ok) { throw userError(gate.reason); } herbId = gate.herb.herbId; herbTier = gate.herb.tier; minMetalTier = metalTierForHerbTier(gate.herb.tier); } const clippers = resolvePlantClippers({ inventorySlots: inventory?.slots, equipmentSlots: equipment?.slots, skills, requireTool: !!plant.requiresClippers, minClothTier: plant.minClothTier ?? null, minMetalTier }); if (!clippers.ok) { throw userError(clippers.reason); } const toolTier = clippers.tool?.tier ?? null; const durationMs = Math.max( 1, Math.floor(herbalismDurationMs(plant.kind, toolTier, herbTier) * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment))) ); const toolItemId = clippers.tool?.stack?.itemId ?? null; const prefixEvents = []; let flowerColorId = null; if (plant.kind === "flower") { flowerColorId = flowerColorIdFromBlockState(block.state); if (!flowerColorId) { // Legacy / uncoloured placements: lock a colour before the pick starts. flowerColorId = flowerColorIdForTile(tileX, tileY); const delta = setBlockState( world, tileX, tileY, BlockType.flower, flowerBlockState(flowerColorId), dim ); if (delta) { prefixEvents.push(delta); } } } const started = beginGatherSwing(world, handle, entityId, position, { kind: "plant", plantKind: plant.kind, herbId, herbTier, tileX, tileY, typeId: block.typeId, flowerColorId, toolTier, toolItemId, durationMs }, now); return { ...started, events: [...prefixEvents, ...(started.events ?? [])] }; } function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = []) { privates.push({ characterId: character.characterId, bag: bagView(world.ecs, handle) }); if (skillsChanged) { events.push({ type: "skills-updated", entityId, characterId: character.characterId, ...publicSkillsPayload(skills), stored: storedSkillXp(skills), levelUps }); } } function completeMining (world, handle, entityId, character, gather, events, privates, now) { const oreItemId = oreItemIdForMaterial(gather.materialId); const def = itemDefinition(oreItemId); const inventory = world.ecs.get(handle, Component.inventory); if (!oreItemId || !def || !inventory) { clearGather(world.ecs, handle); return; } const origin = gatherOrigin(GatherOriginVerb.mined, characterDisplayName(world, handle)); const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment)))); const stack = attachOrigins({ itemId: oreItemId, quantity, origins: [{ origin, quantity }] }); const inserted = insertStack(inventory.slots, stack, def); if (!inserted.ok || inserted.remainder > 0) { clearGather(world.ecs, handle); events.push({ type: "command-error", sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId, message: "Your inventory is full." }); return; } inventory.slots = inserted.slots; const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp) { const result = applySkillXp( skills, SkillId.mining, miningXpForMaterial(gather.materialId), world.ecs.get(handle, Component.equipment) ); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } const exhausted = setBoulderState( world, gather.tileX, gather.tileY, EXHAUSTED_ORE_BOULDER_STATE, normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID) ); if (exhausted) { events.push(exhausted); const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID); ensureOreRespawns(world).set(respawnTileKey(gather.tileX, gather.tileY, dim), { tileX: gather.tileX, tileY: gather.tileY, dimensionId: dim, materialId: gather.materialId, respawnsAt: now + oreExhaustDurationMs(gather.materialId) }); } clearGather(world.ecs, handle); pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps); events.push({ type: "gather-complete", characterId: character.characterId, kind: "mining", materialId: gather.materialId, itemId: oreItemId }); } function completeWoodcutting (world, handle, entityId, character, gather, events, privates, now) { const logItemId = logItemIdForWoodTier(gather.woodTier); const def = itemDefinition(logItemId); const inventory = world.ecs.get(handle, Component.inventory); if (!logItemId || !def || !inventory) { clearGather(world.ecs, handle); return; } const origin = gatherOrigin(GatherOriginVerb.felled, characterDisplayName(world, handle)); const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment)))); const stack = attachOrigins({ itemId: logItemId, quantity, origins: [{ origin, quantity }] }); const inserted = insertStack(inventory.slots, stack, def); if (!inserted.ok || inserted.remainder > 0) { clearGather(world.ecs, handle); events.push({ type: "command-error", sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId, message: "Your inventory is full." }); return; } inventory.slots = inserted.slots; const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp) { const result = applySkillXp( skills, SkillId.woodcutting, woodcuttingXpForWood(gather.woodTier), world.ecs.get(handle, Component.equipment) ); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } const stumpState = treeStumpStateForSeason(seasonIdAt(now)); const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID); const exhausted = setTreeState( world, gather.tileX, gather.tileY, gather.typeId, stumpState, dim ); if (exhausted) { events.push(exhausted); ensureTreeRespawns(world).set(respawnTileKey(gather.tileX, gather.tileY, dim), { tileX: gather.tileX, tileY: gather.tileY, dimensionId: dim, typeId: gather.typeId, woodTier: gather.woodTier, respawnsAt: now + scaleRegrowDurationMs(treeExhaustDurationMs(gather.woodTier), now) }); } clearGather(world.ecs, handle); pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps); events.push({ type: "gather-complete", characterId: character.characterId, kind: "woodcutting", woodTier: gather.woodTier, itemId: logItemId }); } function completeDebark (world, handle, entityId, character, gather, events, privates, now) { const item = world.groundItems.get(gather.groundItemId); if (!item?.stack || (item.stack.itemId | 0) !== (gather.logItemId | 0) || isLogDebarked(item.stack) || item.tileX !== gather.tileX || item.tileY !== gather.tileY) { clearGather(world.ecs, handle); return; } const qty = stackQuantity(item.stack.quantity); if (qty <= 0) { clearGather(world.ecs, handle); return; } const origin = craftOrigin(CraftOriginVerb.made, characterDisplayName(world, handle)); const split = splitOrigins(normalizeOrigins(item.stack), 1); const debarkedStack = attachOrigins({ itemId: item.stack.itemId, quantity: 1, instance: debarkedLogInstance(), origins: split.taken }); const tileX = item.tileX; const tileY = item.tileY; let reuseGroundItemId = null; if (qty === 1) { reuseGroundItemId = item.groundItemId; removeGroundItem(world, item.groundItemId); events.push({ type: "ground-item-despawn", ...publicGroundItem(item) }); } else { item.stack = { itemId: item.stack.itemId, quantity: qty - 1, instance: item.stack.instance ?? null, origins: split.remain }; events.push(publishGroundItem(item)); } const placedDebarked = placeOrMergeGroundStack(world, { tileX, tileY, dimensionId: normalizeDimensionId(item.dimensionId ?? OVERWORLD_ID), stack: debarkedStack, now, source: "debark", droppedByCharacterId: character.characterId, groundItemId: reuseGroundItemId }); events.push(...placedDebarked.events); const placedBark = placeOrMergeGroundStack(world, { tileX, tileY, dimensionId: normalizeDimensionId(item.dimensionId ?? OVERWORLD_ID), stack: attachOrigins({ itemId: gather.barkItemId, quantity: 1, origins: [{ origin, quantity: 1 }] }), now, source: "debark", droppedByCharacterId: character.characterId }); events.push(...placedBark.events); const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp) { const result = applySkillXp( skills, SkillId.woodworking, woodworkingXpForDebark(gather.woodTier), world.ecs.get(handle, Component.equipment) ); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } clearGather(world.ecs, handle); pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps); events.push({ type: "gather-complete", characterId: character.characterId, kind: "debark", woodTier: gather.woodTier, itemId: gather.barkItemId }); } function completePlant (world, handle, entityId, character, gather, events, privates, now) { const inventory = world.ecs.get(handle, Component.inventory); if (!inventory) { clearGather(world.ecs, handle); return; } let itemId = null; let instance = null; if (gather.plantKind === "flower") { itemId = ItemId.flower; const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID); const live = blockAt(world, gather.tileX, gather.tileY, dim); const colorId = gather.flowerColorId ?? flowerColorIdFromBlockState(live?.state) ?? randomFlowerColorId(); instance = flowerItemInstance(colorId); } else if (gather.plantKind === "cotton") { itemId = rawClothItemId(ClothTier.cotton); } else if (gather.plantKind === "flax") { itemId = rawClothItemId(ClothTier.linen); } else if (gather.plantKind === "silk") { itemId = rawClothItemId(ClothTier.silk); } else if (gather.plantKind === "herb") { const herb = herbDefinition(gather.herbId); itemId = herb?.itemId ?? null; } else { clearGather(world.ecs, handle); return; } const def = itemDefinition(itemId); if (!def) { clearGather(world.ecs, handle); return; } const origin = gatherOrigin(GatherOriginVerb.picked, characterDisplayName(world, handle)); const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment)))); const stack = attachOrigins({ itemId, quantity, instance, origins: [{ origin, quantity }] }); const inserted = insertStack(inventory.slots, stack, def); if (!inserted.ok || inserted.remainder > 0) { clearGather(world.ecs, handle); events.push({ type: "command-error", sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId, message: "Your inventory is full." }); return; } inventory.slots = inserted.slots; const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp) { const result = applySkillXp( skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind, gather.herbTier), world.ecs.get(handle, Component.equipment) ); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID); const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId, dim); if (delta) { events.push(delta); } ensurePlantRespawns(world).set(respawnTileKey(gather.tileX, gather.tileY, dim), { tileX: gather.tileX, tileY: gather.tileY, dimensionId: dim, typeId: gather.typeId, // Colour is chosen when the node refreshes (see stepPlantRespawns). state: gather.plantKind === "flower" ? null : (gather.plantKind === "herb" && isHerbId(gather.herbId) ? gather.herbId : defaultPlantState(gather.typeId)), respawnsAt: now + scaleRegrowDurationMs(PLANT_EXHAUST_MS, now) }); clearGather(world.ecs, handle); pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps); events.push({ type: "gather-complete", characterId: character.characterId, kind: "plant", plantKind: gather.plantKind, itemId }); } export function stepGather (world, now) { const events = []; const privates = []; events.push(...stepOreRespawns(world, now).events); events.push(...stepTreeRespawns(world, now).events); events.push(...stepPlantRespawns(world, now).events); for (const entity of world.ecs.query(Component.gather, Component.position, Component.character)) { const { handle, gather, position, character, entityId } = entity; if (world.ecs.has(handle, Component.dead)) { clearGather(world.ecs, handle); continue; } const nearTarget = gather.kind === "debark" ? nearDebarkTarget(position, gather.tileX, gather.tileY) : isAdjacentTile(position.tileX, position.tileY, gather.tileX, gather.tileY); if (!nearTarget) { clearGather(world.ecs, handle); continue; } const block = blockAt( world, gather.tileX, gather.tileY, normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID) ); if (gather.kind === "mining") { if (!block || block.typeId !== BlockType.boulder || materialFromOreBoulderState(block.state) !== gather.materialId) { clearGather(world.ecs, handle); continue; } } else if (gather.kind === "woodcutting") { if (!block || block.typeId !== gather.typeId || !isChopableTreeBlock(block)) { clearGather(world.ecs, handle); continue; } } else if (gather.kind === "plant") { if (!block || block.typeId !== gather.typeId || !plantGatherForBlock(block)) { clearGather(world.ecs, handle); continue; } } else if (gather.kind === "debark") { const item = world.groundItems.get(gather.groundItemId); if (!item?.stack || (item.stack.itemId | 0) !== (gather.logItemId | 0) || isLogDebarked(item.stack) || item.tileX !== gather.tileX || item.tileY !== gather.tileY) { clearGather(world.ecs, handle); continue; } } else { clearGather(world.ecs, handle); continue; } if (now >= gather.nextSwingAt && now < gather.finishesAt) { gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS; events.push({ type: "gather-swing", attackerId: entityId, tileX: gather.tileX, tileY: gather.tileY, fromTileX: position.tileX, fromTileY: position.tileY, toolItemId: gather.toolItemId ?? null, swipe: false, dimensionId: normalizeDimensionId( gather.dimensionId ?? position.dimensionId ?? OVERWORLD_ID ) }); } if (now < gather.finishesAt) { continue; } if (gather.kind === "mining") { completeMining(world, handle, entityId, character, gather, events, privates, now); } else if (gather.kind === "woodcutting") { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); } else if (gather.kind === "debark") { completeDebark(world, handle, entityId, character, gather, events, privates, now); } else { completePlant(world, handle, entityId, character, gather, events, privates, now); } } return { events, privates }; } export function handleGatherCommand (world, sessionId, command, now) { switch (command.type) { case "mine": return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now); case "chop": return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now); case "pick": return startPick(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now); case "debark-log": return startDebark(world, sessionId, command.characterId, command.groundItemId | 0, now); case "cancel-gather": { const entityId = world.characterEntities.get(command.characterId); if (entityId == null) { return { events: [] }; } const handle = world.ecs.handleOf(entityId); clearGather(world.ecs, handle); return { events: [] }; } default: return null; } } function defaultPlantState (typeId) { if (typeId === BlockType.herbPlant) { return "mint"; } if (typeId === BlockType.flaxPlant) { return "flax-plant"; } if (typeId === BlockType.silkCocoon) { return "silk-cocoon"; } return "cotton-plant"; }