BlueGit

timfa questward

Files

questward / shared / items / inventory.js

inventory.js

inventory.js 13.3 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 return `${instance.potionKey ?? ""}|${effectKey}`;
57}
58
59/** Dye stacks merge when RGB matches exactly (fill ignored). */
60export function dyeStackIdentity (instance)
61{
62 if (!instance || instance.kind !== "dye" || !instance.color)
63 { return null; }
64 return [
65 Math.round((instance.color.r ?? 0) * 1000),
66 Math.round((instance.color.g ?? 0) * 1000),
67 Math.round((instance.color.b ?? 0) * 1000)
68 ].join(",");
69}
70
71export function stacksMatch (left, right, definition, { inVault = false } = {})
72{
73 if (!left || !right || left.itemId !== right.itemId)
74 { return false; }
75 const rules = stackRulesFor(definition, { inVault });
76 if (rules.uniqueInstance)
77 {
78 return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
79 }
80 if (definition?.potion)
81 {
82 const a = potionStackIdentity(left.instance);
83 const b = potionStackIdentity(right.instance);
84 return a != null && a === b;
85 }
86 if (definition?.dye)
87 {
88 const a = dyeStackIdentity(left.instance);
89 const b = dyeStackIdentity(right.instance);
90 return a != null && a === b;
91 }
92 if (left.instance != null || right.instance != null)
93 { return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null); }
94 return rules.stackable;
95}
96
97function stackPayload (stack, quantity, origins)
98{
99 return {
100 itemId: stack.itemId,
101 quantity,
102 instance: stack.instance ?? null,
103 origins: origins.map((entry) => ({
104 origin: entry.origin ?? null,
105 quantity: stackQuantity(entry.quantity)
106 })).filter((entry) => entry.quantity > 0)
107 };
108}
109
110export function insertStack (slots, stack, definition, options = {})
111{
112 if (!stack || stack.quantity <= 0)
113 { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; }
114 const rules = stackRulesFor(definition, options);
115 const next = slots.map(cloneStack);
116 let remaining = stackQuantity(stack.quantity);
117 let pendingOrigins = normalizeOrigins(stack);
118
119 if (rules.stackable && !rules.uniqueInstance)
120 {
121 for (const slot of next)
122 {
123 if (!slot || !stacksMatch(slot, stack, definition, options))
124 { continue; }
125 const space = rules.maxStackSize - stackQuantity(slot.quantity);
126 if (space <= 0)
127 { continue; }
128 const add = Math.min(space, remaining);
129 const split = splitOrigins(pendingOrigins, add);
130 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
131 slot.quantity = stackQuantity(slot.quantity) + add;
132 if (stack.instance != null && slot.instance == null)
133 { slot.instance = cloneStack(stack.instance); }
134 delete slot.origin;
135 pendingOrigins = split.remain;
136 remaining -= add;
137 if (remaining === 0)
138 { return { ok: true, slots: next, remainder: 0 }; }
139 }
140 }
141
142 for (let i = 0; i < next.length; i++)
143 {
144 if (next[i])
145 { continue; }
146 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
147 const amount = rules.stackable && !rules.uniqueInstance
148 ? Math.min(remaining, cap)
149 : 1;
150 const split = splitOrigins(pendingOrigins, amount);
151 next[i] = stackPayload(stack, amount, split.taken);
152 pendingOrigins = split.remain;
153 remaining -= amount;
154 if (remaining === 0)
155 { return { ok: true, slots: next, remainder: 0 }; }
156 if (!rules.stackable || rules.uniqueInstance)
157 { break; }
158 }
159 return { ok: false, slots, remainder: remaining };
160}
161
162export function takeFromSlot (slots, slotIndex, quantity = null)
163{
164 const next = slots.map(cloneStack);
165 const slot = next[slotIndex];
166 if (!slot)
167 { return { ok: false, slots, taken: null }; }
168 const maxQty = stackQuantity(slot.quantity);
169 const amount = quantity == null
170 ? maxQty
171 : Math.min(maxQty, Math.max(1, stackQuantity(quantity)));
172 if (amount <= 0)
173 { return { ok: false, slots, taken: null }; }
174 const split = splitOrigins(normalizeOrigins(slot), amount);
175 const taken = stackPayload(slot, amount, split.taken);
176 if (amount >= maxQty)
177 { next[slotIndex] = null; }
178 else
179 {
180 slot.quantity = maxQty - amount;
181 slot.origins = split.remain;
182 delete slot.origin;
183 }
184 return { ok: true, slots: next, taken };
185}
186
187/** Like insertStack, but grows the slot array when capacity runs out (vault). */
188export function insertStackGrowable (slots, stack, definition)
189{
190 if (!stack || stack.quantity <= 0)
191 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
192 let next = (slots ?? []).map(cloneStack);
193 let remaining = stackQuantity(stack.quantity);
194 let pendingOrigins = normalizeOrigins(stack);
195 const rules = stackRulesFor(definition, { inVault: true });
196
197 if (rules.stackable && !rules.uniqueInstance)
198 {
199 for (const slot of next)
200 {
201 if (!slot || !stacksMatch(slot, stack, definition, { inVault: true }))
202 { continue; }
203 const space = rules.maxStackSize - stackQuantity(slot.quantity);
204 if (space <= 0)
205 { continue; }
206 const add = Math.min(space, remaining);
207 const split = splitOrigins(pendingOrigins, add);
208 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
209 slot.quantity = stackQuantity(slot.quantity) + add;
210 if (stack.instance != null && slot.instance == null)
211 { slot.instance = cloneStack(stack.instance); }
212 delete slot.origin;
213 pendingOrigins = split.remain;
214 remaining -= add;
215 if (remaining === 0)
216 { return { ok: true, slots: next, remainder: 0 }; }
217 }
218 }
219
220 while (remaining > 0)
221 {
222 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
223 const amount = rules.stackable && !rules.uniqueInstance
224 ? Math.min(remaining, cap)
225 : 1;
226 const split = splitOrigins(pendingOrigins, amount);
227 next.push(stackPayload(stack, amount, split.taken));
228 pendingOrigins = split.remain;
229 remaining -= amount;
230 if (!rules.stackable || rules.uniqueInstance)
231 { break; }
232 }
233 return { ok: remaining === 0, slots: next, remainder: remaining };
234}
235
236/** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
237export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
238{
239 let remaining = Math.max(0, stackQuantity(quantity));
240 if (!remaining)
241 { return { ok: false, slots, taken: null }; }
242 const next = (slots ?? []).map(cloneStack);
243 const takenOrigins = [];
244 for (let i = 0; i < next.length && remaining > 0; i++)
245 {
246 const slot = next[i];
247 if (!slot || slot.itemId !== itemId)
248 { continue; }
249 if (instance != null)
250 {
251 if (JSON.stringify(slot.instance ?? null) !== JSON.stringify(instance))
252 { continue; }
253 }
254 const amount = Math.min(stackQuantity(slot.quantity), remaining);
255 const split = splitOrigins(normalizeOrigins(slot), amount);
256 takenOrigins.push(...split.taken);
257 if (amount >= stackQuantity(slot.quantity))
258 { next[i] = null; }
259 else
260 {
261 slot.quantity = stackQuantity(slot.quantity) - amount;
262 slot.origins = split.remain;
263 delete slot.origin;
264 }
265 remaining -= amount;
266 }
267 if (remaining > 0)
268 { return { ok: false, slots, taken: null }; }
269 return {
270 ok: true,
271 slots: compact ? next.filter((slot) => slot) : next,
272 taken: attachOrigins({
273 itemId,
274 quantity: stackQuantity(quantity),
275 instance: instance ?? null,
276 origins: mergeOriginLists([], takenOrigins)
277 })
278 };
279}
280
281export function countItemInSlots (slots, itemId)
282{
283 let total = 0;
284 for (const slot of slots ?? [])
285 {
286 if (slot?.itemId === itemId)
287 { total += stackQuantity(slot.quantity); }
288 }
289 return total;
290}
291
292export function countCoinsInSlots (slots)
293{
294 return countItemInSlots(slots, ItemId.coins);
295}
296
297/** Remove coin quantity from bag slots (FIFO across coin stacks). */
298export function takeCoinsFromSlots (slots, amount)
299{
300 let remaining = stackQuantity(amount);
301 if (!remaining)
302 { return { ok: true, slots: (slots ?? []).map(cloneStack) }; }
303 if (countCoinsInSlots(slots) < remaining)
304 { return { ok: false, slots: (slots ?? []).map(cloneStack) }; }
305 let next = (slots ?? []).map(cloneStack);
306 for (let i = 0; i < next.length && remaining > 0; i++)
307 {
308 if (!next[i] || next[i].itemId !== ItemId.coins)
309 { continue; }
310 const taken = takeFromSlot(next, i, remaining);
311 if (!taken.ok)
312 { continue; }
313 next = taken.slots;
314 remaining -= stackQuantity(taken.taken?.quantity);
315 }
316 return { ok: remaining === 0, slots: next };
317}
318
319/** Add coin stacks, splitting at max stack size (999B). */
320export function addCoinsToSlots (slots, amount, { growable = false } = {})
321{
322 const def = itemDefinition(ItemId.coins);
323 if (!def || amount <= 0)
324 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
325 let next = (slots ?? []).map(cloneStack);
326 if (!growable && next.length < INVENTORY_SLOTS)
327 {
328 const padded = emptySlots();
329 for (let i = 0; i < next.length; i++)
330 { padded[i] = next[i]; }
331 next = padded;
332 }
333 let remaining = stackQuantity(amount);
334 const insert = growable ? insertStackGrowable : insertStack;
335 while (remaining > 0)
336 {
337 const chunk = Math.min(remaining, def.maxStackSize ?? 99);
338 const result = insert(next, { itemId: ItemId.coins, quantity: chunk }, def);
339 next = result.slots;
340 const placed = chunk - (result.remainder ?? 0);
341 remaining -= placed;
342 if (!result.ok || result.remainder > 0)
343 { return { ok: false, slots: next, remainder: remaining }; }
344 }
345 return { ok: true, slots: next, remainder: 0 };
346}
347
348/** Convert legacy currency counters into coin stacks. */
349export function migrateBagCoins (bag)
350{
351 let inventory = bag.inventory ?? emptySlots();
352 let vault = bag.vault ?? [];
353 if (bag.currency > 0)
354 {
355 const added = addCoinsToSlots(inventory, stackQuantity(bag.currency), { growable: false });
356 inventory = added.slots;
357 }
358 if (bag.vaultCurrency > 0)
359 {
360 const added = addCoinsToSlots(vault, stackQuantity(bag.vaultCurrency), { growable: true });
361 vault = added.slots;
362 }
363 return {
364 ...bag,
365 inventory,
366 vault,
367 currency: 0,
368 vaultCurrency: 0
369 };
370}
371
372export function migrateInheritanceCoins (inheritance)
373{
374 if (!inheritance?.currency)
375 { return inheritance; }
376 const added = addCoinsToSlots(inheritance.slots ?? emptySlots(), stackQuantity(inheritance.currency), { growable: true });
377 return {
378 ...inheritance,
379 slots: added.slots,
380 currency: 0
381 };
382}
383
384/** Trim excess blank cheques in inventory (e.g. after legacy saves or bugs). */
385export function normalizeInventorySlots (slots)
386{
387 return capItemTotalInSlots(slots ?? emptySlots(), ItemId.blankCheque, BLANK_CHEQUE_CARRY_CAP);
388}
389
390export function capItemTotalInSlots (slots, itemId, cap)
391{
392 const next = (slots ?? []).map(cloneStack);
393 let total = countItemInSlots(next, itemId);
394 if (total <= cap)
395 { return next; }
396 let toRemove = total - cap;
397 for (let i = next.length - 1; i >= 0 && toRemove > 0; i--)
398 {
399 const slot = next[i];
400 if (!slot || slot.itemId !== itemId)
401 { continue; }
402 const beforeQty = stackQuantity(slot.quantity);
403 const drop = Math.min(beforeQty, toRemove);
404 const { remain } = splitOrigins(normalizeOrigins({ ...slot, quantity: beforeQty }), drop);
405 slot.quantity = beforeQty - drop;
406 slot.origins = remain;
407 delete slot.origin;
408 toRemove -= drop;
409 if (slot.quantity <= 0)
410 { next[i] = null; }
411 }
412 return next;
413}
414
415export function normalizeVault (raw)
416{
417 if (Array.isArray(raw))
418 { return { slots: raw.map(cloneStack), reserved: [] }; }
419 return {
420 slots: (raw?.slots ?? []).map(cloneStack),
421 reserved: (raw?.reserved ?? []).map(cloneStack)
422 };
423}
424
425export function serializeVault (vault)
426{
427 const normalized = normalizeVault(vault);
428 return {
429 slots: publicSlots(normalized.slots),
430 reserved: publicSlots(normalized.reserved)
431 };
432}
433
434export function publicSlots (slots)
435{
436 return (slots ?? emptySlots()).map((slot) =>
437 {
438 if (!slot)
439 { return null; }
440 const payload = attachOrigins(cloneStack(slot));
441 const next = {
442 itemId: payload.itemId,
443 quantity: payload.quantity,
444 origins: payload.origins,
445 instance: payload.instance ?? null
446 };
447 // Cheque reservations keep chequeId so redeem can match the paper to vault goods.
448 if (payload.chequeId != null)
449 { next.chequeId = payload.chequeId; }
450 return next;
451 });
452}
453
454export function publicEquipment (equipment)
455{
456 const slots = {};
457 for (const slot of EQUIPMENT_SLOTS)
458 { slots[slot] = equipment?.slots?.[slot] ? cloneStack(equipment.slots[slot]) : null; }
459 return { slots };
460}