BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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