BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

bags.js 30.8 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { syncPlayerHealth } from "../skills/service.js";
3import { canEquipItem } from "../../../shared/equipment/stats.js";
4import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
5import { stackRulesFor } from "../../../shared/items/stackRules.js";
6import { BlockType } from "../../../shared/definitions/tiles.js";
7import { ItemId, itemDefinition, itemSpriteName, stackDisplayLabel, LETTER_MAX_BODY_CHARS, BLANK_CHEQUE_CARRY_CAP } from "../../../shared/definitions/items.js";
8import {
9 emptyEquipment,
10 emptySlots,
11 insertStack,
12 insertStackGrowable,
13 normalizeVault,
14 normalizeInventorySlots,
15 publicEquipment,
16 publicSlots,
17 takeFromSlot,
18 takeMatchingFromSlots,
19 countItemInSlots,
20 cloneStack,
21 singleItemFromStack,
22 stackQuantity,
23 consumeFillCharge
24} from "../../../shared/items/inventory.js";
25import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
26import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
27import { randomUUID } from "node:crypto";
28import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
29import { resolvePotionEffect } from "../../../shared/alchemy/recipes.js";
30import {
31 applyStatusEffect,
32 emptyStatusEffects,
33 StatusEffectType
34} from "../../../shared/statusEffects/rules.js";
35import {
36 attachOrigins,
37 writtenOrigin,
38 bankIssuedOrigin,
39 normalizeOrigins
40} from "../../../shared/items/origin.js";
41import { BANK_LETTER_AUTHOR } from "../../../shared/courier/systemLetters.js";
42
43export function publicGroundItem (item)
44{
45 const instance = item.stack?.instance ?? null;
46 return {
47 groundItemId: item.groundItemId,
48 tileX: item.tileX,
49 tileY: item.tileY,
50 itemId: item.stack.itemId,
51 quantity: item.stack.quantity,
52 displayName: stackDisplayLabel(item.stack),
53 sprite: itemSpriteName(item.stack.itemId, instance),
54 instance: instance && (instance.kind === "potion" || instance.kind === "letter" || instance.kind === "recipe-paper")
55 ? instance
56 : null,
57 expiresAt: item.expiresAt
58 };
59}
60
61export function bagView (ecs, handle)
62{
63 const vault = normalizeVault(ecs.get(handle, Component.vault));
64 return {
65 inventory: publicSlots(normalizeInventorySlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots())),
66 equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()),
67 vault: publicSlots(vault.slots),
68 vaultReserved: publicSlots(vault.reserved)
69 };
70}
71
72export function applyBagView (ecs, handle, bag)
73{
74 const inventory = ensureInventory(ecs, handle);
75 inventory.slots = normalizeInventorySlots(publicSlots(bag.inventory ?? emptySlots()));
76 const equipment = ensureEquipment(ecs, handle);
77 const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment());
78 equipment.slots = nextEquip.slots;
79 const vault = ensureVault(ecs, handle);
80 const normalized = normalizeVault(
81 bag.vaultReserved != null || (bag.vault && !Array.isArray(bag.vault))
82 ? { slots: bag.vault, reserved: bag.vaultReserved }
83 : bag.vault
84 );
85 vault.slots = publicSlots(normalized.slots);
86 vault.reserved = publicSlots(normalized.reserved);
87 return bagView(ecs, handle);
88}
89
90export function handleItemCommand (world, sessionId, command, now)
91{
92 switch (command.type)
93 {
94 case "drop-item":
95 return dropItem(world, sessionId, command, now);
96 case "pickup-item":
97 return pickupItem(world, sessionId, command);
98 case "equip-item":
99 return equipItem(world, sessionId, command);
100 case "unequip-item":
101 return unequipItem(world, sessionId, command);
102 case "open-bank":
103 return openBank(world, sessionId, command);
104 case "bank-deposit":
105 return bankMove(world, sessionId, command, "inventory", "vault");
106 case "bank-withdraw":
107 return bankMove(world, sessionId, command, "vault", "inventory");
108 case "get-blank-cheques":
109 return getBlankCheques(world, sessionId, command);
110 case "return-blank-cheques":
111 return returnBlankCheques(world, sessionId, command);
112 case "write-cheque":
113 return writeCheque(world, sessionId, command);
114 case "redeem-cheque":
115 return redeemCheque(world, sessionId, command);
116 case "claim-inheritance":
117 return claimInheritance(world, sessionId, command);
118 case "write-letter":
119 return writeLetter(world, sessionId, command);
120 case "edit-letter":
121 return editLetter(world, sessionId, command);
122 case "open-letter":
123 return openLetter(world, sessionId, command);
124 case "eat-item":
125 return eatItem(world, sessionId, command);
126 case "drink-item":
127 return drinkItem(world, sessionId, command);
128 default:
129 return null;
130 }
131}
132
133export function expireGroundItems (world, now)
134{
135 const events = [];
136 for (const item of [...world.groundItems.values()])
137 {
138 if (item.expiresAt > now)
139 { continue; }
140 removeGroundItem(world, item.groundItemId);
141 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
142 }
143 return events;
144}
145
146export function groundItemsInChunk (world, chunkX, chunkY)
147{
148 return [...world.groundItems.values()]
149 .filter((item) => tileToChunk(item.tileX) === chunkX && tileToChunk(item.tileY) === chunkY)
150 .map(publicGroundItem);
151}
152
153export function groundItemsInRegion (world, regionX, regionY, tileToRegion)
154{
155 return [...world.groundItems.values()].filter((item) =>
156 tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY
157 );
158}
159
160export function addGroundItem (world, item)
161{
162 world.groundItems.set(item.groundItemId, item);
163 const key = tileKey(item.tileX, item.tileY);
164 if (!world.groundByTile.has(key))
165 { world.groundByTile.set(key, new Set()); }
166 world.groundByTile.get(key).add(item.groundItemId);
167}
168
169export function removeGroundItem (world, groundItemId)
170{
171 const item = world.groundItems.get(groundItemId);
172 if (!item)
173 { return null; }
174 world.groundItems.delete(groundItemId);
175 const key = tileKey(item.tileX, item.tileY);
176 world.groundByTile.get(key)?.delete(groundItemId);
177 return item;
178}
179
180export function replaceGroundItems (world, items)
181{
182 world.groundItems.clear();
183 world.groundByTile.clear();
184 for (const item of items ?? [])
185 { addGroundItem(world, item); }
186}
187
188export function setGroundItemsForRegion (world, regionX, regionY, items, tileToRegion)
189{
190 for (const item of [...world.groundItems.values()])
191 {
192 if (tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY)
193 { removeGroundItem(world, item.groundItemId); }
194 }
195 for (const item of items ?? [])
196 { addGroundItem(world, item); }
197}
198
199function dropItem (world, sessionId, command, now)
200{
201 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
202 const inventory = ensureInventory(world.ecs, handle);
203 const taken = takeFromSlot(inventory.slots, command.slotIndex, command.quantity ?? null);
204 if (!taken.ok)
205 { throw userError("That inventory slot is empty."); }
206 inventory.slots = taken.slots;
207 const position = world.ecs.get(handle, Component.position);
208 const item = {
209 groundItemId: command.groundItemId,
210 tileX: position.tileX,
211 tileY: position.tileY,
212 stack: taken.taken,
213 droppedAt: now,
214 expiresAt: now + (world.settings.groundItemDespawnDurationMs ?? 600_000),
215 source: "player-drop",
216 droppedByCharacterId: command.characterId
217 };
218 addGroundItem(world, item);
219 return {
220 events: [{ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }],
221 private: bagView(world.ecs, handle)
222 };
223}
224
225function pickupItem (world, sessionId, command)
226{
227 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
228 const item = world.groundItems.get(command.groundItemId);
229 if (!item)
230 { throw userError("That item is no longer on the ground."); }
231 const position = world.ecs.get(handle, Component.position);
232 if (position.tileX !== item.tileX || position.tileY !== item.tileY)
233 { throw userError("Stand on the item to pick it up."); }
234 const def = itemDefinition(item.stack.itemId);
235 if (!def)
236 { throw userError("Unknown item."); }
237 const inventory = ensureInventory(world.ecs, handle);
238 let stackToAdd = item.stack;
239 if (item.stack.itemId === ItemId.blankCheque)
240 {
241 const have = countItemInSlots(inventory.slots, ItemId.blankCheque);
242 const room = BLANK_CHEQUE_CARRY_CAP - have;
243 if (room <= 0)
244 { throw userError(`You already carry ${BLANK_CHEQUE_CARRY_CAP} blank cheques.`); }
245 const takeQty = Math.min(item.stack.quantity, room);
246 stackToAdd = { ...item.stack, quantity: takeQty };
247 }
248 const inserted = insertStack(inventory.slots, stackToAdd, def);
249 if (!inserted.ok)
250 { throw userError("Your inventory cannot hold that."); }
251 inventory.slots = inserted.slots;
252 const events = [];
253 if (item.stack.itemId === ItemId.blankCheque && stackToAdd.quantity < item.stack.quantity)
254 {
255 item.stack.quantity -= stackToAdd.quantity;
256 events.push({
257 type: "ground-item-appear",
258 ...publicGroundItem(item),
259 stack: item.stack,
260 droppedAt: item.droppedAt,
261 source: item.source,
262 droppedByCharacterId: item.droppedByCharacterId,
263 expiresAt: item.expiresAt
264 });
265 }
266 else
267 {
268 removeGroundItem(world, item.groundItemId);
269 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
270 }
271 return {
272 events,
273 private: bagView(world.ecs, handle)
274 };
275}
276
277function equipItem (world, sessionId, command)
278{
279 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
280 const inventory = ensureInventory(world.ecs, handle);
281 const equipment = ensureEquipment(world.ecs, handle);
282 const slotIndex = command.slotIndex | 0;
283 const source = inventory.slots[slotIndex];
284 if (!source || stackQuantity(source.quantity) <= 0)
285 { throw userError("That inventory slot is empty."); }
286 const def = itemDefinition(source.itemId);
287 const slot = def?.equipment?.slot;
288 if (!slot)
289 { throw userError("That item cannot be equipped."); }
290 const skills = world.ecs.get(handle, Component.skills);
291 const equipCheck = canEquipItem(skills, def);
292 if (!equipCheck.ok)
293 { throw userError(equipCheck.reason); }
294
295 const isArrowAmmo = def.equipment?.kind === EquipmentKind.arrowAmmo;
296 const taken = takeFromSlot(inventory.slots, slotIndex, isArrowAmmo ? null : 1);
297 if (!taken.ok || stackQuantity(taken.taken?.quantity) <= 0)
298 { throw userError("That inventory slot is empty."); }
299 if (taken.taken.itemId === ItemId.coins)
300 {
301 inventory.slots = insertStack(taken.slots, taken.taken, itemDefinition(ItemId.coins)).slots;
302 throw userError("Coins cannot be equipped.");
303 }
304
305 if (isArrowAmmo)
306 {
307 let slots = taken.slots;
308 const previous = equipment.slots[slot];
309 if (previous)
310 {
311 const previousDef = itemDefinition(previous.itemId);
312 if (previous.itemId === taken.taken.itemId)
313 {
314 const rules = stackRulesFor(def);
315 const space = rules.maxStackSize - stackQuantity(previous.quantity);
316 const add = Math.min(space, stackQuantity(taken.taken.quantity));
317 if (add <= 0)
318 {
319 inventory.slots = insertStack(slots, taken.taken, def).slots;
320 throw userError("Your arrow stack is full.");
321 }
322 previous.quantity = stackQuantity(previous.quantity) + add;
323 const leftover = stackQuantity(taken.taken.quantity) - add;
324 if (leftover > 0)
325 {
326 const back = insertStack(slots, { ...taken.taken, quantity: leftover }, def);
327 if (!back.ok)
328 {
329 previous.quantity = stackQuantity(previous.quantity) - add;
330 inventory.slots = insertStack(slots, taken.taken, def).slots;
331 throw userError("No inventory space for leftover arrows.");
332 }
333 slots = back.slots;
334 }
335 inventory.slots = slots;
336 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: false };
337 }
338 const back = insertStack(slots, previous, previousDef);
339 if (!back.ok)
340 {
341 inventory.slots = insertStack(slots, taken.taken, def).slots;
342 throw userError("No inventory space to unequip the current item.");
343 }
344 slots = back.slots;
345 }
346 inventory.slots = slots;
347 equipment.slots[slot] = taken.taken;
348 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: false };
349 }
350
351 const toEquip = singleItemFromStack(taken.taken);
352 const previous = equipment.slots[slot];
353 if (previous)
354 {
355 const previousSingle = singleItemFromStack(previous);
356 const back = insertStack(taken.slots, previousSingle, itemDefinition(previous.itemId));
357 if (!back.ok)
358 {
359 inventory.slots = insertStack(inventory.slots, toEquip, def).slots;
360 throw userError("No inventory space to unequip the current item.");
361 }
362 inventory.slots = back.slots;
363 }
364 else
365 { inventory.slots = taken.slots; }
366 equipment.slots[slot] = toEquip;
367 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
368}
369
370function unequipItem (world, sessionId, command)
371{
372 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
373 const inventory = ensureInventory(world.ecs, handle);
374 const equipment = ensureEquipment(world.ecs, handle);
375 const worn = equipment.slots[command.equipSlot];
376 if (!worn)
377 { throw userError("Nothing is equipped there."); }
378 const def = itemDefinition(worn.itemId);
379 const toStore = def?.equipment?.kind === EquipmentKind.arrowAmmo
380 ? cloneStack(worn)
381 : singleItemFromStack(worn);
382 const inserted = insertStack(inventory.slots, toStore, def);
383 if (!inserted.ok)
384 { throw userError("Your inventory cannot hold that."); }
385 inventory.slots = inserted.slots;
386 equipment.slots[command.equipSlot] = null;
387 const appearanceChanged = def?.equipment?.kind !== EquipmentKind.arrowAmmo;
388 return { events: [], private: bagView(world.ecs, handle), appearanceChanged };
389}
390
391function eatItem (world, sessionId, command)
392{
393 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
394 syncPlayerHealth(world.ecs, handle);
395 const inventory = ensureInventory(world.ecs, handle);
396 const health = world.ecs.get(handle, Component.health);
397 if (!health)
398 { throw userError("You cannot eat right now."); }
399 if ((health.current | 0) >= (health.max | 0))
400 { throw userError("You are already at full health."); }
401 const slotIndex = command.slotIndex | 0;
402 const slot = inventory.slots[slotIndex];
403 if (!slot || stackQuantity(slot.quantity) <= 0)
404 { throw userError("That inventory slot is empty."); }
405 const def = itemDefinition(slot.itemId);
406 const healing = def?.healing ?? 0;
407 if (healing <= 0)
408 { throw userError("That cannot be eaten."); }
409 const taken = takeFromSlot(inventory.slots, slotIndex, 1);
410 if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1)
411 { throw userError("That inventory slot is empty."); }
412 inventory.slots = taken.slots;
413 health.current = Math.min(health.max | 0, (health.current | 0) + healing);
414 return {
415 events: [],
416 private: bagView(world.ecs, handle),
417 healthChanged: true
418 };
419}
420
421function drinkItem (world, sessionId, command)
422{
423 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
424 syncPlayerHealth(world.ecs, handle);
425 const inventory = ensureInventory(world.ecs, handle);
426 const slotIndex = command.slotIndex | 0;
427 const slot = inventory.slots[slotIndex];
428 if (!slot || slot.itemId !== ItemId.potion || slot.instance?.kind !== "potion")
429 { throw userError("That is not a potion."); }
430 const consumed = consumeFillCharge(inventory.slots, slotIndex, {
431 kind: "potion",
432 itemId: ItemId.potion,
433 returnEmptyItemId: ItemId.glassBottle
434 });
435 if (!consumed.ok)
436 {
437 if (consumed.reason === "space")
438 {
439 throw userError(
440 "Need bag space to keep the partially used potion (or empty bottle)."
441 );
442 }
443 throw userError("That inventory slot is empty.");
444 }
445 inventory.slots = consumed.slots;
446 const effectResult = applyPotionEffect(world.ecs, handle, resolvePotionEffect(consumed.instance));
447 return {
448 events: effectResult.events ?? [],
449 private: bagView(world.ecs, handle),
450 healthChanged: !!effectResult.healthChanged,
451 appearanceChanged: !!effectResult.appearanceChanged,
452 statusEffectsChanged: !!effectResult.statusEffectsChanged
453 };
454}
455
456function ensureStatusEffects (ecs, handle)
457{
458 let component = ecs.get(handle, Component.statusEffects);
459 if (!component)
460 { component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }
461 if (!Array.isArray(component.effects))
462 { component.effects = []; }
463 return component;
464}
465
466function applyPotionEffect (ecs, handle, effect)
467{
468 const result = {
469 healthChanged: false,
470 appearanceChanged: false,
471 statusEffectsChanged: false,
472 events: []
473 };
474 if (!effect || typeof effect !== "object")
475 { return result; }
476
477 const health = ecs.get(handle, Component.health);
478 const type = effect.type;
479
480 if (type === "heal" && health)
481 {
482 const amount = Math.max(0, effect.amount | 0 || 0);
483 health.current = Math.min(health.max | 0, (health.current | 0) + amount);
484 result.healthChanged = true;
485 return result;
486 }
487 if (type === "damage" && health)
488 {
489 const amount = Math.max(0, effect.amount | 0 || 0);
490 health.current = Math.max(0, (health.current | 0) - amount);
491 result.healthChanged = true;
492 return result;
493 }
494
495 const timed = {
496 [StatusEffectType.healthRegen]: true,
497 [StatusEffectType.staminaRegen]: true,
498 [StatusEffectType.strengthBonus]: true,
499 [StatusEffectType.mindBonus]: true,
500 [StatusEffectType.staminaDrain]: true,
501 [StatusEffectType.glow]: true,
502 [StatusEffectType.shrink]: true,
503 [StatusEffectType.blind]: true
504 };
505 if (!timed[type])
506 { return result; }
507
508 const component = ensureStatusEffects(ecs, handle);
509 applyStatusEffect(component, effect, Date.now());
510 result.statusEffectsChanged = true;
511 if (type === StatusEffectType.glow || type === StatusEffectType.shrink)
512 { result.appearanceChanged = true; }
513 return result;
514}
515
516function openBank (world, sessionId, command)
517{
518 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
519 const position = world.ecs.get(handle, Component.position);
520 if (!nearBank(world, position.tileX, position.tileY))
521 { throw userError("Stand next to a bank."); }
522 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank);
523 return {
524 events: shove ? [shove] : [],
525 private: bagView(world.ecs, handle),
526 bank: true
527 };
528}
529
530function bankMove (world, sessionId, command, fromKey, toKey)
531{
532 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
533 requireBank(world, handle);
534 const inventory = ensureInventory(world.ecs, handle);
535 const vault = ensureVault(world.ecs, handle);
536 if (fromKey === "inventory" && toKey === "vault")
537 {
538 const slot = inventory.slots[command.slotIndex | 0];
539 if (slot?.itemId === ItemId.filledCheque)
540 { return redeemCheque(world, sessionId, command); }
541 }
542 const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots;
543 const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null);
544 if (!taken.ok)
545 { throw userError("That slot is empty."); }
546 const def = itemDefinition(taken.taken.itemId);
547 if (toKey === "vault")
548 {
549 const inserted = insertStackGrowable(vault.slots, taken.taken, def);
550 inventory.slots = taken.slots;
551 vault.slots = inserted.slots;
552 }
553 else
554 {
555 const inserted = insertStack(inventory.slots, taken.taken, def);
556 if (!inserted.ok)
557 { throw userError("Not enough space."); }
558 vault.slots = taken.slots;
559 inventory.slots = inserted.slots;
560 }
561 return { events: [], private: bagView(world.ecs, handle), bank: true };
562}
563
564function getBlankCheques (world, sessionId, command)
565{
566 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
567 requireBank(world, handle);
568 const inventory = ensureInventory(world.ecs, handle);
569 const have = countItemInSlots(inventory.slots, ItemId.blankCheque);
570 const need = Math.max(0, BLANK_CHEQUE_CARRY_CAP - have);
571 if (!need)
572 { return { events: [], private: bagView(world.ecs, handle), bank: true }; }
573 const def = itemDefinition(ItemId.blankCheque);
574 const inserted = insertStack(inventory.slots, attachOrigins({
575 itemId: ItemId.blankCheque,
576 quantity: need,
577 origins: [{ origin: bankIssuedOrigin(BANK_LETTER_AUTHOR), quantity: need }]
578 }), def);
579 if (!inserted.ok)
580 { throw userError("Need inventory space for blank cheques."); }
581 inventory.slots = inserted.slots;
582 return { events: [], private: bagView(world.ecs, handle), bank: true };
583}
584
585function returnBlankCheques (world, sessionId, command)
586{
587 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
588 requireBank(world, handle);
589 const inventory = ensureInventory(world.ecs, handle);
590 const slot = inventory.slots[command.slotIndex | 0];
591 if (!slot || slot.itemId !== ItemId.blankCheque)
592 { throw userError("Select blank cheques."); }
593 const quantity = command.quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, command.quantity | 0));
594 const taken = takeFromSlot(inventory.slots, command.slotIndex | 0, quantity);
595 if (!taken.ok)
596 { throw userError("Select blank cheques."); }
597 inventory.slots = taken.slots;
598 return { events: [], private: bagView(world.ecs, handle), bank: true };
599}
600
601function writeCheque (world, sessionId, command)
602{
603 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
604 const inventory = ensureInventory(world.ecs, handle);
605 const vault = ensureVault(world.ecs, handle);
606 const slotIndex = command.slotIndex | 0;
607 const blankSlot = inventory.slots[slotIndex];
608 if (!blankSlot || blankSlot.itemId !== ItemId.blankCheque)
609 { throw userError("Select a blank cheque."); }
610 const vaultSlot = vault.slots[command.vaultSlotIndex | 0];
611 if (!vaultSlot)
612 { throw userError("Select vault goods to reserve."); }
613 const def = itemDefinition(vaultSlot.itemId);
614 if (!def)
615 { throw userError("Unknown item."); }
616 const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0);
617 const available = countItemInSlots(vault.slots, vaultSlot.itemId);
618 if (available < quantity)
619 { throw userError("Not enough unreserved goods in the vault."); }
620 if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry))
621 { throw userError("Need a free inventory slot for the filled cheque."); }
622
623 const pulled = takeMatchingFromSlots(vault.slots, {
624 itemId: vaultSlot.itemId,
625 quantity,
626 instance: def.uniqueInstance ? vaultSlot.instance : null
627 });
628 if (!pulled.ok)
629 { throw userError("Not enough unreserved goods in the vault."); }
630
631 const appearance = world.ecs.get(handle, Component.appearance);
632 const issuerName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim()
633 || "Unknown";
634 const chequeId = randomUUID();
635 const reservedStack = {
636 itemId: pulled.taken.itemId,
637 quantity: pulled.taken.quantity,
638 origins: normalizeOrigins(pulled.taken),
639 instance: pulled.taken.instance ?? null,
640 chequeId
641 };
642 vault.slots = pulled.slots;
643 vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack];
644
645 const filled = attachOrigins({
646 itemId: ItemId.filledCheque,
647 quantity: 1,
648 origins: [{ origin: writtenOrigin(issuerName), quantity: 1 }],
649 instance: {
650 kind: "filled-cheque",
651 chequeId,
652 issuerCharacterId: command.characterId,
653 itemId: pulled.taken.itemId,
654 quantity: pulled.taken.quantity,
655 reservedInstance: pulled.taken.instance ?? null,
656 createdAt: Date.now()
657 }
658 });
659 const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1);
660 inventory.slots = blankTaken.slots;
661 if (!inventory.slots[slotIndex])
662 { inventory.slots[slotIndex] = filled; }
663 else
664 {
665 const free = inventory.slots.findIndex((entry) => !entry);
666 inventory.slots[free] = filled;
667 }
668 return { events: [], private: bagView(world.ecs, handle) };
669}
670
671function redeemCheque (world, sessionId, command)
672{
673 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
674 requireBank(world, handle);
675 const inventory = ensureInventory(world.ecs, handle);
676 const vault = ensureVault(world.ecs, handle);
677 const slotIndex = command.slotIndex | 0;
678 const slot = inventory.slots[slotIndex];
679 if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque")
680 { throw userError("Select a filled cheque."); }
681
682 const chequeId = slot.instance.chequeId;
683 const issuerId = slot.instance.issuerCharacterId;
684 const goodsDef = itemDefinition(slot.instance.itemId);
685 if (!goodsDef)
686 { throw userError("Unknown reserved goods."); }
687
688 const chequeTaken = takeFromSlot(inventory.slots, slotIndex, 1);
689 if (!chequeTaken.ok)
690 { throw userError("Select a filled cheque."); }
691 inventory.slots = chequeTaken.slots;
692
693 let reservedStack = null;
694 if (Number(issuerId) === Number(command.characterId))
695 {
696 const index = findReservedChequeIndex(vault.reserved, slot.instance);
697 if (index < 0)
698 {
699 inventory.slots[slotIndex] = chequeTaken.taken;
700 throw userError("That cheque cannot be redeemed.");
701 }
702 reservedStack = cloneStack(vault.reserved[index]);
703 vault.reserved = vault.reserved.filter((_, i) => i !== index);
704 }
705 else
706 {
707 const release = world.releaseChequeReservation?.(issuerId, chequeId, slot.instance);
708 if (!release?.ok)
709 {
710 inventory.slots[slotIndex] = chequeTaken.taken;
711 throw userError(release?.error ?? "That cheque cannot be redeemed.");
712 }
713 reservedStack = release.stack;
714 }
715
716 const inserted = insertStackGrowable(vault.slots, attachOrigins({
717 itemId: reservedStack.itemId,
718 quantity: reservedStack.quantity,
719 origins: normalizeOrigins(reservedStack),
720 instance: reservedStack.instance ?? null
721 }), goodsDef);
722 if (!inserted.ok)
723 {
724 inventory.slots[slotIndex] = chequeTaken.taken;
725 if (Number(issuerId) === Number(command.characterId))
726 { vault.reserved = [...(vault.reserved ?? []), reservedStack]; }
727 else
728 { world.restoreChequeReservation?.(issuerId, reservedStack); }
729 throw userError("Your vault cannot hold those goods.");
730 }
731 vault.slots = inserted.slots;
732 return { events: [], private: bagView(world.ecs, handle), bank: true };
733}
734
735/** Match reserved vault entry by chequeId, or by goods identity for legacy rows that lost chequeId. */
736export function findReservedChequeIndex (reserved, chequeInstance)
737{
738 const list = reserved ?? [];
739 const chequeId = chequeInstance?.chequeId;
740 if (chequeId != null)
741 {
742 const byId = list.findIndex((entry) => entry?.chequeId === chequeId);
743 if (byId >= 0)
744 { return byId; }
745 }
746 const itemId = chequeInstance?.itemId;
747 const quantity = chequeInstance?.quantity | 0;
748 if (itemId == null || quantity <= 0)
749 { return -1; }
750 return list.findIndex((entry) =>
751 entry
752 && entry.chequeId == null
753 && entry.itemId === itemId
754 && (entry.quantity | 0) === quantity
755 );
756}
757
758function claimInheritance (world, sessionId, command)
759{
760 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
761 requireBank(world, handle);
762 const vault = ensureVault(world.ecs, handle);
763 const remainder = [];
764 for (const stack of command.stacks ?? [])
765 {
766 const def = itemDefinition(stack.itemId);
767 if (!def)
768 {
769 remainder.push(stack);
770 continue;
771 }
772 const inserted = insertStackGrowable(vault.slots, stack, def);
773 if (inserted.ok)
774 { vault.slots = inserted.slots; }
775 else
776 { remainder.push(stack); }
777 }
778 return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };
779}
780
781function writeLetter (world, sessionId, command)
782{
783 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
784 const inventory = ensureInventory(world.ecs, handle);
785 const slotIndex = command.slotIndex | 0;
786 const slot = inventory.slots[slotIndex];
787 if (!slot || slot.itemId !== ItemId.paper)
788 { throw userError("Select blank paper."); }
789 const body = normalizeLetterBody(command.body);
790 const appearance = world.ecs.get(handle, Component.appearance);
791 const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim();
792 const letterStack = attachOrigins({
793 itemId: ItemId.letter,
794 quantity: 1,
795 origins: [{ origin: writtenOrigin(authorDisplayName), quantity: 1 }],
796 instance: {
797 kind: "letter",
798 letterId: randomUUID(),
799 authorCharacterId: command.characterId,
800 authorDisplayName,
801 body,
802 opened: true,
803 writtenAt: Date.now()
804 }
805 });
806 if (slot.quantity <= 1)
807 {
808 inventory.slots[slotIndex] = letterStack;
809 return { events: [], private: bagView(world.ecs, handle) };
810 }
811 const free = inventory.slots.findIndex((entry) => !entry);
812 if (free < 0)
813 { throw userError("Need a free inventory slot for the letter."); }
814 slot.quantity -= 1;
815 inventory.slots[free] = letterStack;
816 return { events: [], private: bagView(world.ecs, handle) };
817}
818
819function editLetter (world, sessionId, command)
820{
821 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
822 const inventory = ensureInventory(world.ecs, handle);
823 const slotIndex = command.slotIndex | 0;
824 const slot = inventory.slots[slotIndex];
825 if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter")
826 { throw userError("That is not a letter."); }
827 if (slot.instance.authorCharacterId !== command.characterId)
828 { throw userError("Only the signer can edit this letter."); }
829 const appearance = world.ecs.get(handle, Component.appearance);
830 const authorDisplayName = `${appearance?.firstName ?? slot.instance.authorDisplayName} ${appearance?.lastName ?? ""}`.trim()
831 || slot.instance.authorDisplayName;
832 slot.instance = {
833 ...slot.instance,
834 authorDisplayName,
835 body: normalizeLetterBody(command.body),
836 writtenAt: Date.now()
837 };
838 slot.origins = [{ origin: writtenOrigin(authorDisplayName), quantity: 1 }];
839 delete slot.origin;
840 return { events: [], private: bagView(world.ecs, handle) };
841}
842
843function openLetter (world, sessionId, command)
844{
845 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
846 const inventory = ensureInventory(world.ecs, handle);
847 const slotIndex = command.slotIndex | 0;
848 const slot = inventory.slots[slotIndex];
849 if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter")
850 { throw userError("That is not a letter."); }
851 if (slot.instance.opened !== false)
852 { return { events: [], private: bagView(world.ecs, handle) }; }
853 slot.instance = { ...slot.instance, opened: true };
854 return { events: [], private: bagView(world.ecs, handle) };
855}
856
857function normalizeLetterBody (raw)
858{
859 const body = String(raw ?? "").replace(/\r\n/g, "\n").trimEnd();
860 if (body.length > LETTER_MAX_BODY_CHARS)
861 { throw userError(`Letters can be at most ${LETTER_MAX_BODY_CHARS} characters.`); }
862 return body;
863}
864
865function requireBank (world, handle)
866{
867 const position = world.ecs.get(handle, Component.position);
868 if (!nearBank(world, position.tileX, position.tileY))
869 { throw userError("Stand next to a bank."); }
870}
871
872function nearBank (world, tileX, tileY)
873{
874 for (let dy = -1; dy <= 1; dy++)
875 {
876 for (let dx = -1; dx <= 1; dx++)
877 {
878 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
879 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
880 if (data.blocks[index]?.typeId === BlockType.bank)
881 { return true; }
882 }
883 }
884 return false;
885}
886
887function ensureInventory (ecs, handle)
888{
889 let inventory = ecs.get(handle, Component.inventory);
890 if (!inventory)
891 { inventory = ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
892 inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
893 return inventory;
894}
895
896function ensureEquipment (ecs, handle)
897{
898 return ecs.get(handle, Component.equipment) ?? ecs.add(handle, Component.equipment, emptyEquipment());
899}
900
901function ensureVault (ecs, handle)
902{
903 let vault = ecs.get(handle, Component.vault);
904 if (!vault)
905 { vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); }
906 if (!Array.isArray(vault.slots))
907 { vault.slots = []; }
908 if (!Array.isArray(vault.reserved))
909 { vault.reserved = []; }
910 return vault;
911}
912
913function userError (message)
914{
915 const error = new Error(message);
916 error.userFacing = true;
917 return error;
918}