BlueGit

timfa questward

Files

questward / shared / items / inventory.js

inventory.js

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