BlueGit

timfa questward

Files

questward / shared / items / inventory.js

inventory.js

inventory.js 17.6 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 * Spend one fill charge from a potion/dye slot without losing the leftover bottle.
192 * Single bottles always mutate in place (or become an empty bottle). Multi-stacks
193 * peel one bottle and re-insert the reduced fill; tries both split orderings so a
194 * matching stack can absorb either side. Never mutates the input slots array.
195 *
196 * @returns {{ ok: true, slots, exhausted: boolean, instance: object } | { ok: false, reason: string }}
197 */
198export function consumeFillCharge (slots, slotIndex, {
199 kind = null,
200 itemId = null,
201 definition = null,
202 returnEmptyItemId = null
203} = {})
204{
205 const index = slotIndex | 0;
206 const source = slots?.[index];
207 if (!source || stackQuantity(source.quantity) <= 0)
208 { return { ok: false, reason: "empty" }; }
209 if (itemId != null && source.itemId !== itemId)
210 { return { ok: false, reason: "wrong-item" }; }
211 if (kind != null && source.instance?.kind !== kind)
212 { return { ok: false, reason: "wrong-item" }; }
213 const def = definition ?? itemDefinition(source.itemId);
214 if (!def)
215 { return { ok: false, reason: "unknown" }; }
216
217 const fill = Math.max(1, Math.min(5, source.instance?.fillLevel | 0 || 4));
218 const qty = stackQuantity(source.quantity);
219 const usedInstance = cloneStack(source.instance) ?? { kind, fillLevel: fill };
220
221 if (qty === 1)
222 {
223 const next = slots.map(cloneStack);
224 if (fill <= 1)
225 {
226 next[index] = null;
227 if (returnEmptyItemId)
228 {
229 const emptyDef = itemDefinition(returnEmptyItemId);
230 const emptyStack = attachOrigins({
231 itemId: returnEmptyItemId,
232 quantity: 1,
233 origins: normalizeOrigins(source)
234 });
235 const inserted = insertStack(next, emptyStack, emptyDef);
236 if (!inserted.ok || inserted.remainder > 0)
237 { return { ok: false, reason: "space" }; }
238 return { ok: true, slots: inserted.slots, exhausted: true, instance: usedInstance };
239 }
240 return { ok: true, slots: next, exhausted: true, instance: usedInstance };
241 }
242 next[index].instance = { ...next[index].instance, fillLevel: fill - 1 };
243 return { ok: true, slots: next, exhausted: false, instance: usedInstance };
244 }
245
246 // Multi-stack: try leaving the remainder in place, then the reduced bottle in place.
247 const reducedFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, false);
248 if (reducedFirst.ok)
249 { return { ...reducedFirst, instance: usedInstance }; }
250 const remainderFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, true);
251 if (remainderFirst.ok)
252 { return { ...remainderFirst, instance: usedInstance }; }
253 return { ok: false, reason: "space" };
254}
255
256function tryPeelFillCharge (slots, index, fill, def, returnEmptyItemId, remainderStaysInSlot)
257{
258 const peeled = takeFromSlot(slots, index, 1);
259 if (!peeled.ok || !peeled.taken)
260 { return { ok: false }; }
261
262 if (fill <= 1)
263 {
264 if (!returnEmptyItemId)
265 { return { ok: true, slots: peeled.slots, exhausted: true }; }
266 const emptyDef = itemDefinition(returnEmptyItemId);
267 const emptyStack = attachOrigins({
268 itemId: returnEmptyItemId,
269 quantity: 1,
270 origins: normalizeOrigins(peeled.taken)
271 });
272 const inserted = insertStack(peeled.slots, emptyStack, emptyDef);
273 if (!inserted.ok || inserted.remainder > 0)
274 { return { ok: false }; }
275 return { ok: true, slots: inserted.slots, exhausted: true };
276 }
277
278 const reduced = {
279 itemId: peeled.taken.itemId,
280 quantity: 1,
281 instance: { ...cloneStack(peeled.taken.instance), fillLevel: fill - 1 },
282 origins: peeled.taken.origins
283 };
284 const remainder = peeled.slots[index]
285 ? cloneStack(peeled.slots[index])
286 : null;
287
288 if (!remainderStaysInSlot)
289 {
290 const inserted = insertStack(peeled.slots, reduced, def);
291 if (!inserted.ok || inserted.remainder > 0)
292 { return { ok: false }; }
293 return { ok: true, slots: inserted.slots, exhausted: false };
294 }
295
296 // Put reduced bottle back in the original slot; re-home the untouched remainder.
297 const next = peeled.slots.map(cloneStack);
298 next[index] = stackPayload(reduced, 1, normalizeOrigins(reduced));
299 if (!remainder)
300 { return { ok: true, slots: next, exhausted: false }; }
301 const inserted = insertStack(next, remainder, def);
302 if (!inserted.ok || inserted.remainder > 0)
303 { return { ok: false }; }
304 return { ok: true, slots: inserted.slots, exhausted: false };
305}
306
307/** Like insertStack, but grows the slot array when capacity runs out (vault). */
308export function insertStackGrowable (slots, stack, definition)
309{
310 if (!stack || stack.quantity <= 0)
311 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
312 let next = (slots ?? []).map(cloneStack);
313 let remaining = stackQuantity(stack.quantity);
314 let pendingOrigins = normalizeOrigins(stack);
315 const rules = stackRulesFor(definition, { inVault: true });
316
317 if (rules.stackable && !rules.uniqueInstance)
318 {
319 for (const slot of next)
320 {
321 if (!slot || !stacksMatch(slot, stack, definition, { inVault: true }))
322 { continue; }
323 const space = rules.maxStackSize - stackQuantity(slot.quantity);
324 if (space <= 0)
325 { continue; }
326 const add = Math.min(space, remaining);
327 const split = splitOrigins(pendingOrigins, add);
328 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
329 slot.quantity = stackQuantity(slot.quantity) + add;
330 if (stack.instance != null && slot.instance == null)
331 { slot.instance = cloneStack(stack.instance); }
332 delete slot.origin;
333 pendingOrigins = split.remain;
334 remaining -= add;
335 if (remaining === 0)
336 { return { ok: true, slots: next, remainder: 0 }; }
337 }
338 }
339
340 while (remaining > 0)
341 {
342 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
343 const amount = rules.stackable && !rules.uniqueInstance
344 ? Math.min(remaining, cap)
345 : 1;
346 const split = splitOrigins(pendingOrigins, amount);
347 next.push(stackPayload(stack, amount, split.taken));
348 pendingOrigins = split.remain;
349 remaining -= amount;
350 if (!rules.stackable || rules.uniqueInstance)
351 { break; }
352 }
353 return { ok: remaining === 0, slots: next, remainder: remaining };
354}
355
356/** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
357export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
358{
359 let remaining = Math.max(0, stackQuantity(quantity));
360 if (!remaining)
361 { return { ok: false, slots, taken: null }; }
362 const next = (slots ?? []).map(cloneStack);
363 const takenOrigins = [];
364 for (let i = 0; i < next.length && remaining > 0; i++)
365 {
366 const slot = next[i];
367 if (!slot || slot.itemId !== itemId)
368 { continue; }
369 if (instance != null)
370 {
371 if (JSON.stringify(slot.instance ?? null) !== JSON.stringify(instance))
372 { continue; }
373 }
374 const amount = Math.min(stackQuantity(slot.quantity), remaining);
375 const split = splitOrigins(normalizeOrigins(slot), amount);
376 takenOrigins.push(...split.taken);
377 if (amount >= stackQuantity(slot.quantity))
378 { next[i] = null; }
379 else
380 {
381 slot.quantity = stackQuantity(slot.quantity) - amount;
382 slot.origins = split.remain;
383 delete slot.origin;
384 }
385 remaining -= amount;
386 }
387 if (remaining > 0)
388 { return { ok: false, slots, taken: null }; }
389 return {
390 ok: true,
391 slots: compact ? next.filter((slot) => slot) : next,
392 taken: attachOrigins({
393 itemId,
394 quantity: stackQuantity(quantity),
395 instance: instance ?? null,
396 origins: mergeOriginLists([], takenOrigins)
397 })
398 };
399}
400
401export function countItemInSlots (slots, itemId)
402{
403 let total = 0;
404 for (const slot of slots ?? [])
405 {
406 if (slot?.itemId === itemId)
407 { total += stackQuantity(slot.quantity); }
408 }
409 return total;
410}
411
412export function countCoinsInSlots (slots)
413{
414 return countItemInSlots(slots, ItemId.coins);
415}
416
417/** Remove coin quantity from bag slots (FIFO across coin stacks). */
418export function takeCoinsFromSlots (slots, amount)
419{
420 let remaining = stackQuantity(amount);
421 if (!remaining)
422 { return { ok: true, slots: (slots ?? []).map(cloneStack) }; }
423 if (countCoinsInSlots(slots) < remaining)
424 { return { ok: false, slots: (slots ?? []).map(cloneStack) }; }
425 let next = (slots ?? []).map(cloneStack);
426 for (let i = 0; i < next.length && remaining > 0; i++)
427 {
428 if (!next[i] || next[i].itemId !== ItemId.coins)
429 { continue; }
430 const taken = takeFromSlot(next, i, remaining);
431 if (!taken.ok)
432 { continue; }
433 next = taken.slots;
434 remaining -= stackQuantity(taken.taken?.quantity);
435 }
436 return { ok: remaining === 0, slots: next };
437}
438
439/** Add coin stacks, splitting at max stack size (999B). */
440export function addCoinsToSlots (slots, amount, { growable = false } = {})
441{
442 const def = itemDefinition(ItemId.coins);
443 if (!def || amount <= 0)
444 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
445 let next = (slots ?? []).map(cloneStack);
446 if (!growable && next.length < INVENTORY_SLOTS)
447 {
448 const padded = emptySlots();
449 for (let i = 0; i < next.length; i++)
450 { padded[i] = next[i]; }
451 next = padded;
452 }
453 let remaining = stackQuantity(amount);
454 const insert = growable ? insertStackGrowable : insertStack;
455 while (remaining > 0)
456 {
457 const chunk = Math.min(remaining, def.maxStackSize ?? 99);
458 const result = insert(next, attachOrigins({ itemId: ItemId.coins, quantity: chunk }), def);
459 next = result.slots;
460 const placed = chunk - (result.remainder ?? 0);
461 remaining -= placed;
462 if (!result.ok || result.remainder > 0)
463 { return { ok: false, slots: next, remainder: remaining }; }
464 }
465 return { ok: true, slots: next, remainder: 0 };
466}
467
468/** Convert legacy currency counters into coin stacks. */
469export function migrateBagCoins (bag)
470{
471 let inventory = bag.inventory ?? emptySlots();
472 let vault = bag.vault ?? [];
473 if (bag.currency > 0)
474 {
475 const added = addCoinsToSlots(inventory, stackQuantity(bag.currency), { growable: false });
476 inventory = added.slots;
477 }
478 if (bag.vaultCurrency > 0)
479 {
480 const added = addCoinsToSlots(vault, stackQuantity(bag.vaultCurrency), { growable: true });
481 vault = added.slots;
482 }
483 return {
484 ...bag,
485 inventory,
486 vault,
487 currency: 0,
488 vaultCurrency: 0
489 };
490}
491
492export function migrateInheritanceCoins (inheritance)
493{
494 if (!inheritance?.currency)
495 { return inheritance; }
496 const added = addCoinsToSlots(inheritance.slots ?? emptySlots(), stackQuantity(inheritance.currency), { growable: true });
497 return {
498 ...inheritance,
499 slots: added.slots,
500 currency: 0
501 };
502}
503
504/** Trim excess blank cheques in inventory (e.g. after legacy saves or bugs). */
505export function normalizeInventorySlots (slots)
506{
507 return capItemTotalInSlots(slots ?? emptySlots(), ItemId.blankCheque, BLANK_CHEQUE_CARRY_CAP);
508}
509
510export function capItemTotalInSlots (slots, itemId, cap)
511{
512 const next = (slots ?? []).map(cloneStack);
513 let total = countItemInSlots(next, itemId);
514 if (total <= cap)
515 { return next; }
516 let toRemove = total - cap;
517 for (let i = next.length - 1; i >= 0 && toRemove > 0; i--)
518 {
519 const slot = next[i];
520 if (!slot || slot.itemId !== itemId)
521 { continue; }
522 const beforeQty = stackQuantity(slot.quantity);
523 const drop = Math.min(beforeQty, toRemove);
524 const { remain } = splitOrigins(normalizeOrigins({ ...slot, quantity: beforeQty }), drop);
525 slot.quantity = beforeQty - drop;
526 slot.origins = remain;
527 delete slot.origin;
528 toRemove -= drop;
529 if (slot.quantity <= 0)
530 { next[i] = null; }
531 }
532 return next;
533}
534
535export function normalizeVault (raw)
536{
537 if (Array.isArray(raw))
538 { return { slots: raw.map(cloneStack), reserved: [] }; }
539 return {
540 slots: (raw?.slots ?? []).map(cloneStack),
541 reserved: (raw?.reserved ?? []).map(cloneStack)
542 };
543}
544
545export function serializeVault (vault)
546{
547 const normalized = normalizeVault(vault);
548 return {
549 slots: publicSlots(normalized.slots),
550 reserved: publicSlots(normalized.reserved)
551 };
552}
553
554export function publicSlots (slots)
555{
556 return (slots ?? emptySlots()).map((slot) =>
557 {
558 if (!slot)
559 { return null; }
560 const payload = attachOrigins(cloneStack(slot));
561 const next = {
562 itemId: payload.itemId,
563 quantity: payload.quantity,
564 origins: payload.origins,
565 instance: payload.instance ?? null
566 };
567 // Cheque reservations keep chequeId so redeem can match the paper to vault goods.
568 if (payload.chequeId != null)
569 { next.chequeId = payload.chequeId; }
570 return next;
571 });
572}
573
574export function publicEquipment (equipment)
575{
576 const slots = {};
577 for (const slot of EQUIPMENT_SLOTS)
578 { slots[slot] = equipment?.slots?.[slot] ? cloneStack(equipment.slots[slot]) : null; }
579 return { slots };
580}