import { Component } from "../ecs/components.js"; import { BlockType } from "../../../shared/definitions/tiles.js"; import { AlchemyStepKind, CAULDRON_SLOT_COUNT, DYE_CAULDRON_SLOT_COUNT } from "../../../shared/definitions/alchemy.js"; import { ItemId, itemDefinition } from "../../../shared/definitions/items.js"; import { evaluateAlchemyBottle, potionItemInstance, recipePaperBody, resolvedAlchemyPotions, cauldronFlavorText } from "../../../shared/alchemy/recipes.js"; import { DEFAULT_DYE_FILL, mixFlowersForDye } from "../../../shared/definitions/dyes.js"; import { bagView } from "../items/bags.js"; import { countItemInSlots, emptySlots, insertStack, normalizeInventorySlots, takeMatchingFromSlots, stackQuantity } from "../../../shared/items/inventory.js"; import { attachOrigins, craftOrigin, CraftOriginVerb } from "../../../shared/items/origin.js"; import { tileToChunk, tileToLocal } from "../world/coordinates.js"; import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { randomUUID } from "node:crypto"; import { tileShoveTowardBlock } from "../simulation/tileInteract.js"; /** * Cauldron sessions live on the worker world (per character while the UI is open). * Clients send intents only; all brew outcomes are evaluated here. */ 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 ensureSessions (world) { if (!world.cauldronSessions) { world.cauldronSessions = new Map(); } return world.cauldronSessions; } function emptySession () { return { slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null), dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null), brew: [], steps: [], lastSuccessRecipe: null }; } function normalizeSession (session) { if (!Array.isArray(session.dyeSlots) || session.dyeSlots.length !== DYE_CAULDRON_SLOT_COUNT) { session.dyeSlots = Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null); } return session; } function slotView (slot) { if (!slot) { return null; } return { itemId: slot.itemId, quantity: slot.quantity | 0, instance: slot.instance ? structuredClone(slot.instance) : null }; } function sessionView (session) { const steps = session.steps ?? []; return { slots: (session.slots ?? []).map(slotView), dyeSlots: (session.dyeSlots ?? []).map(slotView), brew: (session.brew ?? []).map((row) => ({ itemId: row.itemId, quantity: row.quantity | 0, instance: row.instance ? structuredClone(row.instance) : null })), steps: steps.map((step) => ({ ...step })), flavorText: cauldronFlavorText(steps), canProcessActions: steps.some((step) => step.kind === AlchemyStepKind.insert), canSaveRecipe: !!session.lastSuccessRecipe, lastSuccess: session.lastSuccessRecipe ? { potionKey: session.lastSuccessRecipe.potionKey, displayName: session.lastSuccessRecipe.displayName, minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1 } : null }; } function nearCauldron (world, tileX, tileY) { for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy)); const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx); if (data.blocks[index]?.typeId === BlockType.cauldron) { return true; } } } return false; } function requireNearCauldron (world, handle) { const position = world.ecs.get(handle, Component.position); if (!nearCauldron(world, position.tileX, position.tileY)) { throw userError("Stand next to a cauldron."); } } function requireSession (world, characterId) { const session = ensureSessions(world).get(characterId); if (!session) { throw userError("Open a cauldron first."); } return normalizeSession(session); } function clearAlchemy (session) { session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null); session.brew = []; session.steps = []; } function clearDyeSlots (session) { session.dyeSlots = Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null); } function ensureInventory (world, handle) { let inventory = world.ecs.get(handle, Component.inventory); if (!inventory) { inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); } inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots()); return inventory; } export function handleAlchemyCommand (world, sessionId, command) { switch (command.type) { case "open-cauldron": return openCauldron(world, sessionId, command); case "cauldron-set-slot": return setSlot(world, sessionId, command); case "cauldron-set-dye-slot": return setDyeSlot(world, sessionId, command); case "cauldron-insert": return insertFromSlot(world, sessionId, command); case "cauldron-action": return action(world, sessionId, command); case "cauldron-bottle": return bottle(world, sessionId, command); case "cauldron-create-dye": return createDye(world, sessionId, command); case "cauldron-clear": return clear(world, sessionId, command); case "cauldron-clear-dye": return clearDye(world, sessionId, command); case "cauldron-save-recipe": return saveRecipe(world, sessionId, command); case "cauldron-close": return closeCauldron(world, sessionId, command); default: return null; } } function openCauldron (world, sessionId, command) { const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const inventory = ensureInventory(world, handle); if (countItemInSlots(inventory.slots, ItemId.glassBottle) < 1) { throw userError("I don't have any empty bottles."); } const sessions = ensureSessions(world); const existing = normalizeSession(sessions.get(command.characterId) ?? emptySession()); sessions.set(command.characterId, existing); const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron); return { events: shove ? [shove] : [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(existing) }; } function closeCauldron (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); ensureSessions(world).delete(command.characterId); return { events: [], private: bagView(world.ecs, handle), cauldron: false }; } function setSlot (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); const slotIndex = command.slotIndex | 0; if (slotIndex < 0 || slotIndex >= CAULDRON_SLOT_COUNT) { throw userError("Invalid cauldron slot."); } const itemId = command.itemId | 0; const quantity = Math.max(0, command.quantity | 0); if (!itemId || quantity <= 0) { session.slots[slotIndex] = null; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) }; } const def = itemDefinition(itemId); if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle || itemId === ItemId.flower || itemId === ItemId.dye || def.flower || def.dye) { throw userError("Use the Dyes tab for flowers."); } const inventory = ensureInventory(world, handle); const have = countItemInSlots(inventory.slots, itemId); if (have < quantity) { throw userError("Not enough of that item in your inventory."); } session.slots[slotIndex] = { itemId, quantity, instance: null }; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) }; } function setDyeSlot (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); const slotIndex = command.slotIndex | 0; if (slotIndex < 0 || slotIndex >= DYE_CAULDRON_SLOT_COUNT) { throw userError("Invalid dye slot."); } const itemId = command.itemId | 0; const quantity = Math.max(0, command.quantity | 0); if (!itemId || quantity <= 0) { session.dyeSlots[slotIndex] = null; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) }; } if (itemId !== ItemId.flower) { throw userError("Only flowers go in dye slots."); } const inventory = ensureInventory(world, handle); const wanted = command.instance ? structuredClone(command.instance) : null; let instance = wanted; if (!instance) { for (const slot of inventory.slots) { if (slot?.itemId === ItemId.flower && slot.instance) { instance = structuredClone(slot.instance); break; } } } if (!instance?.color) { throw userError("That flower has no colour."); } const have = countMatchingInstance(inventory.slots, ItemId.flower, instance); if (have < quantity) { throw userError("Not enough of that flower in your inventory."); } session.dyeSlots[slotIndex] = { itemId: ItemId.flower, quantity, instance }; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) }; } function insertFromSlot (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); const slotIndex = command.slotIndex | 0; const reserved = session.slots[slotIndex]; if (!reserved) { throw userError("That cauldron slot is empty."); } const inventory = ensureInventory(world, handle); const pulled = takeMatchingFromSlots(inventory.slots, { itemId: reserved.itemId, quantity: reserved.quantity, instance: reserved.instance ?? null, compact: false }); if (!pulled.ok) { throw userError("Not enough of that item in your inventory."); } inventory.slots = pulled.slots; session.slots[slotIndex] = null; const brewRow = { itemId: reserved.itemId, quantity: reserved.quantity, instance: reserved.instance ? structuredClone(reserved.instance) : (pulled.taken?.instance ? structuredClone(pulled.taken.instance) : null) }; const existing = session.brew.find((row) => row.itemId === brewRow.itemId && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null)); if (existing) { existing.quantity += brewRow.quantity; } else { session.brew.push(brewRow); } session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId }); session.lastSuccessRecipe = null; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) }; } function action (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); const kind = command.action; if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool) { throw userError("Unknown cauldron action."); } if (!session.steps.some((step) => step.kind === AlchemyStepKind.insert)) { throw userError("Insert an ingredient first."); } session.steps.push({ kind }); session.lastSuccessRecipe = null; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) }; } function bottle (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); if (!(session.brew?.length > 0) && !(session.steps?.length > 0)) { throw userError("The cauldron is empty."); } const inventory = ensureInventory(world, handle); const skills = world.ecs.get(handle, Component.skills) ?? {}; const evaluation = evaluateAlchemyBottle({ skills, brewStacks: session.brew, takenSteps: session.steps, potions: resolvedAlchemyPotions() }); const wanted = Math.max(1, evaluation.batch | 0); const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle); const produced = Math.min(wanted, bottles); if (produced <= 0) { throw userError("You need glass bottles to bottle the brew."); } const takeBottles = takeMatchingFromSlots(inventory.slots, { itemId: ItemId.glassBottle, quantity: produced, compact: false }); if (!takeBottles.ok) { throw userError("You need glass bottles to bottle the brew."); } inventory.slots = takeBottles.slots; const instance = potionItemInstance(evaluation.result); const potionDef = itemDefinition(ItemId.potion); const origin = craftOrigin(CraftOriginVerb.brewed, characterDisplayName(world, handle)); const inserted = insertStack(inventory.slots, attachOrigins({ itemId: ItemId.potion, quantity: produced, instance, origins: [{ origin, quantity: produced }] }), potionDef); if (!inserted.ok) { const refund = insertStack(inventory.slots, { itemId: ItemId.glassBottle, quantity: produced }, itemDefinition(ItemId.glassBottle)); inventory.slots = refund.ok ? refund.slots : inventory.slots; throw userError("Not enough inventory space for potions."); } inventory.slots = inserted.slots; session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null; clearAlchemy(session); return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session), alchemyResult: { success: !!evaluation.success, reason: evaluation.reason ?? null, produced, wanted, lost: Math.max(0, wanted - produced), potion: { potionKey: instance.potionKey, displayName: instance.displayName, unstable: instance.unstable, color: instance.color, fillLevel: instance.fillLevel } } }; } function createDye (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); const rows = (session.dyeSlots ?? []).filter((slot) => slot?.itemId === ItemId.flower); if (!rows.length) { throw userError("Add flowers to make dye."); } const mixed = mixFlowersForDye(rows); if (!mixed.ok) { throw userError(mixed.reason); } const wanted = mixed.quantity; const inventory = ensureInventory(world, handle); const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle); if (bottles < wanted && !command.confirmOverflow) { return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session), dyeConfirm: { wanted, bottles, lost: Math.max(0, wanted - bottles) } }; } const produced = Math.min(wanted, bottles); if (produced <= 0) { throw userError("You need glass bottles to bottle the dye."); } for (const row of rows) { const pulled = takeMatchingFromSlots(inventory.slots, { itemId: ItemId.flower, quantity: row.quantity, instance: row.instance, compact: false }); if (!pulled.ok) { throw userError("Not enough of those flowers in your inventory."); } inventory.slots = pulled.slots; } const takeBottles = takeMatchingFromSlots(inventory.slots, { itemId: ItemId.glassBottle, quantity: produced, compact: false }); if (!takeBottles.ok) { throw userError("You need glass bottles to bottle the dye."); } inventory.slots = takeBottles.slots; const dyeDef = itemDefinition(ItemId.dye); const origin = craftOrigin(CraftOriginVerb.mixed, characterDisplayName(world, handle)); const inserted = insertStack(inventory.slots, attachOrigins({ itemId: ItemId.dye, quantity: produced, instance: mixed.instance, origins: [{ origin, quantity: produced }] }), dyeDef); if (!inserted.ok) { throw userError("Not enough inventory space for dye."); } inventory.slots = inserted.slots; clearDyeSlots(session); return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session), alchemyResult: { success: true, reason: null, produced, wanted, lost: Math.max(0, wanted - produced), potion: { potionKey: "dye", displayName: "Dye", unstable: false, color: mixed.instance?.color ?? null, fillLevel: mixed.instance?.fillLevel ?? DEFAULT_DYE_FILL } } }; } function clear (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); clearAlchemy(session); session.lastSuccessRecipe = null; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) }; } function clearDye (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); clearDyeSlots(session); return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) }; } function saveRecipe (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); const recipe = session.lastSuccessRecipe; if (!recipe) { throw userError("No successful recipe to save."); } const inventory = ensureInventory(world, handle); const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper); if (paperIndex < 0) { throw userError("You need paper to write a recipe."); } const paperSlot = inventory.slots[paperIndex]; const recipeStack = { itemId: ItemId.recipePaper, quantity: 1, instance: { kind: "recipe-paper", recipeId: randomUUID(), potionKey: recipe.potionKey, displayName: `${recipe.displayName} recipe`, minAlchemyLevel: recipe.minAlchemyLevel ?? 1, body: recipePaperBody(recipe), writtenAt: Date.now() } }; if (stackQuantity(paperSlot.quantity) <= 1) { inventory.slots[paperIndex] = recipeStack; } else { const free = inventory.slots.findIndex((entry) => !entry); if (free < 0) { throw userError("Need a free inventory slot for the recipe paper."); } paperSlot.quantity -= 1; inventory.slots[free] = recipeStack; } session.lastSuccessRecipe = null; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) }; } function countMatchingInstance (slots, itemId, instance) { let total = 0; const key = JSON.stringify(instance ?? null); for (const slot of slots ?? []) { if (!slot || slot.itemId !== itemId) { continue; } if (JSON.stringify(slot.instance ?? null) !== key) { continue; } total += stackQuantity(slot.quantity); } return total; }