aorecomp

Anarchy Online classic in the browser

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


commit 4f256e0146f6dc6113a33d6c972223827f9b8c1f
parent 1a44747956849a516fa3be506ddf5125b92450db
Author: anon <anon@example.com>
Date:   Tue,  3 Nov 2026 00:09:25 +0000

Support intermediate Dull Katana qualities

Diffstat:
MTODO.md | 8++++++++
Adocs/katana.md | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_katana_test.go | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/gamedata/item_families.yaml | 2++
Mserver/gamedata/item_quality_test.go | 3++-
Aserver/katana_quality_test.go | 268+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_katana.mjs | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 641 insertions(+), 1 deletion(-)

diff --git a/TODO.md b/TODO.md @@ -380,6 +380,14 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md). gates, AC/value, native endpoints, pickup, wear/removal, sale and cold ownership. Acquisition remains open; see [Steel-Ribbed contracts](docs/steel-ribbed-armor.md). + The reviewed Dull Katana pair now admits QL1..20 through the shared path, + fixing qualified QL2 wear rejection. Original descriptor audits and focused + public-handler checks cover all three strict skill gates, both anchors, + selected damage/timing/value, unlimited ammunition, pickup, wear/removal, + sale and cold ownership. A short two-client WASM check verifies QL2/10/11 + wear, QL12 refusal, ordinary melee, exact cancelled/accepted sale and page/cold + ownership. Historical acquisition remains open; see + [Katana contracts](docs/katana.md). - [x] Admit the complete Low-Tech armor set through shared quality and shop data. Eight explicit original pairs cover QL1..200, including alternate body and leg styles and independent sleeves. All three basic armor factions offer the diff --git a/docs/katana.md b/docs/katana.md @@ -0,0 +1,87 @@ +# Dull Katana selected qualities + +The reviewed pair 121969/121970 admits Dull Katana QL1..20 through the existing +item-quality, requirements, weapon, price and native delivery paths. Qualified +QL2 wear previously failed through the public inventory handler because the +pair was absent from the reviewed family table. The production change is one +explicit family row; no Katana-specific gameplay branch is added. + +## Original records + +Both complete 14.9.1 payloads were independently read and parsed from the original +resource database, matching their maintained catalog records exactly. Headers, +stat membership, complete sections, attack/defense weights, presentation and +wear predicates agree. Only the selected numeric properties and strict +2h Edged/Brawling/Dimach thresholds vary. This supports the explicit pairing; +it does not recover an original server family table or acquisition rules. + +| QL | Damage | Critical bonus | Minimum 2h Edged/Brawling/Dimach | Value | +| --- | --- | --- | --- | --- | +| 1 | 2-20 | 11 | 6/6/6 | 3350 | +| 2 | 2-21 | 11 | 11/9/7 | 3367 | +| 10 | 2-33 | 15 | 51/33/15 | 4778 | +| 11 | 3-34 | 16 | 57/37/16 | 5113 | +| 19 | 3-46 | 20 | 97/61/24 | 9062 | +| 20 | 3-47 | 20 | 102/64/25 | 9715 | + +The records retain 140-centisecond attack/recharge, 200-centisecond equip delay, +three-metre range, unlimited ammunition, Melee damage, 2h Edged attack, +Evade Close Combat defense and Melee Initiative. The only function is the +identical event-10 presentation function 53076; no new on-hit or wear bonus is +introduced. The adjacent Edge-Less tier remains unreviewed and exact-QL only. + +Original payload SHA-256: + +- 121969: `af4af4381bc0a75f0af494af4f630a823827f28955e1bd6da2fbe56dc37ba7c7`. +- 121970: `2e7b1534ad4a09176bb52aa472ea87044c15a351c040db21e30e0f125223cf48`. + +The original bytes, complete reparse, index digest, scalar differences and +independent integer arithmetic are retained under `local/katana-quality/original/`. +The local Fandom dump has no exact Dull Katana or 121969 plaintext match. Bounded +web queries did not recover period acquisition evidence; direct Auno access +was unavailable. Shop stock, mission selections and creature loot membership +are unchanged. + +## Focused verification + +Public-handler tests cover both stored anchors at all six qualities, strict +equality refusal at each of the three wear gates, the two-second equip deadline, +selected damage/timing/value, native endpoint delivery and cold ownership. +Normal/critical attacks check selected damage at all six QLs, attack/recharge, +the unlimited-ammunition result and unchanged carried Bullets. A controlled +generated drop at QL2/11 follows its exact instance through pickup, repeated +requests, cold loading, rejected wear, wear/remove/rewear, cancelled sale and +accepted/repeated sale. Final fixture wallets are 169/256 credits, including +the pre-existing one corpse credit. This does not establish historical drops. + +`TestBrowserKatanaQualities` uses two controlled WASM clients. The owner has +abilities20, raw 2h Edged56/Brawling33/Dimach12, producing effective 60/37/16. +Its level100 checkpoint supplies survival time for the isolated encounter; +it is not earned progression. A nearby original full-health Leet is held in +place while equipment and combat run normally. Native input wears/removes +QL2 and QL10, wears QL11 and refuses QL12. The observer's weapon deliveries +must retain selected properties and the correct nearer endpoint. One ordinary +Q hit deals 39 Melee damage and carries the unlimited-ammunition sentinel. +Cancelled/accepted QL2 sale at the original training machine must retain the +instance on cancellation and credit exactly 168 on acceptance. Page replay and +a fresh server/two-client startup must retain the other three exact identities, +their qualities/slots and the wallet, with no observer item or cash leak. + +The final native run passes in 88.75 seconds (warm 51.59, cold 37.15), or 96.430 +seconds including Go. Its independent verifier checks both original payload +hashes, the selected wear phases, the single native attack result, five sale +requests and exact page/cold ledgers. All 11 retained traces have empty error +lists and zero dropped events. Reviewed screenshots and full evidence are under +`local/katana-quality/20261102-160249/`. Earlier harness attempts incorrectly +required the finite-magazine stat on an unlimited weapon, then assumed the shop +would occupy its usual position while the weapon panel was open. Checking the +actual unlimited attack result and closing that panel resolved those fixture +assumptions; neither required a server or client change. + +The related Go selection passes 20 top-level tests and 493 individual results: +126.834s for server and 7.660s for gamedata. Two opt-in browser checks are skipped +there; the Katana native run above executes its full check separately. This +selection includes existing pistol qualities, the early bat, equipment +replacement/conservation, selected-quality lifecycle and shared family ranges. +All three new Go roots pass under the race detector, 67 results in 105.234s. +Vet and Node syntax checks pass. diff --git a/server/browser_katana_test.go b/server/browser_katana_test.go @@ -0,0 +1,130 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserKatanaQualities(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for the focused native Katana check") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/katana-quality", time.Now().Format("20060102-150405")) + t.Chdir(t.TempDir()) + for _, phase := range []string{"warm", "cold"} { + t.Run(phase, func(t *testing.T) { + world := newServer() + t.Cleanup(func() { world.db.Close() }) + 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 phase == "warm" { + for index := 0; index < 2; index++ { + player := world.newCharacter() + player.name, player.appearance = fmt.Sprint("Katana", index), 0x515 + player.position = [3]float32{60 - float32(index)*3, 14.75, 53} + player.rotation = [4]float32{0, 1, 0, 0} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("katana-", index)))) + if index == 0 { + player.level = 100 + player.stats.Abilities = characterAbilitiesStats{20, 20, 20, 20, 20, 20} + player.stats.Melee.TwoHandEdged = 56 + player.stats.Body.Brawling, player.stats.Body.Dimach = 33, 12 + for stat, expected := range map[uint32]int32{105: 60, 142: 37, 144: 16} { + if actual, _ := player.effectiveStat(stat); actual != expected { + t.Fatal("controlled effective skill differs", stat, actual) + } + } + } + player.health, player.nano = player.maximumHealth(), player.maximumNano() + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + } + // Controlled contracts and a nearby original Leet isolate the weapon check. + for _, item := range []struct{ template, quality uint32 }{ + {121969, 2}, {121970, 10}, {121970, 11}, {121969, 12}, + } { + if granted, err := world.grantItem_locked(world.characters[1], item.template); err != nil || !granted { + t.Fatal(granted, err) + } + world.characters[1].inventory.Items[len(world.characters[1].inventory.Items)-1].Quality = item.quality + } + if err := world.saveInventory_locked(world.characters[1], world.characters[1].inventory); err != nil { + t.Fatal(err) + } + target.position, target.motion.home = [3]float32{61, 14.75, 51.5}, [3]float32{61, 14.75, 51.5} + world.combatRoll = landedCombatRoll + } + owner, watcher := world.characters[1], world.characters[2] + 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{"inventory": owner.inventory, "observer": watcher.inventory, + "target": target.id, "health": target.health, "fighting": owner.fighting, "ownerHealth": owner.health}) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 3*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.advanceEquipment(now) + world.advanceCombat(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_katana.mjs"), host.URL, filepath.Join(output, phase)) + 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) + } + expected := []ownedItem{ + {ID: 2, Type: 51018, Template: 121970, Quality: 10, Slot: 65, Count: 1}, + {ID: 3, Type: 51018, Template: 121970, Quality: 11, Slot: 6, Count: 1}, + {ID: 4, Type: 51018, Template: 121969, Quality: 12, Slot: 67, Count: 1}, + } + if !slices.Equal(owner.inventory.Items, expected) || owner.inventory.Credits != 168 || owner.health == 0 || + len(watcher.inventory.Items) != 0 || watcher.inventory.Credits != 0 || world.nextItem != 4 { + t.Fatal("native wear, sale or cold recovery lost an instance or cash", owner.inventory) + } + }) + if t.Failed() { + return + } + } +} diff --git a/server/gamedata/item_families.yaml b/server/gamedata/item_families.yaml @@ -22,6 +22,8 @@ - [124260, 124261] # Unbalanced Advanced Baseballbat: original payload audit; docs/early-melee.md. - [122691, 122692] +# Dull Katana: original descriptor audit; docs/katana.md. +- [121969, 121970] # Monster Parts: complete original descriptor audit; docs/npc-loot.md. - [42640, 42641] # Low-Tech armor: complete original descriptor audits; docs/early-armor.md. diff --git a/server/gamedata/item_quality_test.go b/server/gamedata/item_quality_test.go @@ -15,6 +15,7 @@ func TestReviewedItemFamilyQualityRanges(t *testing.T) { {42640, 42641, 1, 400}, {206730, 206731, 50, 150}, {158416, 158417, 1, 200}, {123742, 123743, 1, 11}, {123744, 123745, 12, 21}, {123746, 123747, 22, 37}, {123748, 123749, 38, 119}, + {121969, 121970, 1, 20}, {124256, 124257, 1, 4}, {124258, 124259, 5, 69}, {124260, 124261, 70, 179}, {70558, 85640, 1, 200}, {70559, 85689, 1, 200}, {70560, 85688, 1, 200}, {70561, 85744, 1, 200}, {70562, 85597, 1, 200}, {70563, 85558, 1, 200}, {70564, 85515, 1, 200}, {70565, 85514, 1, 200}, @@ -54,7 +55,7 @@ func TestUnreviewedItemQualityRemainsExact(t *testing.T) { supported bool }{{209283, 1, true}, {209283, 2, false}, {85557, 0, false}, {161966, 200, true}, {161966, 199, false}, {160417, 1, true}, {160417, 2, false}, - {124262, 180, true}, {124262, 179, false}, {124262, 181, false}, {4294967295, 1, false}} { + {124262, 180, true}, {124262, 179, false}, {124262, 181, false}, {121971, 22, false}, {4294967295, 1, false}} { t.Run(fmt.Sprintf("%d/%d", entry.template, entry.quality), func(t *testing.T) { got := gamedata.ItemQualitySupported(entry.template, entry.quality) diff --git a/server/katana_quality_test.go b/server/katana_quality_test.go @@ -0,0 +1,268 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "fmt" + "slices" + "testing" + "time" +) + +func TestKatanaQualitiesEnforceWearBoundariesAndRecover(t *testing.T) { + for _, template := range []uint32{121969, 121970} { + for _, row := range []struct { + quality, minimum, maximum, critical, value uint32 + edged, brawling, dimach uint16 + }{ + {1, 2, 20, 11, 3350, 6, 6, 6}, + {2, 2, 21, 11, 3367, 11, 9, 7}, + {10, 2, 33, 15, 4778, 51, 33, 15}, + {11, 3, 34, 16, 5113, 57, 37, 16}, + {19, 3, 46, 20, 9062, 97, 61, 24}, + {20, 3, 47, 20, 9715, 102, 64, 25}, + } { + for _, failed := range []uint32{0, 105, 142, 144} { + t.Run(fmt.Sprintf("%d/QL%d/below%d", template, row.quality, failed), func(t *testing.T) { + world, output := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.TwoHandEdged = row.edged + player.stats.Body.Brawling, player.stats.Body.Dimach = row.brawling, row.dimach + switch failed { + case 105: + player.stats.Melee.TwoHandEdged-- + case 142: + player.stats.Body.Brawling-- + case 144: + player.stats.Body.Dimach-- + } + player.inventory.Items[0].Template, player.inventory.Items[0].Quality = template, row.quality + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + + started := time.Now() + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment != nil { + finish := client.equipment.readyAt + if finish.Before(started.Add(2*time.Second)) || finish.After(time.Now().Add(2*time.Second)) { + t.Fatal("Katana did not retain its original equip delay") + } + world.advanceEquipment(finish.Add(-time.Nanosecond)) + if player.inventory.Items[0].Slot != 64 { + t.Fatal("weapon moved before its equip deadline") + } + world.advanceEquipment(finish) + } + cold := newTestInventoryServer(t).characters[1] + + expected := ownedItem{ID: 1, Type: 51018, Template: template, Quality: row.quality, Slot: 64, Count: 1} + if failed == 0 { + expected.Slot = 6 + } + if !slices.Equal(player.inventory.Items, []ownedItem{expected}) || !slices.Equal(cold.inventory.Items, []ownedItem{expected}) { + t.Fatal("wear boundary lost the selected instance or placement", player.inventory.Items, cold.inventory.Items) + } + if failed != 0 { + return + } + weapon := cold.attackWeapon() + if weapon == nil || itemStat(weapon, 286) != row.minimum || itemStat(weapon, 285) != row.maximum || itemStat(weapon, 284) != row.critical || + itemStat(weapon, 294) != 140 || itemStat(weapon, 210) != 140 || itemStat(weapon, 211) != 200 || itemStat(weapon, 287) != 3 || + itemStat(weapon, 440) != 118 || expected.usesAmmo() || expected.shopPrice() != row.value { + t.Fatal("selected quality lost damage, timing, ammo, range, damage type or value", weapon) + } + low, high := uint32(121969), uint32(121970) + if row.quality == 1 { + high = low + } else if row.quality == 20 { + low = high + } + var delivered []byte + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x3b1d2268 { + delivered = packet + } + } + if len(delivered) < 91 || binary.BigEndian.Uint32(delivered[71:75]) != row.quality || + binary.BigEndian.Uint32(delivered[79:83]) != low || binary.BigEndian.Uint32(delivered[87:91]) != high { + t.Fatal("native weapon delivery lost the selected endpoints") + } + }) + } + } + } +} + +func TestKatanaSelectedDamageAndTimingWithoutAmmunition(t *testing.T) { + for _, row := range []struct{ quality, normal, critical uint32 }{ + {1, 40, 62}, {2, 42, 64}, {10, 66, 96}, {11, 68, 100}, {19, 92, 132}, {20, 94, 134}, + } { + for _, critical := range []bool{false, true} { + t.Run(fmt.Sprintf("QL%d/critical%v", row.quality, critical), func(t *testing.T) { + world, output := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + target.position = [3]float32{1, 0, 0} + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.TwoHandEdged = 400 + player.stats.Body.Brawling, player.stats.Body.Dimach = 100, 100 + player.stats.Speed.MeleeInitiative, player.aggDef = 0, 75 + player.inventory.Items[0].Template, player.inventory.Items[0].Quality, player.inventory.Items[0].Ammo = 121969, row.quality, 0 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + world.combatRoll = func(limit uint32) uint32 { + if limit == 10000 || limit == 100 && critical { + return 0 + } + return limit - 1 + } + + if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil { + t.Fatal(err) + } + hit := player.nextAttack + world.advanceCombat(hit) + cold := newTestInventoryServer(t) + + damage := row.normal + if critical { + damage = row.critical + } + if target.health != 1000-damage || player.rechargeUntil.Sub(hit) != 1400*time.Millisecond || player.nextAttack.Sub(hit) != 2800*time.Millisecond || + player.inventory.Items[0].Ammo != 0 || cold.characters[1].inventory.Items[0].Ammo != 0 || player.inventory.Items[1].Count != 100 { + t.Fatal("selected Katana damage, cadence or ammunition differs", target.health, player.inventory) + } + found := false + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 && binary.BigEndian.Uint32(packet[24:28]) == player.id { + found = binary.BigEndian.Uint32(packet[33:37]) == 0xffffffff + } + } + if !found { + t.Fatal("melee result lost its unlimited-ammunition sentinel") + } + }) + } + } +} + +func TestKatanaGeneratedPickupEquipRemoveAndSale(t *testing.T) { + for _, scenario := range []struct { + template, quality uint32 + edged, brawling, dimach uint16 + credits uint32 + }{ + {121969, 2, 11, 9, 7, 169}, {121970, 2, 11, 9, 7, 169}, + {121969, 11, 57, 37, 16, 256}, {121970, 11, 57, 37, 16, 256}, + } { + t.Run(fmt.Sprintf("%d/QL%d", scenario.template, scenario.quality), func(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + // Controlled membership tests delivery, not historical Leet equipment drops. + profile := *world.characters[1000000].combatProfile + profile.Loot = []gamedata.NPCLoot{{Template: scenario.template, Quality: [2]uint32{scenario.quality, scenario.quality}, Chance: 100}} + world.characters[1000000].combatProfile = &profile + world.combatRoll = func(uint32) uint32 { return 0 } + identity := world.nextItem + 1 + + attackForExperience(t, world, "unarmed") + if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil { + t.Fatal(err) + } + for range 2 { + if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil { + t.Fatal(err) + } + } + world = newTestInventoryServer(t) + player := world.characters[1] + client := &worldClient{id: 1, conn: &combatTestConn{}, target: true, ready: true} + world.clients[1] = client + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.TwoHandEdged = scenario.edged - 1 + player.stats.Body.Brawling, player.stats.Body.Dimach = scenario.brawling, scenario.dimach + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment != nil || + len(player.inventory.Items) != 1 || player.inventory.Items[0].ID != identity || player.inventory.Items[0].Slot != 64 { + t.Fatal("rejected wear lost the picked-up instance", err) + } + player.stats.Melee.TwoHandEdged++ + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + for _, move := range [][2]uint32{{64, 6}, {6, 64}, {64, 6}, {6, 64}} { + request := inventoryMovePacket(1, move[0], move[1]) + if move[0] < 64 { + request = itemMovePacket(1, move[0], move[1]) + } + if err := world.handleInventory(client, request[20:]); err != nil || client.equipment == nil { + t.Fatal("generated selected-quality weapon did not move", err) + } + world.advanceEquipment(client.equipment.readyAt) + cold := newTestInventoryServer(t) + expected := []ownedItem{{ID: identity, Type: 51018, Template: scenario.template, Quality: scenario.quality, Slot: move[1], Count: 1}} + if !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || + len(cold.characters[1000000].corpse.items) != 0 || cold.characters[1].inventory.Credits != 1 || cold.nextItem != identity { + t.Fatal("pickup, repeated wear or cold recovery lost or duplicated the weapon") + } + } + + // Sell that same instance after cancellation and a cold reconnect. + player.appearance = 0x515 + player.position = [3]float32{60, 14.75, 53} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + if err := world.handleShopUse(client, shopUseRequest(1)); err != nil { + t.Fatal(err) + } + add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:] + if err := world.handleTrade(client, add); err != nil { + t.Fatal(err) + } + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + if len(cold.characters[1].inventory.Items) != 1 || cold.characters[1].inventory.Credits != 1 { + t.Fatal("cancelled sale lost the selected-quality weapon") + } + world, player = cold, cold.characters[1] + client = &worldClient{id: 1, conn: &combatTestConn{}, target: true, ready: true} + world.clients[1] = client + if err := world.handleShopUse(client, shopUseRequest(1)); err != nil { + t.Fatal(err) + } + if err := world.handleTrade(client, add); err != nil { + t.Fatal(err) + } + for range 2 { + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + } + cold = newTestInventoryServer(t) + + for _, current := range []*server{world, cold} { + if len(current.characters[1].inventory.Items) != 0 || current.characters[1].inventory.Credits != scenario.credits || + current.characters[1].experience != 100 || current.nextItem != identity { + t.Fatal("selected-quality sale lost or repeated value, rewards or an instance", current.characters[1].inventory) + } + if _, exists := current.items[identity]; exists { + t.Fatal("sold weapon returned in the shared cache") + } + } + }) + } +} diff --git a/tools/client/test_katana.mjs b/tools/client/test_katana.mjs @@ -0,0 +1,144 @@ +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', headless: false, + 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 = {}; +async function bagClick(game, id) { + await game.wait('native equipment action finishes', state => + !game.local(state).actions.includes(3) && !game.local(state).actions.includes(6)); + const cell = game.local().inventory.find(item => item.id === id).slot - 48; + assert(cell >= 0 && cell < 9); + await game.click(681 + cell % 3 * 54, 45 + Math.floor(cell / 3) * 54, 'right'); +} +try { + for (const index of [0, 1]) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'katana-' + 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 state = async () => (await owner.page.request.get(url + '/test-state')).json(); + evidence.initial = await state(); + if (evidence.initial.inventory.Items.length === 4) { + assert.equal(owner.local().stats[105], 56); + assert.equal(owner.local().stats[142], 33); + assert.equal(owner.local().stats[144], 12); + await owner.key('KeyI'); + await owner.page.keyboard.press('Control+1'); + for (const id of [1, 2, 3]) { + const sequence = observer.sequence; + await bagClick(owner, id); + await owner.wait('selected Katana worn', snapshot => owner.local(snapshot).inventory.some(item => item.id === id && item.slot === 6)); + await observer.wait('observer receives selected Katana', () => observer.events.some(event => + event.sequence > sequence && event.direction === 'framereceived' && event.opcode === '3b1d2268' && + event.actor[0] === 51018 && event.actor[1] === id)); + const event = observer.events.find(event => event.sequence > sequence && event.direction === 'framereceived' && + event.opcode === '3b1d2268' && event.actor[0] === 51018 && event.actor[1] === id); + const packet = Buffer.from(event.hex, 'hex'), stats = new Map(); + for (let offset = 59; offset < packet.readUInt16BE(6) - 4; offset += 8) + stats.set(packet.readUInt32BE(offset), packet.readUInt32BE(offset + 4)); + const [quality, definition, minimum, maximum, critical, value] = { + 1: [2, 121969, 2, 21, 11, 3367], 2: [10, 121969, 2, 33, 15, 4778], + 3: [11, 121970, 3, 34, 16, 5113], + }[id]; + assert.equal(stats.get(23), definition); + const base = { + 121969: {74: 3350, 284: 11, 285: 20, 286: 2}, + 121970: {74: 9715, 284: 20, 285: 47, 286: 3}, + }[definition]; + for (const [stat, expected] of Object.entries({74: value, 284: critical, 285: maximum, 286: minimum, + 701: quality, 702: 121969, 703: 121970})) + assert.equal(stats.get(Number(stat)) ?? base[stat], expected, 'selected native Katana stat ' + stat); + evidence['worn' + id] = {native: owner.local().inventory, server: await state()}; + await owner.save(output + '/worn-' + id); + if (id !== 3) { + await owner.click(867, 206, 'right'); + await owner.wait('same Katana removed', snapshot => owner.local(snapshot).inventory.some(item => item.id === id && item.slot >= 48)); + } + } + const rejected = await state(), rejectionSequence = owner.sequence; + await bagClick(owner, 4); + await owner.save(output + '/rejected-12'); + assert(!owner.events.some(event => event.sequence > rejectionSequence && event.direction === 'framesent' && event.opcode === '47537a24')); + assert.deepEqual((await state()).inventory, rejected.inventory); + + // An ordinary Q attack uses the selected QL11 damage and consumes no ammunition. + const deadline = Date.now() + 10000; + while (owner.state.selected[0] !== 50000 || owner.state.selected[1] !== rejected.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', snapshot => snapshot.selected[0] !== selected[0] || snapshot.selected[1] !== selected[1]); + } + const attack = owner.sequence; + await owner.key('KeyQ'); + await owner.wait('ordinary selected-quality hit', () => owner.events.some(event => event.sequence > attack && + event.direction === 'framereceived' && event.opcode === '46002f16' && event.actor[1] === owner.local().id)); + const result = owner.events.find(event => event.sequence > attack && event.direction === 'framereceived' && + event.opcode === '46002f16' && event.actor[1] === owner.local().id); + assert.equal(Buffer.from(result.hex, 'hex').readUInt32BE(33), 0xffffffff); + await owner.key('KeyQ'); + await Promise.all(games.map(game => game.wait('native selected-quality impact', snapshot => + snapshot.actors.some(actor => actor.id === rejected.target && actor.stats[27] === 61)))); + evidence.hit = await state(); + assert.equal(evidence.hit.health, 61); + assert.equal(evidence.hit.fighting, 0); + assert.equal(evidence.hit.inventory.Items[2].Ammo, 0); + await owner.save(output + '/hit'); + + // Cancel, then accept the QL2 instance's sale at the original training machine. + await owner.page.keyboard.press('Control+1'); + await owner.wait('weapon panel closed', snapshot => !snapshot.regions.some(([left, top, right, bottom]) => + left === 832 && top === 0 && right === 1024 && bottom === 360)); + if (!owner.state.camera.firstPerson) await owner.key('F8'); + const offered = await state(); + for (let attempt = 0; attempt < 2; ++attempt) { + await owner.click(...await owner.pick(51035, 3221226422), 'right'); + await owner.wait('training machine open', snapshot => snapshot.regions.some(([left, top, right, bottom]) => + left === 832 && top === 0 && right === 1024 && bottom === 494)); + const cell = owner.local().inventory.find(item => item.id === 1).slot - 48; + await owner.click(681 + cell % 3 * 54, 45 + Math.floor(cell / 3) * 54); + const sequence = owner.sequence; + await owner.click(864, 416); + await owner.wait('sale offered', () => owner.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '36284f6e')); + assert.deepEqual((await state()).inventory, offered.inventory); + await owner.save(output + '/sale-offer-' + attempt); + if (attempt === 0) { + await owner.click(945, 475); + await owner.wait('cancelled Katana restored', snapshot => owner.local(snapshot).inventory.some(item => item.id === 1 && item.slot === 48)); + assert.deepEqual((await state()).inventory, offered.inventory); + } + } + await owner.click(874, 475); + await owner.wait('exact selected-quality sale', snapshot => owner.local(snapshot).stats[61] === 168); + evidence.sale = await state(); + await owner.page.reload(); + await owner.ready(); + } + assert.deepEqual(owner.local().inventory.map(item => [item.id, item.slot, item.quality, ...item.templates, item.count]).sort((a, b) => a[0] - b[0]), [ + [2, 49, 10, 121969, 121970, 1], [3, 6, 11, 121969, 121970, 1], [4, 51, 12, 121969, 121970, 1], + ]); + assert.equal(owner.local().stats[61], 168); + assert.deepEqual(observer.local().inventory, []); + evidence.final = {native: owner.local().inventory, server: await state()}; + assert.equal(evidence.final.server.inventory.Items[1].Ammo, 0); + assert(evidence.final.server.ownerHealth > 0); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: native Katana qualities, wear/removal, strict refusal, ordinary melee, exact sale and page/cold ownership'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2)); + await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); + } finally { await browser.close(); } +}