BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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