BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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