/** * Item Spawner runtime: refill ground-item piles or openable containers, * channelled open with shove-every-second, condition gates, respawn delay. */ import { Component } from "../ecs/components.js"; import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; import { tileToChunk, tileToRegion, parseChunkKey } from "../world/coordinates.js"; import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js"; import { isItemSpawnerConfig, normalizeItemSpawnerConfig, isItemSpawnerContainerAppearance, itemSpawnerContainerDisplayName, itemSpawnerContainerSpriteName, ITEM_SPAWNER_LOCKED_MESSAGE, ITEM_SPAWNER_SPACE_TOAST, ITEM_SPAWNER_OPEN_DURATION_MS, ITEM_SPAWNER_SHOVE_MS, ItemSpawnerAppearance } from "../../../shared/definitions/itemSpawners.js"; import { emptyConditionSet, evaluateConditionSet } from "../../../shared/quests/conditions.js"; import { itemDefinition } from "../../../shared/definitions/items.js"; import { insertStack } from "../../../shared/items/inventory.js"; import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js"; import { isAdjacentTile } from "../../../shared/navigation/adjacency.js"; import { buildEntityConditionContext } from "../doors/conditionContext.js"; import { tileShoveEvent } from "../simulation/tileInteract.js"; import { placeOrMergeGroundStack, removeGroundItem, bagView, publicGroundItem } from "../items/bags.js"; function userError (message) { const error = new Error(message); error.userFacing = true; return error; } function ensureState (world) { if (!world.itemSpawnerState) { world.itemSpawnerState = { /** @type {Map} spawnerId → live instance */ active: new Map(), /** @type {Map} spawnerId → respawnAt ms */ pendingRespawn: new Map(), /** @type {Map} groundItemId → spawnerId */ groundToSpawner: new Map(), /** @type {Map} characterId → open session */ openSessions: new Map() }; } return world.itemSpawnerState; } export function itemContainersInChunk (world, chunkX, chunkY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const state = ensureState(world); const out = []; for (const entry of state.active.values()) { if (entry.mode !== "container") { continue; } if (normalizeDimensionId(entry.dimensionId) !== dim) { continue; } if (tileToChunk(entry.tileX) !== chunkX || tileToChunk(entry.tileY) !== chunkY) { continue; } out.push(publicItemContainer(entry)); } return out; } export function publicItemContainer (entry) { return { containerId: entry.containerId, spawnerId: entry.spawnerId, tileX: entry.tileX, tileY: entry.tileY, dimensionId: normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID), appearance: entry.appearance, material: entry.material, displayName: itemSpawnerContainerDisplayName(entry.appearance), sprite: itemSpawnerContainerSpriteName(entry.appearance, entry.material) }; } function allocateContainerId (world) { world.nextItemContainerId = (world.nextItemContainerId ?? 1) + 1; return world.nextItemContainerId; } function scopedSpawnerId (rawId, dimensionId, chunkX, chunkY, index) { const dim = normalizeDimensionId(dimensionId); const raw = typeof rawId === "string" && rawId ? rawId : `${chunkX}:${chunkY}:${index}`; return raw.startsWith(`${dim}:`) ? raw : `${dim}:${raw}`; } function pickTile (world, originX, originY, range, dimensionId, reserved = null) { const dim = normalizeDimensionId(dimensionId); const radius = Math.max(0, range | 0); const tryTile = (tileX, tileY) => { const key = `${dim}:${tileX},${tileY}`; if (reserved?.has(key)) { return null; } if (!world.ownsRegion?.(tileToRegion(tileX), tileToRegion(tileY), dim)) { // Editor / single-worker worlds may lack ownsRegion — fall through. if (typeof world.ownsRegion === "function") { return null; } } if (typeof world.isEnterable === "function") { if (!world.isEnterable(tileX, tileY, dim)) { return null; } } return { tileX, tileY, dimensionId: dim }; }; if (radius === 0) { return tryTile(originX, originY); } for (let attempt = 0; attempt < 48; attempt++) { const tileX = originX + randInt(-radius, radius); const tileY = originY + randInt(-radius, radius); const tile = tryTile(tileX, tileY); if (tile) { return tile; } } return tryTile(originX, originY); } function randInt (min, max) { return min + Math.floor(Math.random() * (max - min + 1)); } function cloneStacks (items) { return (items ?? []).map((line) => ({ itemId: line.itemId | 0, quantity: Math.max(1, line.quantity | 0) })); } /** * Spawn (or refill) one item spawner instance. Returns events. */ function spawnInstance (world, entryMeta, config, now, events) { const state = ensureState(world); const spawnerId = config.spawnerId; if (state.active.has(spawnerId)) { return; } if ((state.pendingRespawn.get(spawnerId) ?? 0) > now) { return; } state.pendingRespawn.delete(spawnerId); const tile = pickTile( world, entryMeta.originX, entryMeta.originY, config.spawnRangeTiles, entryMeta.dimensionId ); if (!tile) { return; } if (config.appearance === ItemSpawnerAppearance.item) { const groundIds = []; for (const line of config.items) { const def = itemDefinition(line.itemId); if (!def) { continue; } const stack = attachOrigins({ itemId: line.itemId, quantity: line.quantity, origins: [{ origin: godsOrigin(), quantity: line.quantity }] }); const placed = placeOrMergeGroundStack(world, { tileX: tile.tileX, tileY: tile.tileY, dimensionId: tile.dimensionId, stack, now, source: "item-spawner", // Never auto-despawn authored spawner loot. despawnDurationMs: Number.MAX_SAFE_INTEGER }); for (const ev of placed.events) { events.push(ev); if (ev.type === "ground-item-appear" && ev.groundItemId != null) { const item = world.groundItems.get(ev.groundItemId); if (item) { item.itemSpawnerId = spawnerId; item.source = "item-spawner"; // Far-future expiry (DB column is NOT NULL); expireGroundItems also skips these. item.expiresAt = Number.MAX_SAFE_INTEGER; state.groundToSpawner.set(ev.groundItemId, spawnerId); groundIds.push(ev.groundItemId); } } } } if (!groundIds.length) { return; } state.active.set(spawnerId, { mode: "items", spawnerId, dimensionId: tile.dimensionId, originX: entryMeta.originX, originY: entryMeta.originY, spawnRangeTiles: config.spawnRangeTiles, respawnDelaySeconds: config.respawnDelaySeconds, appearance: config.appearance, items: cloneStacks(config.items), groundItemIds: groundIds, when: emptyConditionSet() }); return; } const containerId = allocateContainerId(world); const live = { mode: "container", containerId, spawnerId, tileX: tile.tileX, tileY: tile.tileY, dimensionId: tile.dimensionId, originX: entryMeta.originX, originY: entryMeta.originY, spawnRangeTiles: config.spawnRangeTiles, respawnDelaySeconds: config.respawnDelaySeconds, appearance: config.appearance, material: config.material, items: cloneStacks(config.items), when: config.when ?? emptyConditionSet() }; state.active.set(spawnerId, live); events.push({ type: "item-container-appear", ...publicItemContainer(live) }); } function clearActive (world, spawnerId, events, { scheduleRespawn = true } = {}) { const state = ensureState(world); const live = state.active.get(spawnerId); if (!live) { return; } state.active.delete(spawnerId); if (live.mode === "items") { for (const id of live.groundItemIds ?? []) { state.groundToSpawner.delete(id); } } else if (live.mode === "container") { events.push({ type: "item-container-despawn", containerId: live.containerId, spawnerId, tileX: live.tileX, tileY: live.tileY, dimensionId: live.dimensionId }); } if (scheduleRespawn) { const delayMs = Math.max(0, (live.respawnDelaySeconds | 0) * 1000); const clock = typeof world.now === "function" ? world.now() : Date.now(); state.pendingRespawn.set(spawnerId, clock + delayMs); } } /** * Called whenever a ground item leaves the world (pickup, transform, burn, …). */ export function notifyGroundItemRemoved (world, groundItemId, events = []) { const state = ensureState(world); const spawnerId = state.groundToSpawner.get(groundItemId); if (!spawnerId) { return events; } state.groundToSpawner.delete(groundItemId); const live = state.active.get(spawnerId); if (!live || live.mode !== "items") { return events; } live.groundItemIds = (live.groundItemIds ?? []).filter((id) => id !== groundItemId); // Remaining piles stay in the world but are unlinked (orphaned normal items). if (live.groundItemIds.length === 0) { clearActive(world, spawnerId, events, { scheduleRespawn: true }); } return events; } /** * Wrap removeGroundItem so item-spawner tracking stays in sync. */ export function removeGroundItemTracked (world, groundItemId) { const events = []; notifyGroundItemRemoved(world, groundItemId, events); removeGroundItem(world, groundItemId); return events; } function listAuthoredItemSpawners (world) { const list = []; for (const [key, chunk] of world.chunks) { if (chunk.replica || !chunk.simulating || !chunk.data?.open) { continue; } const { chunkX, chunkY, dimensionId: keyDimensionId } = parseChunkKey(key); const dimensionId = normalizeDimensionId(chunk.dimensionId ?? keyDimensionId ?? OVERWORLD_ID); for (const entry of chunk.data.spawners ?? []) { if (!isItemSpawnerConfig(entry.config)) { continue; } const localX = entry.localX; const localY = entry.localY; const index = localY * CHUNK_SIZE + localX; const config = normalizeItemSpawnerConfig( entry.config, scopedSpawnerId(entry.config?.spawnerId, dimensionId, chunkX, chunkY, index) ); config.spawnerId = scopedSpawnerId(config.spawnerId, dimensionId, chunkX, chunkY, index); list.push({ config, originX: chunkX * CHUNK_SIZE + localX, originY: chunkY * CHUNK_SIZE + localY, dimensionId }); } } return list; } /** * Tick: refill empty spawners whose respawn timer elapsed; advance open channels. */ export function stepItemSpawners (world, now = Date.now()) { const state = ensureState(world); const events = []; const privates = []; // Drop active entries whose authored spawner vanished. const authoredIds = new Set(listAuthoredItemSpawners(world).map((row) => row.config.spawnerId)); for (const spawnerId of [...state.active.keys()]) { if (!authoredIds.has(spawnerId)) { clearActive(world, spawnerId, events, { scheduleRespawn: false }); } } for (const row of listAuthoredItemSpawners(world)) { const { config } = row; if (state.active.has(config.spawnerId)) { continue; } const readyAt = state.pendingRespawn.get(config.spawnerId) ?? 0; if (readyAt > now) { continue; } spawnInstance(world, row, config, now, events); } const openResult = stepOpenSessions(world, now); events.push(...openResult.events); privates.push(...openResult.privates); return { events, privates }; } function clearOpenSession (world, characterId) { ensureState(world).openSessions.delete(characterId); } export function cancelItemContainerOpen (world, characterId) { clearOpenSession(world, characterId); } /** * Start a 2s shove channel to open a container (adjacent tile required). */ export function startOpenItemContainer (world, sessionId, characterId, containerId, 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 state = ensureState(world); let live = null; for (const entry of state.active.values()) { if (entry.mode === "container" && entry.containerId === (containerId | 0)) { live = entry; break; } } if (!live) { throw userError("That container is gone."); } const position = world.ecs.get(handle, Component.position); const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); if (normalizeDimensionId(live.dimensionId) !== dim) { throw userError("That container is gone."); } if (position.tileX === live.tileX && position.tileY === live.tileY) { throw userError("Stand next to the container."); } if (!isAdjacentTile(position.tileX, position.tileY, live.tileX, live.tileY)) { throw userError("Stand next to the container."); } 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 = []; } clearOpenSession(world, characterId); state.openSessions.set(characterId, { sessionId, containerId: live.containerId, spawnerId: live.spawnerId, tileX: live.tileX, tileY: live.tileY, dimensionId: live.dimensionId, appearance: live.appearance, startedAt: now, endsAt: now + ITEM_SPAWNER_OPEN_DURATION_MS, nextShoveAt: now }); return { events: [] }; } function containerConditionsMet (world, entityId, live) { const when = live.when ?? emptyConditionSet(); if (!(when.all?.length > 0)) { return true; } const ctx = buildEntityConditionContext(world, entityId); if (!ctx) { return false; } return evaluateConditionSet(when, ctx); } function giveStacksToPlayer (world, handle, entityId, stacks, now, events) { const inventory = world.ecs.get(handle, Component.inventory); if (!inventory) { return { dropped: false }; } let dropped = false; const position = world.ecs.get(handle, Component.position); const dim = normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID); for (const line of stacks) { const def = itemDefinition(line.itemId); if (!def) { continue; } let remaining = Math.max(1, line.quantity | 0); const stack = attachOrigins({ itemId: line.itemId, quantity: remaining, origins: [{ origin: godsOrigin(), quantity: remaining }] }); const inserted = insertStack(inventory.slots, stack, def); inventory.slots = inserted.slots; remaining = inserted.remainder | 0; if (remaining > 0) { dropped = true; const leftover = attachOrigins({ itemId: line.itemId, quantity: remaining, origins: [{ origin: godsOrigin(), quantity: remaining }] }); const placed = placeOrMergeGroundStack(world, { tileX: position.tileX, tileY: position.tileY, dimensionId: dim, stack: leftover, now, source: "item-spawner-overflow" }); events.push(...placed.events); } } return { dropped }; } function completeOpen (world, handle, entityId, characterId, session, events, privates, now) { const state = ensureState(world); const live = state.active.get(session.spawnerId); clearOpenSession(world, characterId); if (!live || live.mode !== "container" || live.containerId !== session.containerId) { return; } if (!containerConditionsMet(world, entityId, live)) { events.push({ type: "toast", sessionId: session.sessionId, characterId, message: ITEM_SPAWNER_LOCKED_MESSAGE }); return; } const stacks = cloneStacks(live.items); const { dropped } = giveStacksToPlayer(world, handle, entityId, stacks, now, events); privates.push({ characterId, bag: bagView(world.ecs, handle) }); if (dropped) { events.push({ type: "toast", sessionId: session.sessionId, characterId, message: ITEM_SPAWNER_SPACE_TOAST }); } clearActive(world, live.spawnerId, events, { scheduleRespawn: true }); } function stepOpenSessions (world, now) { const state = ensureState(world); const events = []; const privates = []; for (const [characterId, session] of [...state.openSessions.entries()]) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { clearOpenSession(world, characterId); continue; } const handle = world.ecs.handleOf(entityId); if (world.ecs.has(handle, Component.dead)) { clearOpenSession(world, characterId); continue; } const live = state.active.get(session.spawnerId); if (!live || live.mode !== "container" || live.containerId !== session.containerId) { clearOpenSession(world, characterId); continue; } const position = world.ecs.get(handle, Component.position); const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); if (normalizeDimensionId(live.dimensionId) !== dim || position.tileX === live.tileX && position.tileY === live.tileY || !isAdjacentTile(position.tileX, position.tileY, live.tileX, live.tileY)) { clearOpenSession(world, characterId); continue; } if (now >= session.nextShoveAt && now < session.endsAt) { session.nextShoveAt = now + ITEM_SPAWNER_SHOVE_MS; events.push(tileShoveEvent( entityId, position.tileX, position.tileY, live.tileX, live.tileY, dim )); } if (now < session.endsAt) { continue; } completeOpen(world, handle, entityId, characterId, session, events, privates, now); } return { events, privates }; } export function handleItemSpawnerCommand (world, sessionId, command, now = Date.now()) { if (command.type === "open-item-container") { return startOpenItemContainer( world, sessionId, command.characterId, command.containerId, now ); } if (command.type === "cancel-open-item-container") { cancelItemContainerOpen(world, command.characterId); return { events: [] }; } return null; } /** Find container at a world tile (for client click helpers / tests). */ export function itemContainerAtTile (world, tileX, tileY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const state = ensureState(world); for (const entry of state.active.values()) { if (entry.mode !== "container") { continue; } if (entry.tileX === tileX && entry.tileY === tileY && normalizeDimensionId(entry.dimensionId) === dim) { return entry; } } return null; } export { ensureState as ensureItemSpawnerState };