BlueGit

timfa questward

Files

questward / server / src / alchemy / service.js

service.js

service.js 24.2 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import {
4 AlchemyStepKind,
5 CAULDRON_SLOT_COUNT,
6 DYE_CAULDRON_SLOT_COUNT
7} from "../../../shared/definitions/alchemy.js";
8import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
9import { SkillId } from "../../../shared/definitions/skills.js";
10import {
11 evaluateAlchemyBottle,
12 potionItemInstance,
13 recipePaperBody,
14 resolvedAlchemyPotions,
15 cauldronFlavorText
16} from "../../../shared/alchemy/recipes.js";
17import {
18 DEFAULT_DYE_FILL,
19 FLOWER_MAX_STACK,
20 mixFlowersForDye
21} from "../../../shared/definitions/dyes.js";
22import { bagView, addGroundItem, publicGroundItem } from "../items/bags.js";
23import {
24 countItemInSlots,
25 emptySlots,
26 insertStack,
27 normalizeInventorySlots,
28 takeMatchingFromSlots,
29 stackQuantity
30} from "../../../shared/items/inventory.js";
31import { isFullPotionBottle } from "../../../shared/items/charges.js";
32import { attachOrigins, craftOrigin, CraftOriginVerb, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
33import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
34import {
35 craftXpForConsumedInputs,
36 craftXpMultiplierForSkill
37} from "../../../shared/definitions/gathering.js";
38import { tileToChunk, tileToLocal } from "../world/coordinates.js";
39import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
40import { randomUUID } from "node:crypto";
41import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
42
43/**
44 * Cauldron UI slot contents live on the client only.
45 * Server sessions track brew *steps* and soft ingredient claims (itemId/qty/instance)
46 * without removing items from the bag until bottle / create-dye succeeds.
47 */
48
49function userError (message)
50{
51 const error = new Error(message);
52 error.userFacing = true;
53 return error;
54}
55
56function characterDisplayName (world, handle)
57{
58 const appearance = world.ecs.get(handle, Component.appearance);
59 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
60 return name || "someone";
61}
62
63function ensureSessions (world)
64{
65 if (!world.cauldronSessions)
66 { world.cauldronSessions = new Map(); }
67 return world.cauldronSessions;
68}
69
70function emptySession ()
71{
72 return {
73 /** Soft claims for alchemy inserts — still in the bag until bottle. */
74 pendingBrew: [],
75 steps: [],
76 lastSuccessRecipe: null
77 };
78}
79
80function sessionView (session)
81{
82 const steps = session.steps ?? [];
83 return {
84 // Slots / dye slots are client-only; never authoritative on the server.
85 slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
86 dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null),
87 brew: (session.pendingBrew ?? []).map((row) => ({
88 itemId: row.itemId,
89 quantity: row.quantity | 0,
90 instance: row.instance ? structuredClone(row.instance) : null
91 })),
92 steps: steps.map((step) => ({ ...step })),
93 flavorText: cauldronFlavorText(steps),
94 canProcessActions: steps.some((step) => step.kind === AlchemyStepKind.insert),
95 /** Top ingredient slots lock after the first brew step until Bottle/Clear. */
96 canAddIngredients: steps.length === 0,
97 canSaveRecipe: !!session.lastSuccessRecipe,
98 lastSuccess: session.lastSuccessRecipe
99 ? {
100 potionKey: session.lastSuccessRecipe.potionKey,
101 displayName: session.lastSuccessRecipe.displayName,
102 minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1
103 }
104 : null
105 };
106}
107
108function nearCauldron (world, tileX, tileY)
109{
110 for (let dy = -1; dy <= 1; dy++)
111 {
112 for (let dx = -1; dx <= 1; dx++)
113 {
114 if (dx === 0 && dy === 0)
115 { continue; }
116 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
117 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
118 if (data.blocks[index]?.typeId === BlockType.cauldron)
119 { return true; }
120 }
121 }
122 return false;
123}
124
125function requireNearCauldron (world, handle)
126{
127 const position = world.ecs.get(handle, Component.position);
128 if (!nearCauldron(world, position.tileX, position.tileY))
129 { throw userError("Stand next to a cauldron."); }
130}
131
132function requireSession (world, characterId)
133{
134 const session = ensureSessions(world).get(characterId);
135 if (!session)
136 { throw userError("Open a cauldron first."); }
137 return session;
138}
139
140function clearAlchemy (session)
141{
142 session.pendingBrew = [];
143 session.steps = [];
144}
145
146function ensureInventory (world, handle)
147{
148 let inventory = world.ecs.get(handle, Component.inventory);
149 if (!inventory)
150 { inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
151 inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
152 return inventory;
153}
154
155function countMatchingInstance (slots, itemId, instance)
156{
157 let total = 0;
158 const key = JSON.stringify(instance ?? null);
159 for (const slot of slots ?? [])
160 {
161 if (!slot || slot.itemId !== itemId)
162 { continue; }
163 if (JSON.stringify(slot.instance ?? null) !== key)
164 { continue; }
165 total += stackQuantity(slot.quantity);
166 }
167 return total;
168}
169
170function pendingClaimedQuantity (pendingBrew, itemId, instance)
171{
172 const key = JSON.stringify(instance ?? null);
173 let total = 0;
174 for (const row of pendingBrew ?? [])
175 {
176 if (row.itemId !== itemId)
177 { continue; }
178 if (JSON.stringify(row.instance ?? null) !== key)
179 { continue; }
180 total += row.quantity | 0;
181 }
182 return total;
183}
184
185function addPendingBrew (session, brewRow)
186{
187 const existing = session.pendingBrew.find((row) =>
188 row.itemId === brewRow.itemId
189 && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
190 if (existing)
191 { existing.quantity += brewRow.quantity; }
192 else
193 { session.pendingBrew.push(brewRow); }
194}
195
196function refundStacks (inventory, rows)
197{
198 for (const row of rows ?? [])
199 {
200 const def = itemDefinition(row.itemId);
201 const refund = insertStack(inventory.slots, attachOrigins({
202 itemId: row.itemId,
203 quantity: row.quantity,
204 instance: row.instance ? structuredClone(row.instance) : null,
205 origins: row.origins ?? normalizeOrigins(row)
206 }), def);
207 if (refund.ok)
208 { inventory.slots = refund.slots; }
209 }
210}
211
212export function handleAlchemyCommand (world, sessionId, command)
213{
214 switch (command.type)
215 {
216 case "open-cauldron":
217 return openCauldron(world, sessionId, command);
218 case "cauldron-set-slot":
219 case "cauldron-set-dye-slot":
220 // Slot UI is client-only; ignore mutations, echo session for sync.
221 return echoSession(world, sessionId, command);
222 case "cauldron-insert":
223 return insertIngredient(world, sessionId, command);
224 case "cauldron-action":
225 return action(world, sessionId, command);
226 case "cauldron-bottle":
227 return bottle(world, sessionId, command);
228 case "cauldron-create-dye":
229 return createDye(world, sessionId, command);
230 case "cauldron-clear":
231 return clear(world, sessionId, command);
232 case "cauldron-clear-dye":
233 return clearDye(world, sessionId, command);
234 case "cauldron-save-recipe":
235 return saveRecipe(world, sessionId, command);
236 case "cauldron-close":
237 return closeCauldron(world, sessionId, command);
238 default:
239 return null;
240 }
241}
242
243function echoSession (world, sessionId, command)
244{
245 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
246 requireNearCauldron(world, handle);
247 const session = requireSession(world, command.characterId);
248 return {
249 events: [],
250 private: bagView(world.ecs, handle),
251 cauldron: true,
252 cauldronState: sessionView(session)
253 };
254}
255
256function openCauldron (world, sessionId, command)
257{
258 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
259 requireNearCauldron(world, handle);
260 const inventory = ensureInventory(world, handle);
261 if (countItemInSlots(inventory.slots, ItemId.glassBottle) < 1)
262 { throw userError("I don't have any empty bottles."); }
263
264 const sessions = ensureSessions(world);
265 const existing = sessions.get(command.characterId) ?? emptySession();
266 if (!Array.isArray(existing.pendingBrew))
267 { existing.pendingBrew = []; }
268 if (!Array.isArray(existing.steps))
269 { existing.steps = []; }
270 sessions.set(command.characterId, existing);
271 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
272 return {
273 events: shove ? [shove] : [],
274 private: bagView(world.ecs, handle),
275 cauldron: true,
276 cauldronState: sessionView(existing)
277 };
278}
279
280function closeCauldron (world, sessionId, command)
281{
282 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
283 // Soft claims only — bag never held station items.
284 ensureSessions(world).delete(command.characterId);
285 return { events: [], private: bagView(world.ecs, handle), cauldron: false };
286}
287
288function insertIngredient (world, sessionId, command)
289{
290 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
291 requireNearCauldron(world, handle);
292 const session = requireSession(world, command.characterId);
293
294 const itemId = command.itemId | 0;
295 const quantity = Math.max(0, command.quantity | 0);
296 if (!itemId || quantity <= 0)
297 { throw userError("Nothing to insert."); }
298
299 const def = itemDefinition(itemId);
300 const instance = command.instance ? structuredClone(command.instance) : null;
301 const isPotion = itemId === ItemId.potion && instance?.kind === "potion";
302
303 if (!def || def.uniqueInstance || def.equipment
304 || itemId === ItemId.glassBottle
305 || itemId === ItemId.flower || itemId === ItemId.dye || def.flower || def.dye)
306 { throw userError("Use the Dyes tab for flowers."); }
307
308 if (itemId === ItemId.potion && !isPotion)
309 { throw userError("That is not a bottled brew."); }
310 if (isPotion)
311 {
312 if (!isFullPotionBottle({ itemId, instance }))
313 { throw userError("Only full bottles can be used as ingredients."); }
314 }
315
316 const inventory = ensureInventory(world, handle);
317 const have = instance
318 ? countMatchingInstance(inventory.slots, itemId, instance)
319 : countItemInSlots(inventory.slots, itemId);
320 const alreadyClaimed = pendingClaimedQuantity(session.pendingBrew, itemId, instance);
321 if (have < alreadyClaimed + quantity)
322 { throw userError("Not enough of that item in your inventory."); }
323
324 const uniqueKeys = new Set((session.pendingBrew ?? []).map((row) =>
325 {
326 if ((row.itemId | 0) === ItemId.potion && row.instance?.potionKey)
327 { return `potion:${row.instance.potionKey}`; }
328 return `item:${row.itemId | 0}`;
329 }));
330 const claimKey = isPotion
331 ? `potion:${instance.potionKey}`
332 : `item:${itemId}`;
333 if (!uniqueKeys.has(claimKey) && uniqueKeys.size >= CAULDRON_SLOT_COUNT)
334 {
335 throw userError(
336 `A brew can use at most ${CAULDRON_SLOT_COUNT} different ingredients.`
337 );
338 }
339
340 addPendingBrew(session, { itemId, quantity, instance });
341 session.steps.push({
342 kind: AlchemyStepKind.insert,
343 itemId,
344 ...(isPotion ? { potionKey: instance.potionKey } : {})
345 });
346 session.lastSuccessRecipe = null;
347
348 return {
349 events: [],
350 private: bagView(world.ecs, handle),
351 cauldron: true,
352 cauldronState: sessionView(session)
353 };
354}
355
356function action (world, sessionId, command)
357{
358 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
359 requireNearCauldron(world, handle);
360 const session = requireSession(world, command.characterId);
361 const kind = command.action;
362 if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool)
363 { throw userError("Unknown cauldron action."); }
364 if (!session.steps.some((step) => step.kind === AlchemyStepKind.insert))
365 { throw userError("Insert an ingredient first."); }
366 session.steps.push({ kind });
367 session.lastSuccessRecipe = null;
368 return {
369 events: [],
370 private: bagView(world.ecs, handle),
371 cauldron: true,
372 cauldronState: sessionView(session)
373 };
374}
375
376function grantEmptyGlassBottles (world, handle, characterId, quantity, events, now = Date.now())
377{
378 const want = Math.max(0, quantity | 0);
379 if (want <= 0)
380 { return; }
381 const inventory = ensureInventory(world, handle);
382 const bottleDef = itemDefinition(ItemId.glassBottle);
383 const inserted = insertStack(inventory.slots, {
384 itemId: ItemId.glassBottle,
385 quantity: want
386 }, bottleDef);
387 inventory.slots = inserted.slots;
388 const remainder = inserted.remainder | 0;
389 if (remainder <= 0)
390 { return; }
391 const position = world.ecs.get(handle, Component.position);
392 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
393 const item = {
394 groundItemId,
395 tileX: position.tileX,
396 tileY: position.tileY,
397 stack: { itemId: ItemId.glassBottle, quantity: remainder },
398 droppedAt: now,
399 expiresAt: now + (world.settings.groundItemDespawnDurationMs ?? 600_000),
400 source: "alchemy-overflow",
401 droppedByCharacterId: characterId
402 };
403 addGroundItem(world, item);
404 events.push({
405 type: "ground-item-appear",
406 ...publicGroundItem(item),
407 stack: item.stack,
408 droppedAt: item.droppedAt,
409 source: item.source,
410 droppedByCharacterId: item.droppedByCharacterId,
411 expiresAt: item.expiresAt
412 });
413 events.push({
414 type: "toast",
415 sessionId: null,
416 characterId,
417 message: "Glass bottle dropped on the ground"
418 });
419}
420
421function bottle (world, sessionId, command)
422{
423 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
424 requireNearCauldron(world, handle);
425 const session = requireSession(world, command.characterId);
426 if (!(session.pendingBrew?.length > 0) && !(session.steps?.length > 0))
427 { throw userError("The cauldron is empty."); }
428
429 const inventory = ensureInventory(world, handle);
430 const skills = world.ecs.get(handle, Component.skills) ?? {};
431
432 const evaluation = evaluateAlchemyBottle({
433 skills,
434 brewStacks: session.pendingBrew,
435 takenSteps: session.steps,
436 potions: resolvedAlchemyPotions()
437 });
438
439 const wanted = Math.max(1, evaluation.batch | 0);
440 const requiresEmptyBottles = evaluation.result?.requiresEmptyBottles !== false;
441 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
442 const produced = requiresEmptyBottles ? Math.min(wanted, bottles) : wanted;
443 if (requiresEmptyBottles && produced <= 0)
444 { throw userError("You need glass bottles to bottle the brew."); }
445
446 for (const row of session.pendingBrew ?? [])
447 {
448 if (row.itemId === ItemId.potion && row.instance?.kind === "potion"
449 && !isFullPotionBottle({ itemId: row.itemId, instance: row.instance }))
450 { throw userError("Only full bottles can be used as ingredients."); }
451 const have = row.instance
452 ? countMatchingInstance(inventory.slots, row.itemId, row.instance)
453 : countItemInSlots(inventory.slots, row.itemId);
454 if (have < (row.quantity | 0))
455 { throw userError("Not enough of that item in your inventory."); }
456 }
457
458 // Consume soft-claimed ingredients only now (success path).
459 const consumed = [];
460 for (const row of session.pendingBrew ?? [])
461 {
462 const pulled = takeMatchingFromSlots(inventory.slots, {
463 itemId: row.itemId,
464 quantity: row.quantity,
465 instance: row.instance ?? null,
466 compact: false
467 });
468 if (!pulled.ok)
469 {
470 refundStacks(inventory, consumed);
471 throw userError("Not enough of that item in your inventory.");
472 }
473 inventory.slots = pulled.slots;
474 consumed.push(pulled.taken);
475 }
476
477 let takeBottles = null;
478 if (requiresEmptyBottles)
479 {
480 takeBottles = takeMatchingFromSlots(inventory.slots, {
481 itemId: ItemId.glassBottle,
482 quantity: produced,
483 compact: false
484 });
485 if (!takeBottles.ok)
486 {
487 refundStacks(inventory, consumed);
488 throw userError("You need glass bottles to bottle the brew.");
489 }
490 inventory.slots = takeBottles.slots;
491 }
492
493 const origin = craftOrigin(CraftOriginVerb.brewed, characterDisplayName(world, handle));
494 const outputItemId = evaluation.result?.outputItemId | 0;
495 let alchemyPotionView = null;
496
497 if (outputItemId && evaluation.success)
498 {
499 const outQty = Math.max(1, (evaluation.result.outputQuantity | 0) || 1) * produced;
500 const outDef = itemDefinition(outputItemId);
501 const inserted = insertStack(inventory.slots, attachOrigins({
502 itemId: outputItemId,
503 quantity: outQty,
504 origins: [{ origin, quantity: outQty }]
505 }), outDef);
506 if (!inserted.ok)
507 {
508 refundStacks(inventory, consumed);
509 if (takeBottles)
510 { refundStacks(inventory, [takeBottles.taken]); }
511 throw userError("Not enough inventory space for the brew.");
512 }
513 inventory.slots = inserted.slots;
514 alchemyPotionView = {
515 potionKey: evaluation.result.potionKey,
516 displayName: evaluation.result.displayName,
517 unstable: false,
518 color: evaluation.result.color,
519 fillLevel: null
520 };
521 }
522 else
523 {
524 const instance = potionItemInstance(evaluation.result);
525 const potionDef = itemDefinition(ItemId.potion);
526 const inserted = insertStack(inventory.slots, attachOrigins({
527 itemId: ItemId.potion,
528 quantity: produced,
529 instance,
530 origins: [{ origin, quantity: produced }]
531 }), potionDef);
532 if (!inserted.ok)
533 {
534 refundStacks(inventory, consumed);
535 if (takeBottles)
536 { refundStacks(inventory, [takeBottles.taken]); }
537 throw userError("Not enough inventory space for potions.");
538 }
539 inventory.slots = inserted.slots;
540 alchemyPotionView = {
541 potionKey: instance.potionKey,
542 displayName: instance.displayName,
543 unstable: instance.unstable,
544 color: instance.color,
545 fillLevel: instance.fillLevel
546 };
547 }
548
549 session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
550 clearAlchemy(session);
551
552 const events = [];
553 let returnedBottles = 0;
554 for (const row of consumed)
555 {
556 if ((row.itemId | 0) === ItemId.potion)
557 { returnedBottles += stackQuantity(row.quantity); }
558 }
559 grantEmptyGlassBottles(world, handle, command.characterId, returnedBottles, events);
560
561 if (evaluation.success && skills?.xp)
562 {
563 const xpInputs = (consumed ?? []).map((row) => ({
564 itemId: row.itemId,
565 quantity: row.quantity
566 }));
567 const amount = craftXpForConsumedInputs(xpInputs, SkillId.alchemy);
568 if (amount > 0)
569 {
570 const result = applySkillXp(
571 skills,
572 SkillId.alchemy,
573 amount,
574 world.ecs.get(handle, Component.equipment)
575 );
576 if (result.changed)
577 {
578 events.push({
579 type: "skills-updated",
580 entityId,
581 characterId: command.characterId,
582 ...publicSkillsPayload(skills),
583 stored: storedSkillXp(skills),
584 levelUps: result.levelUp ? [result.levelUp] : []
585 });
586 }
587 }
588 }
589
590 return {
591 events,
592 private: bagView(world.ecs, handle),
593 cauldron: true,
594 cauldronState: sessionView(session),
595 alchemyResult: {
596 success: !!evaluation.success,
597 reason: evaluation.reason ?? null,
598 produced,
599 wanted,
600 lost: Math.max(0, wanted - produced),
601 potion: alchemyPotionView
602 }
603 };
604}
605
606function createDye (world, sessionId, command)
607{
608 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
609 requireNearCauldron(world, handle);
610 requireSession(world, command.characterId);
611
612 const rows = normalizeFlowerRows(command.flowers);
613 if (!rows.length)
614 { throw userError("Add flowers to make dye."); }
615
616 const mixed = mixFlowersForDye(rows);
617 if (!mixed.ok)
618 { throw userError(mixed.reason); }
619
620 const wanted = mixed.quantity;
621 const inventory = ensureInventory(world, handle);
622 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
623 if (bottles < wanted && !command.confirmOverflow)
624 {
625 return {
626 events: [],
627 private: bagView(world.ecs, handle),
628 cauldron: true,
629 cauldronState: sessionView(requireSession(world, command.characterId)),
630 dyeConfirm: {
631 wanted,
632 bottles,
633 lost: Math.max(0, wanted - bottles)
634 }
635 };
636 }
637
638 const produced = Math.min(wanted, bottles);
639 if (produced <= 0)
640 { throw userError("You need glass bottles to bottle the dye."); }
641
642 for (const row of rows)
643 {
644 const have = countMatchingInstance(inventory.slots, ItemId.flower, row.instance);
645 if (have < row.quantity)
646 { throw userError("Not enough of those flowers in your inventory."); }
647 }
648
649 for (const row of rows)
650 {
651 const pulled = takeMatchingFromSlots(inventory.slots, {
652 itemId: ItemId.flower,
653 quantity: row.quantity,
654 instance: row.instance,
655 compact: false
656 });
657 if (!pulled.ok)
658 { throw userError("Not enough of those flowers in your inventory."); }
659 inventory.slots = pulled.slots;
660 }
661
662 const takeBottles = takeMatchingFromSlots(inventory.slots, {
663 itemId: ItemId.glassBottle,
664 quantity: produced,
665 compact: false
666 });
667 if (!takeBottles.ok)
668 { throw userError("You need glass bottles to bottle the dye."); }
669 inventory.slots = takeBottles.slots;
670
671 const dyeDef = itemDefinition(ItemId.dye);
672 const origin = craftOrigin(CraftOriginVerb.mixed, characterDisplayName(world, handle));
673 const inserted = insertStack(inventory.slots, attachOrigins({
674 itemId: ItemId.dye,
675 quantity: produced,
676 instance: mixed.instance,
677 origins: [{ origin, quantity: produced }]
678 }), dyeDef);
679 if (!inserted.ok)
680 { throw userError("Not enough inventory space for dye."); }
681 inventory.slots = inserted.slots;
682
683 const events = [];
684 const skills = world.ecs.get(handle, Component.skills);
685 const flowerCount = rows.reduce((sum, row) => sum + (row.quantity | 0), 0);
686 if (skills?.xp && flowerCount > 0)
687 {
688 const result = applySkillXp(
689 skills,
690 SkillId.alchemy,
691 flowerCount * craftXpMultiplierForSkill(SkillId.alchemy),
692 world.ecs.get(handle, Component.equipment)
693 );
694 if (result.changed)
695 {
696 events.push({
697 type: "skills-updated",
698 entityId,
699 characterId: command.characterId,
700 ...publicSkillsPayload(skills),
701 stored: storedSkillXp(skills),
702 levelUps: result.levelUp ? [result.levelUp] : []
703 });
704 }
705 }
706
707 return {
708 events,
709 private: bagView(world.ecs, handle),
710 cauldron: true,
711 cauldronState: sessionView(requireSession(world, command.characterId)),
712 alchemyResult: {
713 success: true,
714 reason: null,
715 produced,
716 wanted,
717 lost: Math.max(0, wanted - produced),
718 potion: {
719 potionKey: "dye",
720 displayName: "Dye",
721 unstable: false,
722 color: mixed.instance?.color ?? null,
723 fillLevel: mixed.instance?.fillLevel ?? DEFAULT_DYE_FILL
724 }
725 }
726 };
727}
728
729function normalizeFlowerRows (flowers)
730{
731 if (!Array.isArray(flowers))
732 { return []; }
733 const rows = [];
734 for (const entry of flowers)
735 {
736 const itemId = entry?.itemId | 0;
737 const quantity = Math.min(FLOWER_MAX_STACK, Math.max(0, entry?.quantity | 0));
738 if (itemId !== ItemId.flower || quantity <= 0)
739 { continue; }
740 const instance = entry.instance ? structuredClone(entry.instance) : null;
741 if (!instance?.color)
742 { continue; }
743 rows.push({ itemId: ItemId.flower, quantity, instance });
744 }
745 return rows;
746}
747
748function clear (world, sessionId, command)
749{
750 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
751 requireNearCauldron(world, handle);
752 const session = requireSession(world, command.characterId);
753 clearAlchemy(session);
754 session.lastSuccessRecipe = null;
755 return {
756 events: [],
757 private: bagView(world.ecs, handle),
758 cauldron: true,
759 cauldronState: sessionView(session)
760 };
761}
762
763function clearDye (world, sessionId, command)
764{
765 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
766 requireNearCauldron(world, handle);
767 const session = requireSession(world, command.characterId);
768 // Dye slots are client-only; nothing to clear server-side.
769 return {
770 events: [],
771 private: bagView(world.ecs, handle),
772 cauldron: true,
773 cauldronState: sessionView(session)
774 };
775}
776
777function saveRecipe (world, sessionId, command)
778{
779 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
780 requireNearCauldron(world, handle);
781 const session = requireSession(world, command.characterId);
782 const recipe = session.lastSuccessRecipe;
783 if (!recipe)
784 { throw userError("No successful recipe to save."); }
785
786 const inventory = ensureInventory(world, handle);
787 const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper);
788 if (paperIndex < 0)
789 { throw userError("You need paper to write a recipe."); }
790 const paperSlot = inventory.slots[paperIndex];
791 const recipeStack = attachOrigins({
792 itemId: ItemId.recipePaper,
793 quantity: 1,
794 origins: [{
795 origin: writtenOrigin(characterDisplayName(world, handle)),
796 quantity: 1
797 }],
798 instance: {
799 kind: "recipe-paper",
800 recipeId: randomUUID(),
801 potionKey: recipe.potionKey,
802 displayName: `${recipe.displayName} recipe`,
803 authorCharacterId: command.characterId,
804 authorDisplayName: characterDisplayName(world, handle),
805 minAlchemyLevel: recipe.minAlchemyLevel ?? 1,
806 body: recipePaperBody(recipe),
807 writtenAt: Date.now()
808 }
809 });
810
811 if (stackQuantity(paperSlot.quantity) <= 1)
812 { inventory.slots[paperIndex] = recipeStack; }
813 else
814 {
815 const free = inventory.slots.findIndex((entry) => !entry);
816 if (free < 0)
817 { throw userError("Need a free inventory slot for the recipe paper."); }
818 paperSlot.quantity -= 1;
819 inventory.slots[free] = recipeStack;
820 }
821
822 session.lastSuccessRecipe = null;
823 return {
824 events: [],
825 private: bagView(world.ecs, handle),
826 cauldron: true,
827 cauldronState: sessionView(session)
828 };
829}