BlueGit

timfa questward

Files

questward / server / src / alchemy / service.js

service.js

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