aorecomp

Anarchy Online classic in the browser

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


commit 3c47febee558b3cbd1abedbf650f181b3fbe9635
parent 1f057b83579c53425b15a0e2166eb653fb6813aa
Author: anon <anon@example.com>
Date:   Sat, 31 Oct 2026 06:02:23 +0000

Preserve mission pickup templates and verify earned starter missions

Diffstat:
MDEVELOPERS.md | 17+++++++++++------
MTODO.md | 30+++++++++++++++++++++++++-----
Mdocs/mission-encounters.md | 8++++++++
Mdocs/mission-objectives.md | 27+++++++++++++++++++++++++++
Mdocs/starter-progression.md | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mserver/browser_game_test.go | 57+++++++++++++++++++++++++++++++++++++++++++++++++--------
Mserver/world_items.go | 4+++-
Mserver/world_items_test.go | 5+++++
Mtools/client/test_starter_equipment.mjs | 422++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
9 files changed, 495 insertions(+), 133 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -460,7 +460,7 @@ available (`node` on PATH, `playwright` installed locally or on NODE_PATH, `/usr/bin/chromium` installed): ```sh -AO_GAME_TEST=1 go test ./server -run '^TestBrowser(GameHarness|StarterEquipment|StarterMissionTargets)$' -count=1 -timeout=15m -v +AO_GAME_TEST=1 go test ./server -run '^TestBrowser(GameHarness|StarterEquipment|StarterMissionTargets)$' -count=1 -timeout=35m -v ``` This starts an HTTP server on a random loopback port and uses a disposable @@ -475,12 +475,17 @@ DISPLAY/XAUTHORITY environment as the other GPU browser checks. `TestBrowserStarterEquipment` creates two Atrox Enforcers through Options with their normal Omni starter loadouts and the production training-ground population. It checks issued-bat equip/remove/re-wear, normal skill purchases, the issued -shirt and nano crystal, a full-health spawned Leet kill, single-award corpse -cash, any generated part, laboratory use/locked retry and quiet recovery. +shirt and nano crystal, a full-health spawned Leet kill, an earned mission request, +all five full-health private encounters and exact-book hand-in. It accounts for +each corpse's single-award cash, any generated parts, laboratory use/locked retry, +quiet recovery, the request fee and the advertised item/cash reward. Native ownership is compared with server state, observer isolation, page -reconnect and cold database loading. Skills and rewards use ordinary native -commands and production random rolls, without grants or edited characters/enemies. -Earned levels, missions, sales, purchases and actual reclaim remain broader +reconnect and cold database loading, including all five saved encounter deaths. +The artifact directory retains `ledger.json`, native screenshots/traces and a +`world.sqlite` snapshot from the stopped simulation, including after a failed +browser run. Skills and rewards use ordinary native commands and production +random rolls, without grants or edited characters/enemies. +Earned levels, sales, purchases and actual reclaim remain broader regression work. `TestBrowserStarterMissionTargets` walks a normally created starter through its diff --git a/TODO.md b/TODO.md @@ -1916,6 +1916,14 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). contract association and support bound-key entry; native destination metadata remains unimplemented. Cover held, banked, traded, deleted and reclaimed keys; possession of an unrelated template28577 must never admit a player to another mission. +- [x] [P1] Trace zero native identities on simple mission inventory proxies. + Original `kkr.dll` constructors `0x1002d010`/`0x1002d580` leave the simple + proxy's identity fields zero, including newly received keys and collected + books with stat702 metadata. The harness checks exact book identity in the + real pickup request/response and server ledger, then native slot, endpoints, + QL and count. Do not invent a native identity or use template/slot observations + as door credentials. Key destination metadata remains open above. See + [pickup representation](docs/mission-objectives.md). - [x] Complete the fixed return-item objective for its authored cash reward. The exact spawned book must be used on the original issuing booth through native action5; a matching template or remote journal action84 cannot redeem it. @@ -1970,6 +1978,14 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). GPU WASM verifies the visible floor model, immediate native pickup icon, page reconnect, exit/reentry and cold-server recovery with no respawn. See [mission floor items](docs/mission-objectives.md). +- [x] [P1] Preserve native template metadata when collecting mission-floor items. + World stat23 supplies the visible resource, while the original pickup descriptor + independently reads stat702/703. Supply the authored low endpoint in stat702 + and retain the original high-endpoint fallback. The failing packet regression + catches the omission; real R pickup now shows both book endpoints and its icon + before zoning. Exact request/response identities, server ownership and native + proxy metadata are checked separately. See + [pickup metadata](docs/mission-objectives.md). - [ ] [P1] Execute supported world-item Use descriptors through reusable item effects. The original book's right-click emits GenericCmd action3, while its explicit R/Pick Up emits InventoryMove; preserve that distinction and resolve @@ -3458,11 +3474,15 @@ and server restarts. Turn every reproduced bug into a focused regression test. evidence: `local/gameplay-loop-smoke/`; owned characters/items were cleaned up. `TestBrowserStarterEquipment` now repeats normal two-client creation, issued bat equip/remove/re-equip, exact skill purchases, the issued buff and shirt, - a full-health spawned Leet kill, corpse cash/item accounting and laboratory - recovery with locked repeats. It compares native ownership with server state, - page reconnect and cold loading, using production rolls and training-ground - resources. Earned levels, missions, sales/purchases and actual reclaim remain - broader regression work. + a full-health spawned Leet kill, an earned mission request, all five private + full-health encounters and exact-book return to the issuing booth. It accounts + for corpse cash/items, laboratory charges/locked repeats, the request fee and + advertised item/cash reward. The book's simple native proxy is checked before + zoning against exact pickup packets and server ownership. Page reconnect and + cold loading retain the completed assignment and five saved deaths, using + production rolls and training-ground resources. Earned levels, sales/purchases + and actual reclaim remain broader regression work. See + [maintained starter mission](docs/starter-progression.md#maintained-earned-starter-mission). A new two-client harness run now connects seven full-health ordinary kills, an earned Monster Part sale and funded mission request to all five private encounters, exact-book hand-in and earned QL1 Metaplast body armor. Rejected diff --git a/docs/mission-encounters.md b/docs/mission-encounters.md @@ -134,6 +134,14 @@ exception cannot establish a different 14.9.1 threshold. The local fandom dump's `Token and Tokenboards` (2016) and `Missions` (2021) pages say the threshold varies by mission without recovering that arithmetic. +A [player review dated September 17, 2002](https://gamefaqs.gamespot.com/pc/913777-anarchy-online/reviews/40336) +describes five kills out of ten as a 50 percent token chance and ten out of ten +as guaranteed. This contemporary description supports proportional chance, but +is not a controlled boundary measurement. It does not establish the minimum +population/kills, rounding, grey-enemy denominator, backyard exceptions or XP +calculation. Keep those questions open rather than deriving a complete formula +from its example. + ## Verification Go tests cover atomic acceptance and allocation, unsupported definitions/levels, diff --git a/docs/mission-objectives.md b/docs/mission-objectives.md @@ -54,6 +54,33 @@ inventory-slot movement0x1005dd60 instead; it interprets the world instance ID a a slot and cannot collect the book. Native source identity and destination semantics therefore both matter, beyond durable server ownership. +The original `kkr.dll` function at `0x10090eb0` builds the pickup descriptor from +stat701 (QL masked to 16 bits), stat702 (low template) and stat703 (high template, +falling back to stat702 when zero). Inventory constructor `0x1002d580` copies these +values into the proxy. World resource stat23 does not supply those endpoints. +Each fixed mission-floor item therefore also advertises stat702 with its +authored template; its authored endpoint QL needs no distinct high template. +Omitting this field leaves an owned proxy with zero template IDs and no icon +until zoning rebuilds inventory. Original and rebased binary evidence and the +reproduced native snapshots are retained in +`local/mission-objective-research/pickup-metadata-*` and +`local/game-tests/starter-resume-20261030-220743/`. + +Supplying stat702 also selects the original simple inventory representation. +`kkr.dll` function `0x1009fc10` accepts the collectible type51005 with nonzero +stat702; pickup `0x1005f7c0` then calls `0x1002d580`. Its base constructor +`0x1002d010` zeroes the identity fields, and `0x1002d580` fills flags0x21, +count and the QL/template triple without assigning an identity. A fresh native +pickup therefore has the correct visible icon and endpoints but identity0/0. +The maintained test verifies the exact world instance in both native pickup +packets and authoritative ownership, and compares the simple proxy's native +slot, endpoints, QL and count. It must not manufacture an identity in snapshots. +Original evidence: `local/mission-objective-research/simple-proxy-*.json`, +including `ev_53b1e46c4febe1b4e6de89ba7fc47c8aece1842d420a2a946d5f15f099a95a21`. +The fresh `local/game-tests/starter-20261030-224743/mission-book/` capture +verifies both endpoints40822, QL1/count1 and the visible icon before zoning; +the connected run then clears all five encounters and returns the exact book. + Abandonment and expiry destroy remaining floor items with their assignment. Already collected books retain ordinary inventory ownership. Rewards and objective completion are deliberately separate from this ownership transfer. diff --git a/docs/starter-progression.md b/docs/starter-progression.md @@ -1420,5 +1420,59 @@ for this run and seven normal empty-drop runs. Its script and report are focused browser-stream/session Go tests also pass with the race detector. This automated slice complements the earned continuation above. Further earned -levels, mission completion, sales/purchases and actual reclaim remain part of -the broader regression gate. +levels, sales/purchases and actual reclaim remain part of the broader regression +gate. The first funded mission is now part of the maintained scenario below. + +## Maintained earned starter mission + +`TestBrowserStarterEquipment` continues the same fresh owner from its outdoor +kill to the original backyard booth. One earned credit pays the request fee; +acceptance retains the advertised cash, selected item/QL, destination and exact +key binding. Native walking and jumps cross the raised mission doorway lips. +All five private encounters start with the owner at 84 HP and each Leet at its +full provisional 100 HP. Native Tab targeting waits for the observed selection +to change before cycling again, and the outgoing attack must name that actor. +Each fight checks the actual corpse wallet, repeated Use without another cash +award, any generated part and every accepted laboratory charge. + +The book is collected after the second private fight, while its inventory cell +is still visible. The original pickup descriptor reads stat702 independently +of the world resource's stat23; missing stat702 produced an owned native proxy +with zero templates and a blank icon until zoning. The mission-floor packet now +includes its authored template in stat702, using the original stat703-zero +fallback for the second endpoint. A failing packet regression reproduces the +omission before the fix. The original simple proxy leaves identity fields zero; +the test checks exact instance identity in both real pickup packets and server +ownership, then checks the native slot, endpoints, QL and count before zoning. +See [pickup metadata](mission-objectives.md). + +After all five encounters, ordinary item-on-item Use returns that exact book +to the issuing booth. The ledger accounts for six kill awards, the one-credit +fee, twenty advertised credits, one selected QL1 reward, consumed book/key, +issued gear and remaining supplies. Page reload checks every native identity, +type, template endpoint, slot, quality and quantity. A stopped-simulation +SQLite snapshot and cold loading independently check ownership, 600 kill XP, +1170 IP, full health, the completed assignment and all five saved deaths. The +observer retains its seven issued items and zero progress. Mission completion +XP/token eligibility and historical encounter/reward generation remain open. + +The fresh capture `local/game-tests/starter-20261030-224743/` passes in +791.78 seconds. Six corpse wallets total twenty credits; the fee and reward +leave 39. Three naturally generated Monster Parts and QL1 Worn Metaplast Armor +Gloves (instance20/template85596, count1) remain among the owner's ten items. +Thirteen accepted laboratory uses leave twelve charges; native health is +84/84, XP600 and IP1170. Book17 +and key16 are consumed. The observer retains all seven issued items and zero +progress. The book's immediate native proxy has both endpoints40822 in slot56, +matching exact server instance17 in slot72 before completion. + +The independent `local/todo-progression-play/tmp_verify_starter_mission.py` +checks every final native/SQLite item field, both actual pickup messages, +full-health starts, corpse range/projection, cash, completed mission identity, +five saved kills, observer isolation and database integrity. Its report is +`starter-mission-verified.json`. The affected Go run passes 29 roots/139 cases; +five focused concurrency tests pass with the race detector, and all 126 +JavaScript checks pass. Logs are `starter-mission-go-focused.json`, +`starter-mission-go-race.json`, `starter-mission-js-unit-final.log` and +`starter-mission-native-final4.log` in that same directory. Owned test browsers +and servers are closed. This milestone does not claim a full Go-suite rerun. diff --git a/server/browser_game_test.go b/server/browser_game_test.go @@ -110,30 +110,49 @@ func TestBrowserStarterEquipment(t *testing.T) { "health": enemy.health, "maximumHealth": enemy.maximumHealth()}) } } + missions := []map[string]any{} + for _, mission := range world.missionExpiry { + if mission.owner != player.id { + continue + } + missions = append(missions, map[string]any{"id": mission.id, "world": mission.world, + "objective": mission.objective, "completed": mission.completed, + "definition": mission.offer.definition, "layout": mission.layout}) + } + var offer any + if client := world.clients[player.id]; client != nil && client.missionOffer != nil { + offer = client.missionOffer.definition + } json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "health": player.health, - "maximumHealth": player.maximumHealth(), "stats": player.stats, "enemies": enemies, "corpses": corpses}) + "maximumHealth": player.maximumHealth(), "stats": player.stats, "enemies": enemies, "corpses": corpses, + "playfield": player.playfield, "missions": missions, "offer": offer}) }) host := httptest.NewServer(mux) t.Cleanup(host.Close) closeTestBrowserStreams(t, world) // Advance the ordinary world without changing characters, encounters or rolls. - ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) defer cancel() stopped := make(chan struct{}) go func() { defer close(stopped) movement := time.NewTicker(time.Second / 60) + zoning := time.NewTicker(100 * time.Millisecond) simulation := time.NewTicker(250 * time.Millisecond) checkpoint := time.NewTicker(time.Second) defer movement.Stop() + defer zoning.Stop() defer simulation.Stop() defer checkpoint.Stop() for { select { case now := <-movement.C: world.advancePlayerMovement(now) + case now := <-zoning.C: + world.advanceZoneCrossings(now) case now := <-simulation.C: + world.advanceMissions(now) world.advanceCorpseExpiry(now) world.advanceNPCRespawns(now) world.advanceNPCs(now) @@ -163,13 +182,19 @@ func TestBrowserStarterEquipment(t *testing.T) { cancel() <-stopped t.Logf("Browser artifacts: %s", output) + if failure := world.flushWorld(); failure != nil { + t.Fatal(failure) + } + if failure := os.MkdirAll(output, 0755); failure != nil { + t.Fatal(failure) + } + if _, failure := world.db.Exec("VACUUM INTO ?", filepath.Join(output, "world.sqlite")); failure != nil { + t.Fatal(failure) + } if err != nil { t.Fatal(err) } - if err := world.flushWorld(); err != nil { - t.Fatal(err) - } restored := newServer() defer restored.db.Close() world.mutex.Lock() @@ -195,12 +220,28 @@ func TestBrowserStarterEquipment(t *testing.T) { } continue } - if player.experience != 100 || player.stats.ImprovementPoints != 1170 || player.maximumHealth() != 84 || player.aggDef != 100 || - player.inventory.Credits < 1 || player.inventory.Credits > 5 || + if player.experience != 600 || player.stats.ImprovementPoints != 1170 || player.maximumHealth() != 84 || player.aggDef != 100 || + player.inventory.Credits < 25 || player.inventory.Credits > 49 || len(player.missions) != 0 || !reflect.DeepEqual(player.inventory.LearnedNanos, []uint32{43371}) { - t.Fatalf("ordinary starter fight, training or learning was not retained: %+v", player) + t.Fatalf("ordinary starter mission, training or learning was not retained: %+v", player) } } + if len(restored.missionExpiry) != 1 || !restored.missionExpiry[0].completed { + t.Fatal("completed starter mission changed across cold loading") + } + live, cold := world.missionExpiry[0], restored.missionExpiry[0] + if live.id != cold.id || live.owner != cold.owner || live.world != cold.world || live.objective != cold.objective || + !reflect.DeepEqual(live.layout, cold.layout) || live.offer.definition.RewardItem != cold.offer.definition.RewardItem || + live.offer.definition.RewardQuality != cold.offer.definition.RewardQuality || live.offer.definition.Credits != cold.offer.definition.Credits { + t.Fatal("starter mission identity, layout or reward changed across cold loading") + } + var encounters, killed int + if err := restored.db.QueryRow("SELECT count(*),sum(killed) FROM mission_encounters").Scan(&encounters, &killed); err != nil { + t.Fatal(err) + } + if encounters != 5 || killed != 5 { + t.Fatalf("cold mission progress = %d encounters, %d killed; want 5/5", encounters, killed) + } if players != 2 { t.Fatalf("created %d ordinary characters, want 2", players) } diff --git a/server/world_items.go b/server/world_items.go @@ -82,8 +82,10 @@ func (server *server) worldItemPackets_locked(player *character) [][]byte { } } else if mission != nil && placement.mission == mission.id { item := server.items[id] + // client/game/kkr.dll/lifted-0042.c::sub_36090EB0 reads stat702 + // for the pickup proxy, independently of the world template stat23. packets = append(packets, n3Packet(0x3b11256f, item.Type, id, - simpleItemBody(item.Template, player.playfield, placement.position, [4]float32{0, 0, 0, 1}, nil))) + simpleItemBody(item.Template, player.playfield, placement.position, [4]float32{0, 0, 0, 1}, [][2]uint32{{702, item.Template}}))) } } return packets diff --git a/server/world_items_test.go b/server/world_items_test.go @@ -54,10 +54,15 @@ func TestMissionObjectiveSpawnsOnceAndReplaysOnlyInItsWorld(t *testing.T) { t.Fatal("objective allocation, floor or instance isolation changed", cold.worldItems, cold.characters[1].missions) } packet := targetPacket(packets[0]) + packet = packet[:binary.BigEndian.Uint16(packet[6:8])] if binary.BigEndian.Uint32(packet[16:]) != 0x3b11256f || binary.BigEndian.Uint32(packet[20:]) != 51005 || binary.BigEndian.Uint32(packet[24:]) != 3 || binary.BigEndian.Uint32(packet[69:73]) != 65536 { t.Fatal("objective lost its native identity or private world", packets) } + if binary.BigEndian.Uint32(packet[len(packet)-12:]) != 702 || + binary.BigEndian.Uint32(packet[len(packet)-8:]) != 40822 || binary.BigEndian.Uint32(packet[len(packet)-4:]) != 0 { + t.Fatal("world pickup cannot retain the objective's native item template", packet) + } destination := player.userData() destination.Playfield, destination.Position = 3000, [3]float32{89.3, 115.75, 154.5} diff --git a/tools/client/test_starter_equipment.mjs b/tools/client/test_starter_equipment.mjs @@ -11,14 +11,32 @@ const browser = await chromium.launch({executablePath: '/usr/bin/chromium', '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); const games = []; +// Clear the raised mission doorway lips with ordinary forward jumps. +async function jump(game) { + const start = game.local().position; + game.record({kind: 'action', action: 'jump'}); + await game.page.keyboard.down('KeyW'); + try { + await game.key('Space'); + await game.wait('jump across raised lip', state => { + const position = game.local(state).position; + return Math.hypot(position[0] - start[0], position[2] - start[2]) >= 2.5; + }); + } finally { + const sequence = game.sequence; + await game.page.keyboard.up('KeyW'); + await game.waitInput(sequence, 769); + } +} + // Use the issued laboratory on its real unlocks and retain every charge debit. async function recover(game, label) { - const count = game.local().inventory.find(item => item.templates[0] === 116628).count; + const count = game.local().inventory.find(item => item.templates[0] === 116628)?.count ?? 0; await game.key('F1'); await game.key('KeyX'); await game.wait('seated for laboratory use', state => game.local(state).stats[430] === 2); let uses = 0, sequence = game.sequence; - const deadline = Date.now() + 180000; + const deadline = Date.now() + 600000; for (;;) { await game.snapshot(); const server = await (await game.page.request.get(url + '/test-state')).json(); @@ -29,24 +47,167 @@ async function recover(game, label) { const packet = Buffer.from(event.hex, 'hex'); return packet.readUInt32BE(packet.length - 20) === 164 && packet.readUInt32BE(packet.length - 4) === 124; }); - if (uses && (!unlocked || server.maximumHealth - server.health < 15)) continue; + if (uses === count || (uses && (!unlocked || server.maximumHealth - server.health < 15))) continue; sequence = game.sequence; await game.click(681, 45, 'right'); ++uses; await game.wait('one laboratory charge consumed', state => - game.local(state).inventory.find(item => item.templates[0] === 116628).count === count - uses); - await game.click(681, 45, 'right'); + (game.local(state).inventory.find(item => item.templates[0] === 116628)?.count ?? 0) === count - uses); + if (uses < count) await game.click(681, 45, 'right'); const locked = await (await game.page.request.get(url + '/test-state')).json(); - assert.equal(locked.inventory.Items.find(item => item.Template === 116628).Count, count - uses); + assert.equal(locked.inventory.Items.find(item => item.Template === 116628)?.Count ?? 0, count - uses); assert(locked.health >= Math.min(84, server.health + 15)); } - assert(uses > 0); - assert.equal(game.local().inventory.find(item => item.templates[0] === 116628).count, count - uses); + assert.equal(game.local().inventory.find(item => item.templates[0] === 116628)?.count ?? 0, count - uses); await game.key('KeyX'); await game.save(output + '/' + label); return uses; } +// Frame a stationary world object through real native camera input. +async function frame(game, type, id) { + const target = () => game.state.actors.find(actor => actor.type === type && actor.id === id); + if (target().screenPosition[1] < 350 || target().screenPosition[1] > 540) { + const cameraPoint = await game.point(512, 300); + let mouseY = cameraPoint.y, sequence = game.sequence; + const framingDeadline = Date.now() + 10000; + await game.page.mouse.move(cameraPoint.x, mouseY); + await game.page.mouse.down({button: 'right'}); + try { + await game.waitInput(sequence, 1025); + for (;;) { + await game.snapshot(); + const screenY = target().screenPosition[1]; + if (screenY >= 350 && screenY <= 540) break; + assert(Date.now() < framingDeadline, 'Starter did not frame the world object above chat'); + mouseY += screenY > 540 ? 20 : -20; + await game.page.mouse.move(cameraPoint.x, mouseY, {steps: 2}); + } + } finally { + sequence = game.sequence; + await game.page.mouse.up({button: 'right'}); + } + await game.waitInput(sequence, 1026); + } +} + +// Each encounter starts at full health and uses native targeting, attacks and loot. +async function fight(game, enemy, label) { + const experience = game.local().stats[52], credits = game.local().stats[61]; + if (game.local().stats[22] !== 27) { + await game.page.keyboard.press('Control+8'); + await game.key('F1'); + await game.click(857, 128, 'right'); + await game.wait("Thug's Delight active", state => game.local(state).stats[22] === 27); + await game.page.keyboard.press('Control+8'); + } + const targetingDeadline = Date.now() + 30000; + while (game.state.selected[0] !== 50000 || game.state.selected[1] !== enemy.id) { + assert(Date.now() < targetingDeadline, 'Native Tab did not select the encounter'); + const selected = game.state.selected; + await game.key('Tab'); + await game.wait('native target cycle advanced', state => + state.selected[0] !== selected[0] || state.selected[1] !== selected[1]); + } + const beforeFight = await (await game.page.request.get(url + '/test-state')).json(); + const healthyEnemy = beforeFight.enemies.find(actor => actor.id === enemy.id); + assert.equal(beforeFight.health, 84); + assert.equal(game.local().stats[27], 84); + assert.equal(healthyEnemy.health, 100); + assert.equal(healthyEnemy.maximumHealth, 100); + const attack = game.sequence; + await game.key('KeyQ'); + await game.wait('native attack request', () => game.events.some(event => + event.sequence > attack && event.direction === 'framesent' && event.opcode === '28494070')); + const request = Buffer.from(game.events.find(event => event.sequence > attack && + event.direction === 'framesent' && event.opcode === '28494070').hex, 'hex'); + // The native request ends with the target identity and one attack flag. + assert.equal(request.readUInt32BE(request.length - 9), 50000); + assert.equal(request.readUInt32BE(request.length - 5), enemy.id); + let special = game.sequence; + await game.key('KeyN'); + const deadline = Date.now() + 120000; + for (;;) { + await game.snapshot(); + assert(game.local().stats[27] > 0, 'Ordinary starter died during ' + label); + if (game.state.actors.some(actor => actor.type === 51050 && actor.id === enemy.id)) break; + assert(Date.now() < deadline, 'Ordinary Leet fight did not finish'); + const unlocked = game.events.some(event => { + if (event.sequence <= special || event.direction !== 'framereceived' || event.opcode !== '5e477770') return false; + const packet = Buffer.from(event.hex, 'hex'); + return packet.readUInt32BE(packet.length - 20) === 164 && packet.readUInt32BE(packet.length - 4) === 147; + }); + if (unlocked) { + special = game.sequence; + await game.key('KeyN'); + } + } + await game.wait('earned kill XP', state => game.local(state).stats[52] === experience + 100); + await game.save(output + '/' + label + '/earned-kill'); + + // Use the actual remains twice, then take any generated part exactly once. + const killed = await (await game.page.request.get(url + '/test-state')).json(); + const corpse = killed.corpses.find(corpse => corpse.id === enemy.id); + assert(corpse && corpse.credits >= 1 && corpse.credits <= 5); + const corpseDistance = state => { + const position = game.local(state).position; + const remains = state.actors.find(actor => actor.type === 51050 && actor.id === enemy.id); + return Math.hypot(position[0] - remains.position[0], position[1] - remains.position[1], + position[2] - remains.position[2]); + }; + // Expose the small corpse above chat while staying within the five-metre Use range. + const viewingDeadline = Date.now() + 20000; + while (corpseDistance(game.state) < 2.5) { + assert(Date.now() < viewingDeadline, 'Starter did not clear its corpse view'); + const sequence = game.sequence; + await game.page.keyboard.press('KeyS', {delay: 200}); + await game.waitInput(sequence, 769); + await game.snapshot(); + assert.equal(game.local().playfield, killed.playfield, 'Corpse retreat crossed a zone boundary'); + } + assert(corpseDistance(game.state) < 5); + + await frame(game, 51050, enemy.id); + let [x, y] = await game.pick(51050, enemy.id); + await game.click(x, y, 'right'); + await game.wait('earned corpse cash', state => game.local(state).stats[61] === credits + corpse.credits); + await game.wait('corpse window open', state => state.regions.some( + ([left, top, right, bottom]) => left === 0 && top === 0 && right === 178 && bottom === 128)); + await game.click(170, 8); + const reopen = game.sequence; + [x, y] = await game.pick(51050, enemy.id); + await game.click(x, y, 'right'); + await game.wait('native corpse reopen request', () => game.events.some(event => { + if (event.sequence <= reopen || event.direction !== 'framesent' || event.opcode !== '52526858') return false; + const packet = Buffer.from(event.hex, 'hex'); + return packet.readUInt32BE(packet.length - 8) === 51050 && packet.readUInt32BE(packet.length - 4) === enemy.id; + })); + await game.wait('corpse window reopened', state => state.regions.some( + ([left, top, right, bottom]) => left === 0 && top === 0 && right === 178 && bottom === 128)); + await game.save(output + '/' + label + '/corpse-loot'); + if (corpse.items?.length) { + assert.deepEqual(corpse.items, [{ID: corpse.items[0].ID, Type: 51005, + Template: 42640, Quality: 1, Slot: 0, Count: 1, Ammo: 0}]); + await game.click(30, 45); + await game.wait('generated part in native inventory', state => + game.local(state).inventory.some(item => item.id === corpse.items[0].ID)); + } + await game.click(170, 8); + const combatUses = await recover(game, label + '/recovery'); + + const after = await (await game.page.request.get(url + '/test-state')).json(); + assert.equal(after.inventory.Credits, credits + corpse.credits); + for (const item of corpse.items ?? []) { + const slots = new Set(killed.inventory.Items.map(item => item.Slot)); + let slot = 64; + while (slots.has(slot)) ++slot; + assert.deepEqual(after.inventory.Items.find(held => held.ID === item.ID), {...item, Slot: slot}); + } + console.log('PASS: ' + label + ', full-health kill, exact corpse ledger and recovery'); + return {fightStart: {health: beforeFight.health, enemy: healthyEnemy}, corpse, combatUses, + parts: after.inventory.Items.filter(item => (corpse.items ?? []).some(part => part.ID === item.ID))}; +} + try { // Create both characters through the same Options form used during ordinary play. for (const name of ['Starterowner', 'Starterwatch']) { @@ -185,7 +346,6 @@ try { await owner.walk(x, z); if (!owner.state.camera.firstPerson) await owner.key('F8'); - let beforeFight, healthyEnemy; const approachDeadline = Date.now() + 30000; for (;;) { await owner.snapshot(); @@ -197,139 +357,179 @@ try { await owner.walk(target.position[0], target.position[2] - 2); continue; } - // Cycle native combat targets without requiring a moving ground model above chat. - if (owner.state.selected[0] !== 50000 || owner.state.selected[1] !== enemy.id) { - await owner.key('Tab'); - continue; - } - beforeFight = await (await owner.page.request.get(url + '/test-state')).json(); - healthyEnemy = beforeFight.enemies.find(actor => actor.id === enemy.id); + const beforeFight = await (await owner.page.request.get(url + '/test-state')).json(); + const healthyEnemy = beforeFight.enemies.find(actor => actor.id === enemy.id); if (Math.hypot(healthyEnemy.position[0] - owner.local().position[0], healthyEnemy.position[1] - owner.local().position[1], healthyEnemy.position[2] - owner.local().position[2]) <= 3) break; } - assert.equal(beforeFight.health, 84); - assert.equal(owner.local().stats[27], 84); - assert.equal(healthyEnemy.health, 100); - assert.equal(healthyEnemy.maximumHealth, 100); - await owner.key('KeyQ'); - let special = owner.sequence; - await owner.key('KeyN'); - const deadline = Date.now() + 120000; - for (;;) { - await owner.snapshot(); - assert(owner.local().stats[27] > 0, 'Ordinary starter died during its first fight'); - if (owner.state.actors.some(actor => actor.type === 51050 && actor.id === enemy.id)) break; - assert(Date.now() < deadline, 'Ordinary Leet fight did not finish'); - const unlocked = owner.events.some(event => { - if (event.sequence <= special || event.direction !== 'framereceived' || event.opcode !== '5e477770') return false; - const packet = Buffer.from(event.hex, 'hex'); - return packet.readUInt32BE(packet.length - 20) === 164 && packet.readUInt32BE(packet.length - 4) === 147; - }); - if (unlocked) { - special = owner.sequence; - await owner.key('KeyN'); - } - } - await owner.wait('earned kill XP', state => owner.local(state).stats[52] === 100); - await owner.save(output + '/earned-kill'); + const fights = [await fight(owner, enemy, 'outdoor')]; - // Use the actual remains twice, then take any generated part exactly once. - const killed = await (await owner.page.request.get(url + '/test-state')).json(); - const corpse = killed.corpses.find(corpse => corpse.id === enemy.id); - assert(corpse && corpse.credits >= 1 && corpse.credits <= 5); - const corpseDistance = state => { - const position = owner.local(state).position; - const remains = state.actors.find(actor => actor.type === 51050 && actor.id === enemy.id); - return Math.hypot(position[0] - remains.position[0], position[1] - remains.position[1], - position[2] - remains.position[2]); - }; - // Expose the small corpse above chat while staying within the five-metre Use range. - const viewingDeadline = Date.now() + 20000; - while (corpseDistance(owner.state) < 4.3) { - assert(Date.now() < viewingDeadline, 'Starter did not clear its corpse view'); - const sequence = owner.sequence; - await owner.page.keyboard.press('KeyS', {delay: 200}); - await owner.waitInput(sequence, 769); - await owner.snapshot(); - } - assert(corpseDistance(owner.state) < 5); + // Spend one earned credit on the first advertised contract at the original booth. + for (const [x, z] of [[62, 74], [62, 65], [52.5, 57.6], [52.5973, 55.1362]]) + await owner.walk(x, z); + await owner.wait('ordinary backyard arrival', state => owner.local(state)?.playfield === 3000, 60000); + await owner.ready(); + for (const [x, z] of [[102.5, 102], [102.5, 143], [104, 149.5], [103, 149.1]]) + await owner.walk(x, z); + await frame(owner, 56001, 3221228472); + let [x, y] = await owner.pick(56001, 3221228472); + await owner.click(x, y, 'right'); + await owner.wait('visible mission difficulty window', state => state.regions.some( + ([left, top, right, bottom]) => left === 150 && top === 180 && right === 220 && bottom === 200)); + await owner.click(100, 163); + await owner.wait('earned mission request fee', state => + owner.local(state).stats[61] === fights[0].corpse.credits - 1); + const advertised = (await (await owner.page.request.get(url + '/test-state')).json()).offer; + assert(advertised && advertised.Credits === 20 && advertised.RewardQuality === 1); + await owner.save(output + '/mission-offer'); + await owner.click(30, 45); + await owner.click(74, 190); + await owner.wait('ordinary mission key', state => owner.local(state).inventory.some(item => item.templates[0] === 28577)); + const accepted = await (await owner.page.request.get(url + '/test-state')).json(); + assert.equal(accepted.missions.length, 1); + const mission = accepted.missions[0]; + for (const field of ['Description', 'Playfield', 'Entrance', 'Position', 'ObjectiveItem', + 'Credits', 'Experience', 'RewardItem', 'RewardQuality']) + assert.deepEqual(mission.definition[field], advertised[field]); + assert.equal(mission.completed, false); + const key = accepted.inventory.Items.find(item => item.ID === mission.id); + assert(key && key.Type === 51053 && key.Template === 28577); + const nativeKey = owner.local().inventory.find(item => item.templates[0] === 28577); + assert.equal(nativeKey.slot, key.Slot - 16); + assert.equal(nativeKey.quality, 1); + assert.equal(nativeKey.count, 1); + await owner.save(output + '/mission-accepted'); - // Frame the stationary remains through native camera input when terrain puts them behind UI. - const remains = () => owner.state.actors.find(actor => actor.type === 51050 && actor.id === enemy.id); - if (remains().screenPosition[1] < 350 || remains().screenPosition[1] > 540) { - const cameraPoint = await owner.point(512, 300); - let mouseY = cameraPoint.y, sequence = owner.sequence; - const framingDeadline = Date.now() + 10000; - await owner.page.mouse.move(cameraPoint.x, mouseY); - await owner.page.mouse.down({button: 'right'}); - try { - await owner.waitInput(sequence, 1025); - for (;;) { - await owner.snapshot(); - const screenY = remains().screenPosition[1]; - if (screenY >= 350 && screenY <= 540) break; - assert(Date.now() < framingDeadline, 'Starter did not frame its corpse above chat'); - mouseY += screenY > 540 ? 20 : -20; - await owner.page.mouse.move(cameraPoint.x, mouseY, {steps: 2}); + // Enter with the issued key and clear all five authored, full-health encounters. + for (const [x, z] of [[96.4, 150.1], [89.3, 153.6], [89.3, 151.2]]) + await owner.walk(x, z); + await owner.wait('private mission arrival', state => owner.local(state)?.playfield === mission.world, 60000); + await owner.ready(); + const entered = await (await owner.page.request.get(url + '/test-state')).json(); + assert.equal(entered.enemies.length, 5); + assert(entered.enemies.every(enemy => enemy.health === 100 && enemy.maximumHealth === 100)); + assert.equal(entered.missions[0].layout, mission.layout); + mission.objective = entered.missions[0].objective; + const encounters = entered.enemies.sort((a, b) => a.position[2] - b.position[2]); + await owner.save(output + '/mission-entered'); + let book; + for (let index = 0; index < encounters.length; ++index) { + const z = [16.6, 27.5, 33.25, 40.25, 43.25][index]; + await owner.walk(15, z); + fights.push(await fight(owner, encounters[index], 'mission-' + (index + 1))); + if (index === 0) { + for (const z of [16.6, 24.2]) { + await owner.walk(15, z); + await jump(owner); } - } finally { - sequence = owner.sequence; - await owner.page.mouse.up({button: 'right'}); } - await owner.waitInput(sequence, 1026); + if (index === 1) { + // Pick up the exact world book before later loot fills the visible bag rows. + await owner.walk(15, 31); + await frame(owner, 51005, mission.objective); + const beforePickup = (await (await owner.page.request.get(url + '/test-state')).json()).inventory; + [x, y] = await owner.pick(51005, mission.objective); + await owner.click(x, y); + const pickup = owner.sequence; + await owner.key('KeyR'); + for (const direction of ['framesent', 'framereceived']) { + await owner.wait('exact mission book pickup ' + direction, () => owner.events.some(event => { + if (event.sequence <= pickup || event.direction !== direction || event.opcode !== '47537a24') return false; + const packet = Buffer.from(event.hex, 'hex'); + return packet.readUInt32BE(packet.length - 20) === 51005 && + packet.readUInt32BE(packet.length - 16) === mission.objective && + packet.readUInt32BE(packet.length - 12) === 0 && packet.readUInt32BE(packet.length - 8) === 0 && + packet.readUInt32BE(packet.length - 4) === 111; + })); + } + const collected = (await (await owner.page.request.get(url + '/test-state')).json()).inventory; + const occupied = new Set(beforePickup.Items.map(item => item.Slot)); + let slot = 64; + while (occupied.has(slot)) ++slot; + assert.deepEqual(collected.Items, [...beforePickup.Items, {ID: mission.objective, + Type: 51005, Template: 40822, Quality: 1, Slot: slot, Count: 1, Ammo: 0}]); + // client/game/kkr.dll/lifted-0017.c::sub_3602D580 leaves the + // simple proxy's identity fields zero. + await owner.wait('mission book proxy in its native slot', state => + owner.local(state).inventory.some(item => item.slot === slot - 16 && item.templates[0] === 40822)); + book = owner.local().inventory.find(item => item.slot === slot - 16); + assert.deepEqual(book, {slot: slot - 16, type: 0, id: 0, quality: 1, + templates: [40822, 40822], count: 1}); + await owner.save(output + '/mission-book'); + } } - let [x, y] = await owner.pick(51050, enemy.id); - await owner.click(x, y, 'right'); - await owner.wait('earned corpse cash', state => owner.local(state).stats[61] === corpse.credits); - await owner.wait('corpse window open', state => state.regions.some( - ([left, top, right, bottom]) => left === 0 && top === 0 && right === 178 && bottom === 128)); - await owner.click(170, 8); - const reopen = owner.sequence; - [x, y] = await owner.pick(51050, enemy.id); + assert.equal(owner.local().stats[52], 600); + const cleared = await (await owner.page.request.get(url + '/test-state')).json(); + assert.deepEqual(cleared.enemies, []); + assert.equal(cleared.missions[0].completed, false); + + // Return the allocated book to the issuing booth through native item-on-item Use. + await owner.walk(15, 26.5); + await jump(owner); + for (const z of [12.5, 10]) await owner.walk(15, z); + await owner.wait('mission exterior return', state => owner.local(state)?.playfield === 3000, 60000); + await owner.ready(); + for (const [x, z] of [[89.3, 153.6], [96.4, 153.6], [99.8, 154], [99.8, 151.4]]) await owner.walk(x, z); + await frame(owner, 56001, 3221228472); + const bookCell = book.slot - 48; + await owner.click(681 + bookCell % 3 * 54, 45 + Math.floor(bookCell / 3) * 54); + [x, y] = await owner.pick(56001, 3221228472); + const handIn = owner.sequence; await owner.click(x, y, 'right'); - await owner.wait('native corpse reopen request', () => owner.events.some(event => { - if (event.sequence <= reopen || event.direction !== 'framesent' || event.opcode !== '52526858') return false; + const credits = fights.reduce((total, fight) => total + fight.corpse.credits, 0) - 1 + advertised.Credits; + await owner.wait('exact book and key consumed with advertised cash', state => + !owner.local(state).inventory.some(item => item.templates[0] === 28577 || item.templates[0] === 40822) && + owner.local(state).stats[61] === credits); + await owner.wait('native exact-book hand-in request', () => owner.events.some(event => { + if (event.sequence <= handIn || event.direction !== 'framesent' || event.opcode !== '52526858') return false; const packet = Buffer.from(event.hex, 'hex'); - return packet.readUInt32BE(packet.length - 8) === 51050 && packet.readUInt32BE(packet.length - 4) === enemy.id; + return packet.readUInt32BE(37) === 5 && packet.readUInt32BE(packet.length - 8) === 56001 && + packet.readUInt32BE(packet.length - 4) === 3221228472; })); - await owner.wait('corpse window reopened', state => state.regions.some( - ([left, top, right, bottom]) => left === 0 && top === 0 && right === 178 && bottom === 128)); - await owner.save(output + '/corpse-loot'); - if (corpse.items?.length) { - assert.deepEqual(corpse.items, [{ID: corpse.items[0].ID, Type: 51005, - Template: 42640, Quality: 1, Slot: 0, Count: 1, Ammo: 0}]); - await owner.click(30, 45); - await owner.wait('generated part in native inventory', state => - owner.local(state).inventory.some(item => item.templates[0] === 42640)); - } - await owner.click(170, 8); - const combatUses = await recover(owner, 'post-combat-recovery'); + const completed = await (await owner.page.request.get(url + '/test-state')).json(); + assert.equal(completed.missions[0].completed, true); + const rewards = completed.inventory.Items.filter(item => + !cleared.inventory.Items.some(held => held.ID === item.ID)); + assert.equal(rewards.length, 1); + assert.equal(rewards[0].Template, advertised.RewardItem); + assert.equal(rewards[0].Quality, advertised.RewardQuality); + assert.equal(rewards[0].Count, 1); + const occupied = new Set(cleared.inventory.Items.filter(item => + item.ID !== mission.id && item.ID !== mission.objective).map(item => item.Slot)); + let rewardSlot = 64; + while (occupied.has(rewardSlot)) ++rewardSlot; + assert.equal(rewards[0].Slot, rewardSlot); + await owner.save(output + '/mission-completed'); // Account for every issued identity, consumed crystal, charge and generated item. - const expected = before.Items.filter(item => item.ID !== crystal.id).map(item => { + const combatUses = fights.reduce((total, fight) => total + fight.combatUses, 0); + const expected = before.Items.filter(item => item.ID !== crystal.id && + (item.Template !== 116628 || trainingUses + combatUses < 25)).map(item => { if (item.ID === bat.id) return {...item, Slot: 6}; if (item.ID === shirt.id) return {...item, Slot: 21}; if (item.Template === 116628) return {...item, Count: 25 - trainingUses - combatUses}; return item; }); - for (const item of corpse.items ?? []) expected.push({...item, Slot: 67}); + for (const fight of fights) expected.push(...fight.parts); + expected.push(...rewards); expected.sort((a, b) => a.ID - b.ID); const final = await (await owner.page.request.get(url + '/test-state')).json(); assert.deepEqual(final.inventory.Items, expected); - assert.equal(final.inventory.Credits, corpse.credits); + assert.equal(final.inventory.Credits, credits); assert.deepEqual(final.inventory.LearnedNanos, [43371]); await fs.writeFile(output + '/ledger.json', JSON.stringify({issued: before, trained: trained.stats, - fightStart: {health: beforeFight.health, enemy: healthyEnemy}, corpse, trainingUses, combatUses, + fights, mission, advertised, rewards, trainingUses, combatUses, inventory: final.inventory, health: final.health}, null, 2) + '\n'); await owner.page.reload(); await owner.ready(); assert.deepEqual(owner.local().inventory.map(item => item.id).sort(), expected.map(item => item.ID).sort()); for (const item of expected) { const actual = owner.local().inventory.find(actual => actual.id === item.ID); + assert.equal(actual.type, item.Type); assert.equal(actual.slot, item.Slot >= 64 ? item.Slot - 16 : item.Slot); assert.equal(actual.count, item.Count); assert.equal(actual.quality, item.Quality); - assert.equal(actual.templates[0], item.Template); + assert.deepEqual(actual.templates, [item.Template, item.Template]); } await owner.key('KeyI'); await owner.page.keyboard.press('Control+1'); @@ -344,7 +544,7 @@ try { assert.equal(observer.local().stats[53], 1500); assert.equal(observer.local().stats[61], 0); for (const game of games) assert.deepEqual(game.errors, []); - console.log('PASS: normal training, issued buff, spawned kill, corpse ledger, laboratory recovery and page ownership'); + console.log('PASS: ordinary starter mission, six kills, exact rewards, recovery and page ownership'); } finally { try { for (const [index, game] of games.entries()) await game.save(output + '/client-' + index);