aorecomp

Anarchy Online classic in the browser

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


commit 74b15b292e700ff6a2bcb0dd18ebd7bceb4acff8
parent d5f5a5566db70c3639d4392496baf911e47dd5fa
Author: anon <anon@example.com>
Date:   Tue, 27 Oct 2026 10:08:57 +0000

Retain selected item quality through shop purchases

Store an explicit quality on each stock row and validate it against reviewed
item families. Resolve native catalog and delivery endpoints, price baskets
at their selected quality, and persist that same quality on purchased items.

Add a documented provisional QL5 Metaplast subset to basic armor booths.
Keep historical stock generation and ordinary earned-income progression open.
Cover faction bindings, endpoint anchors, distinct qualities, affordability,
rollback, wear requirements, cold restoration and sale. Verify native WASM
purchase, rejected wear, re-equip, restart and cancelled/accepted sale.

Diffstat:
MTODO.md | 19+++++++++++++++++--
Mdocs/shops.md | 68+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mserver/gamedata/load.go | 14+++++++++++++-
Mserver/gamedata/shop_stock.yaml | 65++++++++++++++++++++++++++++++++++++-----------------------------
Mserver/gamedata/types.go | 5+++++
Mserver/map_purchases_test.go | 8++++----
Mserver/plasma_test.go | 2+-
Mserver/shop_live_items_test.go | 9+++++----
Mserver/shop_machines_test.go | 2+-
Mserver/shop_med_suit_test.go | 4++--
Mserver/shop_purchases_test.go | 11++++++-----
Aserver/shop_quality_test.go | 234+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/shop_stock_test.go | 14+++++++-------
Mserver/shops.go | 28++++++++++++++++------------
14 files changed, 410 insertions(+), 73 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -996,6 +996,20 @@ introduction and starting-item gameplay remain open below. The NT route now verifies earned purchase/use of a 20-credit Nano Kit, native rejection of an unaffordable laboratory, and exact cold ownership. The affordable equipment upgrade remains open; see [earned recovery](docs/starter-progression.md#earned-recovery-purchase). + Measure the full upgrade budget: earned cash/loot sales, recovery charges and + the ordinary level/IP needed to meet the purchased item's requirements. QL5 + Metaplast gloves cost 343 at effective Computer Literacy 40 in the Omni basic + booth and require Strength 17/Agility 18; the earlier first-level NT run had + earned only 53 before recovery spending. Audit provisional NPC health/rewards + and recovery economics together; a controlled wallet does not prove affordability. +- [x] Preserve selected QL through shop catalogs, quotes, basket quantities, + purchases and native delivery. Each stock entry specifies template and QL; + reviewed families supply interpolation and invalid rows fail startup. Basic + Omni/Clan/neutral armor booths offer a documented provisional six-piece QL5 + Metaplast subset. Fixed stock, endpoint boundaries, separate same-family QLs, + rollback, strict wear and cold ownership use shared rules; see + [selected-quality armor stock](docs/shops.md#selected-quality-basic-armor). + This does not complete the P0 ordinary earned-income equipment purchase above. - [x] Populate shop rooms with their missing vending machines. Restore all 795 original placements, 582 nonidentity rotations and 188 authored mesh overrides through one registry. Native WASM checks cover Omni, Clan and neutral rooms, @@ -1062,8 +1076,9 @@ introduction and starting-item gameplay remain open below. native live object delivery and any packing rules before admitting these categories. Cover full inventory, freed sale slots, partial failure and stable ownership across reconnect/restart without inventing extra packet identity fields. - Fixed-QL typed delivery is verified below. Keep this open for dated stock - membership, finite-weapon purchase ammunition and interpolated stock generation. + Typed delivery and explicit selected-quality armor stock are verified below. + Keep this open for dated weapon/backpack stock membership, finite-weapon + purchase ammunition and historical stock generation/rotation. - [x] Deliver live fixed-QL weapon/backpack purchases through original subclass FullUpdates. Check: count-one real identities, QL/endpoints, correct first-free slots after sales, immediate wear/open/transfer and cold recovery agree between diff --git a/docs/shops.md b/docs/shops.md @@ -7,7 +7,8 @@ Cancel and removing an offer restore the same item. Tools, Devices, General Tools and Bases, and basic Pharmacy Tools expose documented fixed entries. Basic medical terminals offer a supported QL1 subset with authored charges. Complete historical stock membership, random generation and stock rotation remain unresolved. -Map terminals offer the five supported reader upgrades described below. +Map terminals offer the five supported reader upgrades described below. Basic armor +booths expose an explicit QL5 Metaplast subset, with the evidence limits below. ## Original placements and access @@ -71,13 +72,16 @@ resource payloads found category descriptors but no authoritative membership list. See `local/shop-research/stock/README.md`; starter-looking item names are insufficient evidence for a purchase catalog. -## Supported fixed stock and purchases +## Supported stock and purchases The original Anarchy Arcanum NCU Hacker Interface guide, updated 19 February 2003 and [captured 7 March 2003](https://web.archive.org/web/20030307043050id_/http://home.c2i.net:80/ellusion/gadgets_ncuhackerinterface.html), explicitly places Lock Pick in the local Tools booth. Original item 95577 is Lock Pick, fixed QL 1, type 51005, price stat 74 equal to 230. -`shop_stock.yaml` binds supported fixed entries to original terminal templates: +`shop_stock.yaml` binds each `{template, quality}` entry to an original terminal +template. Qualities must be exact authored values or belong to a reviewed item +family; invalid rows fail startup. No stock quality is inferred from an anchor +record. Existing fixed entries keep QL1: | Terminal family | Templates | Item | Native type | QL | Base price | | --- | --- | --- | --- | --- | --- | @@ -147,6 +151,58 @@ target; its page date and limited corroborating use are retained explicitly. The fresh original item/vendor records, hashes, descriptions and placement audit are under `local/charged-shop-research/catalog/`; source bytes are under `sources/`. +## Selected-quality basic armor + +Original OT Basic Armor (99383) describes a shop selling basic armor. The Clan +(99502) and neutral (99570) templates share its basic armor category, with their +authored faction contracts and price modifiers. These are existing placed booths, +including the reachable combined shops 1180/1183/1186. The original category +ranges do not enumerate item membership or recover random generation/rotation. + +The fixed six-piece QL5 Metaplast selection is an explicit reconstruction, +not a recovered historical stock table. It uses the already reviewed original +QL1/200 endpoint families: gloves 85596, sleeves 85742, boots 85638, pants 85512, +helmet 85557 and body 85686. Both arms can use separate sleeve instances. Advanced, +superior, starter and unrelated terminal stock is unchanged. There is no new +family-specific pricing, requirement, delivery or equipment branch. + +At QL5 the gloves have native curved value 346, strict Strength>16 and Agility>17 +requirements, and ACs 6/5/6/5/2/2/2/2 in stat 90..97 order. Effective Computer +Literacy 40 quotes 343 credits in the Omni basic booth and 360 in Clan/neutral. +This does not establish affordability from ordinary starter earnings: the +previous first-level NT run earned 53 before recovery spending. The P0 earned +upgrade scenario remains open until ordinary income funds a useful purchase. + +Catalogs resolve both reviewed endpoints for intermediate rows and collapse to +the exact endpoint at a boundary. Different QLs of the same family retain +separate catalog indices, quotes, basket counts and durable item records. Buy, +pending-sale funding, Accept, AddTemplate and cold inventory all use the selected +quality. Existing transaction, first-free-slot and replay rules apply unchanged. + +A headed WASM client on the GPU verified the production Omni booth's six +QL5 entries, 343-credit glove quote and native strict Strength 17/Agility 18 +requirements. Add/remove/cancel retained cash and ownership; buying created +item 683 at QL5 and debited the controlled wallet 400->57. Strength 16 rejected +wear without losing it. Qualifying at 17 allowed wear, removal and re-equip; +a server/client restart restored the same item, wallet and all eight AC bonuses. +A later stock pick rejected the exact 286-credit shortfall. Cancelled sale +retained the item; accepted sale credited 20 once, leaving wallet 77, no owned +item and no armor bonus. No page exception or adapter abort occurred. + +These were controlled funds, stats and location. They verify the shared purchase +path rather than ordinary earned progression. The owned QA client closed and +its account was removed; unrelated table hashes and SQLite integrity passed. +Original vendor/item records, native streams, read-only samples, screenshots, +regression negative controls and verification are retained in `local/quality-shop/`. + +The complete server suite passed 1,426 roots / 15,003 results, and gamedata passed +23 roots / 50 results. The affected selection passed 78 server roots / 250 +results plus one gamedata test; race checks passed 7 / 23, and `go vet ./server/...` passed. Separate +negative overlays prove that reverting selected-quality quotes, catalog pairs +or purchase delivery is caught by the new handler regressions. + +## Catalog and transaction protocol + ShopUpdate key 0x58362220 belongs to the selected machine. Its body is a count token `(entries + 1) * 1009`, followed by low template, high template and QL for each entry. It contains neither prices nor owned identities. The native @@ -173,7 +229,7 @@ The native sentinel price 1234567890 contributes zero. This admission formula differs from the displayed and accepted sale calculations below; it does not replace the authoritative funds check on Accept. -For the current fixed template entries, Accept creates one durable owned +For each selected stock entry, Accept creates one durable owned record per selected package. It validates eligibility, all offered sale items, net funds, final inventory capacity and Unique ownership again. Sold items, purchased instances and the resulting cash commit in the same SQLite @@ -203,7 +259,9 @@ separate inventory actions. Admission tests require representable positive counts and exact supported types. Fixed-QL weapons and containers now have a verified [live delivery path](shop-live-items.md), using typed FullUpdates with real identities and the original first-free sentinel. Historical stock admission, -finite purchase clip state and interpolated stock remain separate work. The interface +finite purchase clip state and historical stock generation remain separate work. +Selected-quality armor uses the same AddTemplate path with its resolved endpoint +pair, selected QL and count; pricing and persisted ownership use that same QL. The interface uses the shared [stat-equipment path](stat-equipment.md) for HUD/utility wear. The buy quote recovered from KKR 0x100a9610 is: diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -33,7 +33,7 @@ var ( ShopMachines map[uint32]ShopMachine MissionBooths map[uint32]MissionBooth MissionTemplates map[uint32]MissionTemplate - ShopStock map[uint32][]uint32 + ShopStock map[uint32][]ShopItem ItemCombinations map[uint32]map[uint32]ItemCombination PlayerAppearances struct { Heads []PlayerHead `yaml:"heads"` @@ -179,6 +179,18 @@ func init() { ItemFamilies[pair[0]], ItemFamilies[pair[1]] = pair, pair } + // Stock rows specify their own quality; only reviewed family intervals qualify. + for vendor, stock := range ShopStock { + if ItemTemplates[vendor] == nil || ItemTemplates[vendor].HeaderWords[0] != 51035 { + panic(fmt.Errorf("invalid shop stock owner %d", vendor)) + } + for _, item := range stock { + if !ItemQualitySupported(item.Template, item.Quality) { + panic(fmt.Errorf("invalid shop stock %d: template %d quality %d", vendor, item.Template, item.Quality)) + } + } + } + // Fixed-QL recipes identify both inputs and which ones their result replaces. loadYAML("item_combinations.yaml", &ItemCombinations) for first, targets := range ItemCombinations { diff --git a/server/gamedata/shop_stock.yaml b/server/gamedata/shop_stock.yaml @@ -4,50 +4,57 @@ # medical subset. See docs/shops.md for source provenance and remaining gaps. # Tools: Lock Pick. -99491: [95577] -99492: [95577] -99493: [95577] -99527: [95577] -99528: [95577] -99530: [95577] -99601: [95577] -152008: [95577] -152012: [95577] +99491: [{template: 95577, quality: 1}] +99492: [{template: 95577, quality: 1}] +99493: [{template: 95577, quality: 1}] +99527: [{template: 95577, quality: 1}] +99528: [{template: 95577, quality: 1}] +99530: [{template: 95577, quality: 1}] +99601: [{template: 95577, quality: 1}] +152008: [{template: 95577, quality: 1}] +152012: [{template: 95577, quality: 1}] # Devices: Nano Programming Interface. -155602: [161699] -155603: [161699] -155604: [161699] -155605: [161699] -155606: [161699] -155607: [161699] -155608: [161699] -155609: [161699] -155610: [161699] +155602: [{template: 161699, quality: 1}] +155603: [{template: 161699, quality: 1}] +155604: [{template: 161699, quality: 1}] +155605: [{template: 161699, quality: 1}] +155606: [{template: 161699, quality: 1}] +155607: [{template: 161699, quality: 1}] +155608: [{template: 161699, quality: 1}] +155609: [{template: 161699, quality: 1}] +155610: [{template: 161699, quality: 1}] # General Tools and Bases: Expendable Hologram Camera, ID-extractor. -155284: [156054, 156339] -155285: [156054, 156339] -155286: [156054, 156339] +155284: [{template: 156054, quality: 1}, {template: 156339, quality: 1}] +155285: [{template: 156054, quality: 1}, {template: 156339, quality: 1}] +155286: [{template: 156054, quality: 1}, {template: 156339, quality: 1}] # Basic Pharmacy and Chemistry Tools and Bases: reusable Bio-Comminutor. # Arcanum's pharmacy guide establishes this booth; QL1 is a bounded stock subset. -155287: [154331] +155287: [{template: 154331, quality: 1}] # Basic medical supplies: supported QL1 subset. Original medical-family # descriptions and package definitions; full generation is unresolved. # See docs/shops.md for the reconstruction policy and evidence bounds. -99481: [25812, 85366, 25820] -99508: [25812, 85366, 25820] -99574: [25812, 85366, 25820] +99481: [{template: 25812, quality: 1}, {template: 85366, quality: 1}, {template: 25820, quality: 1}] +99508: [{template: 25812, quality: 1}, {template: 85366, quality: 1}, {template: 25820, quality: 1}] +99574: [{template: 25812, quality: 1}, {template: 85366, quality: 1}, {template: 25820, quality: 1}] # Maps: the five original reader upgrades. Fixed subset, not recovered TIAM stock. # Shipped map-window help and original upgrade contracts; see docs/shops.md. -117649: [116683, 116684, 116685, 116692, 116694] -117749: [116683, 116684, 116685, 116692, 116694] -118050: [116683, 116684, 116685, 116692, 116694] +117649: [{template: 116683, quality: 1}, {template: 116684, quality: 1}, {template: 116685, quality: 1}, {template: 116692, quality: 1}, {template: 116694, quality: 1}] +117749: [{template: 116683, quality: 1}, {template: 116684, quality: 1}, {template: 116685, quality: 1}, {template: 116692, quality: 1}, {template: 116694, quality: 1}] +118050: [{template: 116683, quality: 1}, {template: 116684, quality: 1}, {template: 116685, quality: 1}, {template: 116692, quality: 1}, {template: 116694, quality: 1}] # Omni clothing: fixed-QL Omni-Med suit pieces. May 2002 clothing-terminal # accounts establish the family; the original records supply slots and effects. # See docs/shop-med-suit.md for stock-policy and access evidence boundaries. -99490: [27381, 27382, 27383, 27384, 27385, 27386, 27387] +99490: [{template: 27381, quality: 1}, {template: 27382, quality: 1}, {template: 27383, quality: 1}, {template: 27384, quality: 1}, {template: 27385, quality: 1}, {template: 27386, quality: 1}, {template: 27387, quality: 1}] + +# Basic armor: a fixed QL5 Metaplast subset of the original basic-armor family. +# This is reconstruction policy; complete membership and rotation remain open. +# See docs/shops.md for the stock and authored-value evidence boundary. +99383: [{template: 85596, quality: 5}, {template: 85742, quality: 5}, {template: 85638, quality: 5}, {template: 85512, quality: 5}, {template: 85557, quality: 5}, {template: 85686, quality: 5}] +99502: [{template: 85596, quality: 5}, {template: 85742, quality: 5}, {template: 85638, quality: 5}, {template: 85512, quality: 5}, {template: 85557, quality: 5}, {template: 85686, quality: 5}] +99570: [{template: 85596, quality: 5}, {template: 85742, quality: 5}, {template: 85638, quality: 5}, {template: 85512, quality: 5}, {template: 85557, quality: 5}, {template: 85686, quality: 5}] diff --git a/server/gamedata/types.go b/server/gamedata/types.go @@ -1,5 +1,10 @@ package gamedata +type ShopItem struct { + Template uint32 `yaml:"template"` + Quality uint32 `yaml:"quality"` +} + type ShopMachine struct { Template uint32 `yaml:"template"` Playfield uint32 `yaml:"playfield"` diff --git a/server/map_purchases_test.go b/server/map_purchases_test.go @@ -46,7 +46,7 @@ func TestMapTerminalsExposeOnlyTheSupportedReaderUpgradeSubset(t *testing.T) { err := world.handleShopUse(client, request) - expected := []uint32{116683, 116684, 116685, 116692, 116694} + expected := []gamedata.ShopItem{{Template: 116683, Quality: 1}, {Template: 116684, Quality: 1}, {Template: 116685, Quality: 1}, {Template: 116692, Quality: 1}, {Template: 116694, Quality: 1}} if err != nil || client.shop == nil || !slices.Equal(client.shop.stock, expected) || len(conn.packets) != 5 { t.Fatal("wrong map-terminal catalog", identity, err) } @@ -54,8 +54,8 @@ func TestMapTerminalsExposeOnlyTheSupportedReaderUpgradeSubset(t *testing.T) { if len(packet) != 96 || binary.BigEndian.Uint32(packet[16:20]) != 0x58362220 || binary.BigEndian.Uint32(packet[24:28]) != identity || binary.BigEndian.Uint32(packet[29:33]) != 6054 { t.Fatal("wrong map ShopUpdate owner/count", identity) } - for index, template := range expected { - for field, value := range []uint32{template, template, 1} { + for index, entry := range expected { + for field, value := range []uint32{entry.Template, entry.Template, entry.Quality} { if binary.BigEndian.Uint32(packet[33+12*index+4*field:]) != value { t.Fatal("wrong fixed upgrade template/quality", identity, index, field) } @@ -64,7 +64,7 @@ func TestMapTerminalsExposeOnlyTheSupportedReaderUpgradeSubset(t *testing.T) { } for template, stock := range gamedata.ShopStock { for _, item := range stock { - if slices.Contains([]uint32{116683, 116684, 116685, 116692, 116694}, item) && template != 117649 && template != 117749 && template != 118050 { + if slices.Contains([]uint32{116683, 116684, 116685, 116692, 116694}, item.Template) && template != 117649 && template != 117749 && template != 118050 { t.Fatal("reader upgrade leaked into another terminal family", template) } } diff --git a/server/plasma_test.go b/server/plasma_test.go @@ -283,7 +283,7 @@ func TestPlasmaToolPurchaseUsesOriginalBasicPharmacyStock(t *testing.T) { t.Fatal("purchased tool did not retain its price, identity or reuse behavior", cold.characters[1].inventory) } for _, template := range []uint32{155288, 155289, 100034, 100035, 99481} { - if slices.Contains(gamedata.ShopStock[template], 154331) { + if slices.Contains(gamedata.ShopStock[template], gamedata.ShopItem{Template: 154331, Quality: 1}) { t.Fatal("basic pharmacy subset leaked into another stock family", template) } } diff --git a/server/shop_live_items_test.go b/server/shop_live_items_test.go @@ -1,6 +1,7 @@ package main import ( + "ao/server/gamedata" "bytes" "encoding/binary" "reflect" @@ -16,7 +17,7 @@ func TestShopMixedPurchasesDeliverLiveWeaponsAndBackpacksAfterCommit(t *testing. t.Fatal(err) } // Fixture stock tests delivery without asserting historical vendor membership. - client.shop.stock = []uint32{99228, 209283, 123742, 95577} + client.shop.stock = []gamedata.ShopItem{{Template: 99228, Quality: 1}, {Template: 209283, Quality: 1}, {Template: 123742, Quality: 1}, {Template: 95577, Quality: 1}} for _, index := range []uint32{0, 0, 1, 2, 3} { if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, index})[20:]); err != nil { t.Fatal(err) @@ -67,7 +68,7 @@ func TestShopMixedPurchasesDeliverLiveWeaponsAndBackpacksAfterCommit(t *testing. func TestShopLivePurchaseSQLFailurePublishesNothingAndRetriesOnce(t *testing.T) { world, conn := newPurchaseWorld(t) client, player := world.clients[1], world.characters[1] - client.shop.stock = []uint32{99228} + client.shop.stock = []gamedata.ShopItem{{Template: 99228, Quality: 1}} if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:]); err != nil { t.Fatal(err) } @@ -96,7 +97,7 @@ func TestShopLivePurchaseSQLFailurePublishesNothingAndRetriesOnce(t *testing.T) func TestShopLivePurchaseRejectsOverflowWithoutPartialDelivery(t *testing.T) { world, conn := newPurchaseWorld(t) client, player := world.clients[1], world.characters[1] - client.shop.stock = []uint32{99228} + client.shop.stock = []gamedata.ShopItem{{Template: 99228, Quality: 1}} player.inventory.Credits = 2000 for slot := uint32(65); slot < 93; slot++ { player.inventory.Items = append(player.inventory.Items, ownedItem{ID: slot - 63, Type: 51005, Template: 95577, Quality: 1, Slot: slot, Count: 1}) @@ -125,7 +126,7 @@ func TestShopLivePurchaseRejectsOverflowWithoutPartialDelivery(t *testing.T) { func TestShopLivePurchaseLostCompletionRecoversEveryInstanceOnce(t *testing.T) { world, _ := newPurchaseWorld(t) client, player := world.clients[1], world.characters[1] - client.shop.stock = []uint32{99228, 123742} + client.shop.stock = []gamedata.ShopItem{{Template: 99228, Quality: 1}, {Template: 123742, Quality: 1}} player.inventory.Credits = 10000 if err := world.saveInventory_locked(player, player.inventory); err != nil { t.Fatal(err) diff --git a/server/shop_machines_test.go b/server/shop_machines_test.go @@ -59,7 +59,7 @@ func TestShopUseEvaluatesAuthoredAccessContracts(t *testing.T) { } if scenario.accepted { packets := 4 - if scenario.machine == 3221685407 { + if scenario.machine == 3221685407 || scenario.machine == 3221226655 { packets = 5 } start := conn.packets[len(conn.packets)-1] diff --git a/server/shop_med_suit_test.go b/server/shop_med_suit_test.go @@ -44,7 +44,7 @@ func TestShopMedSuitPurchasedPiecesWearAndRecover(t *testing.T) { t.Run(fmt.Sprint(scenario.template), func(t *testing.T) { world, _ := newMedSuitShopWorld(t) player, client := world.characters[1], world.clients[1] - if !slices.Equal(client.shop.stock, []uint32{27381, 27382, 27383, 27384, 27385, 27386, 27387}) { + if !slices.Equal(client.shop.stock, []gamedata.ShopItem{{Template: 27381, Quality: 1}, {Template: 27382, Quality: 1}, {Template: 27383, Quality: 1}, {Template: 27384, Quality: 1}, {Template: 27385, Quality: 1}, {Template: 27386, Quality: 1}, {Template: 27387, Quality: 1}}) { t.Fatal("original Omni clothing terminal did not expose the fixed suit subset") } weapon := player.inventory.Items[0] @@ -284,7 +284,7 @@ func TestShopMedSuitRejectsUnfundedAndForeignPurchases(t *testing.T) { }) } for _, template := range []uint32{99526, 99637, 100034, 100035, 99643} { - if slices.Contains(gamedata.ShopStock[template], 27381) { + if slices.Contains(gamedata.ShopStock[template], gamedata.ShopItem{Template: 27381, Quality: 1}) { t.Fatal("Omni clothing subset leaked into another terminal", template) } } diff --git a/server/shop_purchases_test.go b/server/shop_purchases_test.go @@ -59,17 +59,18 @@ func TestShopCatalogUsesOriginalPageIndicesAndExactTemplates(t *testing.T) { } } -func TestShopKnownStockOnlyAdmitsSupportedFixedTemplateItems(t *testing.T) { +func TestShopKnownStockOnlyAdmitsSupportedItemQualities(t *testing.T) { for vendor, templates := range gamedata.ShopStock { if gamedata.ItemTemplates[vendor] == nil || gamedata.ItemTemplates[vendor].HeaderWords[0] != 51035 { t.Fatalf("stock owner %d is not an original vending template", vendor) } - for _, template := range templates { + for _, entry := range templates { + template := entry.Template definition := gamedata.ItemTemplates[template] - if definition == nil || definition.Quality == nil || (definition.HeaderWords[0] != 51005 && definition.HeaderWords[0] != 51022) { + if !gamedata.ItemQualitySupported(template, entry.Quality) || (definition.HeaderWords[0] != 51005 && definition.HeaderWords[0] != 51022) { t.Fatalf("stock %d needs a separately verified delivery/packing path", template) } - item := ownedItem{Type: definition.HeaderWords[0], Template: template} + item := ownedItem{Type: definition.HeaderWords[0], Template: template, Quality: entry.Quality} charges := int32(itemStat(definition, 212)) if (item.isStackable() && (charges < 1 || charges > 65535)) || (!item.isStackable() && charges > 1) { t.Fatalf("stock %d cannot represent its authored package count %d", template, charges) @@ -80,7 +81,7 @@ func TestShopKnownStockOnlyAdmitsSupportedFixedTemplateItems(t *testing.T) { func TestShopMedicalSubsetRetainsBasicTerminalBoundary(t *testing.T) { for _, template := range []uint32{99481, 99508, 99574} { - if !slices.Equal(gamedata.ShopStock[template], []uint32{25812, 85366, 25820}) { + if !slices.Equal(gamedata.ShopStock[template], []gamedata.ShopItem{{Template: 25812, Quality: 1}, {Template: 85366, Quality: 1}, {Template: 25820, Quality: 1}}) { t.Fatal("basic medical stock changed", template) } } diff --git a/server/shop_quality_test.go b/server/shop_quality_test.go @@ -0,0 +1,234 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "fmt" + "reflect" + "testing" +) + +func TestShopBasicArmorProductionQualityPurchase(t *testing.T) { + for _, scenario := range []struct { + machine uint32 + side uint16 + credits uint32 + }{ + {3221226655, 2, 657}, {3223389340, 1, 640}, {3222078626, 0, 640}, + } { + t.Run(fmt.Sprint(scenario.machine), func(t *testing.T) { + world, conn := newPurchaseWorld(t) + t.Cleanup(func() { world.db.Close() }) + client, player := world.clients[1], world.characters[1] + machine := gamedata.ShopMachines[scenario.machine] + player.playfield, player.position = machine.Playfield, machine.Position + player.appearance = 0x115 | scenario.side<<9 + request := shopUseRequest(2) + binary.BigEndian.PutUint32(request[44:48], scenario.machine) + + if err := world.handleShopUse(client, request); err != nil { + t.Fatal(err) + } + + if client.shop == nil || !reflect.DeepEqual(client.shop.stock, []gamedata.ShopItem{{Template: 85596, Quality: 5}, {Template: 85742, Quality: 5}, {Template: 85638, Quality: 5}, {Template: 85512, Quality: 5}, {Template: 85557, Quality: 5}, {Template: 85686, Quality: 5}}) { + t.Fatal("basic armor lost its explicit selected-quality subset") + } + + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, scenario.machine}, [2]uint32{111, 0})[20:]); err != nil { + t.Fatal(err) + } + conn.packets = nil + err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]) + + if err != nil || player.inventory.Credits != scenario.credits || len(conn.packets) != 3 || + !reflect.DeepEqual(player.inventory.Items[1:], []ownedItem{{ID: 2, Type: 51022, Template: 85596, Quality: 5, Count: 1, Slot: 65}}) { + t.Fatal("production armor quote or delivery changed", err, player.inventory) + } + }) + } +} + +func TestShopQualityCatalogResolvesBothStoredAnchors(t *testing.T) { + for _, anchor := range []uint32{85596, 85595} { + world, conn := newPurchaseWorld(t) + t.Cleanup(func() { world.db.Close() }) + original := gamedata.ShopStock[99491] + gamedata.ShopStock[99491] = []gamedata.ShopItem{{Template: anchor, Quality: 1}, {Template: anchor, Quality: 5}, {Template: anchor, Quality: 200}} + request := shopUseRequest(2) + binary.BigEndian.PutUint32(request[44:48], 3221488799) + conn.packets = nil + + err := world.handleShopUse(world.clients[1], request) + gamedata.ShopStock[99491] = original + + if err != nil || len(conn.packets) != 6 { + t.Fatal("quality catalog failed", err, len(conn.packets)) + } + catalog := conn.packets[3] + for index, expected := range []uint32{4036, 85596, 85596, 1, 85596, 85595, 5, 85595, 85595, 200} { + if binary.BigEndian.Uint32(catalog[29+4*index:]) != expected { + t.Fatalf("anchor %d catalog field %d changed", anchor, index) + } + } + } +} + +func TestShopQualityRowsKeepDistinctPricesAndDelivery(t *testing.T) { + world, conn := newPurchaseWorld(t) + t.Cleanup(func() { world.db.Close() }) + client, player := world.clients[1], world.characters[1] + client.shop.stock = []gamedata.ShopItem{{Template: 85595, Quality: 1}, {Template: 85596, Quality: 5}, {Template: 85595, Quality: 6}} + player.inventory.Credits = 2000 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + for _, row := range []uint32{2, 1, 0, 1} { + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, row})[20:]); err != nil { + t.Fatal(err) + } + } + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{51035, 3221488799}, [2]uint32{111, 1})[20:]); err != nil { + t.Fatal(err) + } + conn.packets = nil + + err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]) + restored := newTestInventoryServer(t) + t.Cleanup(func() { restored.db.Close() }) + + want := []ownedItem{ + {ID: 2, Type: 51022, Template: 85595, Quality: 1, Count: 1, Slot: 65}, + {ID: 3, Type: 51022, Template: 85596, Quality: 5, Count: 1, Slot: 66}, + {ID: 4, Type: 51022, Template: 85595, Quality: 6, Count: 1, Slot: 67}, + } + if err != nil || !reflect.DeepEqual(player.inventory.Items[1:], want) || !reflect.DeepEqual(restored.characters[1].inventory, player.inventory) || player.inventory.Credits != 1012 || world.nextItem != 4 { + t.Fatalf("quality rows lost price or ownership: %v %+v", err, player.inventory) + } + if len(conn.packets) != 5 { + t.Fatal("wrong delivery count", len(conn.packets)) + } + for index, fields := range [][4]uint32{{85596, 85596, 1, 1}, {85596, 85595, 5, 1}, {85596, 85595, 6, 1}} { + packet := conn.packets[index+1] + if binary.BigEndian.Uint32(packet[16:20]) != 0x052e2f0c { + t.Fatal("missing native template delivery") + } + for field, expected := range fields { + if binary.BigEndian.Uint32(packet[29+4*field:]) != expected { + t.Fatalf("delivery %d field %d changed", index, field) + } + } + } +} + +func TestShopQualityBasketCannotSpendEndpointPrice(t *testing.T) { + world, conn := newPurchaseWorld(t) + t.Cleanup(func() { world.db.Close() }) + client, player := world.clients[1], world.characters[1] + client.shop.stock = []gamedata.ShopItem{{Template: 85596, Quality: 5}} + player.inventory.Credits = 685 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + conn.packets = nil + add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:] + + for _, request := range [][]byte{add, add, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]} { + if err := world.handleTrade(client, request); err != nil { + t.Fatal(err) + } + } + restored := newTestInventoryServer(t) + t.Cleanup(func() { restored.db.Close() }) + + if client.shop != nil || len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[1][33:37]) != 2 || player.inventory.Credits != 685 || len(player.inventory.Items) != 1 || world.nextItem != 1 || !reflect.DeepEqual(restored.characters[1].inventory, player.inventory) { + t.Fatal("basket used endpoint price or retained a rejected purchase") + } +} + +func TestShopQualityPurchaseRollbackAndWearLifetime(t *testing.T) { + world, conn := newPurchaseWorld(t) + t.Cleanup(func() { world.db.Close() }) + client, player := world.clients[1], world.characters[1] + client.shop.stock = []gamedata.ShopItem{{Template: 85596, Quality: 5}} + add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:] + if err := world.handleTrade(client, add); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("CREATE TRIGGER fail_quality_purchase BEFORE INSERT ON items WHEN NEW.quality=5 BEGIN SELECT RAISE(ABORT, 'quality purchase failure'); END"); err != nil { + t.Fatal(err) + } + conn.packets = nil + accept := shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:] + + failed := world.handleTrade(client, accept) + + if failed == nil || len(conn.packets) != 0 || len(player.inventory.Items) != 1 || player.inventory.Credits != 1000 || world.nextItem != 1 || client.shop == nil { + t.Fatal("failed quality purchase published a partial result") + } + + if _, err := world.db.Exec("DROP TRIGGER fail_quality_purchase"); err != nil { + t.Fatal(err) + } + if err := world.handleTrade(client, accept); err != nil { + t.Fatal(err) + } + player.stats.Abilities.Strength, player.stats.Abilities.Agility = 16, 18 + if err := world.handleInventory(client, inventoryMovePacket(1, 65, 24)[20:]); err != nil { + t.Fatal(err) + } + + if client.equipment != nil || player.inventory.Items[1].Slot != 65 || player.inventory.Credits != 657 { + t.Fatal("purchase bypassed interpolated requirements or lost its rejected item") + } + + player.stats.Abilities.Strength = 17 + if err := world.handleInventory(client, inventoryMovePacket(1, 65, 24)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment == nil { + t.Fatal("qualified purchased armor rejected") + } + world.advanceEquipment(client.equipment.readyAt) + restored := newTestInventoryServer(t) + t.Cleanup(func() { restored.db.Close() }) + + want := ownedItem{ID: 2, Type: 51022, Template: 85596, Quality: 5, Count: 1, Slot: 24} + if restored.characters[1].inventory.Items[1] != want || restored.characters[1].inventory.Credits != 657 || world.nextItem != 2 { + t.Fatal("purchased quality or worn ownership did not survive restoration") + } + for index, expected := range []int32{6, 5, 6, 5, 2, 2, 2, 2} { + if restored.characters[1].inventory.equipmentBonus(90+uint32(index)) != expected { + t.Fatal("purchased armor lost its selected quality effects", index) + } + } + + if err := world.handleInventory(client, itemMovePacket(1, 24, 111)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment == nil { + t.Fatal("purchased armor removal rejected") + } + world.advanceEquipment(client.equipment.readyAt) + request := shopUseRequest(2) + binary.BigEndian.PutUint32(request[44:48], 3221488799) + if err := world.handleShopUse(client, request); err != nil { + t.Fatal(err) + } + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleTrade(client, accept); err != nil { + t.Fatal(err) + } + sold := newTestInventoryServer(t) + t.Cleanup(func() { sold.db.Close() }) + + if len(sold.characters[1].inventory.Items) != 1 || sold.characters[1].inventory.Credits != 677 || world.nextItem != 2 { + t.Fatal("sale lost selected-quality price or retained sold ownership") + } + for stat := uint32(90); stat < 98; stat++ { + if sold.characters[1].inventory.equipmentBonus(stat) != 0 { + t.Fatal("sold armor retained its bonus") + } + } +} diff --git a/server/shop_stock_test.go b/server/shop_stock_test.go @@ -11,12 +11,12 @@ import ( func TestShopDocumentedStockUsesTerminalBindings(t *testing.T) { for _, scenario := range []struct { machine uint32 - stock []uint32 + stock []gamedata.ShopItem }{ - {3221488799, []uint32{95577}}, - {3221816479, []uint32{161699}}, - {3225158815, []uint32{156054, 156339}}, - {3225093279, []uint32{154331}}, + {3221488799, []gamedata.ShopItem{{Template: 95577, Quality: 1}}}, + {3221816479, []gamedata.ShopItem{{Template: 161699, Quality: 1}}}, + {3225158815, []gamedata.ShopItem{{Template: 156054, Quality: 1}, {Template: 156339, Quality: 1}}}, + {3225093279, []gamedata.ShopItem{{Template: 154331, Quality: 1}}}, {3221292199, nil}, } { t.Run(fmt.Sprint(scenario.machine), func(t *testing.T) { @@ -43,8 +43,8 @@ func TestShopDocumentedStockUsesTerminalBindings(t *testing.T) { if binary.BigEndian.Uint32(packet[24:28]) != scenario.machine || binary.BigEndian.Uint32(packet[29:33]) != uint32(len(scenario.stock)+1)*1009 { t.Fatal("catalog owner or row count changed") } - for index, template := range scenario.stock { - for field, expected := range []uint32{template, template, 1} { + for index, entry := range scenario.stock { + for field, expected := range []uint32{entry.Template, entry.Template, entry.Quality} { if binary.BigEndian.Uint32(packet[33+12*index+4*field:]) != expected { t.Fatal("catalog endpoint or quality changed") } diff --git a/server/shops.go b/server/shops.go @@ -14,7 +14,7 @@ import ( type shopTrade struct { machine uint32 items map[uint32]ownedItem - stock []uint32 + stock []gamedata.ShopItem purchases map[uint32]uint16 } @@ -117,8 +117,10 @@ func (server *server) handleShopUse(client *worldClient, body []byte) error { if len(client.shop.stock) != 0 { // Native catalog entries are page111 indices, without owned instance IDs. catalog := binary.BigEndian.AppendUint32(nil, uint32(len(client.shop.stock)+1)*1009) - for _, template := range client.shop.stock { - for _, value := range []uint32{template, template, *gamedata.ItemTemplates[template].Quality} { + for _, entry := range client.shop.stock { + item := ownedItem{Type: gamedata.ItemTemplates[entry.Template].HeaderWords[0], Template: entry.Template, Quality: entry.Quality} + low, high := item.templateIDs() + for _, value := range []uint32{low, high, entry.Quality} { catalog = binary.BigEndian.AppendUint32(catalog, value) } } @@ -280,9 +282,9 @@ func (server *server) handleTrade(client *worldClient, body []byte) error { if count == 32767 { return server.abortShop_locked(client) } - template := client.shop.stock[second[1]] - definition := gamedata.ItemTemplates[template] - item := ownedItem{Template: template, Quality: *definition.Quality} + entry := client.shop.stock[second[1]] + definition := gamedata.ItemTemplates[entry.Template] + item := ownedItem{Type: definition.HeaderWords[0], Template: entry.Template, Quality: entry.Quality} if itemStat(definition, 0)&0x08000000 != 0 && (count != 0 || player.inventory.carriesUnique(item)) { return server.abortShop_locked(client) } @@ -292,8 +294,9 @@ func (server *server) handleTrade(client *worldClient, body []byte) error { vendor := gamedata.ItemTemplates[machine.Template] cost := int64(shopBuyPrice(item, itemStat(vendor, 427), literacy)) for index, packages := range client.shop.purchases { - other := gamedata.ItemTemplates[client.shop.stock[index]] - cost += int64(shopBuyPrice(ownedItem{Template: other.ID, Quality: *other.Quality}, itemStat(vendor, 427), literacy)) * int64(packages) + other := client.shop.stock[index] + definition := gamedata.ItemTemplates[other.Template] + cost += int64(shopBuyPrice(ownedItem{Type: definition.HeaderWords[0], Template: other.Template, Quality: other.Quality}, itemStat(vendor, 427), literacy)) * int64(packages) } for _, offered := range client.shop.items { cost -= shopPendingSalePrice(offered, itemStat(vendor, 426), literacy) @@ -378,9 +381,9 @@ func (server *server) handleTrade(client *worldClient, body []byte) error { var cost uint64 nextItem := server.nextItem var purchased []ownedItem - for index, template := range client.shop.stock { - definition := gamedata.ItemTemplates[template] - item := ownedItem{Type: definition.HeaderWords[0], Template: template, Quality: *definition.Quality, Count: 1} + for index, entry := range client.shop.stock { + definition := gamedata.ItemTemplates[entry.Template] + item := ownedItem{Type: definition.HeaderWords[0], Template: entry.Template, Quality: entry.Quality, Count: 1} if item.isStackable() { item.Count = uint16(itemStat(definition, 212)) } @@ -442,7 +445,8 @@ func (server *server) handleTrade(client *worldClient, body []byte) error { continue } var body []byte - for _, value := range []uint32{item.Template, item.Template, item.Quality, uint32(item.Count)} { + low, high := item.templateIDs() + for _, value := range []uint32{low, high, item.Quality, uint32(item.Count)} { body = binary.BigEndian.AppendUint32(body, value) } if err := client.send(n3Packet(0x052e2f0c, 50000, client.id, body)); err != nil {