aorecomp

Anarchy Online classic in the browser

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


commit 1cb422bfdd38ea74ec27361cbae92e58b25aad91
parent a09b87f4b9bc25540f42363652fd75d66f750a1d
Author: anon <anon@example.com>
Date:   Sun, 25 Oct 2026 05:56:50 +0000

Support documented device stock and shared stat equipment

Diffstat:
MTODO.md | 19++++++++++++++++++-
Mdocs/belts-ncu.md | 6++++--
Mdocs/clothing.md | 3+++
Mdocs/shops.md | 59++++++++++++++++++++++++++++++++++++++++++++++-------------
Adocs/stat-equipment.md | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dserver/clothing.go | 33---------------------------------
Mserver/equipment.go | 30++++++++++++------------------
Mserver/gamedata/load.go | 2+-
Mserver/gamedata/shop_stock.yaml | 34++++++++++++++++++++++++++++++----
Mserver/inventory.go | 2+-
Mserver/shop_machines_test.go | 2+-
Mserver/shop_purchases_test.go | 9++++++---
Aserver/shop_stock_test.go | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/shops.go | 19+------------------
Aserver/stat_equipment.go | 33+++++++++++++++++++++++++++++++++
Aserver/utility_equipment_test.go | 153+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16 files changed, 505 insertions(+), 95 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -156,6 +156,17 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md). invalid belt removal cannot strand installed equipment. - [x] Install one NCU memory. Check: available NCU changes by the item's amount and remains correct after reconnect and removal. +- [x] Equip HUD/utility stat devices through catalog slot masks, native action-8 + admission and shared wear effects. Nano Programming Interface uses all six + authored HUD/utility positions and adds 2 Nano Programming. Exact catalog + belts and memories now share this path instead of template-specific cases; + deck capacity and empty-deck belt removal checks remain enforced. See + [stat equipment](docs/stat-equipment.md). +- [ ] Resolve historical server handling of ItemType-1 equipment with only + authored action-6 criteria. The native predicate selects action 8 and does + not check the interface's action-6 Intelligence >12 criterion. Current + admission follows that observed native path; recover server evidence before + changing it or claiming the discrepancy resolved. - [x] Apply overequipping rules to one weapon. Check: dropping below a verified requirement threshold changes effectiveness at the correct boundary. - [x] Apply armor/backpack overequipping to AC and maximum health. Check: @@ -565,10 +576,16 @@ introduction and starting-item gameplay remain open below. space leaves both unchanged. Cover vending-machine types and access rules separately from NPC vendors, including reconnect and restart. - [x] Browse one vendor's documented fixed stock. The period Anarchy Arcanum - guide places QL 1 Lock Pick 95577 in Tools. The nine original OTIM templates + guide places QL 1 Lock Pick 95577 in Tools. The nine original Tools templates expose that entry; native Omni/Clan quotes use their own terminal modifiers. Browsing allocates no owned item and spends no cash. This establishes one entry, not complete Tools inventories or historical stock generation. +- [x] Add period-documented Devices and General Tools and Bases entries. + Nano Programming Interface 161699 is sold by the nine Devices templates; + camera 156054 and ID-extractor 156339 by the three General Tools templates. + Original terminal bindings keep the opaque OTIM code from leaking Tools + entries into Computers. Native purchases preserve each row's template, + price, Unique rules and durable identity. - [ ] Recover complete historical shop stock, including the starter QETS category's actual membership. Original descriptors identify 153 categories but do not establish their stock. Research online for shop diff --git a/docs/belts-ncu.md b/docs/belts-ncu.md @@ -1,6 +1,6 @@ # Belt and NCU memory in 14.9.1 -The supported items are exact QL 1 endpoints from +The initial verified fixtures are exact QL 1 endpoints from `server/gamedata/items/items_001.yaml`, native type 51022, ItemClass 76 = 1. Their catalog action 8 requires Computer Literacy 161 strictly greater than 5. Neither has profession restrictions or authored removal requirements. @@ -17,7 +17,9 @@ Historical 14.2.1 records corroborate the [belt](https://auno.org/ao/db.php?id=36783&patch=14020100) and [memory](https://auno.org/ao/db.php?id=36779&patch=14020100). The memory's name describes a range across qualities; this exact QL 1 item -adds 2 NCU. Higher qualities and other belts are not yet supported. +adds 2 NCU. Other exact catalog belts and memories now use the shared +[stat-equipment path](stat-equipment.md); arbitrary intermediate qualities +remain unsupported. ## Capacity and equipment rules diff --git a/docs/clothing.md b/docs/clothing.md @@ -37,6 +37,9 @@ have one tick with zero interval. Native mesh, texture and visual handlers their authoritative server meaning. They and other unknown OnWear functions are rejected until their gameplay effects are understood and implemented. See [effect handlers](combat-client-effect-handlers.md). +The same stat/presentation validation now supports catalog +[HUD, utility and deck equipment](stat-equipment.md), with its own native +slot-mask and action-8 admission rules. | Starter gift | Template | Absolute slot | Wear criteria | OnWear | | --- | ---: | ---: | --- | --- | diff --git a/docs/shops.md b/docs/shops.md @@ -3,8 +3,8 @@ The server restores the original vending-machine placements and accepts staged sales from ordinary inventory. An offer remains owned by the player until Accept commits its removal and the credit award in one SQLite transaction. -Cancel and removing an offer restore the same item. Tools terminals expose a -documented fixed Lock Pick entry and accept purchases. Complete historical +Cancel and removing an offer restore the same item. Tools, Devices and General +Tools and Bases expose documented fixed entries and accept purchases. Complete historical stock membership, random generation and stock rotation remain unresolved. ## Original placements and access @@ -70,20 +70,40 @@ are insufficient evidence for a purchase catalog. 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. The nine original -Tools templates share category OTIM. `shop_stock.yaml` supplies that documented -fixed entry to those catalogs; it does not claim to recover their complete +Lock Pick, fixed QL 1, type 51005, price stat 74 equal to 230. +`shop_stock.yaml` binds documented fixed entries to original terminal templates: + +| Terminal family | Templates | Item | Native type | QL | Base price | +| --- | --- | --- | --- | --- | --- | +| Tools | 9 | Lock Pick 95577 | 51005 | 1 | 230 | +| Devices | 9 | Nano Programming Interface 161699 | 51022 | 1 | 900 | +| General Tools and Bases | 3 | Expendable Hologram Camera 156054 | 51005 | 1 | 1300 | +| General Tools and Bases | 3 | ID-extractor 156339 | 51005 | 1 | 9500 | + +The original Personal Lockpick guide, updated 28 August 2002 and +[captured 7 March 2003](https://web.archive.org/web/20030307031410id_/http://home.c2i.net:80/ellusion/gadgets_personallockpick.html), +places the camera and ID-extractor in General Tools and Bases. Applying the +documented fixed entries across each booth family is reconstruction policy; +it does not claim to recover their complete inventories, original random selection or refresh policy. Unknown categories retain their working sales without invented purchase entries. -The same period guide places Nano Programming Interface in a Devices booth. +The NCU guide places Nano Programming Interface in a Devices booth. A later guide places it in Tools; that later wording is insufficient to change -the period mapping, so the interface is not admitted. The original public +the period mapping. The original public 2002 domain pages are framesets pointing to the separately archived content host. Exact captures, CDX metadata, original item bytes and hashes are retained under `local/shop-purchase-research/sources/`. The later emulator's full stock tables include expansion data and are not imported as historical truth. +The original ACG code OTIM occurs in both Tools and Computers templates. +Their remaining descriptor fields differ, and no complete generator was +recovered. Sharing that code does not establish identical stock; the fixed +bindings do not infer lockpicks for Computers. Devices and General Tools use +HKJM and ABEG, respectively, but these opaque descriptors are not treated as +recovered membership lists or QL rules. The bounded audit is retained under +`local/shop-stock-expansion-research/`. + 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 @@ -110,7 +130,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 simple-item entries, Accept creates one durable owned +For the current fixed template entries, 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 @@ -126,7 +146,8 @@ null instance identity. The durable server item identity survives reconnect, whose full inventory supplies it. No extra ID word is invented in either packet. Delivery and package packing for charged stacks, weapons, containers and interpolated stock remain separate work; current stock admission tests -require exact, nonstacking type 51005 items. +require exact, nonstacking template items of type 51005 or 51022. The interface +uses the shared [stat-equipment path](stat-equipment.md) for HUD/utility wear. The buy quote recovered from KKR 0x100a9610 is: @@ -275,7 +296,7 @@ space, forged catalog references, Unique acquisition, mixed sale funding and freed slots, concurrent/repeated confirmation, lost replies and SQLite failure with retry. Rapid unfunded Adds abort before they can leave a server purchase absent from the native basket. Stock admission tests keep unverified charged, -weapon and container delivery outside the fixed simple-item catalog. +weapon and container delivery outside the fixed template catalog. Two headed Chromium WASM clients ran on the GPU. Before restoration, Omni room 1183 had the static identity but no native vending object or visible @@ -316,6 +337,16 @@ input path retained only two selections at 456, and cancellation preserved every owned item and credit. Wire captures confirm real Add/Remove messages, Complete followed by AddTemplate and absolute cash, with no client errors. +The documented-stock expansion run purchased interface 103 for 892 from +Omni Devices 3221816479, leaving 19108 credits. General Tools 3225158815 showed +camera/extractor quotes of 1288/9406; selecting their rows in reverse order +still delivered camera 104 and extractor 105 in catalog order, leaving 9306. +Both clients retained their exact identities and balances after reconnect and +cold restart. The interface's Unique rejection and complete wearable effect +path are recorded in [stat equipment](stat-equipment.md). Native picking in +world 1191 also opened Computers 3221292199 with no inferred Tools catalog and +preserved both purchased tools and cash. + `local/shop-room-research/` retains the independent catalog audit, reproducible extraction provenance and original-client access evidence. `local/shop-room-smoke/` retains screenshots, native memory snapshots, database @@ -325,10 +356,12 @@ source change was required. Owned test clients are closed between runs, and the dummy-HDMI display's power-saving state is restored afterward. `local/shop-purchase-smoke/` retains the purchase screenshots, native/database snapshots, WebSocket captures and assertion script. +`local/shop-stock-expansion-smoke/` retains the additional terminal, multi-row +purchase, worn Unique, observer-effect and cold-recovery checks. -The complete tracked Go suite passed (server 739 seconds, gamedata 8 seconds). -After the final GUI-tag correction, all shop checks passed again under the race -detector (176 seconds), as did `go vet -stdversion=false`. +The complete tracked Go suite passed (server 707 seconds, gamedata 8 seconds), +as did shop/utility/belt/clothing race checks (184 seconds), the additional +catalog-belt/data-binding checks, and `go vet -stdversion=false`. Cleanup removed only the two test-owned players. All unrelated database rows were unchanged, foreign-key and integrity checks passed, and the single shared HTTPS preview remains available on port 8443. diff --git a/docs/stat-equipment.md b/docs/stat-equipment.md @@ -0,0 +1,78 @@ +# HUD, utility and deck stat equipment + +Exact catalog type 51022 items with ItemType 76 equal to 1 share the stat and +presentation admission used by clothing. CanWear mask 4 and location mask 298 +select non-hand positions on page 101: HUD/utility slots 1..5 and 15, belt 7, +and deck 9..14. Native weapon hands 6/8 remain on the separate weapon path. +ItemType 2 retains clothing's page-102 mask shift. Implants, vehicles and +wearable containers keep their existing specialized rules. + +Unconditional wearer-targeted one-shot Skill 53012 and Modify 53045 effects +contribute their authored values. Supported visual handlers run in the native +client. Unknown, conditional or repeating OnWear gameplay effects remain +outside admission. Qualities must equal the authored record, except for the +already reviewed Metaplast interpolation pairs. This is shared stat-equipment +support, not implementation of every item's use action or unsupported stat. + +The shared path replaces the Ti-100X/QL1-memory template cases. Other exact +catalog belts and memories with supported effects now use their own masks, +requirements, delays and capacity modifiers. Deck availability still requires +an installed belt, and removing a belt still requires every deck position to +be empty. The [belt and NCU protocol](belts-ncu.md) applies unchanged. + +## Native admission and effects + +Original `kkr.dll` SHA-256: +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +Generic equip predicate 0x10060510 selects action 8 for ItemType 1 through +template callback 0x10090c70. Missing action 8 passes; it does not fall back to +action 6. ItemTypes 2/3 instead use callback 0x10090970 and action 6. This is +separate from TemplateAction 6/7, which executes/removes OnWear effects. + +Mask callback 0x1008eda0 checks `stat298 & (1 << slot)` directly for utility +positions. Their slot numbers have no ordinary-inventory offset. Source-page +validation and move acknowledgements use page 101 for every such slot. +After the durable equipment commit, owner and observers receive the existing +TemplateAction 6/7 notifications. A separate live item object is unnecessary +for a type-51022 template proxy. Owner FullCharacter reconstructs worn effects +on reconnect without a second extra wear action. + +The original Nano Programming Interface 161699 is Unique, QL1 and ItemType 1, +with mask 0x803e: HUD/utility positions 1, 2, 3, 4, 5 and 15. Its unconditional +OnWear Modify adds 2 Nano Programming (stat 160). It has an authored action-6 +Intelligence >12 criterion, but no action 8. The inspected native ItemType-1 +admission therefore permits its placement without checking that action-6 +list. The server follows this observed native selection. Historical server +enforcement remains unknown; the authored criterion is retained in game data. + +Complete procedures, hashes and Evidence IDs are retained in +`local/shop-purchase-research/native/equipment-admission.md` and +`delivery.md`, with exported REA bundles. No historical server implementation +or charged purchase packing rule is claimed from these client procedures. + +## Verification + +`server/utility_equipment_test.go` exercises public inventory moves for all six +interface positions, wear/removal and observer effects, persisted identity and +skill recovery, invalid destinations, forged source pages and failed writes. +The QL120 Component Platform 5000 uses its authored action-8 Computer Literacy +boundary and five-slot capacity, without a template-specific branch. Existing +clothing, implants, vehicles, belt/deck and shop transaction checks cover the +shared paths and their retained restrictions. + +Two headed GPU WASM clients purchased the interface for 892 credits and +verified its modifier on both owner and observer: Nano Programming 5/7/5/7 +through utility-slot wear, removal and HUD2 re-wear. Intelligence remained 1, +matching the observed ItemType-1 admission choice. Reconnect and cold restart +retained item 103 in HUD2 with exactly one +2 contribution. A second purchase +while the Unique interface was worn aborted without allocating or debiting. +Screenshots, native modifier-tree reads, database snapshots and wire assertions +are retained under `local/shop-stock-expansion-smoke/`. + +An additional native run equipped QL120 Component Platform 5000 instance 106 +after its 70-second delay and observed BeltSlots 5. QL50 memory 107 was rejected +from disabled Deck6, retained its ownership, then installed in Deck5 after +its 10-second delay. The native NCU baseline 8 plus modifier 16 produced 24 +maximum NCU alongside the interface's single +2 Nano Programming contribution. +Reconnect retained all three equipped identities, five deck positions, 24 NCU +and the single interface bonus. diff --git a/server/clothing.go b/server/clothing.go @@ -1,33 +0,0 @@ -package main - -import "ao/server/gamedata" - -func (item ownedItem) isClothing() bool { - definition := gamedata.ItemTemplates[item.Template] - if item.Type != 51022 || definition == nil || definition.HeaderWords[0] != item.Type || - itemStat(definition, 76) != 2 || itemStat(definition, 30)&4 == 0 || - !item.isMetaplast() && item.Quality != *definition.Quality { - return false - } - - // Admit stat modifiers and native presentation, not unimplemented gameplay effects. - for _, section := range definition.Sections { - if section.Type != 2 || section.Subtype != 14 { - continue - } - for _, function := range *section.Functions { - switch function.ID { - case 53012, 53045: - if function.Target != 2 || len(function.Requirements) != 0 || function.TickCount != 1 || function.TickInterval != 0 { - return false - } - case 53030, 53035, 53037, 53038, 53039, 53054, 53055, 53079: - // Mesh, texture and visual effects execute in the native client. - default: - // A client no-op does not establish a server-side no-op. - return false - } - } - } - return true -} diff --git a/server/equipment.go b/server/equipment.go @@ -26,20 +26,15 @@ func (item ownedItem) fitsEquipmentSlot(slot uint32) bool { if item.isWieldableWeapon() { return slot == 6 } - if item.isClothing() { + if item.isStatEquipment() { + if itemStat(gamedata.ItemTemplates[item.Template], 76) == 1 { + return slot > 0 && slot < 16 && slot != 6 && slot != 8 && itemStat(gamedata.ItemTemplates[item.Template], 298)&(1<<slot) != 0 + } return slot >= 16 && slot < 32 && itemStat(gamedata.ItemTemplates[item.Template], 298)&(1<<(slot-16)) != 0 } if item.isImplant() { return slot >= 33 && slot <= 45 && itemStat(gamedata.ItemTemplates[item.Template], 298)&(1<<(slot-32)) != 0 } - if item.Type == 51022 && item.Quality == 1 { - switch item.Template { - case 36783: - return slot == 7 - case 36779: - return slot >= 9 && slot <= 14 - } - } return false } @@ -57,14 +52,13 @@ func (character *character) canEquip(item ownedItem) bool { return gamedata.Playfields[character.playfield].Outdoor && !character.driving() && character.effectiveSkill(139, stats.Navigation.VehicleAir, [6]uint32{0, 20, 0, 20, 60, 0}) > 80 } - if item.fitsEquipmentSlot(7) || item.fitsEquipmentSlot(9) { - stats := character.baseStats() - return character.effectiveSkill(161, stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 5 - } if item.isWieldableWeapon() { return item.requirementsMet(8, character.meetsStatRequirement) } - if item.isClothing() || item.isImplant() { + if item.isStatEquipment() && itemStat(gamedata.ItemTemplates[item.Template], 76) == 1 { + return item.requirementsMet(8, character.meetsStatRequirement) + } + if item.isStatEquipment() || item.isImplant() { return item.requirementsMet(6, character.meetsStatRequirement) } return false @@ -144,7 +138,7 @@ func itemStat(item *gamedata.Item, stat uint32) uint32 { func itemMovePacket(owner, source, destination uint32) []byte { page := uint32(104) - if source == 1 || source == 6 || source == 7 || source >= 9 && source <= 14 { + if source > 0 && source < 16 { page = 101 } else if source >= 16 && source < 32 { page = 102 @@ -270,7 +264,7 @@ func (server *server) advanceEquipment(now time.Time) { character.position = position client.movementStarted = now } - if move.source == 1 || move.source == 7 || move.source >= 9 && move.source <= 14 || move.source >= 16 && move.source < 32 || move.source >= 33 && move.source <= 45 { + if move.source < 64 && !item.isWieldableWeapon() { server.queueCombat_locked(updates, character, character, equipmentActionPacket(character.id, item, 7)) } if move.source == 6 { @@ -287,7 +281,7 @@ func (server *server) advanceEquipment(now time.Time) { updates[client] = append(updates[client], n3Packet(0x36510078, item.Type, move.itemID, nil)) } updates[client] = append(updates[client], itemMovePacket(client.id, move.source, move.requestedSlot)) - if move.destination == 1 || move.destination == 7 || move.destination >= 9 && move.destination <= 14 || move.destination >= 16 && move.destination < 32 || move.destination >= 33 && move.destination <= 45 { + if move.destination < 64 && !item.isWieldableWeapon() { server.queueCombat_locked(updates, character, character, equipmentActionPacket(character.id, character.inventory.Items[index], 6)) } if move.source == 6 || move.destination == 6 { @@ -377,7 +371,7 @@ func equipmentActionPacket(owner uint32, item ownedItem, action uint32) []byte { func equippedItemPackets(character *character) [][]byte { packets := equippedWeaponPackets(character) for _, item := range character.inventory.Items { - if item.Slot == 1 || item.Slot == 7 || item.Slot >= 9 && item.Slot <= 14 || item.Slot >= 16 && item.Slot < 32 || item.Slot >= 33 && item.Slot <= 45 { + if item.Slot < 64 && !item.isWieldableWeapon() { packets = append(packets, equipmentActionPacket(character.id, item, 6)) } } diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -30,7 +30,7 @@ var ( TerrainEvidence TerrainExtractionEvidence Playfields map[uint32]Playfield ShopMachines map[uint32]ShopMachine - ShopStock map[string][]uint32 + ShopStock map[uint32][]uint32 PlayerAppearances struct { Heads []PlayerHead `yaml:"heads"` Bodies []PlayerBody `yaml:"bodies"` diff --git a/server/gamedata/shop_stock.yaml b/server/gamedata/shop_stock.yaml @@ -1,4 +1,30 @@ -# Documented fixed stock; other category membership remains unresolved. -# Lock Pick: Anarchy Arcanum, NCU Hacker Interface, updated 19 February 2003. -# Original item 95577 has one fixed QL. See docs/shops.md for source provenance. -OTIM: [95577] +# Documented fixed stock by original terminal template, not opaque ACG code. +# Anarchy Arcanum, NCU Hacker Interface (19 February 2003) and Personal Lockpick +# (28 August 2002). 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] + +# Devices: Nano Programming Interface. +155602: [161699] +155603: [161699] +155604: [161699] +155605: [161699] +155606: [161699] +155607: [161699] +155608: [161699] +155609: [161699] +155610: [161699] + +# General Tools and Bases: Expendable Hologram Camera, ID-extractor. +155284: [156054, 156339] +155285: [156054, 156339] +155286: [156054, 156339] diff --git a/server/inventory.go b/server/inventory.go @@ -238,7 +238,7 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { return server.syncStacks_locked(client) } if index < 0 || (sourceSlot >= 64 && sourceType != 104) || - ((sourceSlot == 1 || sourceSlot == 6 || sourceSlot == 7 || sourceSlot >= 9 && sourceSlot <= 14) && sourceType != 101) || + (sourceSlot > 0 && sourceSlot < 16 && sourceType != 101) || (sourceSlot >= 33 && sourceSlot <= 45 && sourceType != 103) || (sourceSlot >= 16 && sourceSlot < 32 && sourceType != 102) { return nil diff --git a/server/shop_machines_test.go b/server/shop_machines_test.go @@ -79,7 +79,7 @@ func TestShopFullUpdatePreservesRotationAndHighLowMesh(t *testing.T) { err := world.handleShopUse(client, request) - if err != nil || len(conn.packets) != 4 { + if err != nil || len(conn.packets) != 5 { t.Fatalf("shop failed to open: %v", err) } packet := conn.packets[1] diff --git a/server/shop_purchases_test.go b/server/shop_purchases_test.go @@ -59,11 +59,14 @@ func TestShopCatalogUsesOriginalPageIndicesAndExactTemplates(t *testing.T) { } } -func TestShopKnownStockOnlyAdmitsSupportedFixedSimpleItems(t *testing.T) { - for _, templates := range gamedata.ShopStock { +func TestShopKnownStockOnlyAdmitsSupportedFixedTemplateItems(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 { definition := gamedata.ItemTemplates[template] - if definition == nil || definition.Quality == nil || definition.HeaderWords[0] != 51005 || int32(itemStat(definition, 212)) > 0 { + if definition == nil || definition.Quality == nil || (definition.HeaderWords[0] != 51005 && definition.HeaderWords[0] != 51022) || int32(itemStat(definition, 212)) > 0 { t.Fatalf("stock %d needs a separately verified delivery/packing path", template) } } diff --git a/server/shop_stock_test.go b/server/shop_stock_test.go @@ -0,0 +1,118 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "fmt" + "reflect" + "testing" +) + +func TestShopDocumentedStockUsesTerminalBindings(t *testing.T) { + for _, scenario := range []struct { + machine uint32 + stock []uint32 + }{ + {3221488799, []uint32{95577}}, + {3221816479, []uint32{161699}}, + {3225158815, []uint32{156054, 156339}}, + {3221292199, nil}, + } { + t.Run(fmt.Sprint(scenario.machine), func(t *testing.T) { + world, conn := newPurchaseWorld(t) + player, client := world.characters[1], world.clients[1] + machine := gamedata.ShopMachines[scenario.machine] + player.playfield, player.position = machine.Playfield, machine.Position + request := shopUseRequest(1) + binary.BigEndian.PutUint32(request[20:24], 2) + binary.BigEndian.PutUint32(request[44:48], scenario.machine) + conn.packets = nil + + err := world.handleShopUse(client, request) + + if err != nil || client.shop == nil || !reflect.DeepEqual(client.shop.stock, scenario.stock) { + t.Fatalf("wrong documented catalog: %v %+v", err, client.shop) + } + catalogs := 0 + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) != 0x58362220 { + continue + } + catalogs++ + 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} { + if binary.BigEndian.Uint32(packet[33+12*index+4*field:]) != expected { + t.Fatal("catalog endpoint or quality changed") + } + } + } + } + if (len(scenario.stock) == 0 && catalogs != 0) || (len(scenario.stock) != 0 && catalogs != 1) { + t.Fatal("unknown stock was inferred or a known catalog was omitted") + } + }) + } +} + +func TestShopDevicesPurchasePersistsUniqueInterface(t *testing.T) { + world, _ := newPurchaseWorld(t) + client, player := world.clients[1], world.characters[1] + player.position = gamedata.ShopMachines[3221816479].Position + request := shopUseRequest(1) + binary.BigEndian.PutUint32(request[20:24], 2) + binary.BigEndian.PutUint32(request[44:48], 3221816479) + if err := world.handleShopUse(client, request); err != nil { + t.Fatal(err) + } + add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221816479}, [2]uint32{111, 0})[20:] + if err := world.handleShopTrade(client, add); err != nil { + t.Fatal(err) + } + + err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]) + restored := newTestInventoryServer(t).characters[1] + binary.BigEndian.PutUint32(request[20:24], 3) + world.handleShopUse(client, request) + world.handleShopTrade(client, add) + world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]) + + if err != nil || restored.inventory.Credits != 108 || len(restored.inventory.Items) != 2 || + restored.inventory.Items[1] != (ownedItem{ID: 2, Type: 51022, Template: 161699, Quality: 1, Slot: 65, Count: 1}) || + client.shop != nil || world.nextItem != 2 || !reflect.DeepEqual(restored.inventory, player.inventory) { + t.Fatal("interface purchase lost its type, price or Unique ownership") + } +} + +func TestShopGeneralToolsPurchasesKeepDistinctRowsAndIdentities(t *testing.T) { + world, _ := newPurchaseWorld(t) + client, player := world.clients[1], world.characters[1] + player.position = gamedata.ShopMachines[3225158815].Position + player.inventory.Credits = 20000 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + request := shopUseRequest(1) + binary.BigEndian.PutUint32(request[20:24], 2) + binary.BigEndian.PutUint32(request[44:48], 3225158815) + if err := world.handleShopUse(client, request); err != nil { + t.Fatal(err) + } + for _, index := range []uint32{1, 0} { + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3225158815}, [2]uint32{111, index})[20:]); err != nil { + t.Fatal(err) + } + } + + err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]) + restored := newTestInventoryServer(t).characters[1].inventory + + if err != nil || restored.Credits != 9306 || !reflect.DeepEqual(restored.Items[1:], []ownedItem{ + {ID: 2, Type: 51005, Template: 156054, Quality: 1, Slot: 65, Count: 1}, + {ID: 3, Type: 51005, Template: 156339, Quality: 1, Slot: 66, Count: 1}, + }) { + t.Fatalf("different catalog rows lost their prices or identities: %v %+v", err, restored) + } +} diff --git a/server/shops.go b/server/shops.go @@ -16,23 +16,6 @@ type shopTrade struct { purchases map[uint32]uint16 } -func shopStock(definition *gamedata.Item) []uint32 { - var stock []uint32 - for _, section := range definition.Sections { - if section.Type != 23 || section.Subtype != 37 || section.Entries == nil { - continue - } - for _, entry := range *section.Entries { - for _, template := range gamedata.ShopStock[*entry.Code] { - if !slices.Contains(stock, template) { - stock = append(stock, template) - } - } - } - } - return stock -} - func (server *server) canUseShop_locked(client *worldClient, machine gamedata.ShopMachine) bool { player := server.characters[client.id] if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || @@ -124,7 +107,7 @@ func (server *server) handleShopUse(client *worldClient, body []byte) error { return err } } - client.shop = &shopTrade{machine: machineID, items: make(map[uint32]ownedItem), stock: shopStock(gamedata.ItemTemplates[machine.Template]), purchases: make(map[uint32]uint16)} + client.shop = &shopTrade{machine: machineID, items: make(map[uint32]ownedItem), stock: gamedata.ShopStock[machine.Template], purchases: make(map[uint32]uint16)} if err := client.send(shopMachinePacket(machineID, machine)); err != nil { return err } diff --git a/server/stat_equipment.go b/server/stat_equipment.go @@ -0,0 +1,33 @@ +package main + +import "ao/server/gamedata" + +func (item ownedItem) isStatEquipment() bool { + definition := gamedata.ItemTemplates[item.Template] + if item.Type != 51022 || definition == nil || definition.HeaderWords[0] != item.Type || + (itemStat(definition, 76) != 1 && itemStat(definition, 76) != 2) || itemStat(definition, 30)&4 == 0 || + !item.isMetaplast() && item.Quality != *definition.Quality { + return false + } + + // Admit stat modifiers and native presentation, not unimplemented gameplay effects. + for _, section := range definition.Sections { + if section.Type != 2 || section.Subtype != 14 { + continue + } + for _, function := range *section.Functions { + switch function.ID { + case 53012, 53045: + if function.Target != 2 || len(function.Requirements) != 0 || function.TickCount != 1 || function.TickInterval != 0 { + return false + } + case 53030, 53035, 53037, 53038, 53039, 53054, 53055, 53079: + // Mesh, texture and visual effects execute in the native client. + default: + // A client no-op does not establish a server-side no-op. + return false + } + } + } + return true +} diff --git a/server/utility_equipment_test.go b/server/utility_equipment_test.go @@ -0,0 +1,153 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "reflect" + "testing" +) + +func newUtilityWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, conn := newEquipmentWorld(t) + player := world.characters[1] + player.stats.Abilities.Intelligence = 1 + player.inventory.Items[0] = ownedItem{ID: 1, Type: 51022, Template: 161699, Quality: 1, Slot: 64, Count: 1} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + return world, conn +} + +func TestUtilityWearAndRemovalPreserveIdentityAndSkillAcrossRestart(t *testing.T) { + for _, slot := range []uint32{1, 2, 3, 4, 5, 15} { + t.Run(fmt.Sprintf("slot%d", slot), func(t *testing.T) { + world, owner := newUtilityWorld(t) + player, client := world.characters[1], world.clients[1] + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + + if err := world.handleInventory(client, inventoryMovePacket(1, 64, slot)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment == nil { + t.Fatal("native ItemType1 action8 admission rejected the utility") + } + world.advanceEquipment(client.equipment.readyAt) + restored := newTestInventoryServer(t).characters[1] + if err := world.handleInventory(client, itemMovePacket(1, slot, 111)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(client.equipment.readyAt) + removed := newTestInventoryServer(t).characters[1] + + if !reflect.DeepEqual(restored.inventory.Items, []ownedItem{{ID: 1, Type: 51022, Template: 161699, Quality: 1, Slot: slot, Count: 1}}) || + !reflect.DeepEqual(removed.inventory.Items, []ownedItem{{ID: 1, Type: 51022, Template: 161699, Quality: 1, Slot: 64, Count: 1}}) || + restored.equipmentBonus(160) != 2 || removed.equipmentBonus(160) != 0 || player.equipmentBonus(160) != 0 { + t.Fatal("utility move lost ownership or duplicated its Nano Programming bonus") + } + if len(owner.packets) != 4 || len(observer.packets) != 2 { + t.Fatalf("utility replication: owner=%d observer=%d", len(owner.packets), len(observer.packets)) + } + for index, action := range []uint32{6, 7} { + packet := owner.packets[index+1] + if binary.BigEndian.Uint32(packet[16:20]) != 0x35505644 || binary.BigEndian.Uint32(packet[45:49]) != action || + binary.BigEndian.Uint32(packet[49:53]) != 101 || binary.BigEndian.Uint32(packet[53:57]) != slot || + !bytes.Equal(packet[16:], observer.packets[index][16:]) { + t.Fatal("HUD/utility wear effects used the wrong page, slot or action") + } + } + }) + } +} + +func TestUtilityRejectsUnauthoredSlotsWithoutChangingOwnership(t *testing.T) { + for _, slot := range []uint32{0, 6, 7, 8, 9, 14, 16, 17, 33, 63, 94} { + t.Run(fmt.Sprintf("slot%d", slot), func(t *testing.T) { + world, _ := newUtilityWorld(t) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + + err = world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, slot)[20:]) + after, readError := readTestItemStore(world) + + if err != nil || readError != nil || world.clients[1].equipment != nil || !bytes.Equal(before, after) || world.characters[1].equipmentBonus(160) != 0 { + t.Fatal("invalid utility slot changed ownership or effects") + } + }) + } +} + +func TestUtilityRemovalRejectsForgedInventoryPage(t *testing.T) { + world, conn := newUtilityWorld(t) + client := world.clients[1] + world.handleInventory(client, inventoryMovePacket(1, 64, 3)[20:]) + world.advanceEquipment(client.equipment.readyAt) + conn.packets = nil + before, _ := readTestItemStore(world) + + err := world.handleInventory(client, inventoryMovePacket(1, 3, 64)[20:]) + after, readError := readTestItemStore(world) + + if err != nil || readError != nil || client.equipment != nil || len(conn.packets) != 0 || !bytes.Equal(before, after) || world.characters[1].equipmentBonus(160) != 2 { + t.Fatal("forged source page removed an equipped utility") + } +} + +func TestUtilityDatabaseFailureDoesNotPublishWearEffects(t *testing.T) { + world, conn := newUtilityWorld(t) + client := world.clients[1] + if _, err := world.db.Exec("CREATE TRIGGER fail_utility BEFORE INSERT ON item_locations BEGIN SELECT RAISE(ABORT, 'move failure'); END"); err != nil { + t.Fatal(err) + } + before, _ := readTestItemStore(world) + + world.handleInventory(client, inventoryMovePacket(1, 64, 3)[20:]) + world.advanceEquipment(client.equipment.readyAt) + after, err := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || world.characters[1].inventory.Items[0].Slot != 64 || world.characters[1].equipmentBonus(160) != 0 || client.equipment != nil { + t.Fatal("failed utility commit published ownership or skill changes") + } + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x35505644 { + t.Fatal("failed utility commit emitted a wear action") + } + } +} + +func TestCatalogBeltUsesAuthoredAction8InsteadOfTemplateCases(t *testing.T) { + for _, scenario := range []struct { + literacy uint16 + accepted bool + }{{299, false}, {300, true}} { + t.Run(fmt.Sprint(scenario.literacy), func(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.stats.Abilities.Intelligence = 5 + player.stats.TradeRepair.ComputerLiteracy = scenario.literacy + player.inventory.Items[0] = ownedItem{ID: 1, Type: 51022, Template: 36784, Quality: 120, Slot: 64, Count: 1} + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + + err := world.handleInventory(client, inventoryMovePacket(1, 64, 7)[20:]) + if client.equipment != nil { + world.advanceEquipment(client.equipment.readyAt) + } + restored := newTestInventoryServer(t).characters[1] + + if err != nil || (restored.inventory.Items[0].Slot == 7) != scenario.accepted || + (restored.inventory.equipmentBonus(45) == 5) != scenario.accepted { + t.Fatal("catalog belt ignored its strict Computer Literacy boundary or capacity") + } + }) + } +}