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 { SkillId } from "../../../shared/definitions/skills.js"; import { evaluateAlchemyBottle, potionItemInstance, recipePaperBody, resolvedAlchemyPotions, cauldronFlavorText } from "../../../shared/alchemy/recipes.js"; import { DEFAULT_DYE_FILL, FLOWER_MAX_STACK, 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, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js"; import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js"; import { craftXpForConsumedInputs } from "../../../shared/definitions/gathering.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 UI slot contents live on the client only. * Server sessions track brew *steps* and soft ingredient claims (itemId/qty/instance) * without removing items from the bag until bottle / create-dye succeeds. */ 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 { /** Soft claims for alchemy inserts — still in the bag until bottle. */ pendingBrew: [], steps: [], lastSuccessRecipe: null }; } function sessionView (session) { const steps = session.steps ?? []; return { // Slots / dye slots are client-only; never authoritative on the server. slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null), dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null), brew: (session.pendingBrew ?? []).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), /** Top ingredient slots lock after the first brew step until Bottle/Clear. */ canAddIngredients: steps.length === 0, 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 session; } function clearAlchemy (session) { session.pendingBrew = []; session.steps = []; } 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; } 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; } function pendingClaimedQuantity (pendingBrew, itemId, instance) { const key = JSON.stringify(instance ?? null); let total = 0; for (const row of pendingBrew ?? []) { if (row.itemId !== itemId) { continue; } if (JSON.stringify(row.instance ?? null) !== key) { continue; } total += row.quantity | 0; } return total; } function addPendingBrew (session, brewRow) { const existing = session.pendingBrew.find((row) => row.itemId === brewRow.itemId && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null)); if (existing) { existing.quantity += brewRow.quantity; } else { session.pendingBrew.push(brewRow); } } function refundStacks (inventory, rows) { for (const row of rows ?? []) { const def = itemDefinition(row.itemId); const refund = insertStack(inventory.slots, attachOrigins({ itemId: row.itemId, quantity: row.quantity, instance: row.instance ? structuredClone(row.instance) : null, origins: row.origins ?? normalizeOrigins(row) }), def); if (refund.ok) { inventory.slots = refund.slots; } } } export function handleAlchemyCommand (world, sessionId, command) { switch (command.type) { case "open-cauldron": return openCauldron(world, sessionId, command); case "cauldron-set-slot": case "cauldron-set-dye-slot": // Slot UI is client-only; ignore mutations, echo session for sync. return echoSession(world, sessionId, command); case "cauldron-insert": return insertIngredient(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 echoSession (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) }; } 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 = sessions.get(command.characterId) ?? emptySession(); if (!Array.isArray(existing.pendingBrew)) { existing.pendingBrew = []; } if (!Array.isArray(existing.steps)) { existing.steps = []; } 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); // Soft claims only — bag never held station items. ensureSessions(world).delete(command.characterId); return { events: [], private: bagView(world.ecs, handle), cauldron: false }; } function insertIngredient (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); const itemId = command.itemId | 0; const quantity = Math.max(0, command.quantity | 0); if (!itemId || quantity <= 0) { throw userError("Nothing to insert."); } 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 instance = command.instance ? structuredClone(command.instance) : null; const inventory = ensureInventory(world, handle); const have = instance ? countMatchingInstance(inventory.slots, itemId, instance) : countItemInSlots(inventory.slots, itemId); const alreadyClaimed = pendingClaimedQuantity(session.pendingBrew, itemId, instance); if (have < alreadyClaimed + quantity) { throw userError("Not enough of that item in your inventory."); } const uniqueIds = new Set((session.pendingBrew ?? []).map((row) => row.itemId | 0)); if (!uniqueIds.has(itemId) && uniqueIds.size >= CAULDRON_SLOT_COUNT) { throw userError( `A brew can use at most ${CAULDRON_SLOT_COUNT} different ingredients.` ); } addPendingBrew(session, { itemId, quantity, instance }); session.steps.push({ kind: AlchemyStepKind.insert, 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, entityId } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); if (!(session.pendingBrew?.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.pendingBrew, 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."); } for (const row of session.pendingBrew ?? []) { const have = row.instance ? countMatchingInstance(inventory.slots, row.itemId, row.instance) : countItemInSlots(inventory.slots, row.itemId); if (have < (row.quantity | 0)) { throw userError("Not enough of that item in your inventory."); } } // Consume soft-claimed ingredients only now (success path). const consumed = []; for (const row of session.pendingBrew ?? []) { const pulled = takeMatchingFromSlots(inventory.slots, { itemId: row.itemId, quantity: row.quantity, instance: row.instance ?? null, compact: false }); if (!pulled.ok) { refundStacks(inventory, consumed); throw userError("Not enough of that item in your inventory."); } inventory.slots = pulled.slots; consumed.push(pulled.taken); } const takeBottles = takeMatchingFromSlots(inventory.slots, { itemId: ItemId.glassBottle, quantity: produced, compact: false }); if (!takeBottles.ok) { refundStacks(inventory, consumed); 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) { refundStacks(inventory, consumed); refundStacks(inventory, [takeBottles.taken]); throw userError("Not enough inventory space for potions."); } inventory.slots = inserted.slots; session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null; clearAlchemy(session); const events = []; if (evaluation.success && skills?.xp) { const xpInputs = (consumed ?? []).map((row) => ({ itemId: row.itemId, quantity: row.quantity })); const amount = craftXpForConsumedInputs(xpInputs); if (amount > 0) { const result = applySkillXp(skills, SkillId.alchemy, amount); if (result.changed) { events.push({ type: "skills-updated", entityId, characterId: command.characterId, skills: publicSkillsView(skills), stored: storedSkillXp(skills), levelUps: result.levelUp ? [result.levelUp] : [] }); } } } 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, entityId } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); requireSession(world, command.characterId); const rows = normalizeFlowerRows(command.flowers); 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(requireSession(world, command.characterId)), 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 have = countMatchingInstance(inventory.slots, ItemId.flower, row.instance); if (have < row.quantity) { throw userError("Not enough of those flowers in your inventory."); } } 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; const events = []; const skills = world.ecs.get(handle, Component.skills); const flowerCount = rows.reduce((sum, row) => sum + (row.quantity | 0), 0); if (skills?.xp && flowerCount > 0) { const result = applySkillXp(skills, SkillId.alchemy, flowerCount); if (result.changed) { events.push({ type: "skills-updated", entityId, characterId: command.characterId, skills: publicSkillsView(skills), stored: storedSkillXp(skills), levelUps: result.levelUp ? [result.levelUp] : [] }); } } return { events, private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(requireSession(world, command.characterId)), 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 normalizeFlowerRows (flowers) { if (!Array.isArray(flowers)) { return []; } const rows = []; for (const entry of flowers) { const itemId = entry?.itemId | 0; const quantity = Math.min(FLOWER_MAX_STACK, Math.max(0, entry?.quantity | 0)); if (itemId !== ItemId.flower || quantity <= 0) { continue; } const instance = entry.instance ? structuredClone(entry.instance) : null; if (!instance?.color) { continue; } rows.push({ itemId: ItemId.flower, quantity, instance }); } return rows; } 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); // Dye slots are client-only; nothing to clear server-side. 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 = attachOrigins({ itemId: ItemId.recipePaper, quantity: 1, origins: [{ origin: writtenOrigin(characterDisplayName(world, handle)), quantity: 1 }], instance: { kind: "recipe-paper", recipeId: randomUUID(), potionKey: recipe.potionKey, displayName: `${recipe.displayName} Recipe`, authorCharacterId: command.characterId, authorDisplayName: characterDisplayName(world, handle), 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) }; }