BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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