BlueGit

timfa questward

Files

questward / server / src / alchemy / service.js

service.js

service.js 16.8 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "../../../shared/definitions/alchemy.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import {
6 evaluateAlchemyBottle,
7 potionItemInstance,
8 recipePaperBody,
9 resolvedAlchemyPotions
10} from "../../../shared/alchemy/recipes.js";
11import {
12 dyeItemInstance,
13 DEFAULT_DYE_FILL,
14 mixDyeBatches
15} from "../../../shared/definitions/dyes.js";
16import { bagView } from "../items/bags.js";
17import {
18 countItemInSlots,
19 emptySlots,
20 insertStack,
21 normalizeInventorySlots,
22 takeMatchingFromSlots,
23 stackQuantity
24} from "../../../shared/items/inventory.js";
25import { tileToChunk, tileToLocal } from "../world/coordinates.js";
26import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
27import { randomUUID } from "node:crypto";
28import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
29
30/**
31 * Cauldron sessions live on the worker world (per character while the UI is open).
32 * Clients send intents only; all brew outcomes are evaluated here.
33 */
34
35function userError (message)
36{
37 const error = new Error(message);
38 error.userFacing = true;
39 return error;
40}
41
42function ensureSessions (world)
43{
44 if (!world.cauldronSessions)
45 { world.cauldronSessions = new Map(); }
46 return world.cauldronSessions;
47}
48
49function emptySession ()
50{
51 return {
52 slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
53 brew: [],
54 steps: [],
55 lastSuccessRecipe: null
56 };
57}
58
59function sessionView (session)
60{
61 return {
62 slots: (session.slots ?? []).map((slot) => (slot
63 ? { itemId: slot.itemId, quantity: slot.quantity | 0 }
64 : null)),
65 brew: (session.brew ?? []).map((row) => ({ itemId: row.itemId, quantity: row.quantity | 0 })),
66 steps: (session.steps ?? []).map((step) => ({ ...step })),
67 canSaveRecipe: !!session.lastSuccessRecipe,
68 lastSuccess: session.lastSuccessRecipe
69 ? {
70 potionKey: session.lastSuccessRecipe.potionKey,
71 displayName: session.lastSuccessRecipe.displayName,
72 minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1
73 }
74 : null
75 };
76}
77
78function nearCauldron (world, tileX, tileY)
79{
80 for (let dy = -1; dy <= 1; dy++)
81 {
82 for (let dx = -1; dx <= 1; dx++)
83 {
84 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
85 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
86 if (data.blocks[index]?.typeId === BlockType.cauldron)
87 { return true; }
88 }
89 }
90 return false;
91}
92
93function requireNearCauldron (world, handle)
94{
95 const position = world.ecs.get(handle, Component.position);
96 if (!nearCauldron(world, position.tileX, position.tileY))
97 { throw userError("Stand next to a cauldron."); }
98}
99
100function requireSession (world, characterId)
101{
102 const session = ensureSessions(world).get(characterId);
103 if (!session)
104 { throw userError("Open a cauldron first."); }
105 return session;
106}
107
108function clearBrew (session)
109{
110 session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);
111 session.brew = [];
112 session.steps = [];
113}
114
115function ensureInventory (world, handle)
116{
117 let inventory = world.ecs.get(handle, Component.inventory);
118 if (!inventory)
119 { inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
120 inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
121 return inventory;
122}
123
124export function handleAlchemyCommand (world, sessionId, command)
125{
126 switch (command.type)
127 {
128 case "open-cauldron":
129 return openCauldron(world, sessionId, command);
130 case "cauldron-set-slot":
131 return setSlot(world, sessionId, command);
132 case "cauldron-insert":
133 return insertFromSlot(world, sessionId, command);
134 case "cauldron-action":
135 return action(world, sessionId, command);
136 case "cauldron-bottle":
137 return bottle(world, sessionId, command);
138 case "cauldron-clear":
139 return clear(world, sessionId, command);
140 case "cauldron-save-recipe":
141 return saveRecipe(world, sessionId, command);
142 case "cauldron-close":
143 return closeCauldron(world, sessionId, command);
144 default:
145 return null;
146 }
147}
148
149function openCauldron (world, sessionId, command)
150{
151 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
152 requireNearCauldron(world, handle);
153 const sessions = ensureSessions(world);
154 const existing = sessions.get(command.characterId) ?? emptySession();
155 sessions.set(command.characterId, existing);
156 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
157 return {
158 events: shove ? [shove] : [],
159 private: bagView(world.ecs, handle),
160 cauldron: true,
161 cauldronState: sessionView(existing)
162 };
163}
164
165function closeCauldron (world, sessionId, command)
166{
167 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
168 ensureSessions(world).delete(command.characterId);
169 return { events: [], private: bagView(world.ecs, handle), cauldron: false };
170}
171
172function setSlot (world, sessionId, command)
173{
174 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
175 requireNearCauldron(world, handle);
176 const session = requireSession(world, command.characterId);
177 const slotIndex = command.slotIndex | 0;
178 if (slotIndex < 0 || slotIndex >= CAULDRON_SLOT_COUNT)
179 { throw userError("Invalid cauldron slot."); }
180
181 const itemId = command.itemId | 0;
182 const quantity = Math.max(0, command.quantity | 0);
183 if (!itemId || quantity <= 0)
184 {
185 session.slots[slotIndex] = null;
186 return {
187 events: [],
188 private: bagView(world.ecs, handle),
189 cauldron: true,
190 cauldronState: sessionView(session)
191 };
192 }
193
194 const def = itemDefinition(itemId);
195 if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle)
196 { throw userError("That cannot go in a cauldron slot."); }
197 if (itemId === ItemId.dye || itemId === ItemId.flower)
198 {
199 // Allowed — instances are captured on insert.
200 }
201 else if (def.dye || def.flower)
202 { /* ok */ }
203
204 const inventory = ensureInventory(world, handle);
205 let instance = null;
206 if (itemId === ItemId.flower || itemId === ItemId.dye)
207 {
208 const wanted = command.instance ? structuredClone(command.instance) : null;
209 if (wanted)
210 { instance = wanted; }
211 else
212 {
213 for (const slot of inventory.slots)
214 {
215 if (slot?.itemId === itemId && slot.instance)
216 {
217 instance = structuredClone(slot.instance);
218 break;
219 }
220 }
221 }
222 if (!instance && itemId === ItemId.flower)
223 { throw userError("That flower has no colour."); }
224 if (!instance && itemId === ItemId.dye)
225 { throw userError("That dye has no colour."); }
226 const have = countMatchingInstance(inventory.slots, itemId, instance);
227 if (have < quantity)
228 { throw userError("Not enough of that item in your inventory."); }
229 }
230 else
231 {
232 const have = countItemInSlots(inventory.slots, itemId);
233 if (have < quantity)
234 { throw userError("Not enough of that item in your inventory."); }
235 }
236
237 session.slots[slotIndex] = { itemId, quantity, instance };
238 return {
239 events: [],
240 private: bagView(world.ecs, handle),
241 cauldron: true,
242 cauldronState: sessionView(session)
243 };
244}
245
246function insertFromSlot (world, sessionId, command)
247{
248 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
249 requireNearCauldron(world, handle);
250 const session = requireSession(world, command.characterId);
251 const slotIndex = command.slotIndex | 0;
252 const reserved = session.slots[slotIndex];
253 if (!reserved)
254 { throw userError("That cauldron slot is empty."); }
255
256 const inventory = ensureInventory(world, handle);
257 const pulled = takeMatchingFromSlots(inventory.slots, {
258 itemId: reserved.itemId,
259 quantity: reserved.quantity,
260 instance: reserved.instance ?? null,
261 compact: false
262 });
263 if (!pulled.ok)
264 { throw userError("Not enough of that item in your inventory."); }
265 inventory.slots = pulled.slots;
266 session.slots[slotIndex] = null;
267
268 const brewRow = {
269 itemId: reserved.itemId,
270 quantity: reserved.quantity,
271 instance: reserved.instance
272 ? structuredClone(reserved.instance)
273 : (pulled.taken?.instance ? structuredClone(pulled.taken.instance) : null)
274 };
275
276 const existing = session.brew.find((row) =>
277 row.itemId === brewRow.itemId
278 && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
279 if (existing)
280 { existing.quantity += brewRow.quantity; }
281 else
282 { session.brew.push(brewRow); }
283
284 session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId });
285 session.lastSuccessRecipe = null;
286
287 return {
288 events: [],
289 private: bagView(world.ecs, handle),
290 cauldron: true,
291 cauldronState: sessionView(session)
292 };
293}
294
295function action (world, sessionId, command)
296{
297 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
298 requireNearCauldron(world, handle);
299 const session = requireSession(world, command.characterId);
300 const kind = command.action;
301 if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool)
302 { throw userError("Unknown cauldron action."); }
303 session.steps.push({ kind });
304 session.lastSuccessRecipe = null;
305 return {
306 events: [],
307 private: bagView(world.ecs, handle),
308 cauldron: true,
309 cauldronState: sessionView(session)
310 };
311}
312
313function bottle (world, sessionId, command)
314{
315 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
316 requireNearCauldron(world, handle);
317 const session = requireSession(world, command.characterId);
318 if (!(session.brew?.length > 0) && !(session.steps?.length > 0))
319 { throw userError("The cauldron is empty."); }
320
321 const inventory = ensureInventory(world, handle);
322 const dyePath = evaluateDyeBrew(session.brew);
323 if (dyePath)
324 {
325 if (!dyePath.ok)
326 { throw userError(dyePath.reason); }
327 return bottleDyeResult(world, handle, session, inventory, dyePath);
328 }
329
330 const skills = world.ecs.get(handle, Component.skills) ?? {};
331
332 const evaluation = evaluateAlchemyBottle({
333 skills,
334 brewStacks: session.brew,
335 takenSteps: session.steps,
336 potions: resolvedAlchemyPotions()
337 });
338
339 const wanted = Math.max(1, evaluation.batch | 0);
340 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
341 const produced = Math.min(wanted, bottles);
342 if (produced <= 0)
343 { throw userError("You need glass bottles to bottle the brew."); }
344
345 const takeBottles = takeMatchingFromSlots(inventory.slots, {
346 itemId: ItemId.glassBottle,
347 quantity: produced,
348 compact: false
349 });
350 if (!takeBottles.ok)
351 { throw userError("You need glass bottles to bottle the brew."); }
352 inventory.slots = takeBottles.slots;
353
354 const instance = potionItemInstance(evaluation.result);
355 const potionDef = itemDefinition(ItemId.potion);
356 const inserted = insertStack(inventory.slots, {
357 itemId: ItemId.potion,
358 quantity: produced,
359 instance
360 }, potionDef);
361 if (!inserted.ok)
362 {
363 const refund = insertStack(inventory.slots, {
364 itemId: ItemId.glassBottle,
365 quantity: produced
366 }, itemDefinition(ItemId.glassBottle));
367 inventory.slots = refund.ok ? refund.slots : inventory.slots;
368 throw userError("Not enough inventory space for potions.");
369 }
370 inventory.slots = inserted.slots;
371
372 session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
373 clearBrew(session);
374
375 return {
376 events: [],
377 private: bagView(world.ecs, handle),
378 cauldron: true,
379 cauldronState: sessionView(session),
380 alchemyResult: {
381 success: !!evaluation.success,
382 reason: evaluation.reason ?? null,
383 produced,
384 wanted,
385 lost: Math.max(0, wanted - produced),
386 potion: {
387 potionKey: instance.potionKey,
388 displayName: instance.displayName,
389 unstable: instance.unstable,
390 color: instance.color,
391 fillLevel: instance.fillLevel
392 }
393 }
394 };
395}
396
397/**
398 * @returns {null | { ok: false, reason: string } | { ok: true, mode: "flower"|"mix", ... }}
399 */
400function evaluateDyeBrew (brew)
401{
402 const rows = brew ?? [];
403 if (!rows.length)
404 { return null; }
405 const hasFlower = rows.some((row) => row.itemId === ItemId.flower);
406 const hasDye = rows.some((row) => row.itemId === ItemId.dye);
407 const hasOther = rows.some((row) => row.itemId !== ItemId.flower && row.itemId !== ItemId.dye);
408 if (!hasFlower && !hasDye)
409 { return null; }
410 if (hasOther)
411 { return { ok: false, reason: "Do not mix dyes or flowers with alchemy ingredients." }; }
412 if (hasFlower && hasDye)
413 { return { ok: false, reason: "Cannot mix flowers and dyes together." }; }
414
415 if (hasFlower)
416 {
417 const colors = new Set(rows.map((row) => row.instance?.colorId).filter(Boolean));
418 if (colors.size === 0)
419 { return { ok: false, reason: "Those flowers have no colour." }; }
420 if (colors.size > 1)
421 { return { ok: false, reason: "Use flowers of a single colour for dye." }; }
422 const sample = rows.find((row) => row.instance?.color);
423 const quantity = rows.reduce((sum, row) => sum + (row.quantity | 0), 0);
424 return {
425 ok: true,
426 mode: "flower",
427 quantity: Math.max(1, quantity),
428 instance: dyeItemInstance(sample.instance.color, DEFAULT_DYE_FILL, sample.instance.colorId)
429 };
430 }
431
432 const mixed = mixDyeBatches(rows);
433 if (!mixed.ok)
434 { return { ok: false, reason: mixed.reason }; }
435 return { ok: true, mode: "mix", ...mixed };
436}
437
438function bottleDyeResult (world, handle, session, inventory, dyePath)
439{
440 const outputs = dyePath.mode === "flower"
441 ? Array.from({ length: dyePath.quantity }, () => ({
442 quantity: 1,
443 instance: dyePath.instance
444 }))
445 : dyePath.outputs;
446
447 // Flowers need empty glass bottles. Dye remixes reuse the bottles already
448 // consumed into the brew; only overflow bottles need extra glass.
449 const bottleNeed = dyePath.mode === "flower"
450 ? outputs.length
451 : Math.max(0, dyePath.extraBottles | 0);
452 if (bottleNeed > 0)
453 {
454 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
455 if (bottles < bottleNeed)
456 {
457 throw userError(
458 `You need ${bottleNeed} glass bottle${bottleNeed === 1 ? "" : "s"}.`
459 );
460 }
461 const takeBottles = takeMatchingFromSlots(inventory.slots, {
462 itemId: ItemId.glassBottle,
463 quantity: bottleNeed,
464 compact: false
465 });
466 if (!takeBottles.ok)
467 { throw userError("You need glass bottles to bottle the dye."); }
468 inventory.slots = takeBottles.slots;
469 }
470
471 const dyeDef = itemDefinition(ItemId.dye);
472 let slots = inventory.slots;
473 for (const out of outputs)
474 {
475 const inserted = insertStack(slots, {
476 itemId: ItemId.dye,
477 quantity: out.quantity,
478 instance: out.instance
479 }, dyeDef);
480 if (!inserted.ok)
481 {
482 throw userError("Not enough inventory space for dye.");
483 }
484 slots = inserted.slots;
485 }
486 inventory.slots = slots;
487 session.lastSuccessRecipe = null;
488 clearBrew(session);
489
490 const sample = outputs[0]?.instance;
491 return {
492 events: [],
493 private: bagView(world.ecs, handle),
494 cauldron: true,
495 cauldronState: sessionView(session),
496 alchemyResult: {
497 success: true,
498 reason: null,
499 produced: outputs.length,
500 wanted: outputs.length,
501 lost: 0,
502 potion: {
503 potionKey: "dye",
504 displayName: "Dye",
505 unstable: false,
506 color: sample?.color ?? null,
507 fillLevel: sample?.fillLevel ?? DEFAULT_DYE_FILL
508 }
509 }
510 };
511}
512
513function clear (world, sessionId, command)
514{
515 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
516 requireNearCauldron(world, handle);
517 const session = requireSession(world, command.characterId);
518 clearBrew(session);
519 session.lastSuccessRecipe = null;
520 return {
521 events: [],
522 private: bagView(world.ecs, handle),
523 cauldron: true,
524 cauldronState: sessionView(session)
525 };
526}
527
528function saveRecipe (world, sessionId, command)
529{
530 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
531 requireNearCauldron(world, handle);
532 const session = requireSession(world, command.characterId);
533 const recipe = session.lastSuccessRecipe;
534 if (!recipe)
535 { throw userError("No successful recipe to save."); }
536
537 const inventory = ensureInventory(world, handle);
538 const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper);
539 if (paperIndex < 0)
540 { throw userError("You need a sheet of paper."); }
541
542 const paperSlot = inventory.slots[paperIndex];
543 const recipeStack = {
544 itemId: ItemId.recipePaper,
545 quantity: 1,
546 instance: {
547 kind: "recipe-paper",
548 recipeId: randomUUID(),
549 potionKey: recipe.potionKey,
550 displayName: `${recipe.displayName} recipe`,
551 minAlchemyLevel: recipe.minAlchemyLevel ?? 1,
552 body: recipePaperBody(recipe),
553 writtenAt: Date.now()
554 }
555 };
556
557 if (stackQuantity(paperSlot.quantity) <= 1)
558 { inventory.slots[paperIndex] = recipeStack; }
559 else
560 {
561 const free = inventory.slots.findIndex((entry) => !entry);
562 if (free < 0)
563 { throw userError("Need a free inventory slot for the recipe paper."); }
564 paperSlot.quantity -= 1;
565 inventory.slots[free] = recipeStack;
566 }
567
568 session.lastSuccessRecipe = null;
569 return {
570 events: [],
571 private: bagView(world.ecs, handle),
572 cauldron: true,
573 cauldronState: sessionView(session)
574 };
575}
576
577function countMatchingInstance (slots, itemId, instance)
578{
579 let total = 0;
580 const key = JSON.stringify(instance ?? null);
581 for (const slot of slots ?? [])
582 {
583 if (!slot || slot.itemId !== itemId)
584 { continue; }
585 if (JSON.stringify(slot.instance ?? null) !== key)
586 { continue; }
587 total += stackQuantity(slot.quantity);
588 }
589 return total;
590}