commit 9d20d5537fb19b8537a0cd99793ad82c861301a7
parent e85edcdd37aca5828488134d3c8c1c2896eb8764
Author: anon <anon@example.com>
Date: Thu, 22 Oct 2026 15:04:37 +0000
Add persistent native backpacks and container transfers
Diffstat:
14 files changed, 960 insertions(+), 38 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -38,11 +38,11 @@ recorded in [inventory behavior](docs/inventory.md).
applicable limit without changing the total item count.
- [x] Split a stack. Check: splitting a known quantity produces two persistent
stacks with the same combined count; invalid quantities change nothing.
-- [ ] Open one empty backpack. Check: an owned backpack opens its native
+- [x] Open one empty backpack. Check: an owned backpack opens its native
container window with the correct capacity.
-- [ ] Put one item into a backpack and take it out. Check: its location and the
+- [x] Put one item into a backpack and take it out. Check: its location and the
backpack contents survive reconnect and restart, with no duplicate item.
-- [ ] Enforce container placement rules. Check: full bags and prohibited nesting
+- [x] Enforce container placement rules. Check: full bags and prohibited nesting
are rejected without losing items; permitted moves match recovered rules.
Essence of Pure Jealousy now supports persistent native splitting and merging.
@@ -51,6 +51,10 @@ The historical merge cap remains unresolved, so the merge item stays open;
rejected-split recovery and verification are in
[inventory stacks](docs/inventory-stacks.md).
+Small Backpack 99228 uses its recovered 21-slot native inventory and persistent
+contents. Protocol evidence, ownership/placement checks, native tests and the
+unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md).
+
## Equipment, one kind at a time
- [x] Equip and unequip one melee weapon. Check: its appearance and base attack
diff --git a/docs/backpacks.md b/docs/backpacks.md
@@ -0,0 +1,147 @@
+# Backpacks in 14.9.1
+
+The supported container is Small Backpack, template 99228, exact QL 1,
+identity type 51017. Its shipped record is in
+`server/gamedata/items/items_010.yaml`: Can 13, Flags 4097, and stat 24 = 10000.
+Its description says ten kilograms; that value is not a slot count.
+[Auno's historical 14.8 record](https://auno.org/ao/db.php?id=99228&patch=14080000)
+corroborates these fields. The Adventuring requirement belongs to equipping
+the bag; this milestone uses it as an ordinary inventory container.
+
+## Native object and contents
+
+The original `kkr.dll` SHA-256 is
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+`local/reports/backpack-protocol-1491-evidence.json` retains 89 REA records.
+The entry-flag test also uses the retained `stack-protocol-1491-evidence.json` bundle.
+Addresses below refer to that original binary; generated C uses base 0x36000000.
+
+Chest initialization at `1008b490` constructs an inventory of exactly 21 slots,
+numbered 0..20. This capacity is hardcoded; it is not transmitted in a prefix or
+derived from the backpack's mass field. Evidence:
+`ev_31c7736d8359de344339ace5eee17a95254285a4f77b18285caca6f9f0cf2de5`.
+
+Using a bag in ordinary inventory sends GenericCmd `52526858`. Its eight DWORDs
+are `{0,sequence,3,mode,50000,owner,104,nativeSlot}`. The captured first use has
+mode 0; subsequent uses of the instantiated Chest have mode 1. The server returns the normal
+success acknowledgement and supplies a live Chest plus its contents:
+
+| Message | Body |
+| --- | --- |
+| ChestFullUpdate `465a5d73`, outer `(51017,bagID)` | SimpleItem version 11; parent `(50000,owner)`; playfield; auxiliary `(0,0)`; page/slot bytes; encoded stat pairs; extra-data length 0; Lockable version 2; lock field 0; empty identity list 1009; Chest version 3 |
+| InventoryUpdate `4e536976`, outer `(50000,owner)` | Encoded 32-byte item rows; `(51017,bagID)`; container handle; open flag 1 |
+
+The explicit Chest stats are `23=99228,701=1,702=99228,703=99228`.
+SimpleItem has no XYZ/quaternion when it has a parent. ChestFullUpdate has no
+corpse tail or animation list. Reader evidence:
+`ev_275528c4a10136c1a2de368bd4bdbb1c2bf5c0b29f946a68808e609e47d9218d`.
+
+InventoryUpdate replaces the Chest contents, stores its handle and opens the
+window. Each row carries slot, ushort flags/count, instance identity, template
+endpoints, QL and an auxiliary zero.
+Snapshot rows use template-proxy flags 3; transfers retain their existing entry
+flags. Page 107 addresses a row as `(handle << 16) | contentsSlot`. Handles are local
+to the session, distinct from persistent bag IDs, and multiple bags can be open.
+Handle zero remains available for the existing corpse path. Evidence:
+`ev_6504a4ed1d179858989adba8c4a9271e05de39ca7211c397e2352a79b37a965d`.
+
+ActionIIR `2049527c`, outer `(51017,bagID)`, body `{1,102,50000,owner}` closes
+and unregisters the window. The native window's X button sends GenericCmd use
+against `(51017,bagID)` directly, with mode 1, instead of page/slot 104. Both
+request forms require the same current owner. The Chest object remains available
+after closing;
+an initialized closed bag can still receive items. A never-initialized bag
+cannot receive the native transfer acknowledgement without its live Chest.
+
+## Transfers and placement
+
+ContainerAddItem `47537a24` has five DWORDs:
+
+| Direction | Fields |
+| --- | --- |
+| Ordinary inventory to bag | `{104,nativeSlot,51017,bagID,111}` |
+| Bag to ordinary inventory | `{107,packedPosition,50000,owner,111}` |
+| Bag to bag | `{107,packedPosition,51017,otherBagID,111}` |
+
+The server selects the first free destination and persists the whole inventory
+before acknowledging. The native bag receiver also selects its first free slot;
+the ordinary-inventory response carries the resolved native slot. Only ordinary
+inventory positions are translated between saved 64..93 and native 48..77.
+Packed page-107 positions and bag contents slots are not ordinary positions.
+
+Ordinary items without separate live objects use FullCharacter entry flag 1.
+Flag 2 selects identity-object lookup; a visible icon alone does not instantiate
+that object. Keeping an ordinary pistol at flag 2 made the server accept a put
+while the client left its source row untouched. The native template branch moves
+the complete entry instead. Worn items and backpacks retain flag 2. A later
+proper WeaponItemFullUpdate creates the weapon object when it is equipped.
+Evidence for the flag test and both transfer branches:
+`ev_07063ae8fa3a3b6248a0d15562f619930d9db0b3e22375bfc5451088c54d6013`
+and `ev_997b50913c907c830e4ced831d12c72906e0c2d05d956375785e4ff8859f5cf5`.
+
+Validator `10060510` rejects nested Chests, full destination inventories,
+temporary flag `0x00200000`, live temporary state stat 8 above zero, and a
+duplicate template for a Unique item (`0x08000000`). The server checks the
+catalog flags and static state for its current items. Runtime temporary-item
+lifetimes are not implemented. Ownership, current session, loading/death,
+pending equipment, source existence and target availability are also checked.
+Evidence:
+`ev_c0637c99b0b32adec9081a8f14509f3804654ea2e9cd93dd3d5f6f96b556c2aa`.
+
+## Persistence and boundaries
+
+`inventory.yaml` stores a `containers` map from backpack ID to its owned item
+rows. Each item occurs in exactly one location. Startup rejects orphan contents,
+duplicate IDs/slots, nested bags, zero quantities and positions outside 0..20.
+Transfers preserve instance IDs and quantities; split creates a fresh global
+ID using the existing atomic inventory transaction. Stack split/join and item
+deletion also understand packed bag positions. A rejected optimistic bag split
+receives an authoritative InventoryUpdate for that Chest.
+
+Contents follow their backpack into and out of reclaim in the same owner file;
+an unavailable bag cannot be addressed through an old session handle. The current
+delete operation removes a bag and its contents in one transaction, then retires
+its handle. Native DeleteItem does not check whether a bag is filled, and Chest
+destruction frees its local inventory. The historical server's filled-bag
+deletion and reclaim policy remains unverified; the persistence behavior here
+must not be cited as historical proof.
+
+The native slot bound and placement checks are established. Enforcement of the
+description's ten-kilogram limit was not recovered, so no new mass cap is
+invented. Equipment moves currently pass through ordinary inventory first.
+Bag equipping, custom names, trades and other container templates
+remain separate features. As with other slot-addressed messages, the wire has
+no operation token to identify every replay after later slot reuse.
+
+## Verification
+
+`server/backpacks_test.go` exercises the actual world connection for opening and
+transfers, restart persistence, distinct windows and repeated use, closed-bag
+placement, bag-to-bag transfers, 21 slots, full ordinary inventory, stale and
+foreign requests, concurrent transfers, failed saves, contained stacks,
+deletion, reclaim and invalid saved ownership.
+
+Two WASM clients were exercised in `local/backpack-smoke/`. Actual inventory
+gestures opened multiple bags, moved pistols in and out, stored Essence,
+split/joined a contained stack, and recovered a deliberately rejected optimistic
+split through the production Chest correction. The fixture filled all 21 slots;
+native heap inspection confirmed every entry, and the final visible item was
+taken out and replaced without changing its identity or quantity.
+
+The native window's X close and ordinary right-click reopen both worked. A live
+axe was unequipped and stored in the second bag. After a server restart its
+snapshot proxy could be taken into ordinary inventory and equipped again as a
+proper live weapon: the native hand slot showed the axe, attack rating was 400 and
+AC remained 6. The second owner's empty bag stayed independent before and after
+reload/restart. Twelve read-only native snapshots matched saved slot quantities
+and every nonzero instance ID. Saved inventories were identical across restart
+before the subsequent equipment move.
+
+`tmp_verify.py` checks those retained snapshots and the cited evidence IDs.
+There were no client exceptions; sixteen connection refusals were expected
+during the intentional restart. Both clients and the fixture server were closed
+before the full server checks. The focused backpack suite passed in 8.595 seconds.
+The complete maintained suite, `go test ./server/... -count=1`, passed with
+`ao/server` completing in 85.561 seconds.
+The focused race run over backpacks, stacks, inventory, equipment, armor, attack
+rating, overequipping, character stats, reclaim and combat passed in 137.165 seconds.
diff --git a/docs/inventory-stacks.md b/docs/inventory-stacks.md
@@ -49,8 +49,8 @@ Direction and checks are supported by
`ev_22f06fb27128af42a5babde5a290d6fd9f24bcd92d075f86a813261a0a2e60ae`
and `ev_d87a842dd8417af8e91dcb61a97596d71ff6fce8b6bca2b6110cdabd783afcc6`.
-Stack mutations require inventory entry flag `0x1`. Initial Essence rows
-therefore use flag 1; individual items retain flag 2. Local split clones use
+Stack mutations require inventory entry flag `0x1`. Initial Essence and other
+ordinary template rows use flag 1; worn items and backpacks use flag 2. Local split clones use
`0x21` and a zero instance identity. The row stores a ushort quantity at offset
6 and its QL/low/high triple at offsets 16/20/24. Persistent server IDs remain
owned state, while stack requests address page/slot and carry no new instance
@@ -104,6 +104,10 @@ and `ev_78e48f17a73e495dccf184968e44268af825c92b3d9bd79d86ccd44c30c86806`.
Apparent ATR activation calls on these paths resolve to original `0x1010def0`,
a `RET 4` stub, and must not be filled in as a missing adapter method.
+Stacks inside the supported [backpack](backpacks.md) use page 107's packed
+handle/slot positions. Their optimistic-split correction uses the native Chest
+InventoryUpdate replacement instead of rebuilding ordinary inventory.
+
## Verification
`server/stacks_test.go` exercises grant quantities, merge direction, source
diff --git a/docs/inventory.md b/docs/inventory.md
@@ -18,8 +18,9 @@ Profile edits and zoning preserve inventory independently of profile fields.
Items use exact catalog qualities with identical template endpoints. Essence
of Pure Jealousy now supports persistent [native stacks](inventory-stacks.md),
including merge, split and rejected-split correction. Its historical server
-merge cap remains unresolved. Arbitrary-quality interpolation, backpacks and
-starter loadouts remain separate milestones. Native corpse pickup is
+merge cap remains unresolved. [Small Backpack](backpacks.md) now provides its
+native 21-slot inventory and persistent contents. Arbitrary-quality interpolation
+and starter loadouts remain separate milestones. Native corpse pickup is
described in [the corpse and loot protocol](corpse-loot.md). QL 1 Kinetic Axe equipment
is described below. Exact QL 1/200 Metaplast chest armor and QL 1 boots use the
[native armor path](armor.md). Other equipment remains unsupported.
@@ -32,7 +33,7 @@ encoded length is `(items + 1) * 1009`. Each entry has these network-order field
| Field | Size | Initial individual-item value |
| --- | --- | --- |
| Logical slot | 4 | 48 through 77 on the 14.9.1 wire |
-| Entry flags | 2 | 2 |
+| Entry flags | 2 | 1 for ordinary templates; 2 for worn items and backpacks |
| Count | 2 | 1 |
| Instance type and ID | 8 | Template type and persistent server ID |
| Low and high template | 8 | Same exact template ID |
@@ -45,14 +46,17 @@ The maintained client source establishes the 32-byte wire entry:
two shorts, identity and template information. `sub_360011B0` in
`client/game/kkr.dll/lifted-0000.c` reads the final four integers.
The 14.9.1 conversion inserts its seventh list after the variable-length
-inventory, rather than at an offset valid only for an empty list. Flag 2 was
-verified with the native WASM icon, tooltip and QL 1 details window.
+inventory, rather than at an offset valid only for an empty list. Ordinary
+items use template flag 1 so native transfers can move their inventory entries
+without requiring a separate live object. Worn items and initialized backpacks
+retain live flag 2. The [backpack protocol](backpacks.md) explains this distinction.
`ContainerAddItem` (`0x47537a24`) carries source page/slot, target owner identity
and destination slot. The server accepts only an authenticated current session's
own ordinary inventory and an empty destination. It saves before acknowledging
the move. Corpse transfers use the validated opened corpse described above;
-other cross-owner/container transfers are rejected. The supported weapon
+owned backpack transfers follow the checks described below; other cross-owner
+transfers are rejected. The supported weapon
also moves between ordinary inventory and the right hand as described below. This
layout is corroborated by the local AOtomation `ContainerAddItemMessage` and
CellAO `ContainerAddItemMessageHandler` reference sources; it is not the message
diff --git a/server/backpacks.go b/server/backpacks.go
@@ -0,0 +1,249 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "maps"
+ "slices"
+)
+
+type backpackHandle struct {
+ id uint32
+ open bool
+}
+
+func (item ownedItem) isSmallBackpack() bool {
+ return item.Type == 51017 && item.Template == 99228 && item.Quality == 1
+}
+
+func backpackPacket(owner, playfield uint32, item ownedItem) []byte {
+ // ChestFullUpdate inherits SimpleItem 11 and Lockable 2, ending in Chest 3.
+ var body []byte
+ for _, value := range []uint32{11, 50000, owner, playfield, 0, 0} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ body = append(body, 104, byte(item.Slot))
+ body = binary.BigEndian.AppendUint32(body, 5*1009)
+ for _, value := range []uint32{23, item.Template, 701, item.Quality, 702, item.Template, 703, item.Template, 0, 2, 0, 1009, 3} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x465a5d73, 51017, item.ID, body)
+}
+
+func backpackInventoryPacket(owner, bag, index uint32, items []ownedItem) []byte {
+ body := binary.BigEndian.AppendUint32(nil, uint32(len(items)+1)*1009)
+ for _, item := range items {
+ for _, value := range []uint32{item.Slot, 0x00030000 | uint32(item.Count), item.Type, item.ID, item.Template, item.Template, item.Quality, 0} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ }
+ for _, value := range []uint32{51017, bag, index, 1} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x4e536976, 50000, owner, body)
+}
+
+func backpackClosePacket(owner, bag uint32) []byte {
+ var body []byte
+ for _, value := range []uint32{1, 102, 50000, owner} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x2049527c, 51017, bag, body)
+}
+
+func (server *server) handleBackpackUse(client *worldClient, body []byte) error {
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ player := server.characters[client.id]
+ if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || client.equipment != nil ||
+ binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id ||
+ binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 3 || binary.BigEndian.Uint32(body[28:32]) > 1 ||
+ binary.BigEndian.Uint32(body[32:36]) != 50000 || binary.BigEndian.Uint32(body[36:40]) != client.id ||
+ (binary.BigEndian.Uint32(body[40:44]) != 104 && binary.BigEndian.Uint32(body[40:44]) != 51017) {
+ return nil
+ }
+ sequence := binary.BigEndian.Uint32(body[20:24])
+ if sequence <= client.useSequence {
+ return nil
+ }
+ client.useSequence = sequence
+ slot := binary.BigEndian.Uint32(body[44:48])
+ page := binary.BigEndian.Uint32(body[40:44])
+ if page == 104 && (slot < 64 || slot >= 94) {
+ return nil
+ }
+ item := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool {
+ return item.isSmallBackpack() && (page == 104 && item.Slot == slot || page == 51017 && item.ID == slot)
+ })
+ reply := append([]byte(nil), body[16:]...)
+ if item < 0 {
+ binary.BigEndian.PutUint32(reply, 2)
+ return client.send(n3Packet(0x52526858, 50000, client.id, reply))
+ }
+ bag := player.inventory.Items[item]
+ binary.BigEndian.PutUint32(reply, 1)
+ if err := client.send(n3Packet(0x52526858, 50000, client.id, reply)); err != nil {
+ return err
+ }
+ for index, handle := range client.backpacks {
+ if handle.id == bag.ID {
+ client.backpacks[index] = backpackHandle{bag.ID, !handle.open}
+ if handle.open {
+ return client.send(backpackClosePacket(client.id, bag.ID))
+ }
+ return client.send(backpackInventoryPacket(client.id, bag.ID, index, player.inventory.Containers[bag.ID]))
+ }
+ }
+
+ // Page 107 packs this session's container handle above its contents slot.
+ if client.backpacks == nil {
+ client.backpacks = make(map[uint32]backpackHandle)
+ }
+ index := uint32(1)
+ for client.backpacks[index].id != 0 {
+ index++
+ }
+ client.backpacks[index] = backpackHandle{bag.ID, true}
+ if err := client.send(backpackPacket(client.id, player.playfield, bag)); err != nil {
+ return err
+ }
+ return client.send(backpackInventoryPacket(client.id, bag.ID, index, player.inventory.Containers[bag.ID]))
+}
+
+func (server *server) moveBackpackItem_locked(client *worldClient, body []byte) error {
+ if !client.target {
+ return nil
+ }
+ player := server.characters[client.id]
+ inventory := player.inventory
+ sourcePage, sourceSlot := binary.BigEndian.Uint32(body[16:20]), binary.BigEndian.Uint32(body[20:24])
+ sourceBag := uint32(0)
+ items := inventory.Items
+ if sourcePage == 107 {
+ sourceBag = client.backpacks[sourceSlot>>16].id
+ if sourceBag == 0 || !client.backpacks[sourceSlot>>16].open || !slices.ContainsFunc(inventory.Items, func(item ownedItem) bool { return item.ID == sourceBag && item.isSmallBackpack() }) {
+ return nil
+ }
+ sourceSlot &= 65535
+ items = inventory.Containers[sourceBag]
+ } else if sourcePage != 104 || sourceSlot < 64 || sourceSlot >= 94 {
+ return nil
+ }
+ index := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == sourceSlot })
+ if index < 0 {
+ return nil
+ }
+ item := items[index]
+
+ // Validate the owner and placement before changing either side of the transfer.
+ targetType, targetID, slot := binary.BigEndian.Uint32(body[24:28]), binary.BigEndian.Uint32(body[28:32]), binary.BigEndian.Uint32(body[32:36])
+ targetBag := uint32(0)
+ targetItems := inventory.Items
+ first, end := uint32(64), uint32(94)
+ if targetType == 51017 {
+ if targetID == sourceBag || !slices.ContainsFunc(inventory.Items, func(item ownedItem) bool { return item.ID == targetID && item.isSmallBackpack() }) {
+ return nil
+ }
+ known := false
+ for _, handle := range client.backpacks {
+ known = known || handle.id == targetID
+ }
+ if !known || item.Type == 51017 || itemStat(gamedata.ItemTemplates[item.Template], 0)&0x00200000 != 0 || itemStat(gamedata.ItemTemplates[item.Template], 8) > 0 {
+ return nil
+ }
+ targetBag, targetItems, first, end = targetID, inventory.Containers[targetID], 0, 21
+ if itemStat(gamedata.ItemTemplates[item.Template], 0)&0x08000000 != 0 &&
+ slices.ContainsFunc(targetItems, func(other ownedItem) bool { return other.Template == item.Template }) {
+ return nil
+ }
+ // The native Chest receiver always chooses its first free contents slot.
+ slot = 111
+ } else if targetType != 50000 || targetID != client.id || sourceBag == 0 {
+ return nil
+ }
+ if slot == 111 {
+ for slot = first; slot < end; slot++ {
+ if !slices.ContainsFunc(targetItems, func(item ownedItem) bool { return item.Slot == slot }) {
+ break
+ }
+ }
+ }
+ if slot < first || slot >= end || slices.ContainsFunc(targetItems, func(item ownedItem) bool { return item.Slot == slot }) {
+ return nil
+ }
+
+ // One inventory file commits ownership, quantity and both container locations.
+ inventory.Containers = maps.Clone(inventory.Containers)
+ if inventory.Containers == nil {
+ inventory.Containers = make(map[uint32][]ownedItem)
+ }
+ remaining := slices.Delete(slices.Clone(items), index, index+1)
+ if sourceBag == 0 {
+ inventory.Items = remaining
+ } else if len(remaining) == 0 {
+ delete(inventory.Containers, sourceBag)
+ } else {
+ inventory.Containers[sourceBag] = remaining
+ }
+ item.Slot = slot
+ targetItems = append(slices.Clone(targetItems), item)
+ if targetBag == 0 {
+ inventory.Items = targetItems
+ } else {
+ inventory.Containers[targetBag] = targetItems
+ }
+ if len(inventory.Containers) == 0 {
+ inventory.Containers = nil
+ }
+ if err := server.saveInventory_locked(player, inventory); err != nil {
+ return err
+ }
+ reply := append([]byte(nil), body[16:]...)
+ binary.BigEndian.PutUint32(reply[16:20], slot)
+ return client.send(n3Packet(0x47537a24, 50000, client.id, reply))
+}
+
+func (server *server) handleBackpackAction_locked(client *worldClient, body []byte) error {
+ position := binary.BigEndian.Uint32(body[24:28])
+ handle := client.backpacks[position>>16]
+ player := server.characters[client.id]
+ if !client.target || !handle.open || !slices.ContainsFunc(player.inventory.Items, func(item ownedItem) bool { return item.ID == handle.id && item.isSmallBackpack() }) {
+ return nil
+ }
+ action := binary.BigEndian.Uint32(body[16:20])
+ if client.equipment != nil {
+ if action == 52 {
+ return server.syncStackPage_locked(client, handle.id)
+ }
+ return nil
+ }
+ items := player.inventory.Containers[handle.id]
+ index := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == position&65535 })
+ if index < 0 {
+ if action == 52 {
+ return server.syncStackPage_locked(client, handle.id)
+ }
+ return nil
+ }
+ if action == 52 || action == 53 {
+ return server.changeStack_locked(client, index, body)
+ }
+ if action != 112 || binary.BigEndian.Uint32(body[28:32]) != items[index].Template || binary.BigEndian.Uint32(body[32:36]) != items[index].Template {
+ return nil
+ }
+ inventory := player.inventory
+ inventory.Containers = maps.Clone(inventory.Containers)
+ inventory.Containers[handle.id] = slices.Delete(slices.Clone(items), index, index+1)
+ if len(inventory.Containers[handle.id]) == 0 {
+ delete(inventory.Containers, handle.id)
+ }
+ if len(inventory.Containers) == 0 {
+ inventory.Containers = nil
+ }
+ if err := server.saveInventory_locked(player, inventory); err != nil {
+ return err
+ }
+ return client.send(n3Packet(0x5e477770, 50000, client.id, body[16:]))
+}
diff --git a/server/backpacks_test.go b/server/backpacks_test.go
@@ -0,0 +1,416 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "net"
+ "os"
+ "reflect"
+ "slices"
+ "sync"
+ "testing"
+ "time"
+)
+
+func backpackUseRequest(owner, slot, sequence uint32) []byte {
+ var body []byte
+ for _, value := range []uint32{0, sequence, 3, 0, 50000, owner, 104, slot} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x52526858, 50000, owner, body)
+}
+
+func backpackMoveRequest(page, source, targetType, target, destination uint32) []byte {
+ var body []byte
+ for _, value := range []uint32{page, source, targetType, target, destination} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x47537a24, 50000, 1, body)
+}
+
+func newBackpackWorld(t *testing.T) (*server, *combatTestConn) {
+ t.Helper()
+ world, conn := newStackWorld(t)
+ for _, template := range []uint32{99228, 99228, 121567} {
+ if granted, err := world.grantItem_locked(world.characters[1], template); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ }
+ return world, conn
+}
+
+func TestBackpackOpenCloseAndDistinctHandles(t *testing.T) {
+ world, conn := newBackpackWorld(t)
+ client := world.clients[1]
+
+ for _, request := range [][]byte{backpackUseRequest(1, 66, 1), backpackUseRequest(1, 66, 1), backpackUseRequest(1, 67, 2), backpackUseRequest(1, 66, 3), backpackUseRequest(1, 66, 4)} {
+ if binary.BigEndian.Uint32(request[40:44]) >= 3 {
+ // An already instantiated Chest uses mode 1 on both close and reopen.
+ binary.BigEndian.PutUint32(request[48:52], 1)
+ }
+ if binary.BigEndian.Uint32(request[40:44]) == 3 {
+ // The native window's X button addresses the live Chest itself.
+ binary.BigEndian.PutUint32(request[60:64], 51017)
+ binary.BigEndian.PutUint32(request[64:68], 3)
+ }
+ if err := world.handleBackpackUse(client, request[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if !reflect.DeepEqual(client.backpacks, map[uint32]backpackHandle{1: {3, true}, 2: {4, true}}) || len(conn.packets) != 10 {
+ t.Fatalf("repeated use or independent windows lost their handles: %+v packets%d", client.backpacks, len(conn.packets))
+ }
+ if binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x465a5d73 || conn.packets[1][54] != 50 ||
+ binary.BigEndian.Uint32(conn.packets[2][41:45]) != 1 || binary.BigEndian.Uint32(conn.packets[5][41:45]) != 2 ||
+ binary.BigEndian.Uint32(conn.packets[7][16:20]) != 0x2049527c || binary.BigEndian.Uint32(conn.packets[7][33:37]) != 102 {
+ t.Fatal("native Chest placement, handle or close packet differs")
+ }
+}
+
+func TestBackpackNativeWireTransferAndRestart(t *testing.T) {
+ newBackpackWorld(t)
+ world := newTestInventoryServer(t)
+ client, connection := net.Pipe()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ done := make(chan error, 1)
+ go func() { defer connection.Close(); done <- world.serveWorldConnection(connection) }()
+ defer func() {
+ client.Close()
+ if err := <-done; err != nil {
+ t.Error(err)
+ }
+ }()
+ cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})
+ binary.BigEndian.PutUint16(cookie, 0xdfdf)
+ client.Write(cookie)
+ for {
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5f52412e {
+ break
+ }
+ }
+ client.Write(targetPacket(n3Packet(0x570c2039, 50000, 1, nil)))
+ readPacket(client)
+
+ client.Write(targetPacket(backpackUseRequest(1, 66, 1)))
+ ack, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ chest, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ contents, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ client.Write(targetPacket(backpackMoveRequest(104, 68, 51017, 3, 111)))
+ put, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stored := newTestInventoryServer(t).characters[1].inventory
+ client.Write(targetPacket(backpackMoveRequest(107, 1<<16, 50000, 1, 93)))
+ taken, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ restarted := newTestInventoryServer(t).characters[1]
+
+ if binary.BigEndian.Uint32(ack[29:33]) != 1 || binary.BigEndian.Uint32(ack[57:61]) != 50 ||
+ binary.BigEndian.Uint32(chest[20:24]) != 51017 || binary.BigEndian.Uint32(contents[29:33]) != 1009 ||
+ binary.BigEndian.Uint32(put[45:49]) != 0 || binary.BigEndian.Uint32(taken[33:37]) != 1<<16 || binary.BigEndian.Uint32(taken[45:49]) != 77 {
+ t.Fatalf("native backpack fields changed: %x %x %x %x %x", ack, chest, contents, put, taken)
+ }
+ if !reflect.DeepEqual(stored.Containers, map[uint32][]ownedItem{3: {{5, 51018, 121567, 1, 0, 1}}}) ||
+ len(restarted.inventory.Containers) != 0 || !slices.Contains(restarted.inventory.Items, ownedItem{5, 51018, 121567, 1, 93, 1}) || restarted.inventory.LastID != 5 {
+ t.Fatalf("transfer changed item identity or failed persistence: %+v %+v", stored, restarted.inventory)
+ }
+}
+
+func TestBackpackTransferBetweenClosedAndOpenBags(t *testing.T) {
+ world, _ := newBackpackWorld(t)
+ client := world.clients[1]
+ world.handleBackpackUse(client, backpackUseRequest(1, 66, 1)[20:])
+ world.handleBackpackUse(client, backpackUseRequest(1, 67, 2)[20:])
+ world.handleBackpackUse(client, backpackUseRequest(1, 66, 3)[20:])
+
+ for _, request := range [][]byte{backpackMoveRequest(104, 68, 51017, 3, 111), backpackUseRequest(1, 66, 4)} {
+ var err error
+ if binary.BigEndian.Uint32(request[20:24]) == 0x47537a24 {
+ err = world.handleInventory(client, request[20:])
+ } else {
+ err = world.handleBackpackUse(client, request[20:])
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ err := world.handleInventory(client, backpackMoveRequest(107, 1<<16, 51017, 4, 111)[20:])
+ restarted := newTestInventoryServer(t).characters[1]
+
+ if err != nil || !reflect.DeepEqual(restarted.inventory.Containers, map[uint32][]ownedItem{4: {{5, 51018, 121567, 1, 0, 1}}}) || len(restarted.inventory.Items) != 4 {
+ t.Fatalf("closed bag placement or bag-to-bag transfer failed: %+v %v", restarted.inventory, err)
+ }
+}
+
+func TestBackpackRejectsInvalidOwnershipAndPlacement(t *testing.T) {
+ for _, scenario := range []string{"nested", "foreign bag", "unknown handle", "closed source", "unseen bag", "foreign owner", "occupied main", "equipment", "loading", "dead", "stale session"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, conn := newBackpackWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ world.handleBackpackUse(client, backpackUseRequest(1, 66, 1)[20:])
+ world.handleInventory(client, backpackMoveRequest(104, 68, 51017, 3, 111)[20:])
+ request := backpackMoveRequest(107, 1<<16, 50000, 1, 111)[20:]
+ switch scenario {
+ case "nested":
+ request = backpackMoveRequest(104, 67, 51017, 3, 111)[20:]
+ case "foreign bag":
+ request = backpackMoveRequest(104, 64, 51017, 999, 111)[20:]
+ case "unknown handle":
+ request = backpackMoveRequest(107, 8<<16, 50000, 1, 111)[20:]
+ case "closed source":
+ world.handleBackpackUse(client, backpackUseRequest(1, 66, 2)[20:])
+ case "unseen bag":
+ request = backpackMoveRequest(104, 64, 51017, 4, 111)[20:]
+ case "foreign owner":
+ binary.BigEndian.PutUint32(request[28:32], 2)
+ case "occupied main":
+ binary.BigEndian.PutUint32(request[32:36], 64)
+ case "equipment":
+ client.equipment = &equipmentMove{}
+ case "loading":
+ client.loading = true
+ case "dead":
+ player.health = 0
+ case "stale session":
+ world.clients[1] = &worldClient{id: 1}
+ }
+ before, err := os.ReadFile("data/players/1/inventory.yaml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ packets := len(conn.packets)
+
+ err = world.handleInventory(client, request)
+ after, readErr := os.ReadFile("data/players/1/inventory.yaml")
+
+ if err != nil || readErr != nil || !bytes.Equal(before, after) || len(conn.packets) != packets {
+ t.Fatal("invalid placement changed persisted ownership or sent success", err, readErr)
+ }
+ })
+ }
+}
+
+func TestBackpackCapacityTwentyOneAndFullMainInventory(t *testing.T) {
+ world, _ := newBackpackWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ world.handleBackpackUse(client, backpackUseRequest(1, 66, 1)[20:])
+ for range 21 {
+ item := player.inventory.Items[len(player.inventory.Items)-1]
+ if err := world.handleInventory(client, backpackMoveRequest(104, item.Slot, 51017, 3, 111)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(player, 121567); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ }
+ before := player.inventory
+
+ err := world.handleInventory(client, backpackMoveRequest(104, 68, 51017, 3, 111)[20:])
+ fullBag := reflect.DeepEqual(player.inventory, before)
+ for len(player.inventory.Items) < 30 {
+ if granted, err := world.grantItem_locked(player, 121567); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ }
+ world.handleInventory(client, backpackMoveRequest(107, 1<<16|20, 50000, 1, 111)[20:])
+ restarted := newTestInventoryServer(t).characters[1]
+
+ if err != nil || !fullBag || len(restarted.inventory.Items) != 30 || len(restarted.inventory.Containers[3]) != 21 || restarted.inventory.Containers[3][20].Slot != 20 {
+ t.Fatalf("capacity rejection lost an item: %+v %v", restarted.inventory, err)
+ }
+}
+
+func TestBackpackConcurrentTransferAndFailedSave(t *testing.T) {
+ world, conn := newBackpackWorld(t)
+ client := world.clients[1]
+ world.handleBackpackUse(client, backpackUseRequest(1, 66, 1)[20:])
+ conn.packets = nil
+ request := backpackMoveRequest(104, 68, 51017, 3, 111)[20:]
+ var workers sync.WaitGroup
+ errors := make(chan error, 2)
+
+ for range 2 {
+ workers.Go(func() { errors <- world.handleInventory(client, request) })
+ }
+ workers.Wait()
+ close(errors)
+ before := world.characters[1].inventory
+ if err := os.Remove("data/players/1/inventory.yaml"); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Mkdir("data/players/1/inventory.yaml", 0700); err != nil {
+ t.Fatal(err)
+ }
+ err := world.handleInventory(client, backpackMoveRequest(107, 1<<16, 50000, 1, 111)[20:])
+
+ for err := range errors {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err == nil || !reflect.DeepEqual(world.characters[1].inventory, before) || len(conn.packets) != 1 || len(before.Containers[3]) != 1 || len(before.Items) != 4 {
+ t.Fatal("repeat transfer or failed save changed ownership", err)
+ }
+}
+
+func TestBackpackStackSplitJoinAndDelete(t *testing.T) {
+ world, _ := newBackpackWorld(t)
+ client := world.clients[1]
+ world.handleBackpackUse(client, backpackUseRequest(1, 66, 1)[20:])
+ world.handleInventory(client, backpackMoveRequest(104, 64, 51017, 3, 111)[20:])
+ action := func(kind, source, otherPage, argument uint32) []byte {
+ var body []byte
+ for _, value := range []uint32{kind, 107, source, otherPage, argument} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x5e477770, 50000, 1, body)[20:]
+ }
+
+ for _, request := range [][]byte{action(52, 1<<16, 0, 1), action(52, 1<<16, 0, 1), action(53, 1<<16, 107, 1<<16|1)} {
+ if err := world.handleInventory(client, request); err != nil {
+ t.Fatal(err)
+ }
+ }
+ joined := newTestInventoryServer(t).characters[1].inventory
+ err := world.handleInventory(client, action(112, 1<<16, 152030, 152030))
+ restarted := newTestInventoryServer(t).characters[1]
+
+ if err != nil || !reflect.DeepEqual(joined.Containers[3], []ownedItem{{1, 51005, 152030, 42, 0, 3}}) || len(restarted.inventory.Containers) != 0 || restarted.inventory.LastID != 6 {
+ t.Fatalf("bag stack actions lost quantities/identities: %+v %+v %v", joined, restarted.inventory, err)
+ }
+}
+
+func TestBackpackContentsSurviveReclaim(t *testing.T) {
+ world, _ := newBackpackWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ player.level = 10
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ world.handleBackpackUse(client, backpackUseRequest(1, 66, 1)[20:])
+ world.handleInventory(client, backpackMoveRequest(104, 64, 51017, 3, 111)[20:])
+
+ defeatReclaimPlayer(t, world)
+ restarted := newTestInventoryServer(t)
+ contents := restarted.characters[1].inventory.Containers[3]
+ player.health = player.maximumHealth()
+ player.playfield, player.position = 705, [3]float32{918, 20.7, 578}
+ for index := range player.inventory.Reclaim {
+ player.inventory.Reclaim[index].AvailableAt = time.Now().Add(-time.Second)
+ }
+ world.handleReclaim(client, reclaimRequest(109))
+ slot := slices.Index(client.reclaimItems, uint32(3))
+ if slot < 0 {
+ t.Fatal("backpack was lost from reclaim")
+ }
+ err := world.handleInventory(client, reclaimTakeRequest(uint32(slot)))
+ world.handleBackpackUse(client, backpackUseRequest(1, 64, 2)[20:])
+
+ if err != nil || !reflect.DeepEqual(contents, []ownedItem{{1, 51005, 152030, 42, 0, 3}}) ||
+ !reflect.DeepEqual(player.inventory.Containers[3], contents) || !slices.Contains(player.inventory.Items, ownedItem{3, 51017, 99228, 1, 64, 1}) || !client.backpacks[1].open {
+ t.Fatalf("reclaim lost a filled backpack or its contents: %+v %v", player.inventory, err)
+ }
+}
+
+func TestBackpackDeleteRemovesContentsAtomically(t *testing.T) {
+ world, _ := newBackpackWorld(t)
+ client := world.clients[1]
+ world.handleBackpackUse(client, backpackUseRequest(1, 66, 1)[20:])
+ world.handleInventory(client, backpackMoveRequest(104, 68, 51017, 3, 111)[20:])
+ request := inventoryDeletePacket(1, 66)[20:]
+ binary.BigEndian.PutUint32(request[28:32], 99228)
+ binary.BigEndian.PutUint32(request[32:36], 99228)
+
+ err := world.handleInventory(client, request)
+ restarted := newTestInventoryServer(t).characters[1]
+ world.handleInventory(client, backpackMoveRequest(107, 1<<16, 50000, 1, 111)[20:])
+
+ if err != nil || len(restarted.inventory.Containers) != 0 || len(restarted.inventory.Items) != 3 || len(client.backpacks) != 0 || restarted.inventory.LastID != 5 {
+ t.Fatalf("deleting a backpack left recoverable orphan contents: %+v %v", restarted.inventory, err)
+ }
+}
+
+func TestBackpackLoadRejectsOrphanedAndDuplicateContents(t *testing.T) {
+ for _, scenario := range []string{"orphan", "duplicate", "nested", "outside capacity", "occupied"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, _ := newBackpackWorld(t)
+ inventory := world.characters[1].inventory
+ inventory.LastID = 7
+ inventory.Containers = map[uint32][]ownedItem{3: {{6, 51018, 121567, 1, 0, 1}}}
+ switch scenario {
+ case "orphan":
+ inventory.Containers[99] = inventory.Containers[3]
+ delete(inventory.Containers, 3)
+ case "duplicate":
+ inventory.Containers[3][0].ID = 1
+ case "nested":
+ inventory.Containers[3][0] = ownedItem{6, 51017, 99228, 1, 0, 1}
+ case "outside capacity":
+ inventory.Containers[3][0].Slot = 21
+ case "occupied":
+ inventory.Containers[3] = append(inventory.Containers[3], ownedItem{7, 51018, 121567, 1, 0, 1})
+ }
+ if err := world.saveInventory_locked(world.characters[1], inventory); err != nil {
+ t.Fatal(err)
+ }
+ restarted := &server{characters: make(map[uint32]*character)}
+
+ err := restarted.loadUsers()
+
+ if err == nil {
+ t.Fatal("invalid backpack ownership or placement was accepted")
+ }
+ })
+ }
+}
+
+func TestBackpackRejectsInvalidUse(t *testing.T) {
+ for _, scenario := range []string{"outer owner", "target owner", "source page", "source slot", "mode", "loading", "dead", "stale session"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, conn := newBackpackWorld(t)
+ client := world.clients[1]
+ request := backpackUseRequest(1, 66, 1)[20:]
+ switch scenario {
+ case "outer owner":
+ binary.BigEndian.PutUint32(request[8:12], 2)
+ case "target owner":
+ binary.BigEndian.PutUint32(request[36:40], 2)
+ case "source page":
+ binary.BigEndian.PutUint32(request[40:44], 106)
+ case "source slot":
+ binary.BigEndian.PutUint32(request[44:48], 0)
+ case "mode":
+ binary.BigEndian.PutUint32(request[28:32], 2)
+ case "loading":
+ client.loading = true
+ case "dead":
+ world.characters[1].health = 0
+ case "stale session":
+ world.clients[1] = &worldClient{id: 1}
+ }
+
+ err := world.handleBackpackUse(client, request)
+
+ if err != nil || len(client.backpacks) != 0 || len(conn.packets) != 0 {
+ t.Fatal("invalid use opened a backpack", err)
+ }
+ })
+ }
+}
diff --git a/server/combat.go b/server/combat.go
@@ -289,6 +289,7 @@ func (server *server) advanceCombat(now time.Time) {
target.position = predictedPosition_locked(target, client, now)
client.forward = 0
client.reclaimItems = nil
+ client.backpacks = nil
}
server.cancelCombat_locked(target.id, updates)
server.queueCombat_locked(updates, target, target, deathPacket(target))
diff --git a/server/inventory.go b/server/inventory.go
@@ -4,6 +4,7 @@ import (
"ao/server/gamedata"
"encoding/binary"
"fmt"
+ "maps"
"slices"
"time"
@@ -25,14 +26,16 @@ type reclaimItem struct {
}
type playerInventory struct {
- LastID uint32 `yaml:"last_id"`
- Items []ownedItem `yaml:"items"`
- Reclaim []reclaimItem `yaml:"reclaim,omitempty"`
+ LastID uint32 `yaml:"last_id"`
+ Items []ownedItem `yaml:"items"`
+ Reclaim []reclaimItem `yaml:"reclaim,omitempty"`
+ Containers map[uint32][]ownedItem `yaml:"containers,omitempty"`
}
func (inventory playerInventory) validate() error {
ids := make(map[uint32]bool)
slots := make(map[uint32]bool)
+ bags := make(map[uint32]bool)
for _, item := range inventory.Items {
if item.ID == 0 || item.ID > inventory.LastID || ids[item.ID] || item.Count == 0 ||
(item.Count != 1 && !item.isEssenceStack()) ||
@@ -41,6 +44,9 @@ func (inventory playerInventory) validate() error {
return fmt.Errorf("invalid inventory item identity or slot")
}
ids[item.ID], slots[item.Slot] = true, true
+ if item.isSmallBackpack() {
+ bags[item.ID] = true
+ }
}
for _, entry := range inventory.Reclaim {
if entry.Item.ID == 0 || entry.Item.ID > inventory.LastID || ids[entry.Item.ID] || entry.Item.Count == 0 ||
@@ -48,6 +54,22 @@ func (inventory playerInventory) validate() error {
return fmt.Errorf("invalid reclaim item identity or slot")
}
ids[entry.Item.ID] = true
+ if entry.Item.isSmallBackpack() {
+ bags[entry.Item.ID] = true
+ }
+ }
+ for bag, items := range inventory.Containers {
+ if !bags[bag] {
+ return fmt.Errorf("contents without an owned backpack")
+ }
+ var occupied [21]bool
+ for _, item := range items {
+ if item.ID == 0 || item.ID > inventory.LastID || ids[item.ID] || item.Type == 51017 ||
+ item.Count == 0 || (item.Count != 1 && !item.isEssenceStack()) || item.Slot >= 21 || occupied[item.Slot] {
+ return fmt.Errorf("invalid backpack item identity or slot")
+ }
+ ids[item.ID], occupied[item.Slot] = true, true
+ }
}
return nil
}
@@ -116,12 +138,19 @@ func (server *server) handleInventory(client *worldClient, body []byte) error {
binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id {
return nil
}
+ if key == 0x5e477770 && binary.BigEndian.Uint32(body[20:24]) == 107 && binary.BigEndian.Uint32(body[24:28])>>16 != 0 {
+ return server.handleBackpackAction_locked(client, body)
+ }
if client.equipment != nil {
if key == 0x5e477770 && binary.BigEndian.Uint32(body[16:20]) == 52 {
return server.syncStacks_locked(client)
}
return nil
}
+ if key == 0x47537a24 && (binary.BigEndian.Uint32(body[24:28]) == 51017 ||
+ binary.BigEndian.Uint32(body[16:20]) == 107 && binary.BigEndian.Uint32(body[20:24])>>16 != 0) {
+ return server.moveBackpackItem_locked(client, body)
+ }
// Page identities must agree with this owner's actual logical slot.
sourceType, sourceSlot := binary.BigEndian.Uint32(body[16:20]), binary.BigEndian.Uint32(body[20:24])
@@ -169,10 +198,29 @@ func (server *server) handleInventory(client *worldClient, body []byte) error {
return nil
}
inventory.Items = slices.Delete(inventory.Items, index, index+1)
+ if character.inventory.Items[index].isSmallBackpack() {
+ inventory.Containers = maps.Clone(inventory.Containers)
+ delete(inventory.Containers, character.inventory.Items[index].ID)
+ if len(inventory.Containers) == 0 {
+ inventory.Containers = nil
+ }
+ }
}
if err := server.saveInventory_locked(character, inventory); err != nil {
return err
}
+ if key == 0x5e477770 {
+ for handle, bag := range client.backpacks {
+ if !slices.ContainsFunc(inventory.Items, func(item ownedItem) bool { return item.ID == bag.id }) {
+ delete(client.backpacks, handle)
+ if bag.open {
+ if err := client.send(backpackClosePacket(client.id, bag.id)); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ }
// send only enqueues owned packet bytes, never waits for the transport.
return client.send(n3Packet(key, 50000, client.id, body[16:]))
}
diff --git a/server/inventory_test.go b/server/inventory_test.go
@@ -58,7 +58,7 @@ func TestInventoryNativeMoveDeleteAndRestart(t *testing.T) {
t.Fatal(err)
}
if binary.BigEndian.Uint32(packet[16:20]) == 0x29304349 {
- if hex.EncodeToString(packet[33:69]) != "000007e200000030000200010000c74a000000010001dadf0001dadf0000000100000000" {
+ if hex.EncodeToString(packet[33:69]) != "000007e200000030000100010000c74a000000010001dadf0001dadf0000000100000000" {
t.Fatalf("native inventory list: %x", packet[33:69])
}
}
diff --git a/server/main.go b/server/main.go
@@ -407,7 +407,9 @@ func (server *server) serveWorldClient(client *worldClient) error {
switch binary.BigEndian.Uint32(body[0:4]) {
case 0x52526858:
var err error
- if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 51005 || binary.BigEndian.Uint32(body[40:44]) == 51059) {
+ if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 104 || binary.BigEndian.Uint32(body[40:44]) == 51017) {
+ err = server.handleBackpackUse(client, body)
+ } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 51005 || binary.BigEndian.Uint32(body[40:44]) == 51059) {
err = server.handleTerminalUse(client, body)
} else {
err = server.handleLootUse(client, body)
diff --git a/server/stacks.go b/server/stacks.go
@@ -3,6 +3,7 @@ package main
import (
"encoding/binary"
"fmt"
+ "maps"
"slices"
)
@@ -12,54 +13,74 @@ func (item ownedItem) isEssenceStack() bool {
func (server *server) changeStack_locked(client *worldClient, index int, body []byte) error {
player := server.characters[client.id]
- if !player.inventory.Items[index].isEssenceStack() {
+ inventory := player.inventory
+ items := inventory.Items
+ bag := uint32(0)
+ first, end := uint32(64), uint32(94)
+ if binary.BigEndian.Uint32(body[20:24]) == 107 {
+ bag = client.backpacks[binary.BigEndian.Uint32(body[24:28])>>16].id
+ items, first, end = inventory.Containers[bag], 0, 21
+ }
+ if !items[index].isEssenceStack() {
return nil
}
- inventory := player.inventory
- inventory.Items = slices.Clone(player.inventory.Items)
+ items = slices.Clone(items)
if binary.BigEndian.Uint32(body[16:20]) == 52 {
// Action 52 carries the count retained in the original, already split locally.
retained := binary.BigEndian.Uint32(body[32:36])
- if retained == uint32(inventory.Items[index].Count) && binary.BigEndian.Uint32(body[28:32]) == 0 {
+ if retained == uint32(items[index].Count) && binary.BigEndian.Uint32(body[28:32]) == 0 {
return nil
}
- if binary.BigEndian.Uint32(body[28:32]) != 0 || retained == 0 || retained > uint32(inventory.Items[index].Count) {
- return server.syncStacks_locked(client)
+ if binary.BigEndian.Uint32(body[28:32]) != 0 || retained == 0 || retained > uint32(items[index].Count) {
+ return server.syncStackPage_locked(client, bag)
}
var slot uint32
- for slot = 64; slot < 94; slot++ {
- if !slices.ContainsFunc(inventory.Items, func(item ownedItem) bool { return item.Slot == slot }) {
+ for slot = first; slot < end; slot++ {
+ if !slices.ContainsFunc(items, func(item ownedItem) bool { return item.Slot == slot }) {
break
}
}
- if slot == 94 {
- return server.syncStacks_locked(client)
+ if slot == end {
+ return server.syncStackPage_locked(client, bag)
}
if server.nextItem == ^uint32(0) {
return fmt.Errorf("item identities exhausted")
}
- item := inventory.Items[index]
+ item := items[index]
inventory.LastID = server.nextItem + 1
item.ID, item.Slot, item.Count = inventory.LastID, slot, item.Count-uint16(retained)
- inventory.Items[index].Count = uint16(retained)
- inventory.Items = append(inventory.Items, item)
+ items[index].Count = uint16(retained)
+ items = append(items, item)
} else {
// The native join response keeps the first slot and removes the second.
- other := slices.IndexFunc(inventory.Items, func(item ownedItem) bool { return item.Slot == binary.BigEndian.Uint32(body[32:36]) })
- if binary.BigEndian.Uint32(body[28:32]) != 104 || other < 0 || other == index || !inventory.Items[other].isEssenceStack() {
+ otherSlot := binary.BigEndian.Uint32(body[32:36])
+ if bag != 0 {
+ if otherSlot>>16 != binary.BigEndian.Uint32(body[24:28])>>16 {
+ return nil
+ }
+ otherSlot &= 65535
+ }
+ other := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == otherSlot })
+ if binary.BigEndian.Uint32(body[28:32]) != binary.BigEndian.Uint32(body[20:24]) || other < 0 || other == index || !items[other].isEssenceStack() {
return nil
}
- count := uint32(inventory.Items[index].Count) + uint32(inventory.Items[other].Count)
+ count := uint32(items[index].Count) + uint32(items[other].Count)
// Native ushort addition wraps; prevent loss at its representation ceiling.
// This is not evidence of the original server's maximum permitted stack.
if count > 65535 {
return nil
}
- inventory.Items[index].Count = uint16(count)
- inventory.Items = slices.Delete(inventory.Items, other, other+1)
+ items[index].Count = uint16(count)
+ items = slices.Delete(items, other, other+1)
}
// Publish quantities and any new identity only after one atomic inventory save.
+ if bag == 0 {
+ inventory.Items = items
+ } else {
+ inventory.Containers = maps.Clone(inventory.Containers)
+ inventory.Containers[bag] = items
+ }
if err := server.saveInventory_locked(player, inventory); err != nil {
return err
}
@@ -67,6 +88,18 @@ func (server *server) changeStack_locked(client *worldClient, index int, body []
return client.send(n3Packet(0x5e477770, 50000, client.id, body[16:]))
}
+func (server *server) syncStackPage_locked(client *worldClient, bag uint32) error {
+ if bag == 0 {
+ return server.syncStacks_locked(client)
+ }
+ for index, handle := range client.backpacks {
+ if handle.id == bag {
+ return client.send(backpackInventoryPacket(client.id, bag, index, server.characters[client.id].inventory.Containers[bag]))
+ }
+ }
+ return nil
+}
+
func (server *server) syncStacks_locked(client *worldClient) error {
// Preserve live individual items and equipped modifiers. Only Essence has
// optimistic clones here, and its catalog has no deletion event functions.
diff --git a/server/state.go b/server/state.go
@@ -61,6 +61,7 @@ type worldClient struct {
equipment *equipmentMove
lootCorpse uint32
reclaimItems []uint32
+ backpacks map[uint32]backpackHandle
useSequence uint32
}
diff --git a/server/target_protocol.go b/server/target_protocol.go
@@ -105,9 +105,18 @@ func targetPacket(packet []byte) []byte {
binary.BigEndian.PutUint32(packet[40:44], binary.BigEndian.Uint32(packet[40:44])-16)
}
destination := binary.BigEndian.Uint32(packet[52:56])
- if destination >= 64 && destination < 94 {
+ if binary.BigEndian.Uint32(packet[44:48]) == 50000 && destination >= 64 && destination < 94 {
binary.BigEndian.PutUint32(packet[52:56], destination-16)
}
+ case 0x465a5d73:
+ // Owned Chest placement follows its parent, playfield and auxiliary identity.
+ if packet[60] == 104 {
+ packet[61] -= 16
+ }
+ case 0x52526858:
+ if len(packet) == 68 && binary.BigEndian.Uint32(packet[60:64]) == 104 {
+ binary.BigEndian.PutUint32(packet[64:68], binary.BigEndian.Uint32(packet[64:68])-16)
+ }
case 0x5e477770:
action := binary.BigEndian.Uint32(packet[36:40])
if (action == 52 || action == 53 || action == 112) && binary.BigEndian.Uint32(packet[40:44]) == 104 {
@@ -139,6 +148,10 @@ func targetPacket(packet []byte) []byte {
}
func decodeInventory1491(body []byte) {
+ if len(body) == 48 && binary.BigEndian.Uint32(body) == 0x52526858 && binary.BigEndian.Uint32(body[40:44]) == 104 {
+ binary.BigEndian.PutUint32(body[44:48], decodeInventorySlot1491(binary.BigEndian.Uint32(body[44:48])))
+ return
+ }
if len(body) != 36 {
return
}
@@ -148,7 +161,7 @@ func decodeInventory1491(body []byte) {
binary.BigEndian.PutUint32(body[20:24], decodeInventorySlot1491(binary.BigEndian.Uint32(body[20:24])))
}
destination := binary.BigEndian.Uint32(body[32:36])
- if destination != 6 && destination != 21 && destination != 30 && destination != 111 {
+ if binary.BigEndian.Uint32(body[24:28]) == 50000 && destination != 6 && destination != 21 && destination != 30 && destination != 111 {
binary.BigEndian.PutUint32(body[32:36], decodeInventorySlot1491(destination))
}
case 0x5e477770:
diff --git a/server/world.go b/server/world.go
@@ -147,11 +147,11 @@ func characterPacket(character *character) []byte {
func fullCharacterPacket(character *character) []byte {
// Version 16 begins with six encoded lists, followed by four stat lists.
body := binary.BigEndian.AppendUint32(nil, 16)
- // Template-stack rows need flag 1; individual live-item rows retain flag 2.
+ // Ordinary template entries need flag 1; worn items and live Chests use flag 2.
body = binary.BigEndian.AppendUint32(body, uint32(len(character.inventory.Items)+1)*1009)
for _, item := range character.inventory.Items {
flags := uint32(2)
- if item.isEssenceStack() {
+ if item.Slot >= 64 && !item.isSmallBackpack() {
flags = 1
}
for _, value := range []uint32{item.Slot, flags<<16 | uint32(item.Count), item.Type, item.ID, item.Template, item.Template, item.Quality, 0} {