aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 04ea1f9091054de44a376f22e2623e56bc380bed
parent df8255c8281ca81ea7360eef02381b86ecd591ca
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 21:36:05 +0000

Publish committed reload state to native observers

Diffstat:
MDEVELOPERS.md | 5+++++
MTODO.md | 12+++++++-----
Mclient/runtime/browser_testing.c | 38++++++++++++++++++++++++--------------
Mclient/tests/browser_testing.c | 31++++++++++++++++++++++++++++---
Mdocs/catalog-weapons.md | 9+++++----
Adocs/remote-reload.md | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_remote_reload_test.go | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/ranged.go | 8+++++++-
Aserver/remote_reload_test.go | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_remote_reload.mjs | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 520 insertions(+), 27 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -505,6 +505,11 @@ modifiers. Use it when checking actual AC changes; zero raw AC does not imply missing armor. The snapshot reads the native tree without calling guest code. `TestBrowserEffectiveArmor` checks all eight values through wear, removal, page replay and fresh-server startup; see [effective armor snapshots](docs/browser-effective-armor.md). +Each actor's `actions` lists native action categories, including remote reload +category 5. Its `weapons` entries include signed `loadedAmmo` from the native +WeaponItem stat container; infinite ammunition and unbound controllers use -1. +These reads do not invoke guest getters or change queues. Inventory remains +local-player-only. Short key/click helpers release on the fresh consumed SDL event, then read the next full snapshot. Reading a large snapshot while holding a skill button can trigger native autorepeat and buy more points than intended. diff --git a/TODO.md b/TODO.md @@ -878,11 +878,13 @@ Normal-hit additions and weapon-range modifiers are described in catalog capacity/type/recharge drive transfers and one-round shot debits; incompatible ammo, invalid source item types and failed saves preserve state. Infinite-ammo solar shots and Fling retain the native -1 sentinel. -- [ ] [P2] Audit remote reload animation and ammunition state. Check an initially - empty weapon through reload and its first shot on two clients. Reload currently - updates the owner; observers learn the count through AttackInfo or reconnect. - Establish native remote routing before broadcasting a message that also - mutates an inventory stack. +- [x] [P2] Audit remote reload animation and ammunition state. Original routing + scopes ammunition transfers to the receiving character's inventory helper. + Committed reloads now reach observers before the first shot. Two controlled + WASM clients verify partial/depleted stacks, remote reload action, exactly one + native first-shot impact and unchanged observer items through page/cold + recovery. Failed transactions and lost owner output have focused regressions; + see [remote reload](docs/remote-reload.md). - [ ] [P1] Implement one melee special. Check: a suitable weapon/character can use the action once, with native feedback and an enforced skill lock. The Kinetic Axe now has a shared-handler Fast Attack normal-damage prototype. diff --git a/client/runtime/browser_testing.c b/client/runtime/browser_testing.c @@ -185,9 +185,18 @@ static void actor(FILE *output, uint32_t object, uint32_t type, uint32_t id, int uint32_t weapon = MEM32(combat + 0x0c + slot * 4); if (!weapon) continue; if (weapons++) fputc(',', output); + /* KKR sub_3607A660 uses the controller's bound WeaponItem at +0x20; + sub_36003000 reads that item's stat container directly. */ + uint32_t weapon_item = MEM32(weapon + 0x20); + int32_t loaded_ammo = -1; + if (weapon_item) { + uint32_t weapon_stats = MEM32(MEM32(weapon_item + 4) + 4); + loaded_ammo = (int32_t)MEM32(weapon_stats + 26 * 4); + } uint32_t read = MEM32(weapon + 0x18), write = MEM32(weapon + 0x14); uint32_t results = MEM32(MEM32(weapon + 0x10) + 4); - fprintf(output, "{\"slot\":%u,\"read\":%u,\"write\":%u,\"pending\":[", slot, read, write); + fprintf(output, "{\"slot\":%u,\"loadedAmmo\":%d,\"read\":%u,\"write\":%u,\"pending\":[", + slot, loaded_ammo, read, write); for (uint32_t index = read; index != write; index = (index + 1) % 50) { if (index != read) fputc(',', output); fprintf(output, "[%d,%u]", (int32_t)MEM32(results + index * 8), MEM32(results + index * 8 + 4)); @@ -196,20 +205,21 @@ static void actor(FILE *output, uint32_t object, uint32_t type, uint32_t id, int } } fputc(']', output); - if (local) { - /* kkr.dll/lifted-0026.c::sub_36052A20 / sub_36052790 enumerate action types. */ - uint32_t actions = MEM32(object + 0x184); - fputs(",\"actions\":[", output); - unsigned count = 0; - if (actions) { - for (int i = 0; i < (int)MEM32(actions + 4); ++i) { - uint32_t action = MEM32(MEM32(MEM32(actions + 8) + 4) + i * 4); - if (!action) continue; - if (count++) fputc(',', output); - fprintf(output, "%d", (int32_t)MEM32(action + 0x18)); - } + /* kkr.dll/lifted-0026.c::sub_36052A20 / sub_36052790 enumerate action types. */ + uint32_t actions = MEM32(object + 0x184); + fputs(",\"actions\":[", output); + unsigned count = 0; + if (actions) { + for (int i = 0; i < (int)MEM32(actions + 4); ++i) { + uint32_t action = MEM32(MEM32(MEM32(actions + 8) + 4) + i * 4); + if (!action) continue; + if (count++) fputc(',', output); + fprintf(output, "%d", (int32_t)MEM32(action + 0x18)); } - fputs("],\"inventory\":", output); + } + fputc(']', output); + if (local) { + fputs(",\"inventory\":", output); inventory(output, object); } } diff --git a/client/tests/browser_testing.c b/client/tests/browser_testing.c @@ -102,6 +102,10 @@ static void snapshots_preserve_wrapped_weapon_results(void) { MEM32(0x5000116c) = 0x50008100; MEM32(0x50008124) = 0x50008200; + MEM32(0x50008220) = 0x50008700; + MEM32(0x50008704) = 0x500085a0; + MEM32(0x500085a4) = 0x50008600; + MEM32(0x50008668) = 20; MEM32(0x50008210) = 0x50008300; MEM32(0x50008304) = 0x50008400; MEM32(0x50008214) = 1; @@ -114,10 +118,20 @@ static void snapshots_preserve_wrapped_weapon_results(void) browser_test_request(); browser_test_frame(); - assert(strstr(snapshot, "\"weapons\":[{\"slot\":6,\"read\":49,\"write\":1,\"pending\":[[7,4],[13,5]]}]")); + assert(strstr(snapshot, "\"weapons\":[{\"slot\":6,\"loadedAmmo\":20,\"read\":49,\"write\":1,\"pending\":[[7,4],[13,5]]}]")); + assert(MEM32(0x50008668) == 20); assert(MEM32(0x50008214) == 1 && MEM32(0x50008218) == 49); assert(MEM32(0x50008400 + 49 * 8) == 7 && MEM32(0x50008404 + 49 * 8) == 4); assert(g_eax == 123 && g_esp == 456); + + /* An unbound controller has no finite ammunition or item stats to read. */ + MEM32(0x50008220) = 0; + browser_test_request(); + browser_test_frame(); + assert(strstr(snapshot, "\"slot\":6,\"loadedAmmo\":-1")); + assert(MEM32(0x50008214) == 1 && MEM32(0x50008218) == 49); + assert(g_eax == 123 && g_esp == 456); + MEM32(0x50008220) = 0x50008700; } static void completed_picks_record_the_query_pixel_and_result(void) @@ -163,7 +177,7 @@ static void snapshots_observe_directory_clear_and_new_frames(void) assert(strstr(snapshot, "\"pick\":null")); } -static void snapshots_observe_active_local_actions_without_mutation(void) +static void snapshots_observe_local_and_remote_actions_without_mutation(void) { MEM32(0x50000304) = 0x50000500; MEM32(0x50001184) = 0x5000d800; @@ -182,6 +196,17 @@ static void snapshots_observe_active_local_actions_without_mutation(void) assert(MEM32(0x5000d804) == 4 && MEM32(0x5000db18) == 6); assert(MEM32(0x5000dc18) == 3 && MEM32(0x5000dd18) == 12); assert(g_eax == 123 && g_esp == 456); + + /* A remote actor exposes the same action list without exposing inventory. */ + MEM32(0x50000088) = 0; + browser_test_request(); + browser_test_frame(); + assert(strstr(snapshot, "\"actions\":[6,3,12]")); + assert(!strstr(snapshot, "\"inventory\":")); + assert(MEM32(0x5000d804) == 4 && MEM32(0x5000db18) == 6); + assert(MEM32(0x5000dc18) == 3 && MEM32(0x5000dd18) == 12); + assert(g_eax == 123 && g_esp == 456); + MEM32(0x50000088) = 0x50001000; } static void snapshots_record_visible_grid_cells_and_scroll_without_mutation(void) @@ -350,7 +375,7 @@ int main(void) completed_picks_record_the_query_pixel_and_result(); snapshots_do_not_advance_the_pick_generation(); snapshots_observe_directory_clear_and_new_frames(); - snapshots_observe_active_local_actions_without_mutation(); + snapshots_observe_local_and_remote_actions_without_mutation(); snapshots_include_reclaim_booths_without_mutation(); snapshots_preserve_wrapped_weapon_results(); snapshots_record_visible_grid_cells_and_scroll_without_mutation(); diff --git a/docs/catalog-weapons.md b/docs/catalog-weapons.md @@ -330,10 +330,11 @@ loaded 10 rounds from 100 Energy Weapon Ammo, leaving 90 in the source stack. Packet captures, native object probes, SQLite snapshots and error logs are retained under `local/starter-weapon-smoke/`. -Reload currently updates only the owner's native loaded count. Observers get -the authoritative count in subsequent AttackInfo or FullUpdateItem. Original -remote reload routing and the first animation after loading an empty weapon -remain an explicit TODO; the reload message also changes an inventory stack. +Committed reloads now update the owner and same-world observers before a first +shot. Original routing scopes the ammunition transfer to the receiving +character's inventory helper. Two controlled clients verify empty-gun reload, +native action 5, the first impact and an unchanged observer weapon/stack through +page/cold ownership recovery; see [remote reload](remote-reload.md). The native delete sender (`N3Msg_DeleteItem`, 10027670) forwards the auxiliary identity pair unchanged to CharacterAction112. The observed live Meta Shield diff --git a/docs/remote-reload.md b/docs/remote-reload.md @@ -0,0 +1,69 @@ +# Remote weapon reload + +A committed explicit reload now sends ReloadIIR `0x26515e61` to the owner and +ready observers in the same runtime playfield. GenericCmd acknowledgement stays +private. Observers receive the committed update even if the owner's reply fails. +Failed transactions and refused requests publish no remote success. + +## Original receiver + +Original KKR apply `10080ca0` resolves the outer character identity, then calls +that character's weapon holder `1007bca0`. Its inventory update selects the +receiving character's inventory helper, rather than the local player's helper. +Normal page 104 resolves through helper+0x0c in `10061800`; `10062320` updates +that container's row count, and `1002d2f0` ignores an absent row. The depleted +path `10062440` uses the same character-scoped resolver before deletion. + +The holder sets stat 26 on the referenced WeaponItem and creates native action +category 5 with its RechargeDelay. Reload chat text is guarded by the local +character flag. The static receiver therefore supports remote weapon state and +timing without applying the other player's ammunition transfer to the local +inventory. The two-client regression below checks both update and deletion. + +Complete original evidence, matching snapshots, SHA256 and individual Evidence +IDs are retained in `local/remote-reload/README.md`, `native-routing.json` and +`evidence.json`, together with the earlier `local/ranged-research/` export. +These are original-client observations. They do not establish the original +server's stack selection, automatic reload, cancellation or scheduling policy; +those remain separately documented in the ranged/reload audit. + +## Focused verification + +`TestBrowserRemoteReload` starts with two controlled QL30 Colt pistols. The +shooter has an empty gun; the observer has nine loaded rounds and seven Bullets +in the same ordinary slot as the shooter's ammunition. Real pickup/right-click +input reloads the shooter. Both native holders must receive the loaded count +and the shooter's action 5 before any attack. The observer's own gun, stack and +action state remain unchanged. + +| Initial shooter stack | Loaded after reload | After first shot | Remaining stack | +| --- | --- | --- | --- | +| 100 | 20 | 19 | 80 | +| 5 | 5 | 4 | removed | + +Both clients then consume exactly one queued native weapon result, with +read/write indices 1/1, and show the same 72-point impact on the controlled +target. Page replay retains both native round counts; fresh Go database loading +retains exact weapons, remaining stacks, quantities, cash and allocation. +The scene, skills, weapons and ammunition are fixtures, not earned progression +or acquisition evidence. + +The corrected baseline uses an explicit overlay of the original `ranged.go`. +The shooter loads 20 rounds while its live observer remains empty through +frame 756, without an attack. This fails in 28.35 seconds. The initial pair of +startup timeouts came from an uncommitted observation-layout mistake and are +excluded; the ledger retains their diagnosis and corrected-layout unit failure. + +The public-handler regressions cover partial/depleted stacks, one-time +publication, another playfield, failed/ignored writes, failed COMMIT, retry and +lost owner output. They preserve the observer's separate items through cold +loading. Read-only C snapshots expose bound WeaponItem ammunition and local/ +remote action categories without calling guest getters or changing queues; +their unit covers bound/unbound controllers and register/queue preservation. + +The final two-client run passes both cases in 65.57 seconds. All 16 retained +stage traces have zero errors or dropped events. Related server coverage passes +76 roots / 496 results in 72.96 seconds; focused race coverage passes five roots / +10 results in 96.69 seconds. Maintained-package vet and the rebuilt C snapshot +unit pass. Artifact paths and an independent trace/hash audit are retained under +`local/remote-reload/`. diff --git a/server/browser_remote_reload_test.go b/server/browser_remote_reload_test.go @@ -0,0 +1,126 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserRemoteReload(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for the two-client remote reload check") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + for _, count := range []uint16{100, 5} { + t.Run(fmt.Sprint(count), func(t *testing.T) { + output := filepath.Join(root, "local/remote-reload", time.Now().Format("20060102-150405"), fmt.Sprint(count)) + world := newTestServer(t) + var target *character + for _, actor := range world.characters { + if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (target == nil || actor.id < target.id) { + target = actor + } + } + if target == nil { + t.Fatal("no controlled Leet target") + } + for index := 0; index < 2; index++ { + player := world.newCharacter() + player.name, player.level, player.profession, player.appearance, player.aggDef = fmt.Sprint("Reload", index), 100, 6, 0x515, 75 + player.position = target.position + player.position[0] -= float32(index * 3) + player.position[2] -= 2 + player.rotation = [4]float32{0, 0, 0, 1} + player.stats.Abilities = characterAbilitiesStats{200, 200, 200, 200, 200, 200} + player.stats.Ranged.Pistol, player.stats.Ranged.FlingShot = 351, 23 + player.health, player.nano = player.maximumHealth(), player.maximumNano() + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("remote-reload-", index)))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + for _, template := range []uint32{123747, 21605} { + if granted, err := world.grantItem_locked(player, template); err != nil || !granted { + t.Fatal(granted, err) + } + } + player.inventory.Items[0].Quality, player.inventory.Items[0].Slot = 30, 6 + player.inventory.Items[1].Slot = 64 + player.inventory.Items[1].Count = count + if index == 1 { + player.inventory.Items[0].Ammo, player.inventory.Items[1].Count = 9, 7 + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + } + profile := *target.combatProfile + profile.Health = 10000 + target.combatProfile, target.health = &profile, 10000 + world.combatRoll = landedCombatRoll + 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() + json.NewEncoder(w).Encode(map[string]any{"owner": world.characters[1].inventory, + "observer": world.characters[2].inventory, "target": target.id, "health": target.health}) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + world.advanceCombat(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + observer := slices.Clone(world.characters[2].inventory.Items) + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_remote_reload.mjs"), host.URL, output) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + cancel() + <-stopped + + t.Logf("Browser artifacts: %s", output) + if err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + loaded, remaining := min(uint32(count), 20)-1, max(int(count)-20, 0) + expected := []ownedItem{{ID: 1, Type: 51018, Template: 123747, Quality: 30, Slot: 6, Count: 1, Ammo: loaded}} + if remaining != 0 { + expected = append(expected, ownedItem{ID: 2, Type: 51005, Template: 21605, Quality: 1, Slot: 64, Count: uint16(remaining)}) + } + for _, current := range []*server{world, cold} { + if !slices.Equal(current.characters[1].inventory.Items, expected) || + !slices.Equal(current.characters[2].inventory.Items, observer) || current.nextItem != 4 || + current.characters[1].inventory.Credits != 0 || current.characters[2].inventory.Credits != 0 { + t.Fatal("remote reload changed another owner's weapon/stack or lost a committed round") + } + } + }) + } +} diff --git a/server/ranged.go b/server/ranged.go @@ -77,6 +77,7 @@ func (server *server) handleReload(client *worldClient, body []byte) error { return nil } var packets [][]byte + var reload []byte sequence := binary.BigEndian.Uint32(body[20:24]) if sequence <= client.useSequence { server.mutex.Unlock() @@ -154,10 +155,15 @@ func (server *server) handleReload(client *worldClient, body []byte) error { for _, value := range []uint32{104, source.Slot, gun.Type, gun.ID, remaining, gun.Ammo + loaded, remove} { response = binary.BigEndian.AppendUint32(response, value) } - packets = append(packets, n3Packet(0x26515e61, 50000, player.id, response)) + reload = n3Packet(0x26515e61, 50000, player.id, response) + packets = append(packets, reload) } packets = append([][]byte{n3Packet(0x52526858, 50000, player.id, acknowledgement)}, packets...) server.mutex.Unlock() + if reload != nil { + // Remote holders need the committed rounds and reload action too. + server.broadcast(player.playfield, client.id, reload) + } for _, packet := range packets { if err := client.send(packet); err != nil { return err diff --git a/server/remote_reload_test.go b/server/remote_reload_test.go @@ -0,0 +1,133 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "slices" + "testing" +) + +func newRemoteReloadWorld(t *testing.T) (*server, [3]*combatTestConn) { + t.Helper() + world, owner := newRangedWorld(t) + world.characters[1].inventory.Items[0].Ammo = 0 + if err := world.saveInventory_locked(world.characters[1], world.characters[1].inventory); err != nil { + t.Fatal(err) + } + world.nextCharacter = 1 + observer := world.newCharacter() + if err := world.saveUser_locked(observer); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 4, Items: []ownedItem{ + {ID: 3, Type: 51018, Template: 123742, Quality: 1, Slot: 6, Count: 1, Ammo: 9}, + {ID: 4, Type: 51005, Template: 21605, Quality: 1, Slot: 64, Count: 7}, + }} + if err := world.saveInventory_locked(observer, inventory); err != nil { + t.Fatal(err) + } + outsider := world.newCharacter() + outsider.playfield = 952 + connections := [3]*combatTestConn{owner, {}, {}} + world.clients[2] = &worldClient{id: 2, conn: connections[1], target: true, ready: true} + world.clients[3] = &worldClient{id: 3, conn: connections[2], target: true, ready: true} + owner.packets = nil + return world, connections +} + +func TestReloadPublishesCommittedStateToVisibleObservers(t *testing.T) { + for _, row := range []struct{ source, loaded, remaining, removed uint32 }{{100, 20, 80, 0}, {5, 5, 0, 1}} { + t.Run(fmt.Sprint(row.source), func(t *testing.T) { + world, connections := newRemoteReloadWorld(t) + owner, observer := world.characters[1], world.characters[2] + owner.inventory.Items[1].Count = uint16(row.source) + if err := world.saveInventory_locked(owner, owner.inventory); err != nil { + t.Fatal(err) + } + other := slices.Clone(observer.inventory.Items) + expected := []ownedItem{{ID: 1, Type: 51018, Template: 123742, Quality: 1, Slot: 6, Count: 1, Ammo: row.loaded}} + if row.remaining != 0 { + expected = append(expected, ownedItem{ID: 2, Type: 51005, Template: 21605, Quality: 1, Slot: 64, Count: uint16(row.remaining)}) + } + + for range 2 { + if err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1)); err != nil { + t.Fatal(err) + } + } + cold := newTestInventoryServer(t) + + if len(connections[0].packets) != 2 || len(connections[1].packets) != 1 || len(connections[2].packets) != 0 { + t.Fatal("reload did not publish once to its observer while retaining the private acknowledgement") + } + reply := connections[1].packets[0] + if !bytes.Equal(reply[16:], connections[0].packets[1][16:]) || binary.BigEndian.Uint32(reply[16:20]) != 0x26515e61 || + binary.BigEndian.Uint32(reply[24:28]) != 1 || binary.BigEndian.Uint32(reply[29:33]) != 104 || + binary.BigEndian.Uint32(reply[33:37]) != 48 || binary.BigEndian.Uint32(reply[41:45]) != 1 || + binary.BigEndian.Uint32(reply[45:49]) != row.remaining || binary.BigEndian.Uint32(reply[49:53]) != row.loaded || + binary.BigEndian.Uint32(reply[53:57]) != row.removed { + t.Fatal("observer reload changed its subject, source, weapon or committed round counts") + } + for _, current := range []*server{world, cold} { + if !slices.Equal(current.characters[1].inventory.Items, expected) || + !slices.Equal(current.characters[2].inventory.Items, other) || current.nextItem != 4 { + t.Fatal("reload changed another owner's items or lost a committed round") + } + } + }) + } +} + +func TestReloadFailureDoesNotPublishRemoteSuccess(t *testing.T) { + for _, fault := range []struct{ name, statement string }{ + {"failed update", "CREATE TRIGGER reject_reload BEFORE UPDATE OF ammo ON items WHEN NEW.id=1 BEGIN SELECT RAISE(ABORT, 'reload fault'); END"}, + {"ignored update", "CREATE TRIGGER reject_reload BEFORE UPDATE OF ammo ON items WHEN NEW.id=1 BEGIN SELECT RAISE(IGNORE); END"}, + {"failed commit", "CREATE TABLE pending_reload (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_reload AFTER UPDATE OF ammo ON items WHEN NEW.id=1 BEGIN INSERT INTO pending_reload VALUES(999999); END"}, + } { + t.Run(fault.name, func(t *testing.T) { + world, connections := newRemoteReloadWorld(t) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec(fault.statement); err != nil { + t.Fatal(err) + } + + failed := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1)) + after, err := readTestItemStore(world) + + if failed == nil || err != nil || !bytes.Equal(before, after) || world.characters[1].inventory.Items[0].Ammo != 0 || + world.characters[1].inventory.Items[1].Count != 100 || !world.clients[1].reloadUntil.IsZero() || + len(connections[0].packets)+len(connections[1].packets)+len(connections[2].packets) != 0 { + t.Fatal("failed reload published success or changed either side of the transfer", failed, err) + } + + if _, err := world.db.Exec("DROP TRIGGER reject_reload"); err != nil { + t.Fatal(err) + } + if err := world.handleReload(world.clients[1], explicitReloadRequest(2, 64, 1)); err != nil { + t.Fatal(err) + } + + if len(connections[0].packets) != 2 || len(connections[1].packets) != 1 || len(connections[2].packets) != 0 { + t.Fatal("a normal retry did not publish one committed reload") + } + }) + } +} + +func TestReloadLostOwnerReplyStillUpdatesItsObserver(t *testing.T) { + world, connections := newRemoteReloadWorld(t) + world.clients[1].conn = &shortWorldConn{} + + err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1)) + cold := newTestInventoryServer(t) + + if err == nil || len(connections[1].packets) != 1 || len(connections[2].packets) != 0 || + cold.characters[1].inventory.Items[0].Ammo != 20 || cold.characters[1].inventory.Items[1].Count != 80 || + cold.characters[2].inventory.Items[0].Ammo != 9 || cold.characters[2].inventory.Items[1].Count != 7 { + t.Fatal("lost owner output hid the committed reload from its observer or changed ownership", err) + } +} diff --git a/tools/client/test_remote_reload.mjs b/tools/client/test_remote_reload.mjs @@ -0,0 +1,116 @@ +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 = {}; +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: 'remote-reload-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + } + const [owner, observer] = games; + const server = async () => (await owner.page.request.get(url + '/test-state')).json(); + const actor = (state, id) => state.actors.find(actor => actor.type === 50000 && actor.id === id); + const weapon = (state, id) => actor(state, id)?.weapons.find(weapon => weapon.slot === 6); + evidence.initial = await server(); + const count = evidence.initial.owner.Items.find(item => item.ID === 2).Count; + const loaded = Math.min(20, count), remaining = count - loaded; + for (const game of games) { + await game.wait('both native weapon controllers are ready', state => + weapon(state, 1)?.loadedAmmo === 0 && weapon(state, 2)?.loadedAmmo === 9); + assert.equal(weapon(game.state, 1).read, 0); + assert.equal(weapon(game.state, 1).write, 0); + } + assert.equal(observer.local().inventory.find(item => item.id === 4).count, 7); + await Promise.all(games.map((game, index) => game.save(output + '/empty-' + index))); + + // Reload the owner's empty gun through the real ammunition-on-weapon gesture. + await owner.key('KeyI'); + await owner.page.keyboard.press('Control+1'); + const sequences = games.map(game => game.sequence); + await owner.click(681, 45); + await owner.wait('ordinary ammunition picked', state => state.dragged[0] === 104 && state.dragged[1] === 48); + await owner.click(867, 206, 'right'); + await owner.wait('owner receives committed reload', state => weapon(state, 1)?.loadedAmmo === loaded); + evidence.committed = await server(); + await observer.wait('observer receives reload before the first attack', state => + weapon(state, 1)?.loadedAmmo === loaded && actor(state, 1).actions.includes(5)); + evidence.loaded = await server(); + assert.deepEqual(evidence.loaded.observer, evidence.initial.observer); + assert.equal(evidence.loaded.owner.Items[0].Ammo, loaded); + assert.equal(evidence.loaded.owner.Items.find(item => item.ID === 2)?.Count ?? 0, remaining); + assert.equal(weapon(observer.state, 2).loadedAmmo, 9); + assert.equal(observer.local().inventory.find(item => item.id === 4).count, 7); + assert(!observer.local().actions.includes(5)); + for (let index = 0; index < games.length; ++index) { + const reloads = games[index].events.filter(event => event.sequence > sequences[index] && + event.direction === 'framereceived' && event.opcode === '26515e61'); + assert.equal(reloads.length, 1); + assert.deepEqual(reloads[0].actor, [50000, 1]); + const bytes = Buffer.from(reloads[0].hex, 'hex'); + assert.deepEqual([29, 33, 37, 41, 45, 49, 53].map(offset => bytes.readUInt32BE(offset)), + [104, 48, 51018, 1, remaining, loaded, remaining === 0 ? 1 : 0]); + assert(!games[index].events.some(event => event.sequence > sequences[index] && + event.direction === 'framereceived' && event.opcode === '46002f16')); + } + await Promise.all(games.map((game, index) => game.save(output + '/loaded-' + index))); + + // Both native reload actions must finish before the first ordinary shot. + for (const game of games) { + await game.wait('native reload action finishes', state => !actor(state, 1).actions.includes(5)); + } + const deadline = Date.now() + 10000; + while (owner.state.selected[0] !== 50000 || owner.state.selected[1] !== evidence.initial.target) { + assert(Date.now() < deadline, 'Native Tab did not select the controlled Leet'); + const selected = owner.state.selected; + await owner.key('Tab'); + await owner.wait('native target cycle advances', state => state.selected[0] !== selected[0] || state.selected[1] !== selected[1]); + } + const shot = owner.sequence; + await owner.key('KeyQ'); + await owner.wait('first reloaded shot arrives', () => owner.events.some(event => event.sequence > shot && + event.direction === 'framereceived' && event.opcode === '46002f16' && event.actor[1] === 1)); + await owner.key('KeyQ'); + for (const game of games) { + await game.wait('native first shot consumes one round and reaches impact', state => + weapon(state, 1)?.loadedAmmo === loaded - 1 && weapon(state, 1).read === 1 && weapon(state, 1).write === 1 && + actor(state, evidence.initial.target)?.stats[27] === 9928); + assert.equal(weapon(game.state, 2).loadedAmmo, 9); + } + evidence.shot = await server(); + assert.equal(evidence.shot.owner.Items[0].Ammo, loaded - 1); + assert.equal(evidence.shot.owner.Items.find(item => item.ID === 2)?.Count ?? 0, remaining); + assert.equal(evidence.shot.health, 9928); + assert.deepEqual(evidence.shot.observer, evidence.initial.observer); + await Promise.all(games.map((game, index) => game.save(output + '/shot-' + index))); + + for (const game of games) { + await game.page.reload(); + await game.ready(); + } + for (const game of games) { + await game.wait('page replay retains both native ammunition values', state => + weapon(state, 1)?.loadedAmmo === loaded - 1 && weapon(state, 2)?.loadedAmmo === 9); + assert.deepEqual(game.errors, []); + } + evidence.final = await server(); + assert.deepEqual(evidence.final.owner, evidence.shot.owner); + assert.deepEqual(evidence.final.observer, evidence.initial.observer); + console.log('PASS: remote empty-gun reload, native action, first shot and unchanged observer inventory; source count', count); +} 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(); } +}