BlueGit

timfa questward

Files

questward / server / src / alchemy / service.js

service.js

service.js 18.5 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 {
10 evaluateAlchemyBottle,
11 potionItemInstance,
12 recipePaperBody,
13 resolvedAlchemyPotions,
14 cauldronFlavorText
15} from "../../../shared/alchemy/recipes.js";
16import {
17 DEFAULT_DYE_FILL,
18 mixFlowersForDye
19} from "../../../shared/definitions/dyes.js";
20import { bagView } from "../items/bags.js";
21import {
22 countItemInSlots,
23 emptySlots,
24 insertStack,
25 normalizeInventorySlots,
26 takeMatchingFromSlots,
27 stackQuantity
28} from "../../../shared/items/inventory.js";
29import { attachOrigins, craftOrigin, CraftOriginVerb } from "../../../shared/items/origin.js";
30import { tileToChunk, tileToLocal } from "../world/coordinates.js";
31import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
32import { randomUUID } from "node:crypto";
33import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
34
35/**
36 * Cauldron UI slot contents live on the client only.
37 * Server sessions track brew *steps* and soft ingredient claims (itemId/qty/instance)
38 * without removing items from the bag until bottle / create-dye succeeds.
39 */
40
41function userError (message)
42{
43 const error = new Error(message);
44 error.userFacing = true;
45 return error;
46}
47
48function characterDisplayName (world, handle)
49{
50 const appearance = world.ecs.get(handle, Component.appearance);
51 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
52 return name || "someone";
53}
54
55function ensureSessions (world)
56{
57 if (!world.cauldronSessions)
58 { world.cauldronSessions = new Map(); }
59 return world.cauldronSessions;
60}
61
62function emptySession ()
63{
64 return {
65 /** Soft claims for alchemy inserts — still in the bag until bottle. */
66 pendingBrew: [],
67 steps: [],
68 lastSuccessRecipe: null
69 };
70}
71
72function sessionView (session)
73{
74 const steps = session.steps ?? [];
75 return {
76 // Slots / dye slots are client-only; never authoritative on the server.
77 slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
78 dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null),
79 brew: (session.pendingBrew ?? []).map((row) => ({
80 itemId: row.itemId,
81 quantity: row.quantity | 0,
82 instance: row.instance ? structuredClone(row.instance) : null
83 })),
84 steps: steps.map((step) => ({ ...step })),
85 flavorText: cauldronFlavorText(steps),
86 canProcessActions: steps.some((step) => step.kind === AlchemyStepKind.insert),
87 canSaveRecipe: !!session.lastSuccessRecipe,
88 lastSuccess: session.lastSuccessRecipe
89 ? {
90 potionKey: session.lastSuccessRecipe.potionKey,
91 displayName: session.lastSuccessRecipe.displayName,
92 minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1
93 }
94 : null
95 };
96}
97
98function nearCauldron (world, tileX, tileY)
99{
100 for (let dy = -1; dy <= 1; dy++)
101 {
102 for (let dx = -1; dx <= 1; dx++)
103 {
104 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
105 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
106 if (data.blocks[index]?.typeId === BlockType.cauldron)
107 { return true; }
108 }
109 }
110 return false;
111}
112
113function requireNearCauldron (world, handle)
114{
115 const position = world.ecs.get(handle, Component.position);
116 if (!nearCauldron(world, position.tileX, position.tileY))
117 { throw userError("Stand next to a cauldron."); }
118}
119
120function requireSession (world, characterId)
121{
122 const session = ensureSessions(world).get(characterId);
123 if (!session)
124 { throw userError("Open a cauldron first."); }
125 return session;
126}
127
128function clearAlchemy (session)
129{
130 session.pendingBrew = [];
131 session.steps = [];
132}
133
134function ensureInventory (world, handle)
135{
136 let inventory = world.ecs.get(handle, Component.inventory);
137 if (!inventory)
138 { inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
139 inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
140 return inventory;
141}
142
143function countMatchingInstance (slots, itemId, instance)
144{
145 let total = 0;
146 const key = JSON.stringify(instance ?? null);
147 for (const slot of slots ?? [])
148 {
149 if (!slot || slot.itemId !== itemId)
150 { continue; }
151 if (JSON.stringify(slot.instance ?? null) !== key)
152 { continue; }
153 total += stackQuantity(slot.quantity);
154 }
155 return total;
156}
157
158function pendingClaimedQuantity (pendingBrew, itemId, instance)
159{
160 const key = JSON.stringify(instance ?? null);
161 let total = 0;
162 for (const row of pendingBrew ?? [])
163 {
164 if (row.itemId !== itemId)
165 { continue; }
166 if (JSON.stringify(row.instance ?? null) !== key)
167 { continue; }
168 total += row.quantity | 0;
169 }
170 return total;
171}
172
173function addPendingBrew (session, brewRow)
174{
175 const existing = session.pendingBrew.find((row) =>
176 row.itemId === brewRow.itemId
177 && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
178 if (existing)
179 { existing.quantity += brewRow.quantity; }
180 else
181 { session.pendingBrew.push(brewRow); }
182}
183
184function refundStacks (inventory, rows)
185{
186 for (const row of rows ?? [])
187 {
188 const def = itemDefinition(row.itemId);
189 const refund = insertStack(inventory.slots, {
190 itemId: row.itemId,
191 quantity: row.quantity,
192 instance: row.instance ? structuredClone(row.instance) : null
193 }, def);
194 if (refund.ok)
195 { inventory.slots = refund.slots; }
196 }
197}
198
199export function handleAlchemyCommand (world, sessionId, command)
200{
201 switch (command.type)
202 {
203 case "open-cauldron":
204 return openCauldron(world, sessionId, command);
205 case "cauldron-set-slot":
206 case "cauldron-set-dye-slot":
207 // Slot UI is client-only; ignore mutations, echo session for sync.
208 return echoSession(world, sessionId, command);
209 case "cauldron-insert":
210 return insertIngredient(world, sessionId, command);
211 case "cauldron-action":
212 return action(world, sessionId, command);
213 case "cauldron-bottle":
214 return bottle(world, sessionId, command);
215 case "cauldron-create-dye":
216 return createDye(world, sessionId, command);
217 case "cauldron-clear":
218 return clear(world, sessionId, command);
219 case "cauldron-clear-dye":
220 return clearDye(world, sessionId, command);
221 case "cauldron-save-recipe":
222 return saveRecipe(world, sessionId, command);
223 case "cauldron-close":
224 return closeCauldron(world, sessionId, command);
225 default:
226 return null;
227 }
228}
229
230function echoSession (world, sessionId, command)
231{
232 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
233 requireNearCauldron(world, handle);
234 const session = requireSession(world, command.characterId);
235 return {
236 events: [],
237 private: bagView(world.ecs, handle),
238 cauldron: true,
239 cauldronState: sessionView(session)
240 };
241}
242
243function openCauldron (world, sessionId, command)
244{
245 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
246 requireNearCauldron(world, handle);
247 const inventory = ensureInventory(world, handle);
248 if (countItemInSlots(inventory.slots, ItemId.glassBottle) < 1)
249 { throw userError("I don't have any empty bottles."); }
250
251 const sessions = ensureSessions(world);
252 const existing = sessions.get(command.characterId) ?? emptySession();
253 if (!Array.isArray(existing.pendingBrew))
254 { existing.pendingBrew = []; }
255 if (!Array.isArray(existing.steps))
256 { existing.steps = []; }
257 sessions.set(command.characterId, existing);
258 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
259 return {
260 events: shove ? [shove] : [],
261 private: bagView(world.ecs, handle),
262 cauldron: true,
263 cauldronState: sessionView(existing)
264 };
265}
266
267function closeCauldron (world, sessionId, command)
268{
269 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
270 // Soft claims only — bag never held station items.
271 ensureSessions(world).delete(command.characterId);
272 return { events: [], private: bagView(world.ecs, handle), cauldron: false };
273}
274
275function insertIngredient (world, sessionId, command)
276{
277 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
278 requireNearCauldron(world, handle);
279 const session = requireSession(world, command.characterId);
280
281 const itemId = command.itemId | 0;
282 const quantity = Math.max(0, command.quantity | 0);
283 if (!itemId || quantity <= 0)
284 { throw userError("Nothing to insert."); }
285
286 const def = itemDefinition(itemId);
287 if (!def || def.uniqueInstance || def.equipment
288 || itemId === ItemId.potion || itemId === ItemId.glassBottle
289 || itemId === ItemId.flower || itemId === ItemId.dye || def.flower || def.dye)
290 { throw userError("Use the Dyes tab for flowers."); }
291
292 const instance = command.instance ? structuredClone(command.instance) : null;
293 const inventory = ensureInventory(world, handle);
294 const have = instance
295 ? countMatchingInstance(inventory.slots, itemId, instance)
296 : countItemInSlots(inventory.slots, itemId);
297 const alreadyClaimed = pendingClaimedQuantity(session.pendingBrew, itemId, instance);
298 if (have < alreadyClaimed + quantity)
299 { throw userError("Not enough of that item in your inventory."); }
300
301 addPendingBrew(session, { itemId, quantity, instance });
302 session.steps.push({ kind: AlchemyStepKind.insert, itemId });
303 session.lastSuccessRecipe = null;
304
305 return {
306 events: [],
307 private: bagView(world.ecs, handle),
308 cauldron: true,
309 cauldronState: sessionView(session)
310 };
311}
312
313function action (world, sessionId, command)
314{
315 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
316 requireNearCauldron(world, handle);
317 const session = requireSession(world, command.characterId);
318 const kind = command.action;
319 if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool)
320 { throw userError("Unknown cauldron action."); }
321 if (!session.steps.some((step) => step.kind === AlchemyStepKind.insert))
322 { throw userError("Insert an ingredient first."); }
323 session.steps.push({ kind });
324 session.lastSuccessRecipe = null;
325 return {
326 events: [],
327 private: bagView(world.ecs, handle),
328 cauldron: true,
329 cauldronState: sessionView(session)
330 };
331}
332
333function bottle (world, sessionId, command)
334{
335 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
336 requireNearCauldron(world, handle);
337 const session = requireSession(world, command.characterId);
338 if (!(session.pendingBrew?.length > 0) && !(session.steps?.length > 0))
339 { throw userError("The cauldron is empty."); }
340
341 const inventory = ensureInventory(world, handle);
342 const skills = world.ecs.get(handle, Component.skills) ?? {};
343
344 const evaluation = evaluateAlchemyBottle({
345 skills,
346 brewStacks: session.pendingBrew,
347 takenSteps: session.steps,
348 potions: resolvedAlchemyPotions()
349 });
350
351 const wanted = Math.max(1, evaluation.batch | 0);
352 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
353 const produced = Math.min(wanted, bottles);
354 if (produced <= 0)
355 { throw userError("You need glass bottles to bottle the brew."); }
356
357 for (const row of session.pendingBrew ?? [])
358 {
359 const have = row.instance
360 ? countMatchingInstance(inventory.slots, row.itemId, row.instance)
361 : countItemInSlots(inventory.slots, row.itemId);
362 if (have < (row.quantity | 0))
363 { throw userError("Not enough of that item in your inventory."); }
364 }
365
366 // Consume soft-claimed ingredients only now (success path).
367 for (const row of session.pendingBrew ?? [])
368 {
369 const pulled = takeMatchingFromSlots(inventory.slots, {
370 itemId: row.itemId,
371 quantity: row.quantity,
372 instance: row.instance ?? null,
373 compact: false
374 });
375 if (!pulled.ok)
376 { throw userError("Not enough of that item in your inventory."); }
377 inventory.slots = pulled.slots;
378 }
379
380 const takeBottles = takeMatchingFromSlots(inventory.slots, {
381 itemId: ItemId.glassBottle,
382 quantity: produced,
383 compact: false
384 });
385 if (!takeBottles.ok)
386 {
387 refundStacks(inventory, session.pendingBrew);
388 throw userError("You need glass bottles to bottle the brew.");
389 }
390 inventory.slots = takeBottles.slots;
391
392 const instance = potionItemInstance(evaluation.result);
393 const potionDef = itemDefinition(ItemId.potion);
394 const origin = craftOrigin(CraftOriginVerb.brewed, characterDisplayName(world, handle));
395 const inserted = insertStack(inventory.slots, attachOrigins({
396 itemId: ItemId.potion,
397 quantity: produced,
398 instance,
399 origins: [{ origin, quantity: produced }]
400 }), potionDef);
401 if (!inserted.ok)
402 {
403 refundStacks(inventory, session.pendingBrew);
404 const refundBottles = insertStack(inventory.slots, {
405 itemId: ItemId.glassBottle,
406 quantity: produced
407 }, itemDefinition(ItemId.glassBottle));
408 inventory.slots = refundBottles.ok ? refundBottles.slots : inventory.slots;
409 throw userError("Not enough inventory space for potions.");
410 }
411 inventory.slots = inserted.slots;
412
413 session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
414 clearAlchemy(session);
415
416 return {
417 events: [],
418 private: bagView(world.ecs, handle),
419 cauldron: true,
420 cauldronState: sessionView(session),
421 alchemyResult: {
422 success: !!evaluation.success,
423 reason: evaluation.reason ?? null,
424 produced,
425 wanted,
426 lost: Math.max(0, wanted - produced),
427 potion: {
428 potionKey: instance.potionKey,
429 displayName: instance.displayName,
430 unstable: instance.unstable,
431 color: instance.color,
432 fillLevel: instance.fillLevel
433 }
434 }
435 };
436}
437
438function createDye (world, sessionId, command)
439{
440 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
441 requireNearCauldron(world, handle);
442 requireSession(world, command.characterId);
443
444 const rows = normalizeFlowerRows(command.flowers);
445 if (!rows.length)
446 { throw userError("Add flowers to make dye."); }
447
448 const mixed = mixFlowersForDye(rows);
449 if (!mixed.ok)
450 { throw userError(mixed.reason); }
451
452 const wanted = mixed.quantity;
453 const inventory = ensureInventory(world, handle);
454 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
455 if (bottles < wanted && !command.confirmOverflow)
456 {
457 return {
458 events: [],
459 private: bagView(world.ecs, handle),
460 cauldron: true,
461 cauldronState: sessionView(requireSession(world, command.characterId)),
462 dyeConfirm: {
463 wanted,
464 bottles,
465 lost: Math.max(0, wanted - bottles)
466 }
467 };
468 }
469
470 const produced = Math.min(wanted, bottles);
471 if (produced <= 0)
472 { throw userError("You need glass bottles to bottle the dye."); }
473
474 for (const row of rows)
475 {
476 const have = countMatchingInstance(inventory.slots, ItemId.flower, row.instance);
477 if (have < row.quantity)
478 { throw userError("Not enough of those flowers in your inventory."); }
479 }
480
481 for (const row of rows)
482 {
483 const pulled = takeMatchingFromSlots(inventory.slots, {
484 itemId: ItemId.flower,
485 quantity: row.quantity,
486 instance: row.instance,
487 compact: false
488 });
489 if (!pulled.ok)
490 { throw userError("Not enough of those flowers in your inventory."); }
491 inventory.slots = pulled.slots;
492 }
493
494 const takeBottles = takeMatchingFromSlots(inventory.slots, {
495 itemId: ItemId.glassBottle,
496 quantity: produced,
497 compact: false
498 });
499 if (!takeBottles.ok)
500 { throw userError("You need glass bottles to bottle the dye."); }
501 inventory.slots = takeBottles.slots;
502
503 const dyeDef = itemDefinition(ItemId.dye);
504 const origin = craftOrigin(CraftOriginVerb.mixed, characterDisplayName(world, handle));
505 const inserted = insertStack(inventory.slots, attachOrigins({
506 itemId: ItemId.dye,
507 quantity: produced,
508 instance: mixed.instance,
509 origins: [{ origin, quantity: produced }]
510 }), dyeDef);
511 if (!inserted.ok)
512 { throw userError("Not enough inventory space for dye."); }
513 inventory.slots = inserted.slots;
514
515 return {
516 events: [],
517 private: bagView(world.ecs, handle),
518 cauldron: true,
519 cauldronState: sessionView(requireSession(world, command.characterId)),
520 alchemyResult: {
521 success: true,
522 reason: null,
523 produced,
524 wanted,
525 lost: Math.max(0, wanted - produced),
526 potion: {
527 potionKey: "dye",
528 displayName: "Dye",
529 unstable: false,
530 color: mixed.instance?.color ?? null,
531 fillLevel: mixed.instance?.fillLevel ?? DEFAULT_DYE_FILL
532 }
533 }
534 };
535}
536
537function normalizeFlowerRows (flowers)
538{
539 if (!Array.isArray(flowers))
540 { return []; }
541 const rows = [];
542 for (const entry of flowers)
543 {
544 const itemId = entry?.itemId | 0;
545 const quantity = Math.max(0, entry?.quantity | 0);
546 if (itemId !== ItemId.flower || quantity <= 0)
547 { continue; }
548 const instance = entry.instance ? structuredClone(entry.instance) : null;
549 if (!instance?.color)
550 { continue; }
551 rows.push({ itemId: ItemId.flower, quantity, instance });
552 }
553 return rows;
554}
555
556function clear (world, sessionId, command)
557{
558 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
559 requireNearCauldron(world, handle);
560 const session = requireSession(world, command.characterId);
561 clearAlchemy(session);
562 session.lastSuccessRecipe = null;
563 return {
564 events: [],
565 private: bagView(world.ecs, handle),
566 cauldron: true,
567 cauldronState: sessionView(session)
568 };
569}
570
571function clearDye (world, sessionId, command)
572{
573 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
574 requireNearCauldron(world, handle);
575 const session = requireSession(world, command.characterId);
576 // Dye slots are client-only; nothing to clear server-side.
577 return {
578 events: [],
579 private: bagView(world.ecs, handle),
580 cauldron: true,
581 cauldronState: sessionView(session)
582 };
583}
584
585function saveRecipe (world, sessionId, command)
586{
587 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
588 requireNearCauldron(world, handle);
589 const session = requireSession(world, command.characterId);
590 const recipe = session.lastSuccessRecipe;
591 if (!recipe)
592 { throw userError("No successful recipe to save."); }
593
594 const inventory = ensureInventory(world, handle);
595 const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper);
596 if (paperIndex < 0)
597 { throw userError("You need paper to write a recipe."); }
598 const paperSlot = inventory.slots[paperIndex];
599 const recipeStack = {
600 itemId: ItemId.recipePaper,
601 quantity: 1,
602 instance: {
603 kind: "recipe-paper",
604 recipeId: randomUUID(),
605 potionKey: recipe.potionKey,
606 displayName: `${recipe.displayName} Recipe`,
607 authorCharacterId: command.characterId,
608 authorDisplayName: characterDisplayName(world, handle),
609 minAlchemyLevel: recipe.minAlchemyLevel ?? 1,
610 body: recipePaperBody(recipe),
611 writtenAt: Date.now()
612 }
613 };
614
615 if (stackQuantity(paperSlot.quantity) <= 1)
616 { inventory.slots[paperIndex] = recipeStack; }
617 else
618 {
619 const free = inventory.slots.findIndex((entry) => !entry);
620 if (free < 0)
621 { throw userError("Need a free inventory slot for the recipe paper."); }
622 paperSlot.quantity -= 1;
623 inventory.slots[free] = recipeStack;
624 }
625
626 session.lastSuccessRecipe = null;
627 return {
628 events: [],
629 private: bagView(world.ecs, handle),
630 cauldron: true,
631 cauldronState: sessionView(session)
632 };
633}