import { Component } from "../ecs/components.js"; import { BlockType, GroundType, isLiquidWaterGround, normalizeGround } from "../../../shared/definitions/tiles.js"; import { FISH_SPECIES, fishTierRankFromItemId, fishingDifficulty, fishingExhaustDurationMs, baitItemIdForCloth, BaitItemId, normalizeFishingSpotConfig, fishingPoleItemIdForWood, woodTierFromFishingRodItemId } from "../../../shared/definitions/fishItems.js"; import { resolveFishingTool } from "../../../shared/definitions/gathering.js"; import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js"; import { ClothTier, tierRank, clothTierForWood } from "../../../shared/definitions/materialTiers.js"; import { yarnItemId } from "../../../shared/definitions/clothItems.js"; import { itemDefinition } from "../../../shared/definitions/items.js"; import { SkillId, skillLevel } from "../../../shared/definitions/skills.js"; import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js"; import { gatherDurationMultiplier, harvestYieldMultiplier } from "../../../shared/equipment/jewelryEffects.js"; import { rollSkill } from "../../../shared/combat/rolls.js"; import { insertStack, stackQuantity, takeMatchingFromSlots, takeFromSlot } from "../../../shared/items/inventory.js"; import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js"; import { placeOrMergeGroundStack, bagView } from "../items/bags.js"; import { isAdjacentTile } from "../../../shared/navigation/adjacency.js"; import { tileToChunk, tileToLocal } from "../world/coordinates.js"; import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { tileShoveEvent } from "../simulation/tileInteract.js"; import { seasonIdAt } from "../../../shared/world/season.js"; const FISH_ATTEMPT_MS = 3000; const FISH_SHOVE_MS = 1000; const MAX_FISH_ATTEMPTS = 3; /** Chance the fishing line snaps after a fully failed rod session. */ const LINE_BREAK_CHANCE = 0.05; function userError (message) { const error = new Error(message); error.userFacing = true; return error; } function tileKey (tileX, tileY) { return `${tileX},${tileY}`; } 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 ensureFishSessions (world) { if (!world.fishSessions) { world.fishSessions = new Map(); } return world.fishSessions; } function ensureFishSpotRespawns (world) { if (!world.fishingSpotRespawns) { world.fishingSpotRespawns = new Map(); } return world.fishingSpotRespawns; } function clearFishSession (world, characterId) { ensureFishSessions(world).delete(characterId); } function blockAt (world, tileX, tileY) { const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY)); const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX); return data.blocks[index] ?? null; } function groundAt (world, tileX, tileY) { const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY)); const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX); return normalizeGround(data.grounds[index]).typeId; } function setBlockState (world, tileX, tileY, state) { const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); const localX = tileToLocal(tileX); const localY = tileToLocal(tileY); const data = world.chunkData(chunkX, chunkY); const index = localY * CHUNK_SIZE + localX; const existing = data.blocks[index]; if (!existing) { return null; } const block = { ...existing, state }; data.blocks[index] = block; return { type: "chunk-delta", chunkX, chunkY, tileX, tileY, localX, localY, block }; } function spotFishItemIds (block) { return normalizeFishingSpotConfig(block?.config).fishes; } function maxFishTierInList (fishItemIds) { let max = 0; for (const itemId of fishItemIds) { max = Math.max(max, fishTierRankFromItemId(itemId)); } return max; } function eligibleFishItemIds (fishItemIds, baitTierRank) { return fishItemIds.filter((itemId) => fishTierRankFromItemId(itemId) <= baitTierRank); } function findBestBaitSlot (slots, maxRank) { let best = null; for (let i = 0; i < (slots?.length ?? 0); i++) { const slot = slots[i]; if (!slot || stackQuantity(slot.quantity) <= 0) { continue; } const def = itemDefinition(slot.itemId); if (!def?.bait || !def.tier) { continue; } const rank = tierRank(def.tier); if (rank < 1 || rank > maxRank) { continue; } if (!best || rank > best.rank) { best = { slotIndex: i, itemId: slot.itemId, rank, tier: def.tier }; } } return best; } function toolTierRank (tool) { const tier = tool?.def?.equipment?.tier ?? tool?.tier; return tierRank(tier); } /** * Start fishing at a fishing-spot block tile. */ export function startFish (world, sessionId, characterId, tileX, tileY, now = Date.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 fishing spot."); } const block = blockAt(world, tileX, tileY); if (!block || block.typeId !== BlockType.fishingSpot) { throw userError("There is no fishing spot there."); } if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY))) { throw userError("The fish have scattered. Wait for them to return."); } const ground = groundAt(world, tileX, tileY); const season = seasonIdAt(now); if (ground !== GroundType.water && ground !== GroundType.deepWater) { throw userError("Fishing spots must be on water."); } if (!isLiquidWaterGround(ground, season)) { throw userError("The water is frozen solid."); } const fishList = spotFishItemIds(block); if (!fishList.length) { throw userError("No fish swim here."); } const inventory = world.ecs.get(handle, Component.inventory); const equipment = world.ecs.get(handle, Component.equipment); const skills = world.ecs.get(handle, Component.skills); const resolved = resolveFishingTool({ inventorySlots: inventory?.slots, equipmentSlots: equipment?.slots, skills }); if (!resolved.ok) { throw userError(resolved.reason); } const isNet = resolved.kind === EquipmentKind.fishingNet; const rodRank = isNet ? 1 : toolTierRank(resolved.tool); const maxInSpot = maxFishTierInList(fishList); const usefulMax = Math.min(rodRank, maxInSpot); let baitRank = 1; let baitItemId = null; let baitConsumedRank = 0; if (isNet) { baitRank = 1; baitConsumedRank = 0; } else { const bait = findBestBaitSlot(inventory?.slots, usefulMax); if (!bait) { throw userError("You need suitable bait for this spot."); } baitRank = bait.rank; baitItemId = bait.itemId; baitConsumedRank = bait.rank; } const eligible = eligibleFishItemIds(fishList, baitRank); if (!eligible.length) { throw userError("No fish here match your bait."); } if (!isNet) { const taken = takeMatchingFromSlots(inventory.slots, { itemId: baitItemId, quantity: 1, compact: false }); if (!taken.ok) { throw userError("You need suitable bait for this spot."); } inventory.slots = taken.slots; } clearFishSession(world, characterId); if (world.ecs.has(handle, Component.gather)) { world.ecs.remove(handle, Component.gather); } const path = world.ecs.get(handle, Component.path); if (path) { path.tiles = []; } ensureFishSessions(world).set(characterId, { sessionId, tileX, tileY, toolItemId: resolved.tool.def.itemId, isNet, baitRank, baitConsumedRank, baitItemId, eligible, difficulty: fishingDifficulty(baitRank), attemptsLeft: MAX_FISH_ATTEMPTS, attemptStartedAt: now, nextShoveAt: now, attemptEndsAt: now + Math.max( 1, Math.floor(FISH_ATTEMPT_MS * gatherDurationMultiplier(equipment)) ) }); return { events: [], private: isNet ? null : bagView(world.ecs, handle) }; } export function handleFishingCommand (world, sessionId, command, now = Date.now()) { if (command.type === "start-fish") { return startFish( world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now ); } if (command.type === "cancel-fish") { clearFishSession(world, command.characterId); return { events: [] }; } return null; } function completeCatch (world, handle, entityId, characterId, session, events, privates, now) { const eligible = session.eligible ?? []; if (!eligible.length) { events.push({ type: "command-error", sessionId: session.sessionId, message: "The fish got away." }); clearFishSession(world, characterId); return; } const rng = world.rng ?? Math.random; const pick = eligible[Math.floor(rng() * eligible.length) % eligible.length]; const fishRank = fishTierRankFromItemId(pick); const inventory = world.ecs.get(handle, Component.inventory); const def = itemDefinition(pick); const origin = gatherOrigin(GatherOriginVerb.caught, characterDisplayName(world, handle)); const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment)))); const stack = attachOrigins({ itemId: pick, quantity, origins: [{ origin, quantity }] }); const inserted = insertStack(inventory.slots, stack, def); if (!inserted.ok || inserted.remainder > 0) { events.push({ type: "command-error", sessionId: session.sessionId, message: "Your inventory is full." }); clearFishSession(world, characterId); return; } inventory.slots = inserted.slots; const xpAmount = (session.baitConsumedRank | 0) + fishRank; const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp && xpAmount > 0) { const result = applySkillXp( skills, SkillId.fishing, xpAmount, world.ecs.get(handle, Component.equipment) ); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } if (skillsChanged) { events.push({ type: "skills-updated", entityId, characterId, ...publicSkillsPayload(skills), stored: storedSkillXp(skills), levelUps }); } const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted"); if (exhausted) { events.push(exhausted); } ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY), { tileX: session.tileX, tileY: session.tileY, respawnsAt: now + fishingExhaustDurationMs(fishRank) }); privates.push({ characterId, bag: bagView(world.ecs, handle) }); events.push({ type: "item-bubble", entityId, itemId: pick, quantity: 1 }); clearFishSession(world, characterId); } export function stepFishing (world, now) { const events = []; const privates = []; events.push(...stepFishingSpotRespawns(world, now).events); const sessions = ensureFishSessions(world); for (const [characterId, session] of [...sessions.entries()]) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { clearFishSession(world, characterId); continue; } const handle = world.ecs.handleOf(entityId); if (world.ecs.has(handle, Component.dead)) { clearFishSession(world, characterId); continue; } const position = world.ecs.get(handle, Component.position); if (!isAdjacentTile(position.tileX, position.tileY, session.tileX, session.tileY)) { clearFishSession(world, characterId); continue; } if (now >= session.nextShoveAt && now < session.attemptEndsAt) { session.nextShoveAt = now + FISH_SHOVE_MS; events.push(tileShoveEvent( entityId, position.tileX, position.tileY, session.tileX, session.tileY )); // Also emit gather-swing so tool overlay shows. events.push({ type: "gather-swing", attackerId: entityId, tileX: session.tileX, tileY: session.tileY, fromTileX: position.tileX, fromTileY: position.tileY, toolItemId: session.toolItemId, swipe: false }); } if (now < session.attemptEndsAt) { continue; } const skills = world.ecs.get(handle, Component.skills); const level = skillLevel(skills, SkillId.fishing); const roll = rollSkill(level, world.rng ?? Math.random); session.attemptsLeft -= 1; if (roll >= session.difficulty) { completeCatch(world, handle, entityId, characterId, session, events, privates, now); continue; } if (session.attemptsLeft <= 0) { events.push({ type: "command-error", sessionId: session.sessionId, message: "The fish got away." }); maybeBreakFishingLine(world, handle, entityId, characterId, session, events, privates, now); clearFishSession(world, characterId); continue; } session.attemptStartedAt = now; session.nextShoveAt = now; session.attemptEndsAt = now + Math.max( 1, Math.floor(FISH_ATTEMPT_MS * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment))) ); } return { events, privates }; } function spawnGroundStack (world, tileX, tileY, itemId, now, events, source = "fishing-line-break") { const stack = attachOrigins({ itemId, quantity: 1, origins: [] }); const placed = placeOrMergeGroundStack(world, { tileX, tileY, stack, now, source }); events.push(...placed.events); } /** * After a fully failed rod session: 5% chance the line snaps → rod becomes pole + 1 yarn. */ function maybeBreakFishingLine (world, handle, entityId, characterId, session, events, privates, now) { if (session.isNet) { return; } const rng = world.rng ?? Math.random; if (rng() >= LINE_BREAK_CHANCE) { return; } const rodItemId = session.toolItemId | 0; const rodDef = itemDefinition(rodItemId); const woodTier = woodTierFromFishingRodItemId(rodItemId) ?? rodDef?.tier; const poleItemId = rodDef?.poleItemId ?? fishingPoleItemIdForWood(woodTier); const clothTier = rodDef?.clothTier ?? clothTierForWood(woodTier); const yarnId = yarnItemId(clothTier); if (!poleItemId || !yarnId) { return; } const inventory = world.ecs.get(handle, Component.inventory); const equipment = world.ecs.get(handle, Component.equipment); let removed = false; let appearanceChanged = false; if (inventory?.slots) { const idx = inventory.slots.findIndex((s) => s?.itemId === rodItemId); if (idx >= 0) { const taken = takeFromSlot(inventory.slots, idx, 1); if (taken.ok) { inventory.slots = taken.slots; removed = true; } } } if (!removed && equipment?.slots?.weapon?.itemId === rodItemId) { equipment.slots.weapon = null; removed = true; appearanceChanged = true; } if (!removed) { return; } const position = world.ecs.get(handle, Component.position); const poleDef = itemDefinition(poleItemId); const yarnDef = itemDefinition(yarnId); let slots = inventory.slots; const poleIns = insertStack(slots, attachOrigins({ itemId: poleItemId, quantity: 1, origins: [] }), poleDef); if (poleIns.ok && poleIns.remainder === 0) { slots = poleIns.slots; } else { spawnGroundStack(world, position.tileX, position.tileY, poleItemId, now, events); } const yarnIns = insertStack(slots, attachOrigins({ itemId: yarnId, quantity: 1, origins: [] }), yarnDef); if (yarnIns.ok && yarnIns.remainder === 0) { slots = yarnIns.slots; } else { spawnGroundStack(world, position.tileX, position.tileY, yarnId, now, events); } inventory.slots = slots; events.push({ type: "command-error", sessionId: session.sessionId, message: "Your fishing line broke!" }); privates.push({ characterId, bag: bagView(world.ecs, handle), ...(appearanceChanged ? { appearanceChanged: true } : {}) }); } export function stepFishingSpotRespawns (world, now) { const respawns = world.fishingSpotRespawns; if (!respawns?.size) { return { events: [] }; } const events = []; for (const [key, entry] of [...respawns.entries()]) { if (now < entry.respawnsAt) { continue; } respawns.delete(key); const block = blockAt(world, entry.tileX, entry.tileY); if (!block || block.typeId !== BlockType.fishingSpot) { continue; } const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot"); if (delta) { events.push(delta); } } return { events }; } export { ClothTier, BaitItemId, baitItemIdForCloth, FISH_SPECIES };