commit 06fb2e1b901ff57be40048bff290d7a8d5c684b4
parent 0a525107796dd9d9c9e4df961b349ce07daad8e0
Author: anon <anon@example.com>
Date: Wed, 4 Nov 2026 18:12:53 +0000
Equip supported items directly from carried backpacks
Diffstat:
9 files changed, 656 insertions(+), 7 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -253,6 +253,18 @@ recorded in [inventory behavior](docs/inventory.md).
combining unwear effects and placement. Check exact identities/effects,
occupied/full destinations, pending equipment, failed commits and native
page/cold recovery, without silently requiring an intermediate carried slot.
+ January 2003 reports also disagree on whether a backpack weapon replacement
+ puts the displaced item in the bag or ordinary inventory. Keep occupied
+ backpack-to-wear swaps refused until that policy is established; see
+ [backpack equipment evidence](docs/backpack-wear.md).
+- [x] [P1] Equip supported items directly from carried backpacks into empty slots.
+ A real native source107 request formerly received cancellation. The shared
+ wear delay/requirements now atomically move the same child and apply complete
+ effects. Handler checks cover six equipment families, boundary child slots,
+ changed gates, failed/ignored writes and COMMIT retry. Two WASM clients verify
+ failed completion/source restoration, real retry with all 30 ordinary slots
+ full, weapon/armor effects and all 32 IDs through page/cold ownership recovery.
+ Occupied swaps remain above; see [direct backpack wear](docs/backpack-wear.md).
- [ ] [P2] Merge one stackable item type. Check: compatible stacks combine up to the
applicable limit without changing the total item count.
diff --git a/docs/backpack-wear.md b/docs/backpack-wear.md
@@ -0,0 +1,76 @@
+# Equipment from carried backpacks
+
+Supported equipment can move directly from an open carried backpack into an
+empty wear slot. The move uses the ordinary item's requirements, EquipDelay,
+combat/recharge gates, implant permission, enabled deck slots and complete wear
+effects. It does not need a free ordinary inventory slot.
+
+## Period evidence and limits
+
+In the [January 27..29, 2003 equipment discussion](https://archives.jeuxonline.info/fils/161470.html),
+munn reports successful backpack equipment with Vektors and cushions. Wiseman
+describes directly equipping weapons and other objects, with ordinary inventory
+as a workaround when that fails. This establishes the operation separately from
+the currently supported catalog's individual requirements.
+
+Occupied destinations remain unresolved. MiaJong reports the displaced weapon
+returning to ordinary inventory; Godzilla reports it taking the other weapon's
+bag position, qualified by bugs. These accounts do not establish one reliable
+replacement policy. The server explicitly cancels that source without moving
+either item. Direct worn-to-container placement and bank equipment remain open.
+The April 2002 [backpack discussion](https://archives.jeuxonline.info/fils/80900.html)
+confirms ordinary purchasing/use but supplies no named terminal stock entry.
+Neither thread is used to invent production stock or timing rules.
+
+Raw pages, dates/authors, hashes and parsed messages are retained under
+`local/backpack-period-followup/`. The native request and completion below are
+observations of the maintained 14.9.1 client, not an original-server capture.
+
+## Shared delayed transaction
+
+The native request uses page107 with the session handle in the upper word and
+the child position in the lower word. The pending equipment record retains that
+source plus the physical bag/item IDs. A packed carried source is kept distinct
+from a worn slot when applying shared equipment validation.
+
+Admission performs no ownership write. Completion rechecks the handle binding,
+carried parent, exact child, requirements and empty destination. It clones the
+changed bag contents and root inventory, then commits the existing item's new
+placement through the ordinary inventory transaction. There is no new item ID
+or intermediate carried placement. Successful completion runs the shared native
+move, weapon binding, wear effects, derived-resource updates and inverse cache.
+
+The window may close after admission while its original handle remains bound.
+An admitted-source duplicate stays pending; other requests retain the existing
+refusal behavior. Missing/moved sources, changed gates or failed persistence
+cancel the actual packed source. Failed deletion/insertion, ignored writes and
+COMMIT preserve both ownership and live slices before retry. This adds no new
+equipment timing or combat-swap policy.
+
+## Verification
+
+The 18.59-second native baseline sends the contained axe wear request but gets
+source cancellation with no admitted move. The corrected two-client fixture
+fills all 30 ordinary slots. An ignored placement deletion cancels its first
+attempt and restores the exact bag icon; real pickup/drop retries successfully.
+The axe and vest then enter empty slots6/21 directly from the same bag.
+
+Both clients retain all eight AC values after the vest's single wear event.
+Owner page replay restores the exact worn IDs, empty parent and 29 fillers;
+observer replay retains the effects. Cold Go loading retains all 32 identities
+and properties. No levels, money, gear or supplies are earned for this
+controlled checkpoint. The test advances each
+admitted deadline explicitly and does not measure original-server scheduling.
+
+Public-handler checks cover weapon/finite ammunition, armor, HUD, memory and
+implants at inner positions0/20, before/exact completion, duplicate requests,
+closed-after-admission handles and protected pending sources. Rejection checks
+cover occupied/invalid destinations, unsupported items, requirements, recharge,
+combat, implant permission, deck capacity and changed physical sources. All
+five placement/COMMIT failure forms retain ownership and retry once.
+Artifacts and independent audits are in `local/backpack-equipment/`.
+
+The accepted two-client check took 30.43 seconds and retained 11 clean captures.
+The focused equipment/backpack suite passed 70 roots and 463 results in 81.987
+seconds; the race check passed 16 roots and 133 results in 120.188 seconds.
+Maintained-package vet and the browser script's syntax check passed.
diff --git a/docs/backpacks.md b/docs/backpacks.md
@@ -136,7 +136,10 @@ must not be cited as historical proof.
The native slot bound and placement checks are established. Enforcement of the
catalog's kilogram limits was not recovered, so no new mass cap is
-invented. Equipment moves currently pass through ordinary inventory first.
+invented. Supported equipment can now move directly from an open carried bag
+into an empty wear slot through the shared delayed transaction; see
+[backpack equipment](backpack-wear.md). Occupied-destination swaps and direct worn
+deposits remain refused pending their original placement policy.
Custom names and trades remain separate features. As with other slot-addressed messages, the wire has
no operation token to identify every replay after later slot reuse.
diff --git a/server/backpack_wear_test.go b/server/backpack_wear_test.go
@@ -0,0 +1,293 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "reflect"
+ "slices"
+ "testing"
+ "time"
+)
+
+func newBackpackWearWorld(t *testing.T, template, source uint32) (*server, *combatTestConn) {
+ t.Helper()
+ world, output := newEquipmentWorld(t)
+ player := world.characters[1]
+ player.stats.NanoAiding.Treatment = 20
+ player.stats.Ranged.Pistol, player.stats.Ranged.FlingShot = 100, 100
+ player.implantChangesUntil = time.Now().Add(time.Minute)
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(player, 99228); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ if template == 36779 {
+ if granted, err := world.grantItem_locked(player, 36783); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ if err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 66, 7)[20:]); err != nil || world.clients[1].equipment == nil {
+ t.Fatal("fixture belt did not begin", err)
+ }
+ world.advanceEquipment(world.clients[1].equipment.readyAt)
+ }
+ if granted, err := world.grantItem_locked(player, template); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ inventory := player.inventory
+ child := inventory.Items[len(inventory.Items)-1]
+ child.Slot = source
+ if template == 123742 {
+ child.Quality, child.Ammo = 2, 3
+ }
+ inventory.Items = slices.Clone(inventory.Items[:len(inventory.Items)-1])
+ inventory.Containers = map[uint32][]ownedItem{2: {child}}
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 65, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+ return world, output
+}
+
+func TestBackpackWearSharesDelayedEquipmentAndColdOwnership(t *testing.T) {
+ for _, scenario := range [][2]uint32{{209283, 6}, {123742, 6}, {85481, 21}, {161699, 3}, {36779, 9}, {101173, 37}} {
+ for _, source := range []uint32{0, 20} {
+ t.Run(fmt.Sprintf("template%d/source%d", scenario[0], source), func(t *testing.T) {
+ world, output := newBackpackWearWorld(t, scenario[0], source)
+ player, client := world.characters[1], world.clients[1]
+ before := player.inventory
+ child := before.Containers[2][0]
+ retained := slices.Clone(before.Containers[2])
+ request := backpackMoveRequest(107, 1<<16|source, 50000, 1, scenario[1])[20:]
+ auditCheckpointWrites(t, world)
+
+ if err := world.handleInventory(client, request); err != nil || client.equipment == nil {
+ t.Fatal("contained wear was not admitted", err)
+ }
+ pending := *client.equipment
+ if err := world.handleInventory(client, request); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleInventory(client, groundDropPacket(1, 107, 1<<16|source)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceEquipment(pending.readyAt.Add(-time.Nanosecond))
+ if !reflect.DeepEqual(player.inventory, before) || client.equipment == nil || *client.equipment != pending ||
+ len(output.packets) != 0 || len(checkpointWrites(t, world)) != 0 || pending.sourceBag != 2 || pending.itemID != child.ID {
+ t.Fatal("admission/repeat changed ownership, timing or the pending native source")
+ }
+ if source == 20 {
+ client.backpacks[1] = backpackHandle{2, false}
+ }
+ world.advanceEquipment(pending.readyAt)
+ writes, packets := checkpointWrites(t, world), len(output.packets)
+ world.advanceEquipment(pending.readyAt.Add(time.Second))
+ cold := newTestInventoryServer(t)
+
+ expected := before
+ expected.Items = slices.Clone(before.Items)
+ child.Slot = scenario[1]
+ expected.Items = append(expected.Items, child)
+ expected.Containers = nil
+ if client.equipment != nil || !reflect.DeepEqual(player.inventory, expected) || !reflect.DeepEqual(cold.characters[1].inventory, expected) ||
+ world.nextItem != before.LastID || cold.nextItem != before.LastID || len(writes) == 0 ||
+ !reflect.DeepEqual(checkpointWrites(t, world), writes) || len(output.packets) != packets ||
+ !slices.Equal(retained, before.Containers[2]) {
+ t.Fatal("contained wear lost properties, mutated its old slice or repeated the durable outcome")
+ }
+ moves := 0
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x47537a24 {
+ if !bytes.Equal(packet, targetPacket(backpackMoveRequest(107, 1<<16|source, 50000, 1, scenario[1]))) {
+ t.Fatal("contained wear changed the packed native source")
+ }
+ moves++
+ }
+ }
+ if moves != 1 {
+ t.Fatal("contained wear did not publish one native move", moves)
+ }
+ })
+ }
+ }
+}
+
+func TestBackpackWearRechecksSourceAndEquipmentAtCompletion(t *testing.T) {
+ for _, scenario := range []string{"requirements", "own combat", "recharge", "occupied", "banked bag", "changed handle", "changed child", "implant permission"} {
+ t.Run(scenario, func(t *testing.T) {
+ template, destination := uint32(209283), uint32(6)
+ if scenario == "implant permission" {
+ template, destination = 101173, 37
+ }
+ world, output := newBackpackWearWorld(t, template, 20)
+ player, client := world.characters[1], world.clients[1]
+ request := backpackMoveRequest(107, 1<<16|20, 50000, 1, destination)[20:]
+ if err := world.handleInventory(client, request); err != nil || client.equipment == nil {
+ t.Fatal("fixture admission failed", err)
+ }
+ finish := client.equipment.readyAt
+ switch scenario {
+ case "requirements":
+ player.stats.Body.Brawling = 0
+ case "own combat":
+ player.fighting = 1000000
+ world.fighting[1] = player
+ case "recharge":
+ player.rechargeUntil = finish.Add(time.Second)
+ case "changed handle":
+ client.backpacks[1] = backpackHandle{999, true}
+ case "implant permission":
+ player.implantChangesUntil = time.Time{}
+ default:
+ inventory := player.inventory
+ inventory.Items = slices.Clone(inventory.Items)
+ if scenario == "occupied" {
+ inventory.Items[0].Slot = 6
+ } else if scenario == "banked bag" {
+ bag := inventory.Items[1]
+ bag.Slot = 0
+ inventory.Bank = []ownedItem{bag}
+ inventory.Items = inventory.Items[:1]
+ } else {
+ child := inventory.Containers[2][0]
+ child.Slot = 19
+ inventory.Containers = map[uint32][]ownedItem{2: {child}}
+ }
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ }
+ before := player.inventory
+ data, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+ auditCheckpointWrites(t, world)
+
+ world.advanceEquipment(finish)
+ after, err := readTestItemStore(world)
+
+ if err != nil || !bytes.Equal(data, after) || !reflect.DeepEqual(player.inventory, before) || client.equipment != nil ||
+ len(checkpointWrites(t, world)) != 0 || len(output.packets) != 1 ||
+ !bytes.Equal(output.packets[0], targetPacket(characterActionPacket(1, [5]uint32{146, 107, 1<<16 | 20}))) {
+ t.Fatal("unavailable contained source or changed equipment gate applied a partial move", err)
+ }
+ })
+ }
+}
+
+func TestBackpackWearPlacementFailuresPreserveSourceAndRetry(t *testing.T) {
+ for _, fault := range []string{"delete error", "delete ignored", "insert error", "insert ignored", "commit failure"} {
+ t.Run(fault, func(t *testing.T) {
+ world, output := newBackpackWearWorld(t, 85481, 20)
+ player, client := world.characters[1], world.clients[1]
+ before := player.inventory
+ statement := "CREATE TRIGGER reject_bag_wear BEFORE DELETE ON item_locations WHEN OLD.item_id=3 BEGIN SELECT RAISE(ABORT,'placement failure'); END"
+ switch fault {
+ case "delete ignored":
+ statement = "CREATE TRIGGER reject_bag_wear BEFORE DELETE ON item_locations WHEN OLD.item_id=3 BEGIN SELECT RAISE(IGNORE); END"
+ case "insert error":
+ statement = "CREATE TRIGGER reject_bag_wear BEFORE INSERT ON item_locations WHEN NEW.item_id=3 BEGIN SELECT RAISE(ABORT,'placement failure'); END"
+ case "insert ignored":
+ statement = "CREATE TRIGGER reject_bag_wear BEFORE INSERT ON item_locations WHEN NEW.item_id=3 BEGIN SELECT RAISE(IGNORE); END"
+ case "commit failure":
+ if _, err := world.db.Exec("CREATE TABLE bag_wear_commit_failure (id INTEGER REFERENCES items(id) DEFERRABLE INITIALLY DEFERRED)"); err != nil {
+ t.Fatal(err)
+ }
+ statement = "CREATE TRIGGER reject_bag_wear AFTER INSERT ON item_locations WHEN NEW.item_id=3 BEGIN INSERT INTO bag_wear_commit_failure VALUES (999999); END"
+ }
+ if _, err := world.db.Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+ request := backpackMoveRequest(107, 1<<16|20, 50000, 1, 21)[20:]
+
+ if err := world.handleInventory(client, request); err != nil || client.equipment == nil {
+ t.Fatal("fixture admission failed", err)
+ }
+ world.advanceEquipment(client.equipment.readyAt)
+ cold := newTestInventoryServer(t)
+
+ if client.equipment != nil || !reflect.DeepEqual(player.inventory, before) || !reflect.DeepEqual(cold.characters[1].inventory, before) ||
+ world.nextItem != 3 || len(output.packets) != 1 ||
+ !bytes.Equal(output.packets[0], targetPacket(characterActionPacket(1, [5]uint32{146, 107, 1<<16 | 20}))) {
+ t.Fatal("failed contained wear changed ownership, applied effects or falsely acknowledged success")
+ }
+ if _, err := world.db.Exec("DROP TRIGGER reject_bag_wear"); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+ if err := world.handleInventory(client, request); err != nil || client.equipment == nil {
+ t.Fatal("contained wear could not retry", err)
+ }
+ world.advanceEquipment(client.equipment.readyAt)
+ if len(player.inventory.Items) != 3 || player.inventory.Items[2].Slot != 21 || player.inventory.Containers != nil || world.nextItem != 3 {
+ t.Fatal("retry lost or duplicated the retained instance")
+ }
+ })
+ }
+}
+
+func TestBackpackWearAdmissionRejectsIncompleteOrUnavailableMoves(t *testing.T) {
+ for _, scenario := range []string{"occupied", "requirements", "recharge", "own combat", "wrong slot", "closed source", "implant permission", "no deck capacity", "unsupported item"} {
+ t.Run(scenario, func(t *testing.T) {
+ template, destination := uint32(209283), uint32(6)
+ switch scenario {
+ case "implant permission":
+ template, destination = 101173, 37
+ case "no deck capacity":
+ template, destination = 36779, 9
+ case "unsupported item":
+ template = 95577
+ case "wrong slot":
+ destination = 21
+ }
+ world, output := newBackpackWearWorld(t, template, 20)
+ player, client := world.characters[1], world.clients[1]
+ switch scenario {
+ case "occupied", "no deck capacity":
+ inventory := player.inventory
+ inventory.Items = slices.Clone(inventory.Items)
+ if scenario == "occupied" {
+ inventory.Items[0].Slot = 6
+ } else {
+ inventory.Items = inventory.Items[:2]
+ }
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ case "requirements":
+ player.stats.Body.Brawling = 0
+ case "recharge":
+ player.rechargeUntil = time.Now().Add(time.Minute)
+ case "own combat":
+ player.fighting = 1000000
+ world.fighting[1] = player
+ case "closed source":
+ client.backpacks[1] = backpackHandle{2, false}
+ case "implant permission":
+ player.implantChangesUntil = time.Time{}
+ }
+ before := player.inventory
+ data, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+ auditCheckpointWrites(t, world)
+
+ err = world.handleInventory(client, backpackMoveRequest(107, 1<<16|20, 50000, 1, destination)[20:])
+ after, readErr := readTestItemStore(world)
+
+ if err != nil || readErr != nil || !bytes.Equal(data, after) || !reflect.DeepEqual(player.inventory, before) || client.equipment != nil ||
+ len(checkpointWrites(t, world)) != 0 || len(output.packets) != 1 ||
+ !bytes.Equal(output.packets[0], targetPacket(characterActionPacket(1, [5]uint32{146, 107, 1<<16 | 20}))) {
+ t.Fatal("refused contained wear changed ownership, effects or native source", err, readErr)
+ }
+ })
+ }
+}
diff --git a/server/backpacks.go b/server/backpacks.go
@@ -5,6 +5,7 @@ import (
"encoding/binary"
"maps"
"slices"
+ "time"
)
type backpackHandle struct {
@@ -281,6 +282,9 @@ func (server *server) moveContainerItem_locked(client *worldClient, body []byte)
}
if client.equipment != nil {
if sourceBag != 0 {
+ if sourceBag == client.equipment.sourceBag && item.ID == client.equipment.itemID {
+ return nil
+ }
return client.send(characterActionPacket(client.id, [5]uint32{146, sourcePage, binary.BigEndian.Uint32(body[20:24])}))
}
// Keep the admitted source pending and restore a separate carried icon.
@@ -309,6 +313,19 @@ func (server *server) moveContainerItem_locked(client *worldClient, body []byte)
// 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])
+ if sourceBag != 0 && targetType == 50000 && targetID == client.id && slot < 64 {
+ // Use the existing wear contract and delay; occupied-container swaps remain unsupported.
+ equipping := item
+ equipping.Slot = binary.BigEndian.Uint32(body[20:24])
+ now := time.Now()
+ if slices.ContainsFunc(inventory.Items, func(other ownedItem) bool { return other.Slot == slot }) ||
+ !player.canMoveEquipment(equipping, slot, now) || server.equipmentBlocked_locked(player, item, now) {
+ return refuse()
+ }
+ client.equipment = &equipmentMove{itemID: item.ID, source: equipping.Slot, destination: slot, requestedSlot: slot,
+ sourceBag: sourceBag, readyAt: now.Add(item.equipDelay())}
+ return nil
+ }
targetBag := uint32(0)
targetItems := inventory.Items
first, end := uint32(64), uint32(94)
diff --git a/server/browser_backpack_equipment_test.go b/server/browser_backpack_equipment_test.go
@@ -0,0 +1,116 @@
+package main
+
+import (
+ "cmp"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "slices"
+ "testing"
+ "time"
+)
+
+func TestBrowserBackpackEquipment(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for direct equipment from a backpack")
+ }
+
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/backpack-equipment", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ for index := range 2 {
+ player := world.newCharacter()
+ player.level = 2
+ player.position[0] += float32(index * 2)
+ player.stats.Abilities.Sense, player.stats.Abilities.Agility = 8, 8
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("backpack-equipment-", index))))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ }
+ player := world.characters[1]
+ inventory := playerInventory{LastID: 32, Items: []ownedItem{
+ {ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}},
+ Containers: map[uint32][]ownedItem{1: {
+ {ID: 2, Type: 51018, Template: 209283, Quality: 1, Slot: 5, Count: 1},
+ {ID: 3, Type: 51022, Template: 85481, Quality: 1, Slot: 0, Count: 1}}}}
+ // Fill every ordinary slot so direct wear cannot depend on a temporary free one.
+ for id := uint32(4); id <= 32; id++ {
+ inventory.Items = append(inventory.Items, ownedItem{ID: id, Type: 51005, Template: 95577, Quality: 1, Slot: id + 61, Count: 1})
+ }
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ mux := http.NewServeMux()
+ mux.Handle("/", world.httpHandler())
+ mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ var pending any
+ if client := world.clients[1]; client != nil && client.equipment != nil {
+ pending = map[string]any{"itemID": client.equipment.itemID, "source": client.equipment.source,
+ "destination": client.equipment.destination, "readyAt": client.equipment.readyAt}
+ }
+ var armor [8]int32
+ for index := range armor {
+ armor[index] = player.equipmentBonus(90 + uint32(index))
+ }
+ json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "pending": pending, "armor": armor})
+ })
+ // Exercise admission and completion separately without earning a test state.
+ mux.HandleFunc("POST /test-complete", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ finish := world.clients[1].equipment.readyAt
+ world.mutex.Unlock()
+ world.advanceEquipment(finish)
+ })
+ mux.HandleFunc("POST /test-fail-placement", func(w http.ResponseWriter, r *http.Request) {
+ if _, err := world.db.Exec("CREATE TRIGGER reject_native_bag_wear BEFORE DELETE ON item_locations WHEN OLD.item_id=2 BEGIN SELECT RAISE(IGNORE); END"); err != nil {
+ t.Error(err)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+ })
+ mux.HandleFunc("POST /test-allow-placement", func(w http.ResponseWriter, r *http.Request) {
+ if _, err := world.db.Exec("DROP TRIGGER reject_native_bag_wear"); err != nil {
+ t.Error(err)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+ })
+ host := httptest.NewServer(mux)
+ t.Cleanup(host.Close)
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_backpack_equipment.mjs"), host.URL, output)
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+ t.Logf("Browser artifacts: %s", output)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ expected := inventory
+ expected.Containers = nil
+ expected.Items = append(slices.Clone(inventory.Items), []ownedItem{
+ {ID: 2, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1},
+ {ID: 3, Type: 51022, Template: 85481, Quality: 1, Slot: 21, Count: 1}}...)
+ if !reflect.DeepEqual(player.inventory, expected) {
+ t.Fatal("direct contained equipment changed a carried instance")
+ }
+ slices.SortFunc(expected.Items, func(first, second ownedItem) int { return cmp.Compare(first.ID, second.ID) })
+ cold := newTestInventoryServer(t)
+ if !reflect.DeepEqual(cold.characters[1].inventory, expected) ||
+ world.nextItem != 32 || cold.nextItem != 32 || len(world.characters[2].inventory.Items) != 0 {
+ t.Fatal("direct contained equipment lost or duplicated ownership")
+ }
+}
diff --git a/server/equipment.go b/server/equipment.go
@@ -4,6 +4,7 @@ import (
"ao/server/gamedata"
"encoding/binary"
"log"
+ "maps"
"slices"
"time"
)
@@ -14,6 +15,7 @@ type equipmentMove struct {
destination uint32
requestedSlot uint32
replacedID uint32
+ sourceBag uint32
readyAt time.Time
}
@@ -142,7 +144,9 @@ func itemStat(item *gamedata.Item, stat uint32) uint32 {
func itemMovePacket(owner, source, destination uint32) []byte {
page := uint32(104)
- if source > 0 && source < 16 {
+ if source>>16 != 0 {
+ page = 107
+ } else if source > 0 && source < 16 {
page = 101
} else if source >= 16 && source < 32 {
page = 102
@@ -157,6 +161,9 @@ func itemMovePacket(owner, source, destination uint32) []byte {
}
func equipmentCorrectionPackets(owner, source uint32) [][]byte {
+ if source>>16 != 0 {
+ return [][]byte{characterActionPacket(owner, [5]uint32{146, 107, source})}
+ }
if source < 64 {
return [][]byte{itemMovePacket(owner, source, source)}
}
@@ -223,7 +230,8 @@ func (server *server) beginEquipment_locked(client *worldClient, index int, dest
delay += character.inventory.Items[replaced].equipDelay()
replacedID = character.inventory.Items[replaced].ID
}
- client.equipment = &equipmentMove{item.ID, item.Slot, destination, requestedSlot, replacedID, time.Now().Add(delay)}
+ client.equipment = &equipmentMove{itemID: item.ID, source: item.Slot, destination: destination,
+ requestedSlot: requestedSlot, replacedID: replacedID, readyAt: time.Now().Add(delay)}
return nil
}
@@ -242,26 +250,56 @@ func (server *server) advanceEquipment(now time.Time) {
if !client.ready || client.loading || character.health == 0 {
continue
}
- index := slices.IndexFunc(character.inventory.Items, func(item ownedItem) bool { return item.ID == move.itemID && item.Slot == move.source })
+ // Resolve the admitted physical source in its current owned container.
+ sourceItems, sourceSlot := character.inventory.Items, move.source
+ if move.sourceBag != 0 {
+ if client.backpacks[move.source>>16].id != move.sourceBag || !slices.ContainsFunc(character.inventory.Items, func(item ownedItem) bool {
+ return item.ID == move.sourceBag && item.isPortableContainer()
+ }) {
+ updates[client] = append(updates[client], equipmentCorrectionPackets(client.id, move.source)...)
+ continue
+ }
+ sourceItems, sourceSlot = character.inventory.Containers[move.sourceBag], move.source&65535
+ }
+ index := slices.IndexFunc(sourceItems, func(item ownedItem) bool { return item.ID == move.itemID && item.Slot == sourceSlot })
if index < 0 {
+ if move.sourceBag != 0 {
+ updates[client] = append(updates[client], equipmentCorrectionPackets(client.id, move.source)...)
+ }
continue
}
+ item := sourceItems[index]
+ // A packed carried source must not be interpreted as an inner worn slot.
+ item.Slot = move.source
replaced := slices.IndexFunc(character.inventory.Items, func(item ownedItem) bool { return item.Slot == move.destination })
replacedID := uint32(0)
if replaced >= 0 {
replacedID = character.inventory.Items[replaced].ID
}
- if server.equipmentBlocked_locked(character, character.inventory.Items[index], now) || replacedID != move.replacedID ||
- !character.canMoveEquipment(character.inventory.Items[index], move.destination, now) ||
+ if server.equipmentBlocked_locked(character, item, now) || replacedID != move.replacedID ||
+ !character.canMoveEquipment(item, move.destination, now) ||
replaced >= 0 && !character.canMoveEquipment(character.inventory.Items[replaced], move.source, now) {
updates[client] = append(updates[client], equipmentCorrectionPackets(client.id, move.source)...)
continue
}
// Save the entire move before publishing inventory or appearance changes.
- item := character.inventory.Items[index]
inventory := character.inventory
inventory.Items = slices.Clone(character.inventory.Items)
+ if move.sourceBag != 0 {
+ inventory.Containers = maps.Clone(inventory.Containers)
+ remaining := slices.Delete(slices.Clone(sourceItems), index, index+1)
+ if len(remaining) == 0 {
+ delete(inventory.Containers, move.sourceBag)
+ } else {
+ inventory.Containers[move.sourceBag] = remaining
+ }
+ if len(inventory.Containers) == 0 {
+ inventory.Containers = nil
+ }
+ index = len(inventory.Items)
+ inventory.Items = append(inventory.Items, item)
+ }
removedItems := []ownedItem{}
if move.source < 64 {
removedItems = append(removedItems, item)
diff --git a/server/inventory.go b/server/inventory.go
@@ -263,6 +263,7 @@ func (server *server) handleInventory(client *worldClient, body []byte) error {
} else if page == 107 {
bag := client.backpacks[slot>>16].id
if bag == 0 || slot&65535 >= 21 ||
+ client.equipment != nil && client.equipment.sourceBag == bag && client.equipment.source == slot ||
!slices.ContainsFunc(character.inventory.Items, func(item ownedItem) bool { return item.ID == bag && item.isPortableContainer() }) {
return nil
}
diff --git a/tools/client/test_backpack_equipment.mjs b/tools/client/test_backpack_equipment.mjs
@@ -0,0 +1,93 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import {createRequire} from 'node:module';
+import {GameTest} from './game_test.mjs';
+
+const {chromium} = createRequire(import.meta.url)('playwright');
+const [url, output] = process.argv.slice(2);
+const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [
+ '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage',
+ '--disable-background-timer-throttling', '--disable-renderer-backgrounding']});
+const games = [], evidence = {};
+const actor = game => game.state.actors.find(actor => actor.type === 50000 && actor.id === 1);
+try {
+ for (let index = 0; index < 2; index++) {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'backpack-equipment-' + index, url}]);
+ const page = await context.newPage(), game = await GameTest.attach(page);
+ games.push(game);
+ await page.goto(url);
+ await game.ready();
+ }
+ const [owner] = games;
+ const carried = owner.local().inventory.filter(item => item.id >= 4);
+ assert.equal(carried.length, 29);
+ const server = async () => (await owner.page.request.get(url + '/test-state')).json();
+ const cell = (state, page, slot) => state.grids.flatMap(grid => grid.cells).find(cell =>
+ cell.identity[0] === page && cell.identity[1] === slot && !cell.dummy);
+ const click = async (cell, button = 'left') => {
+ assert(cell);
+ await owner.click((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2, button);
+ };
+ await owner.key('i');
+ await click(cell(owner.state, 104, 48), 'right');
+ await owner.wait('both contained equipment sources available', state => cell(state, 107, 65541) && cell(state, 107, 65536));
+ await owner.page.keyboard.press('Control+1');
+ for (const item of [
+ {name: 'failed', id: 2, source: 65541, destination: 6, tab: 867, x: 867, y: 206},
+ {name: 'weapon', id: 2, source: 65541, destination: 6, tab: 867, x: 867, y: 206},
+ {name: 'armor', id: 3, source: 65536, destination: 21, tab: 953, x: 927, y: 148}]) {
+ await owner.wait('previous native equipment action ended', state => !owner.local(state).actions.includes(3) && !owner.local(state).actions.includes(6));
+ await owner.click(item.tab, 53);
+ const before = await server(), sequence = owner.sequence;
+ await click(cell(owner.state, 107, item.source));
+ await owner.wait('real contained equipment pickup', state => state.dragged[0] === 107 && state.dragged[1] === item.source);
+ await owner.click(item.x, item.y);
+ await owner.wait('real contained wear request', () => owner.events.some(event => event.sequence > sequence &&
+ event.direction === 'framesent' && event.opcode === '47537a24' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(29) === 107 && Buffer.from(event.hex, 'hex').readUInt32BE(33) === item.source));
+ evidence[item.name] = {before, admitted: await server()};
+ await owner.save(output + '/' + item.name + '-requested');
+ assert(evidence[item.name].admitted.pending, 'contained wear must enter shared equipment admission');
+ assert.equal(evidence[item.name].admitted.pending.itemID, item.id);
+ assert.equal(evidence[item.name].admitted.pending.source, item.source);
+ assert.equal(evidence[item.name].admitted.pending.destination, item.destination);
+ assert.deepEqual(evidence[item.name].admitted.inventory, before.inventory);
+ if (item.name === 'failed') assert((await owner.page.request.post(url + '/test-fail-placement')).ok());
+ assert((await owner.page.request.post(url + '/test-complete')).ok());
+ if (item.name === 'failed') {
+ await owner.wait('failed wear restores the same contained source', state => cell(state, 107, item.source));
+ evidence.failed.refused = await server();
+ assert.deepEqual(evidence.failed.refused, before);
+ assert(!owner.local().inventory.some(owned => owned.id === 2));
+ assert((await owner.page.request.post(url + '/test-allow-placement')).ok());
+ await Promise.all(games.map((game, index) => game.save(output + '/failed-restored-' + index)));
+ continue;
+ }
+ await owner.wait('exact contained item reaches equipment', state => owner.local(state).inventory.some(owned => owned.id === item.id && owned.slot === item.destination));
+ await owner.wait('contained source removed', state => !cell(state, 107, item.source));
+ const armor = item.id === 3 ? [5, 5, 1, 1, 5, 5, 1, 5] : [0, 0, 0, 0, 0, 0, 0, 0];
+ await Promise.all(games.map(game => game.wait('both replicas retain exact wear effects', () => actor(game).effectiveArmor.every((value, index) => value === armor[index]))));
+ evidence[item.name].completed = await server();
+ assert.equal(evidence[item.name].completed.pending, null);
+ assert.deepEqual(evidence[item.name].completed.armor, armor);
+ await Promise.all(games.map((game, index) => game.save(output + '/' + item.name + '-worn-' + index)));
+ }
+ evidence.final = await server();
+ assert.deepEqual(evidence.final.inventory.Items.filter(item => item.ID < 4).map(item => [item.ID, item.Slot]), [[1, 64], [2, 6], [3, 21]]);
+ assert.deepEqual(evidence.final.inventory.Items.filter(item => item.ID >= 4), evidence.weapon.before.inventory.Items.filter(item => item.ID >= 4));
+ assert.equal(evidence.final.inventory.Containers, null);
+ await Promise.all(games.map(async game => { await game.page.reload(); await game.ready(); }));
+ await Promise.all(games.map(game => game.wait('native effects survive page replay', () => actor(game).effectiveArmor.every((value, index) => value === [5, 5, 1, 1, 5, 5, 1, 5][index]))));
+ assert.deepEqual(await server(), evidence.final);
+ assert.deepEqual(owner.local().inventory.filter(item => item.id < 4).map(item => [item.id, item.slot]), [[2, 6], [3, 21], [1, 48]]);
+ assert.deepEqual(owner.local().inventory.filter(item => item.id >= 4), carried);
+ assert(games.every(game => game.errors.length === 0 && game.dropped === 0));
+ console.log('PASS: full-inventory contained weapon/armor wear shares delay/effects; both native replicas, page/cold retain all 32 identities');
+} finally {
+ try {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n');
+ await Promise.all(games.map((game, index) => game.save(output + '/final-' + index)));
+ } finally { await browser.close(); }
+}