aorecomp

Anarchy Online classic in the browser

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


commit 04fc5e11f5959cd67a8c497b2cbee1df1abbdcd3
parent 42840980e83ec46d3943451fd2223a92039fe32c
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 22:00:05 +0000

Support catalog main-hand weapons and native item lifetimes

Diffstat:
MTODO.md | 34++++++++++++++++++++++++++++++----
Adocs/catalog-weapons.md | 137+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/fling-shot.md | 10++++++----
Mdocs/inventory.md | 25+++++++++++++++++--------
Mdocs/overequipping.md | 12++++++++++++
Mdocs/ranged-weapons.md | 14+++++++++-----
Mserver/backpacks.go | 5++---
Mserver/bank.go | 6+++---
Mserver/bank_test.go | 3++-
Mserver/combat.go | 8+++++---
Mserver/equipment.go | 20++++++++++++--------
Mserver/equipment_test.go | 38+++++++++++++++++++++++++-------------
Mserver/inventory.go | 36++++++++++++++++++++++++++++++++----
Mserver/item_store_test.go | 3++-
Mserver/ranged.go | 42+++++++++++++++++++++++++++++++-----------
Aserver/starter_weapons_test.go | 447+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/target_protocol_test.go | 3+++
Mserver/weapon_special.go | 7++++---
Mserver/weapon_stats.go | 56++++++++++++++++++++++++++++++++------------------------
Mserver/world.go | 2+-
20 files changed, 812 insertions(+), 96 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -97,9 +97,24 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md). - [x] Re-equip the same weapon instance after removal. Check: owner and observer restore its combat weapon, native special actions and existing skill lock; its inventory identity/count survive. Full updates skip existing native - instances, so unequip must retire the owner's detached instance as well. + instances, so accepted re-equip must retire the owner's detached instance + before replacing it. Retain it while returned to ordinary inventory: + native possession checks require the live identity before emitting a request. - [x] Enforce that weapon's requirements. Check: a character below one required skill cannot equip it, while a qualifying character can. +- [x] Equip starter weapons through shared catalog rules. Check: all eight + original starter weapon definitions use their profession restrictions, equip + delays, attack skills, damage, range and initiative; owner/observer instances + survive equip, unequip and reconnect. Solar weapons need no finite ammunition; + Meta Shield's three +10 AC bonuses follow its equipment state. See + [catalog weapons](docs/catalog-weapons.md). +- [ ] Extend catalog weapons beyond current exact-QL, main-hand support. Check: + recover interpolation endpoint families, OR/NOT/faction-rank/unsupported-stat + requirements, original malformed damage ranges (including template 123868), + all OnWear/OnHit functions and action gates. Do not silently satisfy unknown + requirements or invent normalization for reversed min/max damage. + Audit retained weapon dynels through native bank, reclaim and death round + trips, checking source-row usability, later re-equip and exactly-once bonuses. - [x] Equip one armor piece. Check: the correct native slot and appearance update, and its armor stats appear and disappear with equip/unequip. - [x] Apply one equipment stat bonus. Check: a known bonus affects derived stats @@ -202,6 +217,15 @@ Normal-hit additions and weapon-range modifiers are described in continue dealing damage or create ammunition on reconnect. - [x] Reload that weapon. Check: compatible inventory ammunition fills the magazine after the correct delay and the total round count is conserved. +- [x] Generalize finite ammunition and reload beyond one pistol. Check: + catalog capacity/type/recharge drive transfers and one-round shot debits; + incompatible ammo, invalid source item types and failed saves preserve state. + Infinite-ammo solar shots and Fling retain the native -1 sentinel. +- [ ] Audit remote reload animation and ammunition state. Check an initially + empty weapon through reload and its first shot on two clients. Reload currently + updates the owner; observers learn the count through AttackInfo or reconnect. + Establish native remote routing before broadcasting a message that also + mutates an inventory stack. - [ ] Implement one melee special. Check: a suitable weapon/character can use the action once, with native feedback and an enforced skill lock. The Kinetic Axe now has a shared-handler Fast Attack normal-damage prototype. @@ -444,9 +468,11 @@ introduction and starting-item gameplay remain open below. weapons/actions, the faction map and sided gifts atomically. Engineer gets one QL1 robot shell. This does not complete their gameplay support. Audit equip/use/unequip, requirements, charge consumption, deaths/reclaim and cold - recovery for every issued item. Most solar weapons, startup crystals, - startup healing kits, maps, shell, boards and shirt remain unsupported by - the current use/equipment handlers. Prefer shared catalog-driven rules. + recovery for every issued item. Starter weapons now equip and attack through + shared catalog rules, including Meta Shield AC and solar Fling. Startup + crystals, healing-kit use, maps, shell, boards, shirt and remaining weapon + specials (Burst, Aimed Shot, Brawl and Dimach) still need gameplay support. + Verify those actions and each starting profession in its real training ground. Corroborate the four provisional pistol allocations, MA Oak Bo allocation, and observed laboratory/first-aid issue counts 25/3; see [starting-state evidence](docs/character-creation.md). diff --git a/docs/catalog-weapons.md b/docs/catalog-weapons.md @@ -0,0 +1,137 @@ +# Catalog main-hand weapons + +Weapon admission uses the original type 51018 definition, exact shipped QL, +right-hand slot mask (298 bit 6) and an ordered damage range. It no longer +requires a particular template ID. Unknown stats and requirement operators +reject equip rather than treating an unknown stat as zero. Equality and strict +minimum predicates joined by AND use effective abilities/skills, level, title, +profession, breed, sex, side and race. Other predicate forms remain open. + +The existing combat calculations read damage, protection type, range, attack +skill weights, initiative, attack/recharge delay and overequipping thresholds +from that definition. This enables the original Baseballbat, Oak Bo, Meta +Shield and five solar guns. Left-hand scheduling, dual wield, QL interpolation, +critical/hit selection and unimplemented item functions remain separate work. +A reversed damage range, including template 123868, is rejected until the +original interpretation is established; unsigned damage arithmetic must not +turn it into an enormous hit. + +| Template | Weapon | Profession restriction | +| --- | --- | --- | +| 121564 | Baseballbat | Enforcer | +| 121565 | Oak Bo | Martial Artist | +| 121566 | Meta Shield | Meta-Physicist | +| 121567 | Solar-Powered Pistol | None | +| 121568 | Solar-Powered Rifle | Agent | +| 121569 | Solar-Powered Assault Rifle | Soldier | +| 121570 | Solar Trader Shotgun | Trader | +| 121571 | Solar Powered Submachinegun | Fixer | + +Allocation of Oak Bo and the four provisional pistol professions remains a +[starting-loadout research question](character-creation.md). Admission of the +weapon does not settle which character should receive it at birth. + +Meta Shield's OnWear AddSkill functions add 10 Projectile, Melee and Energy AC. +They use the ordinary equipment bonus path and native weapon instance, without +a shield-specific stat override. Worn weapons use persistent live identities +in FullCharacter and FullUpdateItem for both owner and observers. Unequip +retains the owner's detached dynel so its live inventory row remains usable; +observers retire it immediately. A successful later equip retires the owner's +old dynel before moving and recreating it. Native row deletion needs a separate +dynel despawn after the durable delete, including deleted bag children. +The original lifetime evidence is retained in +`local/starter-weapon-research/inventory-reuse/findings.md`. + +## Ammunition contract + +Original `kkr.dll` SHA-256: +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +Bounded REA evidence and the observed/inferred/unknown ledger are retained in +`local/starter-weapon-research/findings.md` and `native-evidence.json`. + +- WeaponItem initialization `100abb20` supplies omitted AmmoType 420 as -1. + The HasEnergy flags setter `1009f390` initializes absent Energy 26 and Clip + 212 to -1. These defaults are distinct from Can 30 capability bits. +- Empty-weapon helper `100acd20` accepts Energy -1, rejecting other values + below 1. All five solar guns have Clip -1 and AmmoType 10; none has Can's + NoAmmo bit 10. Their catalog descriptions and native behavior support + unlimited firing. +- Special predicate `100aaf10` selects Fling by Can bit 12. Solar Trader + Shotgun has that bit. Result helper `1007c0f0` preserves ammunition -1; + the server supplies that sentinel for unlimited normal and special results. +- Reload predicate `1007bba0` and inventory search `100ae410` match source + AmmoType 420 with the weapon and require source ItemType 76 == 0. + Class 88 == 9 is not a native requirement. Missing source AmmoType has no + verified default and is rejected by the server. + +The server classifies positive finite catalog Clip values, excluding UINT_MAX, +as consumable magazines. This is reconstruction policy, not an exact recovered +native predicate for every omitted or malformed catalog combination. Other +weapon instances store Ammo 0 internally and expose the native unlimited +sentinel in combat results. The original finite magazine's initial loaded +count remains unresolved; newly created finite weapons start empty. + +Finite weapon FullUpdateItem packets carry the loaded count as stat 26. +Shots commit one round with any lethal outcome; reload atomically transfers +from the named compatible stack up to the weapon's own Clip, with its own +RechargeDelay. Full, incompatible and failed transfers conserve both sides. +The original [reload protocol and durability rules](ranged-weapons.md) apply. +Fling keeps its [pre-15.5.5 special prototype](fling-shot.md), with no round +consumption and a persistent shared lock. Other advertised specials still +need their own rules and outcomes. + +## Verification + +`server/starter_weapons_test.go` covers all eight starter definitions, every +incorrect profession, equip deadlines, owner/observer instance packets, +unequip/reopen identity conservation, Meta Shield bonuses and removal, unknown +predicates, appearance restrictions, invalid QL, reversed ranges and left-hand +rejection. Solar normal/Fling results use -1 and cannot repeat a locked special. +Another shipped finite weapon (122099, QL161) checks energy-ammo matching, +10-round capacity, 2.5-second reload, per-shot durable debit and rollback before +damage on a failed save. Source-type regressions distinguish ItemType from +Class. Deletion cases cover inventory, bank, backpack, carried/banked bag +children and failed saves, checking that native row removal precedes dynel +retirement. Live-item delete requests may omit both template endpoints; +partial or mismatched nonzero endpoints remain rejected. Zero-valued wield +thresholds contribute no OE penalty and cannot cause integer division by zero +after skill loss. The zero edge follows the native masked-x87 conversion +model, not a native zero-denominator branch; see +`local/starter-weapon-research/oe-zero-findings.md`. +Existing equipment, ranged, special and atomic-outcome suites +remain applicable to the shared paths. + +Two GPU/OpenGL WASM clients verified Meta Shield's native model and exactly +10/0/10 AC through equip, removal and same-session re-equip, plus a backpack +round trip with the same item identity. A wrong-profession character retained +its shield. Native Q and Fling hotkeys delivered solar shotgun normal and +special damage with ammunition -1. A QL161 energy rifle rejected Bullets and +loaded 10 rounds from 100 Energy Weapon Ammo, leaving 90 in the source stack. +Packet captures, native object probes, SQLite snapshots and error logs are +retained under `local/starter-weapon-smoke/`. + +Reload currently updates only the owner's native loaded count. Observers get +the authoritative count in subsequent AttackInfo or FullUpdateItem. Original +remote reload routing and the first animation after loading an empty weapon +remain an explicit TODO; the reload message also changes an inventory stack. + +The native delete sender (`N3Msg_DeleteItem`, 10027670) forwards the auxiliary +identity pair unchanged to CharacterAction112. The observed live Meta Shield +request carries `(0,0)`, so deletion accepts an omitted pair while retaining +source ownership/page/slot checks and exact matching of supplied endpoints. +The native evidence is retained in +`local/starter-weapon-research/delete-auxiliary-findings.md`. + +A full server restart and fresh native clients restored the same shield/rifle +identities, exactly 10 shield AC and 10 loaded rifle rounds in both views, +plus the 90/100 compatible/incompatible ammo stacks. The native live-item +Delete confirmation then removed the shield durably, acknowledged its ordinary +inventory row and retired its cached dynel in that order. The other weapon +and ammunition remained unchanged. All owned browser sessions closed without +page errors or adapter failures. + +Scoped cleanup removed the four owned characters and 20 remaining items, +restored the one nonlethal test NPC, and verified every unrelated stopped-world +row unchanged. Foreign keys and SQLite integrity passed. One default-port +HTTPS preview remains available for manual testing. Full evidence and final +verification are indexed by `local/starter-weapon-research/verification.json`. diff --git a/docs/fling-shot.md b/docs/fling-shot.md @@ -1,6 +1,6 @@ # Fling Shot: native path and remaining rules -The QL 1 Rusty OT M-10 Flechette Pistol now supports the native Fling Shot +Catalog main-hand weapons with Can bit 12 support the native Fling Shot request, named damage feedback and a persistent shared skill lock. This is a prototype of the normal-damage branch. The ranged-special milestone stays open: critical outcomes and several historical rules below are not yet established. @@ -36,7 +36,7 @@ The attributed Funcom 15.5.5 notes, dated July 20, 2004 and preserved in [the patch-note copy](https://wiki.aodb.us/wiki/Patch_15.5#Version_15.5.5), introduce ammunition deductions and defensive checks for Fling and other named specials. Accordingly, this 14.9.1 implementation leaves ammunition unchanged -and does not add the later evade check. An empty clip is still rejected; +and does not add the later evade check. An empty finite clip is still rejected; the historical empty-clip/autoreload behavior remains unresolved. The old official article URL is unavailable. The official launcher's `patch_id=23` URL now returns current 18.8 content, so HTTP 200 from it is not verification @@ -72,8 +72,10 @@ Fresh REA evidence is in `local/fling-shot-research/native-evidence.json`: ## Server behavior and limits -The shared weapon-special handler accepts Fling150 with the supported right-hand -pistol and Fast Attack147 with the axe. Fling requires the authenticated, ready +The shared weapon-special handler accepts Fling150 with Can bit 12 and +Fast Attack147 with Can bit 18 on a supported right-hand weapon. Unlimited-ammo +weapons, including the solar shotgun, send result ammunition -1; see +[catalog weapons](catalog-weapons.md). Fling requires the authenticated, ready 14.9.1 owner and a visible living creature in range. It rejects dead/loading/replaced sessions, other owners, player targets, empty clips, active reload/equip, sitting, vehicles and an existing lock. Some of those action diff --git a/docs/inventory.md b/docs/inventory.md @@ -282,12 +282,19 @@ owner and binds hand slots on inventory page 1. The native equip handler behavior. No full-character appearance refresh is needed for live equipment. Unequip sends native CharacterAction 97 with parameter 2 equal to slot 6, -followed by an item despawn (`0x36510078`) for owner and observers, then the -owner's container acknowledgement. Full-update activation100b38b0 immediately -returns when the item dynel already exists. CharacterAction97 detaches that -dynel without destroying it, so the owner must also retire it before the same -item can be equipped again. The persistent inventory instance is retained; -the despawn retires its native world representation. +followed by an item despawn (`0x36510078`) for observers and the owner's +container acknowledgement. The owner retains the detached weapon dynel: +attachment10063340 changes the row to live-identity flag 2, movement1005dd60 +preserves that flag, and possession100619d0 requires the corresponding dynel +before the UI can request another equip. Retiring it at unwear leaves an +unusable inventory row. Once a subsequent equip succeeds, the owner receives +despawn, move acknowledgement and a fresh FullUpdate in that order. +Full-update activation100b38b0 ignores an existing dynel, so replacement is +necessary before attaching the weapon again. Row deletion1002d620 does not +destroy its live dynel: committed deletes from inventory, bank or backpacks +send an explicit weapon despawn after the native deletion acknowledgement, +including weapon children destroyed with a bag. Failed saves send neither. +The persistent inventory identity is retained throughout ordinary moves. The native holder restores its existing Martial Arts fists. New connections receive the character before the weapon instance; the owner also receives its persistent FullCharacter inventory before the weapon update. Packets and state @@ -300,10 +307,12 @@ of fist data. Manual WASM captures and the isolated fixture are retained in `local/equipment-smoke/`. The same-instance round trip is also covered by -`TestWeaponUnequipRetiresNativeInstanceForOwnerAndObserver`. Actual two-client +`TestWeaponReequipRetiresOwnerInstanceAfterItsNativeRequest`. Actual two-client WASM testing under `local/fast-attack-smoke/` reproduced the stale owner dynel, then verified retirement/recreation restores the weapon and its locked Fast -Attack action without losing its inventory identity or count. Original full +Attack action without losing its inventory identity or count. The broader +starter-weapon test exposed the separate missing-dynel possession check; +[catalog weapons](catalog-weapons.md) describes its corrected lifetime. Original full update activation and despawn evidence is retained in `local/fast-attack-research/native/re-equip.md`. diff --git a/docs/overequipping.md b/docs/overequipping.md @@ -129,3 +129,15 @@ contexts and terminates its server before regression builds. The full `go test ./server/... -count=1` suite passes. Focused race checks for overequipping, attack rating, character stats, armor, equipment, combat, inventory and reclaim also pass. Logs are retained alongside the WASM evidence. + +Catalog-wide main-hand admission also includes zero-valued wield thresholds +(58 predicates in the shipped catalog). A negative effective skill must not +turn them into a Go integer division panic. The server omits those zero +thresholds from the penalty calculation. Original10090f10 instead divides +through x87; under masked exceptions and the recovered 64-bit conversion +contract, infinity/NaN cannot raise the accumulated tier. This zero-edge parity +is derived from the arithmetic model, not an observed native zero guard. +The source record and controlled x87 probe, including their limits, are retained +in `local/starter-weapon-research/oe-zero-findings.md`. +`TestZeroWeaponRequirementCannotDivideByZeroAfterSkillLoss` reproduces the panic +and checks skills -1, 0 and 1 against an original zero-threshold weapon. diff --git a/docs/ranged-weapons.md b/docs/ranged-weapons.md @@ -1,11 +1,15 @@ -# Conventional pistol and ammunition +# Conventional weapons and ammunition -The supported example is the exact QL 1 Rusty OT M-10 Flechette Pistol, +The first verified example is the exact QL 1 Rusty OT M-10 Flechette Pistol, template 123742, with QL 1 Bullets, template 21605. It occupies the right hand. The catalog also permits the left hand; dual wield and left-hand scheduling remain separate TODOs. Unsupported wear requests receive a source-slot reply so the native client can restore the inventory item. +Main-hand weapon admission and ammunition now use shared catalog rules; +[starter and catalog weapons](catalog-weapons.md) describes the scope and +unlimited-ammunition contract. The Flechette remains a regression fixture. + ## Catalog rules The embedded 14.9.1 records provide: @@ -22,8 +26,8 @@ The embedded 14.9.1 records provide: The pistol uses Ranged Initiative and the existing aggression/timing rules. Its attack rating uses Pistol with 60% Agility and 40% Sense trickle-down; Fling Shot uses Agility. The requirement's raw value 5 is also used for the -native overequipping calculation. Critical hits, misses and Fling Shot are -not implemented by this milestone. +native overequipping calculation. Critical hits and misses remain open. Fling Shot uses the +[shared special prototype](fling-shot.md). The [AOPPA source mirror](https://github.com/Noeda/aoppa) provides the stat and ammo enumeration names (`output-xml.map`), record interpretation (`parser.cc`) @@ -90,7 +94,7 @@ source-stack reduction/removal and the weapon deadline in one transaction before publishing ACK/Reload. Failed saves leave the live state unchanged. Equipment moves, admin assignment, backpacks, reclaim and restart preserve the instance's loaded count. Other item types cannot have nonzero ammunition; -the pistol cannot exceed its catalog capacity. There are no schema migrations +a finite-ammo weapon cannot exceed its own catalog capacity. There are no schema migrations for earlier development databases. Automatic reload, multiple-stack reload, left-hand weapons, cancellation policy diff --git a/server/backpacks.go b/server/backpacks.go @@ -345,8 +345,7 @@ func (server *server) handleBackpackAction_locked(client *worldClient, body []by if action == 52 || action == 53 { return server.changeStack_locked(client, index, body) } - low, high := items[index].templateIDs() - if action != 112 || binary.BigEndian.Uint32(body[28:32]) != low || binary.BigEndian.Uint32(body[32:36]) != high { + if action != 112 || !items[index].acceptsDeleteTemplates(binary.BigEndian.Uint32(body[28:32]), binary.BigEndian.Uint32(body[32:36])) { return nil } inventory := player.inventory @@ -361,5 +360,5 @@ func (server *server) handleBackpackAction_locked(client *worldClient, body []by if err := server.saveInventory_locked(player, inventory); err != nil { return err } - return client.send(n3Packet(0x5e477770, 50000, client.id, body[16:])) + return client.sendItemDeletion(body, []ownedItem{items[index]}) } diff --git a/server/bank.go b/server/bank.go @@ -178,12 +178,12 @@ func (server *server) handleBankAction_locked(client *worldClient, body []byte) return server.changeStack_locked(client, index, body) } item := player.inventory.Bank[index] - low, high := item.templateIDs() - if action != 112 || binary.BigEndian.Uint32(body[28:32]) != low || binary.BigEndian.Uint32(body[32:36]) != high { + if action != 112 || !item.acceptsDeleteTemplates(binary.BigEndian.Uint32(body[28:32]), binary.BigEndian.Uint32(body[32:36])) { return nil } // Deleting a bag destroys its children in the same transaction as its root. + deleted := append([]ownedItem{item}, player.inventory.Containers[item.ID]...) inventory := player.inventory inventory.Bank = slices.Delete(slices.Clone(inventory.Bank), index, index+1) if item.isPortableContainer() { @@ -201,5 +201,5 @@ func (server *server) handleBankAction_locked(client *worldClient, body []byte) delete(client.backpacks, handle) } } - return client.send(n3Packet(0x5e477770, 50000, client.id, body[16:])) + return client.sendItemDeletion(body, deleted) } diff --git a/server/bank_test.go b/server/bank_test.go @@ -323,7 +323,8 @@ func TestBankDeletingFilledBagRemovesChildrenAtomically(t *testing.T) { restarted := newTestInventoryServer(t) if err != nil || len(restarted.items) != 3 || len(restarted.characters[1].inventory.Bank) != 0 || len(restarted.characters[1].inventory.Containers) != 0 || - len(client.backpacks) != 0 || len(conn.packets) != 1 { + len(client.backpacks) != 0 || len(conn.packets) != 2 || + binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x36510078 || binary.BigEndian.Uint32(conn.packets[1][24:28]) != 5 { t.Fatal("deleted bank bag retained children or stale handles", err) } } diff --git a/server/combat.go b/server/combat.go @@ -102,7 +102,8 @@ func (character *character) attackDelays() (time.Duration, time.Duration) { initiative = stat[1] } } - return weaponDelays(weapon, character.effectiveStat(initiative), character.aggDef) + value, _ := character.effectiveStat(initiative) + return weaponDelays(weapon, value, character.aggDef) } initiative := character.effectiveSkill(120, stats.Speed.PhysicalInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) return weaponDelays(nil, initiative, character.aggDef) @@ -155,7 +156,8 @@ func (character *character) attackRating() int32 { for _, entry := range *section.Entries { if entry.Type != nil && *entry.Type == 12 { for _, weight := range *entry.Stats { - rating += character.effectiveStat(weight[0]) * int32(weight[1]) / 100 + value, _ := character.effectiveStat(weight[0]) + rating += value * int32(weight[1]) / 100 } } } @@ -519,7 +521,7 @@ func hitPacket(attacker, target *character, damage uint32) []byte { slot = 6 } for _, item := range attacker.inventory.Items { - if item.Slot == 6 && item.isFlechettePistol() { + if item.Slot == 6 && item.usesAmmo() { ammo = item.Ammo } } diff --git a/server/equipment.go b/server/equipment.go @@ -16,10 +16,6 @@ type equipmentMove struct { readyAt time.Time } -func (item ownedItem) isKineticAxe() bool { - return item.Type == 51018 && item.Template == 209283 && item.Quality == 1 -} - func (item ownedItem) fitsEquipmentSlot(slot uint32) bool { if item.isWearableContainer() { return slot >= 16 && slot < 32 && itemStat(gamedata.ItemTemplates[item.Template], 298)&(1<<(slot-16)) != 0 @@ -301,8 +297,16 @@ func (server *server) advanceEquipment(now time.Time) { } if move.source == 6 { server.queueCombat_locked(updates, character, character, weaponUnequipPacket(client.id)) - // FullUpdate100b38b0 ignores an existing dynel; retire it for re-equip. - server.queueCombat_locked(updates, character, character, n3Packet(0x36510078, item.Type, move.itemID, nil)) + // The owner's live inventory row still needs its detached weapon dynel. + for id, observer := range server.clients { + if id != client.id && observer.ready && !observer.loading && server.characters[id].playfield == character.playfield { + updates[observer] = append(updates[observer], n3Packet(0x36510078, item.Type, move.itemID, nil)) + } + } + } + if move.destination == 6 { + // FullUpdate100b38b0 only creates absent dynels. Retire after the UI request. + 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 == 37 { @@ -360,13 +364,13 @@ func equippedWeaponPackets(character *character) [][]byte { body = append(body, 1, 6) // sub_360B2830 loads StaticInstance 23, then applies item-quality stat 701. count := uint32(3027) - if item.isFlechettePistol() { + if item.usesAmmo() { count = 4036 } for _, value := range []uint32{count, 23, item.Template, 701, item.Quality} { body = binary.BigEndian.AppendUint32(body, value) } - if item.isFlechettePistol() { + if item.usesAmmo() { body = binary.BigEndian.AppendUint32(body, 26) body = binary.BigEndian.AppendUint32(body, item.Ammo) } diff --git a/server/equipment_test.go b/server/equipment_test.go @@ -69,21 +69,22 @@ func TestEquipmentDelayedNativeMoveAndRestart(t *testing.T) { if len(conn.packets) != 5 || len(observer.packets) != 3 { t.Fatalf("equipment replication: owner=%d observer=%d", len(conn.packets), len(observer.packets)) } - if binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x47537a24 || - binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x3b1d2268 || + if binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x36510078 || + binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x47537a24 || + binary.BigEndian.Uint32(conn.packets[2][16:20]) != 0x3b1d2268 || binary.BigEndian.Uint32(observer.packets[0][20:24]) != 51018 || binary.BigEndian.Uint32(observer.packets[2][16:20]) != 0x36510078 || - binary.BigEndian.Uint32(conn.packets[2][29:33]) != 97 || + binary.BigEndian.Uint32(conn.packets[3][29:33]) != 97 || binary.BigEndian.Uint32(conn.packets[4][45:49]) != 111 { t.Fatalf("native equipment packets: %x %x", conn.packets, observer.packets) } - length := binary.BigEndian.Uint16(conn.packets[1][6:8]) - if hex.EncodeToString(conn.packets[1][29:length]) != "0000000b0000c35000000001000003b60000000000000000010600000bd30000001700033183000002bd0000000100000000" { + length := binary.BigEndian.Uint16(conn.packets[2][6:8]) + if hex.EncodeToString(conn.packets[2][29:length]) != "0000000b0000c35000000001000003b60000000000000000010600000bd30000001700033183000002bd0000000100000000" { t.Fatalf("native weapon instance: %x", conn.packets[1]) } } -func TestWeaponUnequipRetiresNativeInstanceForOwnerAndObserver(t *testing.T) { +func TestWeaponReequipRetiresOwnerInstanceAfterItsNativeRequest(t *testing.T) { world, owner := newEquipmentWorld(t) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} @@ -102,15 +103,26 @@ func TestWeaponUnequipRetiresNativeInstanceForOwnerAndObserver(t *testing.T) { []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1}}) { t.Fatal("retiring the native weapon lost or moved the owned item incorrectly", err) } - if len(owner.packets) != 3 || len(observer.packets) != 2 || + if len(owner.packets) != 2 || len(observer.packets) != 2 || binary.BigEndian.Uint32(owner.packets[0][16:20]) != 0x5e477770 || binary.BigEndian.Uint32(owner.packets[0][29:33]) != 97 || - binary.BigEndian.Uint32(owner.packets[1][16:20]) != 0x36510078 || - binary.BigEndian.Uint32(owner.packets[1][20:24]) != 51018 || - binary.BigEndian.Uint32(owner.packets[1][24:28]) != 1 || - !bytes.Equal(owner.packets[1][16:], observer.packets[1][16:]) || - binary.BigEndian.Uint32(owner.packets[2][16:20]) != 0x47537a24 { - t.Fatalf("owner/observer did not retire the detached weapon before its next full update: %x / %x", owner.packets, observer.packets) + binary.BigEndian.Uint32(owner.packets[1][16:20]) != 0x47537a24 || + binary.BigEndian.Uint32(observer.packets[1][16:20]) != 0x36510078 { + t.Fatalf("unwear retired the owner's reusable inventory dynel: %x / %x", owner.packets, observer.packets) + } + owner.packets, observer.packets = nil, nil + if err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(world.clients[1].equipment.readyAt) + if len(owner.packets) != 3 || len(observer.packets) != 1 || + binary.BigEndian.Uint32(owner.packets[0][16:20]) != 0x36510078 || + binary.BigEndian.Uint32(owner.packets[0][20:24]) != 51018 || + binary.BigEndian.Uint32(owner.packets[0][24:28]) != 1 || + binary.BigEndian.Uint32(owner.packets[1][16:20]) != 0x47537a24 || + binary.BigEndian.Uint32(owner.packets[2][16:20]) != 0x3b1d2268 || + !bytes.Equal(owner.packets[2][16:], observer.packets[0][16:]) { + t.Fatalf("re-equip failed to replace the old dynel before attaching its fresh instance: %x / %x", owner.packets, observer.packets) } } diff --git a/server/inventory.go b/server/inventory.go @@ -266,9 +266,8 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { } inventory.Items[index].Slot = destination } else { - low, high := inventory.Items[index].templateIDs() - if binary.BigEndian.Uint32(body[28:32]) != low || - binary.BigEndian.Uint32(body[32:36]) != high { + if binary.BigEndian.Uint32(body[16:20]) != 112 || + !inventory.Items[index].acceptsDeleteTemplates(binary.BigEndian.Uint32(body[28:32]), binary.BigEndian.Uint32(body[32:36])) { return nil } inventory.Items = slices.Delete(inventory.Items, index, index+1) @@ -280,6 +279,11 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { } } } + var deleted []ownedItem + if key == 0x5e477770 { + item := character.inventory.Items[index] + deleted = append([]ownedItem{item}, character.inventory.Containers[item.ID]...) + } if err := server.saveInventory_locked(character, inventory); err != nil { return err } @@ -294,7 +298,31 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { } } } + return client.sendItemDeletion(body, deleted) } - // send only enqueues owned packet bytes, never waits for the transport. return client.send(n3Packet(key, 50000, client.id, body[16:])) } + +func (item ownedItem) acceptsDeleteTemplates(low, high uint32) bool { + // Native live-item deletion can omit the auxiliary template pair entirely. + if low == 0 && high == 0 { + return true + } + first, second := item.templateIDs() + return low == first && high == second +} + +func (client *worldClient) sendItemDeletion(body []byte, deleted []ownedItem) error { + if err := client.send(n3Packet(0x5e477770, 50000, client.id, body[16:])); err != nil { + return err + } + // Native row deletion does not destroy detached weapon dynels. + for _, item := range deleted { + if item.isWieldableWeapon() { + if err := client.send(n3Packet(0x36510078, item.Type, item.ID, nil)); err != nil { + return err + } + } + } + return nil +} diff --git a/server/item_store_test.go b/server/item_store_test.go @@ -88,7 +88,8 @@ func TestControlItemAssignmentOffersOnlyFreeCompatibleSlots(t *testing.T) { contained := postControlForm(world, "/control/items/4", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"3:20"}}) restarted := newServer() - if page.Code != http.StatusOK || strings.Contains(page.Body.String(), "value='0:64'") || strings.Contains(page.Body.String(), "value='0:6'") || !strings.Contains(page.Body.String(), "value='0:65'") { + if page.Code != http.StatusOK || strings.Contains(page.Body.String(), "value='0:64'") || strings.Contains(page.Body.String(), "value='0:8'") || + !strings.Contains(page.Body.String(), "value='0:6'") || !strings.Contains(page.Body.String(), "value='0:65'") { t.Fatal("assignment form included an occupied or incompatible slot") } if occupied.Code != http.StatusBadRequest || placed.Code != http.StatusSeeOther || bag.Code != http.StatusSeeOther || contained.Code != http.StatusSeeOther { diff --git a/server/ranged.go b/server/ranged.go @@ -8,20 +8,35 @@ import ( "time" ) -func (item ownedItem) isFlechettePistol() bool { - return item.Type == 51018 && item.Template == 123742 && item.Quality == 1 +func (item ownedItem) usesAmmo() bool { + if !item.isWieldableWeapon() { + return false + } + // Native weapons without a finite clip retain the -1 ammunition sentinel. + clip := itemStat(gamedata.ItemTemplates[item.Template], 212) + return clip != 0 && clip != ^uint32(0) } func (item ownedItem) validAmmo() bool { - if item.isFlechettePistol() { - return item.Ammo <= itemStat(gamedata.ItemTemplates[123742], 212) + if item.usesAmmo() { + return item.Ammo <= itemStat(gamedata.ItemTemplates[item.Template], 212) } return item.Ammo == 0 } +func ammunitionType(definition *gamedata.Item) (uint32, bool) { + // Omitted source ammo types have no verified default; do not equate them to zero. + for _, stat := range definition.Stats { + if stat[0] == 420 { + return stat[1], true + } + } + return 0, false +} + func (server *server) applyWeaponDamage_locked(attacker, target *character, damage uint32, now time.Time) (bool, *experienceAward, error) { for index, item := range attacker.inventory.Items { - if item.Slot != 6 || !item.isFlechettePistol() { + if item.Slot != 6 || !item.usesAmmo() { continue } if item.Ammo == 0 { @@ -72,9 +87,9 @@ func (server *server) handleReload(client *worldClient, body []byte) error { binary.BigEndian.PutUint32(acknowledgement, 2) // Native ammo-on-weapon use names both sides of the transfer. - weapon := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { return item.Slot == 6 && item.isFlechettePistol() }) + weapon := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { return item.Slot == 6 && item.usesAmmo() }) ammo := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { - return item.Type == 51005 && item.Template == 21605 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && + return item.Type == 51005 && item.Slot >= 64 && item.Slot < 94 && binary.BigEndian.Uint32(body[40:44]) == 104 && binary.BigEndian.Uint32(body[44:48]) == item.Slot }) now := time.Now() @@ -82,11 +97,16 @@ func (server *server) handleReload(client *worldClient, body []byte) error { !now.Before(client.reloadUntil) && !player.driving() if accepted { targetType, targetID := binary.BigEndian.Uint32(body[48:52]), binary.BigEndian.Uint32(body[52:56]) - accepted = targetType == 101 && targetID == 6 || targetType == 51018 && targetID == player.inventory.Items[weapon].ID + source := gamedata.ItemTemplates[player.inventory.Items[ammo].Template] + gun := gamedata.ItemTemplates[player.inventory.Items[weapon].Template] + sourceType, sourceHasType := ammunitionType(source) + gunType, gunHasType := ammunitionType(gun) + accepted = (targetType == 101 && targetID == 6 || targetType == 51018 && targetID == player.inventory.Items[weapon].ID) && + itemStat(source, 76) == 0 && sourceHasType && gunHasType && sourceType == gunType } - if accepted && player.inventory.Items[weapon].Ammo < 20 { + if accepted && player.inventory.Items[weapon].Ammo < itemStat(gamedata.ItemTemplates[player.inventory.Items[weapon].Template], 212) { source, gun := player.inventory.Items[ammo], player.inventory.Items[weapon] - loaded := min(uint32(source.Count), 20-gun.Ammo) + loaded := min(uint32(source.Count), itemStat(gamedata.ItemTemplates[gun.Template], 212)-gun.Ammo) inventory := player.inventory inventory.Items = slices.Clone(inventory.Items) inventory.Items[weapon].Ammo += loaded @@ -98,7 +118,7 @@ func (server *server) handleReload(client *worldClient, body []byte) error { // Pause recharge, or restart an interrupted attack, as in native 100529a0. candidate := *player candidate.inventory = inventory - delay := time.Duration(itemStat(gamedata.ItemTemplates[123742], 210)) * 10 * time.Millisecond + delay := time.Duration(itemStat(gamedata.ItemTemplates[gun.Template], 210)) * 10 * time.Millisecond readyAt := now.Add(delay) if candidate.fighting != 0 && now.Before(candidate.rechargeUntil) { candidate.rechargeUntil = candidate.rechargeUntil.Add(delay) diff --git a/server/starter_weapons_test.go b/server/starter_weapons_test.go @@ -0,0 +1,447 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "fmt" + "reflect" + "slices" + "testing" + "time" +) + +func TestStarterWeaponsEquipWithCatalogRequirementsAndRecover(t *testing.T) { + for _, scenario := range []struct { + template, profession uint32 + delay time.Duration + }{ + {121564, 9, 500 * time.Millisecond}, {121565, 2, 500 * time.Millisecond}, + {121566, 12, 500 * time.Millisecond}, {121567, 0, 2 * time.Second}, + {121568, 5, 2 * time.Second}, {121569, 1, 500 * time.Millisecond}, + {121570, 7, time.Second}, {121571, 4, 2 * time.Second}, + } { + t.Run(fmt.Sprint(scenario.template), func(t *testing.T) { + world, owner := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory.Items[0].Template = scenario.template + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + before, _ := readTestItemStore(world) + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + + for profession := uint16(1); profession <= 12; profession++ { + if scenario.profession == 0 || uint32(profession) == scenario.profession { + continue + } + player.profession = profession + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment != nil { + t.Fatalf("profession %d admitted the weapon: %v", profession, err) + } + if after, _ := readTestItemStore(world); !bytes.Equal(before, after) || player.inventory.Items[0].Slot != 64 { + t.Fatal("rejected equip changed the item") + } + } + player.profession = uint16(max(1, scenario.profession)) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + owner.packets, observer.packets = nil, nil + started := time.Now() + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment == nil { + t.Fatalf("qualified profession could not equip: %v", err) + } + finish := client.equipment.readyAt + world.advanceEquipment(finish.Add(-time.Nanosecond)) + if player.inventory.Items[0].Slot != 64 { + t.Fatal("weapon moved before the equip deadline") + } + world.advanceEquipment(finish) + restored := newTestInventoryServer(t).characters[1] + if err := world.handleInventory(client, itemMovePacket(1, 6, 111)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(client.equipment.readyAt) + removed := newTestInventoryServer(t).characters[1] + + if finish.Before(started.Add(scenario.delay)) || finish.After(started.Add(scenario.delay+50*time.Millisecond)) || + restored.attackWeapon() == nil || restored.attackWeapon().ID != scenario.template || + !reflect.DeepEqual(restored.inventory.Items, []ownedItem{{ID: 1, Type: 51018, Template: scenario.template, Quality: 1, Slot: 6, Count: 1}}) || + !reflect.DeepEqual(removed.inventory.Items, []ownedItem{{ID: 1, Type: 51018, Template: scenario.template, Quality: 1, Slot: 64, Count: 1}}) || + player.attackWeapon() != nil || removed.attackWeapon() != nil { + t.Fatal("weapon timing, identity or cold recovery mismatch") + } + if len(owner.packets) != 5 || len(observer.packets) != 3 || + binary.BigEndian.Uint32(owner.packets[0][16:20]) != 0x36510078 || + binary.BigEndian.Uint32(owner.packets[2][16:20]) != 0x3b1d2268 || + !bytes.Equal(owner.packets[2][16:], observer.packets[0][16:]) { + t.Fatal("weapon instance did not reach owner and observer") + } + for _, stat := range []uint32{90, 91, 92} { + expected := int32(0) + if scenario.template == 121566 { + expected = 10 + } + if restored.equipmentBonus(stat) != expected || player.equipmentBonus(stat) != 0 || removed.equipmentBonus(stat) != 0 { + t.Fatal("Meta Shield modifiers did not follow equipment") + } + } + }) + } +} + +func TestWeaponUnsupportedPredicatesAndMalformedDefinitionsRetainItem(t *testing.T) { + for _, scenario := range []string{"unknown stat", "unknown operator", "wrong breed", "wrong side", "wrong sex", "wrong quality", "reversed damage", "left hand"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newEquipmentWorld(t) + player := world.characters[1] + original := gamedata.ItemTemplates[121567] + definition := *original + definition.Stats = slices.Clone(original.Stats) + requirement := gamedata.ItemRequirement{Stat: 9999, Value: 0, Operator: 0} + switch scenario { + case "unknown operator": + requirement = gamedata.ItemRequirement{Stat: 60, Value: 1, Operator: 3} + case "wrong breed": + requirement = gamedata.ItemRequirement{Stat: 4, Value: 4, Operator: 0} + case "wrong side": + requirement = gamedata.ItemRequirement{Stat: 33, Value: 2, Operator: 0} + case "wrong sex": + requirement = gamedata.ItemRequirement{Stat: 59, Value: 3, Operator: 0} + } + if scenario == "wrong quality" || scenario == "reversed damage" || scenario == "left hand" { + definition.Sections = nil + } else { + actions := []gamedata.ItemAction{{Type: 8, Requirements: []gamedata.ItemRequirement{requirement}}} + definition.Sections = []gamedata.ItemSection{{Actions: &actions}} + } + if scenario == "reversed damage" { + for index, stat := range definition.Stats { + if stat[0] == 286 { + definition.Stats[index][1] = 100 + } + } + } + gamedata.ItemTemplates[121567] = &definition + t.Cleanup(func() { gamedata.ItemTemplates[121567] = original }) + player.inventory.Items[0].Template = 121567 + if scenario == "wrong quality" { + player.inventory.Items[0].Quality = 2 + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + before, _ := readTestItemStore(world) + destination := uint32(6) + if scenario == "left hand" { + destination = 8 + } + + err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, destination)[20:]) + after, _ := readTestItemStore(world) + + if err != nil || world.clients[1].equipment != nil || player.inventory.Items[0].Slot != 64 || + !bytes.Equal(before, after) || len(conn.packets) != 2 { + t.Fatal("unsupported equip changed or lost the item", err) + } + }) + } +} + +func TestSolarShotgunFiresAndFlingsWithoutFiniteAmmo(t *testing.T) { + world, owner := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + player.profession = 7 + target.position = [3]float32{8, 0, 0} + inventory := player.inventory + inventory.Items[0].Template, inventory.Items[0].Ammo = 121570, 0 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + + if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(player.nextAttack) + if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, target.id)[20:]); err != nil { + t.Fatal(err) + } + world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, target.id)[20:]) + restored := newTestInventoryServer(t).characters[1] + + normal, fling := 0, 0 + for _, packet := range owner.packets { + switch binary.BigEndian.Uint32(packet[16:20]) { + case 0x46002f16: + normal++ + if binary.BigEndian.Uint32(packet[33:37]) != ^uint32(0) { + t.Fatal("solar normal hit lost its infinite-ammo sentinel") + } + case 0x754f1115: + fling++ + if binary.BigEndian.Uint32(packet[37:41]) != ^uint32(0) { + t.Fatal("solar Fling lost its infinite-ammo sentinel") + } + } + } + if normal != 1 || fling != 1 || target.health >= 1000 || player.inventory.Items[0].Ammo != 0 || + restored.inventory.Items[0].Ammo != 0 || restored.inventory.Items[1].Count != 100 || + !restored.specialAttackLocks[150].Equal(player.specialAttackLocks[150]) { + t.Fatal("solar combat consumed ammunition or repeated a locked special") + } +} + +func TestReloadUsesCatalogCapacityTypeAndDelayForAnotherWeapon(t *testing.T) { + for _, source := range []uint32{21609, 21605} { + t.Run(fmt.Sprint(source), func(t *testing.T) { + world, owner := newRangedWorld(t) + player := world.characters[1] + inventory := player.inventory + inventory.Items[0].Template, inventory.Items[0].Quality = 122099, 161 + inventory.Items[1].Template = source + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + started := time.Now() + + err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1)) + restored := newTestInventoryServer(t).characters[1] + + if err != nil { + t.Fatal(err) + } + if source == 21605 { + if restored.inventory.Items[0].Ammo != 3 || restored.inventory.Items[1].Count != 100 || + len(owner.packets) != 1 || binary.BigEndian.Uint32(owner.packets[0][29:33]) != 2 { + t.Fatal("incompatible bullets reloaded an energy weapon") + } + return + } + if restored.inventory.Items[0].Ammo != 10 || restored.inventory.Items[1].Count != 93 || + restored.rechargeUntil.Before(started.Add(2500*time.Millisecond)) || + restored.rechargeUntil.After(time.Now().Add(2500*time.Millisecond)) || len(owner.packets) != 2 || + binary.BigEndian.Uint32(owner.packets[1][49:53]) != 10 { + t.Fatal("reload ignored the other weapon's capacity, ammo type or delay") + } + }) + } +} + +func TestOtherFiniteWeaponPersistsOneRoundOrRollsBackDamage(t *testing.T) { + for _, failed := range []bool{false, true} { + t.Run(fmt.Sprint(failed), func(t *testing.T) { + world, owner := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + player.stats.Ranged.Rifle, player.stats.Ranged.FlingShot = 1000, 1000 + target.position = [3]float32{8, 0, 0} + inventory := player.inventory + inventory.Items[0].Template, inventory.Items[0].Quality = 122099, 161 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if failed { + if _, err := world.db.Exec("CREATE TRIGGER fail_ammo BEFORE UPDATE OF ammo ON items BEGIN SELECT RAISE(FAIL, 'test save failure'); END"); err != nil { + t.Fatal(err) + } + } + world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]) + owner.packets = nil + + world.advanceCombat(player.nextAttack) + restored := newTestInventoryServer(t).characters[1] + + shots := 0 + for _, packet := range owner.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 { + shots++ + if binary.BigEndian.Uint32(packet[33:37]) != 2 { + t.Fatal("other weapon did not publish its loaded count") + } + } + } + if failed { + if target.health != 1000 || shots != 0 || player.inventory.Items[0].Ammo != 3 || restored.inventory.Items[0].Ammo != 3 { + t.Fatal("failed other-weapon shot changed damage or ammunition") + } + } else if target.health >= 1000 || shots != 1 || player.inventory.Items[0].Ammo != 2 || restored.inventory.Items[0].Ammo != 2 { + t.Fatalf("other-weapon shot: HP=%d shots=%d ammo=%d restored=%d", target.health, shots, player.inventory.Items[0].Ammo, restored.inventory.Items[0].Ammo) + } + }) + } +} + +func TestReloadChecksSourceAmmoTypeAndItemTypeWithoutRequiringClassNine(t *testing.T) { + for _, scenario := range []string{"different class", "wrong item type", "omitted ammo type", "omitted source versus zero weapon"} { + t.Run(scenario, func(t *testing.T) { + world, owner := newRangedWorld(t) + original := gamedata.ItemTemplates[21605] + definition := *original + definition.Stats = slices.Clone(original.Stats) + for index := len(definition.Stats) - 1; index >= 0; index-- { + stat := definition.Stats[index][0] + if scenario == "different class" && stat == 88 { + definition.Stats[index][1] = 0 + } + if scenario == "wrong item type" && stat == 76 { + definition.Stats[index][1] = 1 + } + if (scenario == "omitted ammo type" || scenario == "omitted source versus zero weapon") && stat == 420 { + definition.Stats = slices.Delete(definition.Stats, index, index+1) + } + } + gamedata.ItemTemplates[21605] = &definition + t.Cleanup(func() { gamedata.ItemTemplates[21605] = original }) + if scenario == "omitted source versus zero weapon" { + originalWeapon := gamedata.ItemTemplates[123742] + weapon := *originalWeapon + weapon.Stats = slices.Clone(originalWeapon.Stats) + for index, stat := range weapon.Stats { + if stat[0] == 420 { + weapon.Stats[index][1] = 0 + } + } + gamedata.ItemTemplates[123742] = &weapon + t.Cleanup(func() { gamedata.ItemTemplates[123742] = originalWeapon }) + } + + err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1)) + restored := newTestInventoryServer(t).characters[1] + + if err != nil { + t.Fatal(err) + } + if scenario == "different class" { + if restored.inventory.Items[0].Ammo != 20 || restored.inventory.Items[1].Count != 83 || len(owner.packets) != 2 { + t.Fatal("item class blocked compatible ammunition") + } + } else if restored.inventory.Items[0].Ammo != 3 || restored.inventory.Items[1].Count != 100 || len(owner.packets) != 1 { + t.Fatal("invalid ammo source transferred rounds") + } + }) + } +} + +func TestDeletingStoredWeaponsRetiresNativeDynelsOnlyAfterCommit(t *testing.T) { + for _, scenario := range []string{"inventory", "bank", "backpack", "bag", "banked bag", "save failure"} { + t.Run(scenario, func(t *testing.T) { + world, owner := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + request := inventoryDeletePacket(1, 68)[20:] + if scenario == "backpack" || scenario == "bag" || scenario == "banked bag" { + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, backpackMoveRequest(104, 68, 51017, 3, 0)[20:]); err != nil { + t.Fatal(err) + } + request = characterActionPacket(1, [5]uint32{112, 107, 1 << 16, 121567, 121567})[20:] + } + if scenario == "bag" { + request = characterActionPacket(1, [5]uint32{112, 104, 66, 99228, 99228})[20:] + } + if scenario == "bank" || scenario == "banked bag" { + source := uint32(68) + template := uint32(121567) + if scenario == "banked bag" { + source, template = 66, 99228 + } + if err := world.handleInventory(client, backpackMoveRequest(104, source, 57005, 1, 111)[20:]); err != nil { + t.Fatal(err) + } + request = characterActionPacket(1, [5]uint32{112, 105, 0, template, template})[20:] + } + if scenario == "save failure" { + if _, err := world.db.Exec("CREATE TRIGGER fail_delete BEFORE DELETE ON items BEGIN SELECT RAISE(FAIL, 'test delete failure'); END"); err != nil { + t.Fatal(err) + } + } + owner.packets = nil + + err := world.handleInventory(client, request) + restored := newTestInventoryServer(t) + + if scenario == "save failure" { + if err == nil || len(owner.packets) != 0 || restored.items[5].Template != 121567 || len(player.inventory.Items) != 5 { + t.Fatal("failed deletion retired or lost its live weapon") + } + return + } + if err != nil || restored.items[5].Template != 0 || len(owner.packets) < 2 { + t.Fatal("weapon deletion did not commit and retire its dynel", err) + } + ack, quit := owner.packets[len(owner.packets)-2], owner.packets[len(owner.packets)-1] + if binary.BigEndian.Uint32(ack[16:20]) != 0x5e477770 || binary.BigEndian.Uint32(ack[29:33]) != 112 || + binary.BigEndian.Uint32(quit[16:20]) != 0x36510078 || binary.BigEndian.Uint32(quit[20:24]) != 51018 || + binary.BigEndian.Uint32(quit[24:28]) != 5 { + t.Fatalf("native weapon retirement preceded row deletion: %x %x", ack, quit) + } + }) + } +} + +func TestZeroWeaponRequirementCannotDivideByZeroAfterSkillLoss(t *testing.T) { + for _, actual := range []int32{-1, 0, 1} { + t.Run(fmt.Sprint(actual), func(t *testing.T) { + world, _ := newEquipmentWorld(t) + player := world.characters[1] + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Melee.OneHandEdged = 0 + original := gamedata.ItemTemplates[123057] + weapon := *original + stat := int32(103) + functions := []gamedata.ItemFunction{{ID: 53045, Arguments: []gamedata.ItemArgument{{Integer: &stat}, {Integer: &actual}}}} + weapon.Sections = append(slices.Clone(original.Sections), gamedata.ItemSection{Type: 2, Subtype: 14, Functions: &functions}) + gamedata.ItemTemplates[123057] = &weapon + t.Cleanup(func() { gamedata.ItemTemplates[123057] = original }) + player.inventory.Items[0].Template, player.inventory.Items[0].Slot = 123057, 6 + + damage := player.normalDamage(world.characters[1000000], func(limit uint32) uint32 { return 0 }) + + value, known := player.effectiveStat(103) + if !known || value != actual || damage != 2 { + t.Fatalf("zero requirement: skill=%d damage=%d", value, damage) + } + }) + } +} + +func TestDeleteLiveWeaponMayOmitBothTemplateEndpoints(t *testing.T) { + for _, page := range []uint32{104, 105, 107} { + for _, endpoints := range [][2]uint32{{0, 0}, {0, 121567}, {121567, 0}, {121568, 121568}} { + t.Run(fmt.Sprintf("%d/%d-%d", page, endpoints[0], endpoints[1]), func(t *testing.T) { + world, owner := newBankWorld(t) + client := world.clients[1] + slot := uint32(68) + if page == 105 { + if err := world.handleInventory(client, backpackMoveRequest(104, 68, 57005, 1, 111)[20:]); err != nil { + t.Fatal(err) + } + slot = 0 + } + if page == 107 { + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, backpackMoveRequest(104, 68, 51017, 3, 0)[20:]); err != nil { + t.Fatal(err) + } + slot = 1 << 16 + } + owner.packets = nil + request := characterActionPacket(1, [5]uint32{112, page, slot, endpoints[0], endpoints[1]})[20:] + + err := world.handleInventory(client, request) + restored := newTestInventoryServer(t) + + omitted := endpoints == [2]uint32{0, 0} + _, retained := restored.items[5] + if err != nil || retained == omitted || omitted && len(owner.packets) != 2 || !omitted && len(owner.packets) != 0 { + t.Fatalf("delete endpoints %v: retained=%v packets=%d, %v", endpoints, retained, len(owner.packets), err) + } + }) + } + } +} diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go @@ -255,6 +255,9 @@ func TestTargetInventoryBoundsAndLastSlotMovesSurviveRestart(t *testing.T) { if _, err := readPacket(client); err != nil { t.Fatal(err) } + if quit, err := readPacket(client); err != nil || binary.BigEndian.Uint32(quit[16:20]) != 0x36510078 { + t.Fatal("deleted weapon did not retire its native dynel", err) + } // Native 78 is outside the inventory, even though persisted slot 78 is empty. invalid = targetPacket(inventoryMovePacket(1, 93, 64)) binary.BigEndian.PutUint32(invalid[45:49], 78) diff --git a/server/weapon_special.go b/server/weapon_special.go @@ -11,7 +11,8 @@ import ( func (player *character) weaponSpecialLockSeconds(weapon *gamedata.Item, skill uint32) uint32 { // February 2003 formula: attack delay * 15 - special skill / 100. // Whole-second rounding and the minimum are provisional; see docs/fling-shot.md. - centiseconds := int64(itemStat(weapon, 294))*15 - int64(player.effectiveStat(skill)) + value, _ := player.effectiveStat(skill) + centiseconds := int64(itemStat(weapon, 294))*15 - int64(value) return uint32(max(1, (centiseconds+99)/100)) } @@ -51,7 +52,7 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro break } } - if item == nil || itemStat(gamedata.ItemTemplates[item.Template], 30)&capability == 0 || skill == 150 && item.Ammo == 0 { + if item == nil || itemStat(gamedata.ItemTemplates[item.Template], 30)&capability == 0 || skill == 150 && item.usesAmmo() && item.Ammo == 0 { server.mutex.Unlock() return nil } @@ -72,7 +73,7 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro var result []byte death := uint32(0) ammunition := ^uint32(0) - if skill == 150 { + if skill == 150 && item.usesAmmo() { ammunition = item.Ammo } if target.health == 0 { diff --git a/server/weapon_stats.go b/server/weapon_stats.go @@ -3,32 +3,42 @@ package main import "ao/server/gamedata" func (item ownedItem) isWieldableWeapon() bool { - return item.isKineticAxe() || item.isFlechettePistol() || - item.Type == 51018 && item.Template == 205736 && item.Quality == 100 + definition := gamedata.ItemTemplates[item.Template] + return item.Type == 51018 && definition != nil && definition.HeaderWords[0] == item.Type && + item.Quality == *definition.Quality && itemStat(definition, 298)&64 != 0 && + itemStat(definition, 285) >= itemStat(definition, 286) } -func (character *character) effectiveStat(stat uint32) int32 { +func (character *character) effectiveStat(stat uint32) (int32, bool) { switch stat { + case 4: + return int32(unpackAppearance(character.appearance).Breed), true + case 33: + return int32(unpackAppearance(character.appearance).Side), true + case 59: + return int32(unpackAppearance(character.appearance).Sex), true + case 89: + return int32(unpackAppearance(character.appearance).Race), true case 16, 17, 18, 19, 20, 21: - return character.effectiveAbility(stat) + return character.effectiveAbility(stat), true case 37: - return int32(character.titleLevel()) + return int32(character.titleLevel()), true case 54: - return int32(character.level) + return int32(character.level), true case 60: - return int32(character.profession) + return int32(character.profession), true } stats := character.baseStats() for _, field := range stats.trainingStats() { if field.stat == stat { - return character.effectiveSkill(stat, *field.value, gamedata.IPTraining.Weights[stat]) + return character.effectiveSkill(stat, *field.value, gamedata.IPTraining.Weights[stat]), true } } - return 0 + return 0, false } func (character *character) weaponRequirementsMet(item ownedItem) bool { - // Supported weapon action-8 lists contain equality/strict bounds joined by AND. + // Evaluate supported action-8 predicates; unknown stats or operators cannot grant wear. for _, section := range gamedata.ItemTemplates[item.Template].Sections { if section.Actions == nil { continue @@ -38,18 +48,13 @@ func (character *character) weaponRequirementsMet(item ownedItem) bool { continue } for _, requirement := range action.Requirements { - switch requirement.Operator { - case 0: - if character.effectiveStat(uint32(requirement.Stat)) != requirement.Value { - return false - } - case 2: - if character.effectiveStat(uint32(requirement.Stat)) <= requirement.Value { - return false - } - case 4: - // Conjunction has no independent stat predicate. - default: + if requirement.Operator == 4 { + continue + } + actual, known := character.effectiveStat(uint32(requirement.Stat)) + if !known || requirement.Operator != 0 && requirement.Operator != 2 || + requirement.Operator == 0 && actual != requirement.Value || + requirement.Operator == 2 && actual <= requirement.Value { return false } } @@ -70,8 +75,11 @@ func (character *character) weaponOverequippingTier(weapon *gamedata.Item) uint3 continue } for _, requirement := range action.Requirements { - if requirement.Operator == 2 { - actual := character.effectiveStat(uint32(requirement.Stat)) + if requirement.Operator == 2 && requirement.Value != 0 { + actual, known := character.effectiveStat(uint32(requirement.Stat)) + if !known { + return 4 + } if actual < requirement.Value { tier = max(tier, min(4, uint32((int64(requirement.Value)-int64(actual))*5/int64(requirement.Value)))) } diff --git a/server/world.go b/server/world.go @@ -168,7 +168,7 @@ func fullCharacterPacket(character *character) []byte { body = binary.BigEndian.AppendUint32(body, uint32(len(character.inventory.Items)+1)*1009) for _, item := range character.inventory.Items { flags := uint32(1) - if item.isPortableContainer() || (item.isKineticAxe() || item.isFlechettePistol()) && item.Slot == 6 { + if item.isPortableContainer() || item.isWieldableWeapon() && item.Slot == 6 { flags = 2 } low, high := item.templateIDs()