import { Component } from "../ecs/components.js"; import { BlockType } from "../../../shared/definitions/tiles.js"; import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "../../../shared/definitions/craftingItems.js"; import { ashItemIdForWood, logItemIdForWood } from "../../../shared/definitions/woodItems.js"; import { campfireDurationMs, firestartingDifficulty, woodTierRank } from "../../../shared/definitions/craftingStations.js"; import { MATERIAL_DISPLAY_NAME, WOOD_TIER_ORDER } from "../../../shared/definitions/materialTiers.js"; import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.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 { rollSkill } from "../../../shared/combat/rolls.js"; import { stackQuantity } from "../../../shared/items/inventory.js"; import { attachOrigins, ashOrigin, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js"; import { placeOrMergeGroundStack, publicGroundItem, removeGroundItem, 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 { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; const FIRE_ATTEMPT_MS = 1100; const MAX_LIGHT_ATTEMPTS = 3; 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 tileKey (tileX, tileY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); return `${dim}:${tileX},${tileY}`; } function ensureCampfires (world) { if (!world.campfireExpires) { world.campfireExpires = new Map(); } return world.campfireExpires; } function ensureFireSessions (world) { if (!world.fireSessions) { world.fireSessions = new Map(); } return world.fireSessions; } function clearFireSession (world, characterId) { ensureFireSessions(world).delete(characterId); } function woodTierFromLogItemId (itemId) { const def = itemDefinition(itemId); if (!def || def.familyId !== ItemFamilyId.log) { return null; } return def.tier ?? null; } function findTinderboxSlot (slots) { for (let i = 0; i < (slots?.length ?? 0); i++) { const slot = slots[i]; if (!slot || slot.itemId !== CraftingItemId.tinderbox) { continue; } const charges = slot.instance?.kind === "tinderbox" ? (slot.instance.charges | 0) : TINDERBOX_MAX_CHARGES; if (charges > 0) { return i; } } return -1; } /** Consume one tinderbox charge in place; remove item at 0. */ function consumeTinderboxCharge (slots, slotIndex) { const next = slots.map((s) => (s ? structuredClone(s) : null)); const slot = next[slotIndex]; if (!slot || slot.itemId !== CraftingItemId.tinderbox) { return { ok: false, slots }; } const charges = slot.instance?.kind === "tinderbox" ? (slot.instance.charges | 0) : TINDERBOX_MAX_CHARGES; if (charges <= 0) { return { ok: false, slots }; } if (charges <= 1) { next[slotIndex] = null; return { ok: true, slots: next, exhausted: true }; } next[slotIndex].instance = { kind: "tinderbox", charges: charges - 1 }; return { ok: true, slots: next, exhausted: false }; } function placeBlock (world, tileX, tileY, typeId, state, config = null, 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 }; data.blocks[index] = block; return { type: "chunk-delta", chunkX, chunkY, dimensionId: dim, tileX, tileY, localX, localY, block }; } function clearBlockAt (world, tileX, tileY, 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; if (!data.blocks[index]) { return null; } data.blocks[index] = null; return { type: "chunk-delta", chunkX, chunkY, dimensionId: dim, tileX, tileY, localX, localY, block: null }; } function blockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim); const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX); return data.blocks[index] ?? null; } function consumeOneGroundLog (world, item, events) { const qty = stackQuantity(item.stack?.quantity); if (qty <= 1) { removeGroundItem(world, item.groundItemId); events.push({ type: "ground-item-despawn", ...publicGroundItem(item) }); return; } const split = splitOrigins(normalizeOrigins(item.stack), 1); item.stack.quantity = qty - 1; item.stack.origins = split.remain; delete item.stack.origin; events.push({ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, expiresAt: item.expiresAt }); } function spawnAsh (world, tileX, tileY, woodTier, litByName, now, events, dimensionId = OVERWORLD_ID) { const ashItemId = ashItemIdForWood(woodTier); if (!ashItemId) { return; } const woodName = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier; const stack = attachOrigins({ itemId: ashItemId, quantity: 1, origins: [{ origin: ashOrigin(woodName, litByName), quantity: 1 }] }); const placed = placeOrMergeGroundStack(world, { tileX, tileY, dimensionId: normalizeDimensionId(dimensionId), stack, now, source: "campfire-ash" }); events.push(...placed.events); } /** * Start lighting a ground log with a tinderbox (up to 3 skill rolls). */ export function startFire (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 | 0); if (!item) { throw userError("That item is no longer on the ground."); } const woodTier = woodTierFromLogItemId(item.stack?.itemId); if (!woodTier) { throw userError("You can only light wood logs."); } const position = world.ecs.get(handle, Component.position); if (!isAdjacentTile(position.tileX, position.tileY, item.tileX, item.tileY)) { throw userError("You need to stand next to the logs."); } const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); if (blockAt(world, item.tileX, item.tileY, dim)) { throw userError("There is no room for a fire there."); } const difficulty = firestartingDifficulty(woodTier); const skills = world.ecs.get(handle, Component.skills); const level = skillLevel(skills, SkillId.firestarting); if (level < difficulty) { const label = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier; throw userError(`Your Firestarting skill is too low to light ${label} logs.`); } const inventory = world.ecs.get(handle, Component.inventory); const tinderSlot = findTinderboxSlot(inventory?.slots); if (tinderSlot < 0) { throw userError("You need a tinderbox with charges remaining."); } const consumed = consumeTinderboxCharge(inventory.slots, tinderSlot); if (!consumed.ok) { throw userError("You need a tinderbox with charges remaining."); } inventory.slots = consumed.slots; clearFireSession(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 = []; } ensureFireSessions(world).set(characterId, { sessionId, groundItemId: item.groundItemId, tileX: item.tileX, tileY: item.tileY, dimensionId: dim, woodTier, difficulty, attemptsLeft: MAX_LIGHT_ATTEMPTS, nextAttemptAt: now, toolItemId: CraftingItemId.tinderbox }); return { events: [], private: bagView(world.ecs, handle) }; } export function cancelFirestarting (world, characterId) { clearFireSession(world, characterId); } export function handleFirestartingCommand (world, sessionId, command, now = Date.now()) { if (command.type === "start-fire") { return startFire(world, sessionId, command.characterId, command.groundItemId, now); } if (command.type === "cancel-fire") { cancelFirestarting(world, command.characterId); return { events: [] }; } return null; } function succeedLight (world, handle, entityId, characterId, session, events, privates, now) { const item = world.groundItems.get(session.groundItemId); if (!item || woodTierFromLogItemId(item.stack?.itemId) !== session.woodTier) { events.push({ type: "command-error", sessionId: session.sessionId, message: "Those logs are gone." }); clearFireSession(world, characterId); return; } if (blockAt(world, session.tileX, session.tileY, normalizeDimensionId(session.dimensionId ?? OVERWORLD_ID))) { events.push({ type: "command-error", sessionId: session.sessionId, message: "There is no room for a fire there." }); clearFireSession(world, characterId); return; } consumeOneGroundLog(world, item, events); const expiresAt = now + campfireDurationMs(session.woodTier); const litByName = characterDisplayName(world, handle); const dim = normalizeDimensionId(session.dimensionId ?? OVERWORLD_ID); const delta = placeBlock( world, session.tileX, session.tileY, BlockType.campfire, session.woodTier, { woodTier: session.woodTier, litAt: now, expiresAt, litByName }, dim ); events.push(delta); ensureCampfires(world).set(tileKey(session.tileX, session.tileY, dim), { tileX: session.tileX, tileY: session.tileY, dimensionId: dim, woodTier: session.woodTier, expiresAt, litByName }); const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp) { const result = applySkillXp( skills, SkillId.firestarting, session.difficulty, 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 }); } privates.push({ characterId, bag: bagView(world.ecs, handle) }); clearFireSession(world, characterId); } /** * Advance lighting attempts and expire campfires. */ export function stepFirestarting (world, now) { const events = []; const privates = []; events.push(...stepCampfireExpires(world, now).events); const sessions = ensureFireSessions(world); for (const [characterId, session] of [...sessions.entries()]) { if (now < session.nextAttemptAt) { continue; } const entityId = world.characterEntities.get(characterId); if (entityId == null) { clearFireSession(world, characterId); continue; } const handle = world.ecs.handleOf(entityId); if (world.ecs.has(handle, Component.dead)) { clearFireSession(world, characterId); continue; } const position = world.ecs.get(handle, Component.position); if (!isAdjacentTile(position.tileX, position.tileY, session.tileX, session.tileY)) { clearFireSession(world, characterId); continue; } const item = world.groundItems.get(session.groundItemId); if (!item) { events.push({ type: "command-error", sessionId: session.sessionId, message: "Those logs are gone." }); clearFireSession(world, characterId); continue; } events.push({ type: "gather-swing", attackerId: entityId, tileX: session.tileX, tileY: session.tileY, fromTileX: position.tileX, fromTileY: position.tileY, toolItemId: session.toolItemId, swipe: false, dimensionId: normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID) }); const skills = world.ecs.get(handle, Component.skills); const level = skillLevel(skills, SkillId.firestarting); const roll = rollSkill(level, world.rng ?? Math.random); session.attemptsLeft -= 1; if (roll >= session.difficulty) { succeedLight(world, handle, entityId, characterId, session, events, privates, now); continue; } if (session.attemptsLeft <= 0) { events.push({ type: "command-error", sessionId: session.sessionId, message: "The sparks fail to catch." }); clearFireSession(world, characterId); continue; } session.nextAttemptAt = now + FIRE_ATTEMPT_MS; } return { events, privates }; } export function stepCampfireExpires (world, now) { const expires = world.campfireExpires; if (!expires?.size) { return { events: [] }; } const events = []; for (const [key, entry] of [...expires.entries()]) { if (now < entry.expiresAt) { continue; } expires.delete(key); const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID); const block = blockAt(world, entry.tileX, entry.tileY, dim); if (!block || block.typeId !== BlockType.campfire) { continue; } const delta = clearBlockAt(world, entry.tileX, entry.tileY, dim); if (delta) { events.push(delta); } spawnAsh( world, entry.tileX, entry.tileY, entry.woodTier, entry.litByName, now, events, dim ); } return { events }; } /** True if itemId is any wood log. */ export function isWoodLogItemId (itemId) { return woodTierFromLogItemId(itemId) != null || WOOD_TIER_ORDER.some((tier) => logItemIdForWood(tier) === itemId); } export { woodTierFromLogItemId, woodTierRank, findTinderboxSlot };