BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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