BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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