BlueGit

timfa questward

Files

questward / shared / items / inventory.js

inventory.js

inventory.js 19.8 KiB Download Raw
1export const INVENTORY_SLOTS = 32;
2export const EQUIPMENT_SLOTS = Object.freeze([
3 "head",
4 "chest",
5 "legs",
6 "boots",
7 "weapon",
8 "offhand",
9 "ring",
10 "bracelet",
11 "amulet"
12]);
13
14import { attachOrigins, mergeOriginLists, normalizeOrigins, splitOrigins } from "./origin.js";
15import { stackRulesFor } from "./stackRules.js";
16import { BLANK_CHEQUE_CARRY_CAP, ItemId, itemDefinition } from "../definitions/items.js";
17import { normalizeChargeStack } from "./charges.js";
18
19/** Stack counts can exceed 32-bit range (coin stacks up to 999B). */
20export function stackQuantity (value)
21{
22 const n = Number(value);
23 if (!Number.isFinite(n) || n <= 0)
24 { return 0; }
25 const q = Math.floor(n);
26 return Number.isSafeInteger(q) ? q : 0;
27}
28
29export function emptySlots (count = INVENTORY_SLOTS)
30{
31 return Array.from({ length: count }, () => null);
32}
33
34export function emptyEquipment ()
35{
36 const slots = {};
37 for (const slot of EQUIPMENT_SLOTS)
38 { slots[slot] = null; }
39 return { slots };
40}
41
42export function cloneStack (stack)
43{
44 return stack ? structuredClone(stack) : null;
45}
46
47/** One item from a stack, preserving a single origin slice (for equip). */
48export function singleItemFromStack (stack)
49{
50 if (!stack)
51 { return null; }
52 const split = splitOrigins(normalizeOrigins(stack), 1);
53 return {
54 itemId: stack.itemId,
55 quantity: 1,
56 instance: stack.instance ? cloneStack(stack.instance) : null,
57 origins: split.taken
58 };
59}
60
61export function potionStackIdentity (instance)
62{
63 if (!instance || instance.kind !== "potion")
64 { return null; }
65 const effectKey = instance.effectKey
66 ?? (instance.effect ? JSON.stringify(instance.effect) : "");
67 const fill = Math.max(1, Math.min(5, instance.fillLevel | 0 || 4));
68 return `${instance.potionKey ?? ""}|${effectKey}|${fill}`;
69}
70
71/** Dye stacks merge when RGB and remaining uses match exactly. */
72export function dyeStackIdentity (instance)
73{
74 if (!instance || instance.kind !== "dye" || !instance.color)
75 { return null; }
76 const fill = Math.max(1, Math.min(5, instance.fillLevel | 0 || 4));
77 return [
78 Math.round((instance.color.r ?? 0) * 1000),
79 Math.round((instance.color.g ?? 0) * 1000),
80 Math.round((instance.color.b ?? 0) * 1000),
81 fill
82 ].join(",");
83}
84
85export function stacksMatch (left, right, definition, { inVault = false } = {})
86{
87 if (!left || !right || left.itemId !== right.itemId)
88 { return false; }
89 const rules = stackRulesFor(definition, { inVault });
90 if (rules.uniqueInstance)
91 {
92 return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
93 }
94 if (definition?.potion)
95 {
96 const a = potionStackIdentity(left.instance);
97 const b = potionStackIdentity(right.instance);
98 return a != null && a === b;
99 }
100 if (definition?.dye)
101 {
102 const a = dyeStackIdentity(left.instance);
103 const b = dyeStackIdentity(right.instance);
104 return a != null && a === b;
105 }
106 if (left.instance != null || right.instance != null)
107 { return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null); }
108 return rules.stackable;
109}
110
111function stackPayload (stack, quantity, origins)
112{
113 return {
114 itemId: stack.itemId,
115 quantity,
116 instance: stack.instance ?? null,
117 origins: origins.map((entry) => ({
118 origin: entry.origin ?? null,
119 quantity: stackQuantity(entry.quantity)
120 })).filter((entry) => entry.quantity > 0)
121 };
122}
123
124export function insertStack (slots, stack, definition, options = {})
125{
126 if (!stack || stack.quantity <= 0)
127 { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; }
128 const rules = stackRulesFor(definition, options);
129 const next = slots.map(cloneStack);
130 let remaining = stackQuantity(stack.quantity);
131 let pendingOrigins = normalizeOrigins(stack);
132
133 if (rules.stackable && !rules.uniqueInstance)
134 {
135 for (const slot of next)
136 {
137 if (!slot || !stacksMatch(slot, stack, definition, options))
138 { continue; }
139 const space = rules.maxStackSize - stackQuantity(slot.quantity);
140 if (space <= 0)
141 { continue; }
142 const add = Math.min(space, remaining);
143 const split = splitOrigins(pendingOrigins, add);
144 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
145 slot.quantity = stackQuantity(slot.quantity) + add;
146 if (stack.instance != null && slot.instance == null)
147 { slot.instance = cloneStack(stack.instance); }
148 delete slot.origin;
149 pendingOrigins = split.remain;
150 remaining -= add;
151 if (remaining === 0)
152 { return { ok: true, slots: next, remainder: 0 }; }
153 }
154 }
155
156 for (let i = 0; i < next.length; i++)
157 {
158 if (next[i])
159 { continue; }
160 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
161 const amount = rules.stackable && !rules.uniqueInstance
162 ? Math.min(remaining, cap)
163 : 1;
164 const split = splitOrigins(pendingOrigins, amount);
165 next[i] = stackPayload(stack, amount, split.taken);
166 pendingOrigins = split.remain;
167 remaining -= amount;
168 if (remaining === 0)
169 { return { ok: true, slots: next, remainder: 0 }; }
170 if (!rules.stackable || rules.uniqueInstance)
171 { break; }
172 }
173 return { ok: false, slots, remainder: remaining };
174}
175
176export function takeFromSlot (slots, slotIndex, quantity = null)
177{
178 const next = slots.map(cloneStack);
179 const slot = next[slotIndex];
180 if (!slot)
181 { return { ok: false, slots, taken: null }; }
182 const maxQty = stackQuantity(slot.quantity);
183 const amount = quantity == null
184 ? maxQty
185 : Math.min(maxQty, Math.max(1, stackQuantity(quantity)));
186 if (amount <= 0)
187 { return { ok: false, slots, taken: null }; }
188 const split = splitOrigins(normalizeOrigins(slot), amount);
189 const taken = stackPayload(slot, amount, split.taken);
190 if (amount >= maxQty)
191 { next[slotIndex] = null; }
192 else
193 {
194 slot.quantity = maxQty - amount;
195 slot.origins = split.remain;
196 delete slot.origin;
197 }
198 return { ok: true, slots: next, taken };
199}
200
201/**
202 * Move or merge a bag stack from one slot into another (same bag).
203 * Empty target → move. Matching stackable → merge into target. Else → swap.
204 */
205export function moveInventorySlot (slots, fromIndex, toIndex)
206{
207 const next = (slots ?? emptySlots()).map(cloneStack);
208 const from = fromIndex | 0;
209 const to = toIndex | 0;
210 if (from === to)
211 { return { ok: true, slots: next, changed: false }; }
212 if (from < 0 || to < 0 || from >= next.length || to >= next.length)
213 { return { ok: false, slots, reason: "Invalid slot." }; }
214 const source = next[from];
215 if (!source || stackQuantity(source.quantity) <= 0)
216 { return { ok: false, slots, reason: "That inventory slot is empty." }; }
217
218 const dest = next[to];
219 if (!dest)
220 {
221 next[to] = source;
222 next[from] = null;
223 return { ok: true, slots: next, changed: true };
224 }
225
226 const def = itemDefinition(source.itemId);
227 if (stacksMatch(source, dest, def))
228 {
229 const rules = stackRulesFor(def);
230 if (rules.stackable && !rules.uniqueInstance)
231 {
232 const space = rules.maxStackSize === Number.POSITIVE_INFINITY
233 ? stackQuantity(source.quantity)
234 : Math.max(0, rules.maxStackSize - stackQuantity(dest.quantity));
235 if (space > 0)
236 {
237 const add = Math.min(space, stackQuantity(source.quantity));
238 const split = splitOrigins(normalizeOrigins(source), add);
239 dest.origins = mergeOriginLists(normalizeOrigins(dest), split.taken);
240 dest.quantity = stackQuantity(dest.quantity) + add;
241 if (source.instance != null && dest.instance == null)
242 { dest.instance = cloneStack(source.instance); }
243 delete dest.origin;
244 const remainQty = stackQuantity(source.quantity) - add;
245 if (remainQty <= 0)
246 { next[from] = null; }
247 else
248 {
249 source.quantity = remainQty;
250 source.origins = split.remain;
251 delete source.origin;
252 }
253 return { ok: true, slots: next, changed: true };
254 }
255 }
256 }
257
258 next[from] = dest;
259 next[to] = source;
260 return { ok: true, slots: next, changed: true };
261}
262
263/**
264 * Spend one fill charge from a potion/dye slot without losing the leftover bottle.
265 * Single bottles always mutate in place (or become an empty bottle). Multi-stacks
266 * peel one bottle and re-insert the reduced fill; tries both split orderings so a
267 * matching stack can absorb either side. Never mutates the input slots array.
268 *
269 * @returns {{ ok: true, slots, exhausted: boolean, instance: object } | { ok: false, reason: string }}
270 */
271export function consumeFillCharge (slots, slotIndex, {
272 kind = null,
273 itemId = null,
274 definition = null,
275 returnEmptyItemId = null
276} = {})
277{
278 const index = slotIndex | 0;
279 const source = slots?.[index];
280 if (!source || stackQuantity(source.quantity) <= 0)
281 { return { ok: false, reason: "empty" }; }
282 if (itemId != null && source.itemId !== itemId)
283 { return { ok: false, reason: "wrong-item" }; }
284 if (kind != null && source.instance?.kind !== kind)
285 { return { ok: false, reason: "wrong-item" }; }
286 const def = definition ?? itemDefinition(source.itemId);
287 if (!def)
288 { return { ok: false, reason: "unknown" }; }
289
290 const fill = Math.max(1, Math.min(5, source.instance?.fillLevel | 0 || 4));
291 const qty = stackQuantity(source.quantity);
292 const usedInstance = cloneStack(source.instance) ?? { kind, fillLevel: fill };
293
294 if (qty === 1)
295 {
296 const next = slots.map(cloneStack);
297 if (fill <= 1)
298 {
299 next[index] = null;
300 if (returnEmptyItemId)
301 {
302 const emptyDef = itemDefinition(returnEmptyItemId);
303 const emptyStack = attachOrigins({
304 itemId: returnEmptyItemId,
305 quantity: 1,
306 origins: normalizeOrigins(source)
307 });
308 const inserted = insertStack(next, emptyStack, emptyDef);
309 if (!inserted.ok || inserted.remainder > 0)
310 { return { ok: false, reason: "space" }; }
311 return { ok: true, slots: inserted.slots, exhausted: true, instance: usedInstance };
312 }
313 return { ok: true, slots: next, exhausted: true, instance: usedInstance };
314 }
315 next[index].instance = { ...next[index].instance, fillLevel: fill - 1 };
316 return { ok: true, slots: next, exhausted: false, instance: usedInstance };
317 }
318
319 // Multi-stack: try leaving the remainder in place, then the reduced bottle in place.
320 const reducedFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, false);
321 if (reducedFirst.ok)
322 { return { ...reducedFirst, instance: usedInstance }; }
323 const remainderFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, true);
324 if (remainderFirst.ok)
325 { return { ...remainderFirst, instance: usedInstance }; }
326 return { ok: false, reason: "space" };
327}
328
329function tryPeelFillCharge (slots, index, fill, def, returnEmptyItemId, remainderStaysInSlot)
330{
331 const peeled = takeFromSlot(slots, index, 1);
332 if (!peeled.ok || !peeled.taken)
333 { return { ok: false }; }
334
335 if (fill <= 1)
336 {
337 if (!returnEmptyItemId)
338 { return { ok: true, slots: peeled.slots, exhausted: true }; }
339 const emptyDef = itemDefinition(returnEmptyItemId);
340 const emptyStack = attachOrigins({
341 itemId: returnEmptyItemId,
342 quantity: 1,
343 origins: normalizeOrigins(peeled.taken)
344 });
345 const inserted = insertStack(peeled.slots, emptyStack, emptyDef);
346 if (!inserted.ok || inserted.remainder > 0)
347 { return { ok: false }; }
348 return { ok: true, slots: inserted.slots, exhausted: true };
349 }
350
351 const reduced = {
352 itemId: peeled.taken.itemId,
353 quantity: 1,
354 instance: { ...cloneStack(peeled.taken.instance), fillLevel: fill - 1 },
355 origins: peeled.taken.origins
356 };
357 const remainder = peeled.slots[index]
358 ? cloneStack(peeled.slots[index])
359 : null;
360
361 if (!remainderStaysInSlot)
362 {
363 const inserted = insertStack(peeled.slots, reduced, def);
364 if (!inserted.ok || inserted.remainder > 0)
365 { return { ok: false }; }
366 return { ok: true, slots: inserted.slots, exhausted: false };
367 }
368
369 // Put reduced bottle back in the original slot; re-home the untouched remainder.
370 const next = peeled.slots.map(cloneStack);
371 next[index] = stackPayload(reduced, 1, normalizeOrigins(reduced));
372 if (!remainder)
373 { return { ok: true, slots: next, exhausted: false }; }
374 const inserted = insertStack(next, remainder, def);
375 if (!inserted.ok || inserted.remainder > 0)
376 { return { ok: false }; }
377 return { ok: true, slots: inserted.slots, exhausted: false };
378}
379
380/** Like insertStack, but grows the slot array when capacity runs out (vault). */
381export function insertStackGrowable (slots, stack, definition)
382{
383 if (!stack || stack.quantity <= 0)
384 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
385 let next = (slots ?? []).map(cloneStack);
386 let remaining = stackQuantity(stack.quantity);
387 let pendingOrigins = normalizeOrigins(stack);
388 const rules = stackRulesFor(definition, { inVault: true });
389
390 if (rules.stackable && !rules.uniqueInstance)
391 {
392 for (const slot of next)
393 {
394 if (!slot || !stacksMatch(slot, stack, definition, { inVault: true }))
395 { continue; }
396 const space = rules.maxStackSize - stackQuantity(slot.quantity);
397 if (space <= 0)
398 { continue; }
399 const add = Math.min(space, remaining);
400 const split = splitOrigins(pendingOrigins, add);
401 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
402 slot.quantity = stackQuantity(slot.quantity) + add;
403 if (stack.instance != null && slot.instance == null)
404 { slot.instance = cloneStack(stack.instance); }
405 delete slot.origin;
406 pendingOrigins = split.remain;
407 remaining -= add;
408 if (remaining === 0)
409 { return { ok: true, slots: next, remainder: 0 }; }
410 }
411 }
412
413 while (remaining > 0)
414 {
415 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
416 const amount = rules.stackable && !rules.uniqueInstance
417 ? Math.min(remaining, cap)
418 : 1;
419 const split = splitOrigins(pendingOrigins, amount);
420 next.push(stackPayload(stack, amount, split.taken));
421 pendingOrigins = split.remain;
422 remaining -= amount;
423 if (!rules.stackable || rules.uniqueInstance)
424 { break; }
425 }
426 return { ok: remaining === 0, slots: next, remainder: remaining };
427}
428
429/** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
430export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
431{
432 let remaining = Math.max(0, stackQuantity(quantity));
433 if (!remaining)
434 { return { ok: false, slots, taken: null }; }
435 const next = (slots ?? []).map(cloneStack);
436 const takenOrigins = [];
437 for (let i = 0; i < next.length && remaining > 0; i++)
438 {
439 const slot = next[i];
440 if (!slot || slot.itemId !== itemId)
441 { continue; }
442 if (instance != null)
443 {
444 if (JSON.stringify(slot.instance ?? null) !== JSON.stringify(instance))
445 { continue; }
446 }
447 const amount = Math.min(stackQuantity(slot.quantity), remaining);
448 const split = splitOrigins(normalizeOrigins(slot), amount);
449 takenOrigins.push(...split.taken);
450 if (amount >= stackQuantity(slot.quantity))
451 { next[i] = null; }
452 else
453 {
454 slot.quantity = stackQuantity(slot.quantity) - amount;
455 slot.origins = split.remain;
456 delete slot.origin;
457 }
458 remaining -= amount;
459 }
460 if (remaining > 0)
461 { return { ok: false, slots, taken: null }; }
462 return {
463 ok: true,
464 slots: compact ? next.filter((slot) => slot) : next,
465 taken: attachOrigins({
466 itemId,
467 quantity: stackQuantity(quantity),
468 instance: instance ?? null,
469 origins: mergeOriginLists([], takenOrigins)
470 })
471 };
472}
473
474export function countItemInSlots (slots, itemId)
475{
476 let total = 0;
477 for (const slot of slots ?? [])
478 {
479 if (slot?.itemId === itemId)
480 { total += stackQuantity(slot.quantity); }
481 }
482 return total;
483}
484
485export function countCoinsInSlots (slots)
486{
487 return countItemInSlots(slots, ItemId.coins);
488}
489
490/** Remove coin quantity from bag slots (FIFO across coin stacks). */
491export function takeCoinsFromSlots (slots, amount)
492{
493 let remaining = stackQuantity(amount);
494 if (!remaining)
495 { return { ok: true, slots: (slots ?? []).map(cloneStack) }; }
496 if (countCoinsInSlots(slots) < remaining)
497 { return { ok: false, slots: (slots ?? []).map(cloneStack) }; }
498 let next = (slots ?? []).map(cloneStack);
499 for (let i = 0; i < next.length && remaining > 0; i++)
500 {
501 if (!next[i] || next[i].itemId !== ItemId.coins)
502 { continue; }
503 const taken = takeFromSlot(next, i, remaining);
504 if (!taken.ok)
505 { continue; }
506 next = taken.slots;
507 remaining -= stackQuantity(taken.taken?.quantity);
508 }
509 return { ok: remaining === 0, slots: next };
510}
511
512/** Add coin stacks, splitting at max stack size (999B). */
513export function addCoinsToSlots (slots, amount, { growable = false } = {})
514{
515 const def = itemDefinition(ItemId.coins);
516 if (!def || amount <= 0)
517 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
518 let next = (slots ?? []).map(cloneStack);
519 if (!growable && next.length < INVENTORY_SLOTS)
520 {
521 const padded = emptySlots();
522 for (let i = 0; i < next.length; i++)
523 { padded[i] = next[i]; }
524 next = padded;
525 }
526 let remaining = stackQuantity(amount);
527 const insert = growable ? insertStackGrowable : insertStack;
528 while (remaining > 0)
529 {
530 const chunk = Math.min(remaining, def.maxStackSize ?? 99);
531 const result = insert(next, attachOrigins({ itemId: ItemId.coins, quantity: chunk }), def);
532 next = result.slots;
533 const placed = chunk - (result.remainder ?? 0);
534 remaining -= placed;
535 if (!result.ok || result.remainder > 0)
536 { return { ok: false, slots: next, remainder: remaining }; }
537 }
538 return { ok: true, slots: next, remainder: 0 };
539}
540
541/** Convert legacy currency counters into coin stacks. */
542export function migrateBagCoins (bag)
543{
544 let inventory = bag.inventory ?? emptySlots();
545 let vault = bag.vault ?? [];
546 if (bag.currency > 0)
547 {
548 const added = addCoinsToSlots(inventory, stackQuantity(bag.currency), { growable: false });
549 inventory = added.slots;
550 }
551 if (bag.vaultCurrency > 0)
552 {
553 const added = addCoinsToSlots(vault, stackQuantity(bag.vaultCurrency), { growable: true });
554 vault = added.slots;
555 }
556 return {
557 ...bag,
558 inventory,
559 vault,
560 currency: 0,
561 vaultCurrency: 0
562 };
563}
564
565export function migrateInheritanceCoins (inheritance)
566{
567 if (!inheritance?.currency)
568 { return inheritance; }
569 const added = addCoinsToSlots(inheritance.slots ?? emptySlots(), stackQuantity(inheritance.currency), { growable: true });
570 return {
571 ...inheritance,
572 slots: added.slots,
573 currency: 0
574 };
575}
576
577/** Trim excess blank cheques in inventory (e.g. after legacy saves or bugs). */
578export function normalizeInventorySlots (slots)
579{
580 const capped = capItemTotalInSlots(slots ?? emptySlots(), ItemId.blankCheque, BLANK_CHEQUE_CARRY_CAP);
581 return capped.map((slot) => normalizeChargeStack(slot));
582}
583
584export function capItemTotalInSlots (slots, itemId, cap)
585{
586 const next = (slots ?? []).map(cloneStack);
587 let total = countItemInSlots(next, itemId);
588 if (total <= cap)
589 { return next; }
590 let toRemove = total - cap;
591 for (let i = next.length - 1; i >= 0 && toRemove > 0; i--)
592 {
593 const slot = next[i];
594 if (!slot || slot.itemId !== itemId)
595 { continue; }
596 const beforeQty = stackQuantity(slot.quantity);
597 const drop = Math.min(beforeQty, toRemove);
598 const { remain } = splitOrigins(normalizeOrigins({ ...slot, quantity: beforeQty }), drop);
599 slot.quantity = beforeQty - drop;
600 slot.origins = remain;
601 delete slot.origin;
602 toRemove -= drop;
603 if (slot.quantity <= 0)
604 { next[i] = null; }
605 }
606 return next;
607}
608
609export function normalizeVault (raw)
610{
611 if (Array.isArray(raw))
612 {
613 return {
614 slots: raw.map((slot) => normalizeChargeStack(cloneStack(slot))),
615 reserved: []
616 };
617 }
618 return {
619 slots: (raw?.slots ?? []).map((slot) => normalizeChargeStack(cloneStack(slot))),
620 reserved: (raw?.reserved ?? []).map((slot) => normalizeChargeStack(cloneStack(slot)))
621 };
622}
623
624export function serializeVault (vault)
625{
626 const normalized = normalizeVault(vault);
627 return {
628 slots: publicSlots(normalized.slots),
629 reserved: publicSlots(normalized.reserved)
630 };
631}
632
633export function publicSlots (slots)
634{
635 return (slots ?? emptySlots()).map((slot) =>
636 {
637 if (!slot)
638 { return null; }
639 const payload = attachOrigins(cloneStack(slot));
640 const next = {
641 itemId: payload.itemId,
642 quantity: payload.quantity,
643 origins: payload.origins,
644 instance: payload.instance ?? null
645 };
646 // Cheque reservations keep chequeId so redeem can match the paper to vault goods.
647 if (payload.chequeId != null)
648 { next.chequeId = payload.chequeId; }
649 return next;
650 });
651}
652
653export function publicEquipment (equipment)
654{
655 const slots = {};
656 for (const slot of EQUIPMENT_SLOTS)
657 { slots[slot] = equipment?.slots?.[slot] ? cloneStack(equipment.slots[slot]) : null; }
658 return { slots };
659}