aorecomp

Anarchy Online classic in the browser

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


commit df76dca0907c83f145259aa5af4608879a18d37b
parent 89735fc46f91ef563b0f39c64d064d5b883a3c85
Author: anon <anon@example.com>
Date:   Fri, 23 Oct 2026 19:03:33 +0000

Support portable-container wear and derived equipment stats

Diffstat:
MTODO.md | 23++++++++++++++++++++---
Mdocs/backpacks.md | 154++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mserver/armor_damage_test.go | 4++--
Mserver/armor_quality_test.go | 2+-
Aserver/backpack_catalog_effects_test.go | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/backpack_effects_test.go | 197+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/backpack_equipment.go | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/backpack_equipment_test.go | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/backpack_quality_test.go | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/backpack_requirements_test.go | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/backpacks.go | 16++++++++++++----
Mserver/combat.go | 44+++++++++++++++++++++++++++-----------------
Mserver/control_items.go | 2+-
Mserver/equipment.go | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------
Mserver/implants.go | 2+-
Mserver/insurance.go | 2+-
Mserver/inventory.go | 9++++++++-
Mserver/item_pages.go | 5+++--
Mserver/item_quality.go | 16++++++++++++----
Mserver/main.go | 2+-
Mserver/metaplast_test.go | 6+++---
Mserver/nano_casting.go | 6+++---
Mserver/nano_kit.go | 2+-
Mserver/nano_learning.go | 6+++---
Mserver/regeneration.go | 6+++---
Mserver/stats.go | 15++++++++++-----
Mserver/treatment_kit.go | 2+-
Mserver/world.go | 8+++++---
Mserver/zoning.go | 2+-
29 files changed, 1021 insertions(+), 93 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -62,9 +62,19 @@ recorded in [inventory behavior](docs/inventory.md). reconnect and restart. Cover the control panel, looting, deletion and reclaim. - [ ] Equip portable bags with their authored requirements and effects. Check: back-slot bags and the Pre-Universe Storage Device use the correct slots; - ability/skill/level boundaries, signed bonuses, health and XP effects, use while + ability/skill/level boundaries, signed bonuses, health and XP modifiers, use while worn, and supported QL interpolation match recovered behavior. Storage support alone must not enable unsupported equipment effects. + Server catalog requirements, all six Pre-Universe positions, signed modifiers, + ability trickle, Survival QL 50..150, atomic resource clamping and worn-use + routing now have regression coverage. Keep this item open until real-client + Pre-Universe placement/use/removal is verified beyond its default finger slot; + distinguish native cursor/window state from missing server requests. Damage-type + additions, critical chance and kill XP still have the separate milestones below. +- [ ] Verify the Notum Threaded Backpack icon against original resource 10771. + Check: explain the solid magenta icon seen in the WASM inventory before changing + decoding or rendering; preserve any intentional source placeholder. Capture: + `local/backpack-equipment-smoke/phase-two-above-bottom.png`. Essence of Pure Jealousy now supports persistent native splitting and merging. The historical merge cap remains unresolved, so the merge item stays open; @@ -120,7 +130,12 @@ capacity checks are recorded in [belts and NCU](docs/belts-ncu.md). - [ ] Resolve hit versus miss. Check: controlled test rolls produce the matching native outcomes; a miss does not reduce health. - [ ] Resolve a critical hit. Check: a known weapon and controlled roll produce - the expected critical damage and client feedback. + the expected critical damage and client feedback. Include the Sniper's Friend + backpack's CriticalIncrease modifier and removal of that modifier. +- [ ] Apply damage-type equipment modifiers in the recovered combat order. + Check: Robust Backpack's projectile, energy, radiation and fire bonuses affect + the matching attacks, leave other types unchanged, and interact correctly with + armor, weapon minimum damage, overequipping and critical hits. - [x] Apply armor to one damage type. Check: known armor/damage inputs produce sourced results, including the minimum-damage boundary. - [x] Select armor by damage type. Check: changing only the attack's damage type @@ -249,7 +264,9 @@ Known-amount credit collection and native balance limits are verified in ## Character progression - [ ] Award XP for one creature kill. Check: the eligible killer gains one known - reward exactly once; the total survives restart. + reward exactly once; the total survives restart. Include the Pioneer backpack's + XPModifier, removal, rounding and eligibility rules; displaying that modifier + alone does not establish correct rewards. - [ ] Advance through one level threshold. Check: crossing it updates the native level display and the correct derived resources without a second level-up. - [ ] Award IP for that level. Check: the expected amount is granted once and diff --git a/docs/backpacks.md b/docs/backpacks.md @@ -23,8 +23,8 @@ Every portable Chest has 21 native slots. Small, Medium and Large describe 10, 50 and 100 kilograms respectively (stat 24); those values do not set slot capacity. The storage path forwards each instance's template and QL unchanged. The Adventuring and other wear requirements do not gate opening an ordinary -inventory container. Equipping bags and applying their effects remain separate -work, including signed bonuses and the unusual Pre-Universe equipment slots. +inventory container. Wear requirements, signed equipment effects and the unusual +Pre-Universe equipment slots are described below. The full shipped catalog audit is retained in `local/backpack-sizes-research/catalog.json` (60 records, including source files), @@ -56,7 +56,8 @@ success acknowledgement and supplies a live Chest plus its contents: | ChestFullUpdate `465a5d73`, outer `(51017,bagID)` | SimpleItem version 11; parent `(50000,owner)`; playfield; auxiliary `(0,0)`; page/slot bytes; encoded stat pairs; extra-data length 0; Lockable version 2; lock field 0; empty identity list 1009; Chest version 3 | | InventoryUpdate `4e536976`, outer `(50000,owner)` | Encoded 32-byte item rows; `(51017,bagID)`; container handle; open flag 1 | -The explicit Chest stats are `23=template,701=QL,702=template,703=template`. +The explicit Chest stats are `23=template,701=QL,702=lowTemplate,703=highTemplate`. +The endpoints are equal except for supported intermediate Backpack of Survival QLs. SimpleItem has no XYZ/quaternion when it has a parent. ChestFullUpdate has no corpse tail or animation list. Reader evidence: `ev_275528c4a10136c1a2de368bd4bdbb1c2bf5c0b29f946a68808e609e47d9218d`. @@ -136,8 +137,7 @@ must not be cited as historical proof. The native slot bound and placement checks are established. Enforcement of the catalog's kilogram limits was not recovered, so no new mass cap is invented. Equipment moves currently pass through ordinary inventory first. -Bag equipping, signed equipment effects, QL interpolation, custom names and -trades remain separate features. As with other slot-addressed messages, the wire has +Custom names and trades remain separate features. As with other slot-addressed messages, the wire has no operation token to identify every replay after later slot reuse. Filled containers on corpses keep their contents through periodic checkpoints. @@ -227,3 +227,147 @@ restart snapshots matched as well. Both owned browser sessions closed in screenshots, JSON snapshots and verification results are retained in `local/container-catalog-smoke/`. The preview remained on HTTPS 8443 and the ordinary server ports throughout; no extra gameplay server was started. + + +## Portable container equipment + +The 27 portable Chest records with Wear enabled can occupy their authored +clothing positions. All use the back slot (19), except Pre-Universe Storage +Device, which permits right shoulder/arm (20/22), wrists (26/28) and fingers (29/31). +The nine portable props and Book of Knowledge remain storage-only. A spoofed +instance type or unsupported quality cannot enable wear. + +The original item records were checked against resource type 1000020, including +matching payload SHA-256 values for all 37 portable templates. The independent +skill weight audit uses type 1000204. The results are retained in +`local/backpack-equipment-research/catalog-verification.json`. +Requirements below use effective skills, including ability trickle and existing +equipment modifiers; each numeric bound is strict unless equality is shown. + +| Container | Wear requirements | +| --- | --- | +| Small / Medium / Large | Adventuring > 20 / 99 / 179 | +| Pioneer / Modified Pioneer | Adventuring > 5 | +| Fourteen named Large variants | Adventuring > 199 | +| Robust | Adventuring > 229; level > 119 | +| Notum Threaded | Adventuring > 74; Intelligence > 419 | +| Beeping | Adventuring > 99; Computer Literacy > 799 | +| Pre-Universe | Adventuring > 49; title > 4; Time and Space > 199; Computer Literacy > 499 | +| Dust Collector | Adventuring > 99; Computer Literacy > 849 | +| Survival QL 50 / 150 | Adventuring > 99 / 299; Adventurer profession; title > 1 / 3 | +| Personal | Adventuring > 99 | + +Pre-Universe authors action 8 rather than the other bags' action 6. Its +requirements are still evaluated when equipping. All reviewed wear lists use +conjunctions of equality and strict-greater comparisons. No requirement language +or arbitrary template interpolation is inferred beyond these records. + +None of these bags authors EquipDelay. Original Beholder construction defaults +stat 211 to 10 centiseconds, so their pending move takes 100 milliseconds. +An explicitly authored delay on other equipment still takes precedence, including +zero. Requirements and free destination are checked again at completion, and a +failed database transaction publishes no successful move or equipment effects. +The default evidence is `ev_22cc89e69dfca9bb2f8e22e0f7390bc72c079499df2a60a911a38a859cb4942d` +in `local/backpack-equipment-research/native-evidence.json`. + +Survival QL 50..150 uses endpoints 206730/206731. Requirements and numeric +OnWear modifiers use the recovered float interpolation and rounding rule, as do +supported Metaplast items. Inventory entries, wear actions and live Chest objects +all preserve the same endpoint pair. QL 49/151 are rejected by the item editor; +other bags retain their authored QL. + +All unconditional OnWear Modify amounts are signed. This includes the Pioneer's ++3 percent and Modified Pioneer's -3 percent scale, their six +1 abilities, +First Aid +10, Swimming +25, Tutoring +150, Run Speed +10 and XPModifier +1. +The other authored modifiers include AC, resources, evades, initiative, perception, +concealment, damage types, critical chance and Pre-Universe's five NCU. +`server/backpack_catalog_effects_test.go` pins the exact amounts for all 27 +wearable records and Survival QL 100, including zero effects after removal. + +Effective skills include ability modifiers before applying the original weights. +Native `kkr.dll::FUN_10073fa0`, `FUN_10074a30` and `FUN_10075c60` establish that +order. The evidence IDs are +`ev_a4aca3401a3fced81dd6fffbccb18d260de0511d1bef5ce01cbf5393180106f8`, +`ev_7fddf02e6153943d8363079fd6f40792bfb5afdd539c72df37ab07897270a84b` +and `ev_5ad8baac16922030739eff30aa7952c874a9e04db2d5adbedc70bbcf7736934b` +in `local/backpack-equipment-research/vitals-evidence.json`. +This affects server wear checks, supported attack skills, treatment, nano casting, +regeneration and Body Development/Nano Pool derived resources. Trained profile +values remain unchanged. Held movement is anchored at the old speed before a +Run Speed modifier changes. + +Owner and observer initialization transmit derived health foundations separately +from direct equipment modifiers, so replaying OnWear applies each bonus once. +The same applies to the owner's maximum nano. Equipment changes refresh changed +health/nano foundations and attack rating explicitly: native ability dependency +notifications alone leave those cached display values stale. When removal lowers +a resource maximum below its current amount, the inventory transaction persists +the clamped value immediately, then updates memory and the client. + +Worn right-click use addresses page 102 and the clothing slot. Both request +routing and the owned-item handler accept this form, and ChestFullUpdate retains +that worn page/slot. Ordinary page 104 and direct Chest identity use continue to +share ownership and session checks. Contents retain their own instance identities +while their parent is worn, removed, reopened or reloaded. + +The server's existing combat calculation consumes supported attack skills, +initiative, armor and resource modifiers. Damage-type additions, critical chance +resolution and kill XP rewards still need their separate combat/progression +milestones. Their authored modifiers are preserved and displayed; that does not +establish their final combat or reward formulas. In particular, native XPModifier +starts at 100, so the Pioneer displays 101; no kill reward is invented here. + +The focused tests cover every wearable template and Pre-Universe position, +all other clothing positions, 54 skill/ability/level/profession boundaries, +contents across wear/restart, pending requirement changes, failed persistence, +signed scale, skill trickle, derived stat refreshes, resource clamping and held +movement. A real native protocol connection exercises worn use through the +world dispatcher, rather than only invoking its handler. + +## Equipment verification + +The full maintained Go suite passed with `ao/server` completing in 264.102s. +The focused race run over backpack equipment, contents, requirement boundaries, +character stats, vehicles and Metaplast passed in 176.542s. The fixed all-template +modifier table passed in 14.549s. An additional resource-removal save-failure test +passed under the race detector in 91.508s: neither the worn item, its modifiers, +current resources nor saved resources change when the transaction fails. +Logs are retained in `local/backpack-equipment-research/`. + +Two owned visitors exercised the unchanged published WASM client on the single +normal HTTPS preview. All 27 wearable templates and Survival QL 100 were worn +through native inventory gestures. Exact native modifier values and template +endpoints matched their paired SQLite snapshots. This includes the Pioneers' +opposite scale signs and ability-derived health/attack-rating refresh, every +named variant, Robust's 400 health and damage modifiers, Notum Threaded, Beeping, +Dust Collector and both Survival endpoints. Removal restored the baseline stats. +The Pre-Universe device was verified in its default right-finger slot (29), +including stacking its EnergyAC and NCU bonuses with Dust Collector. + +A Small Backpack accepted a NoDrop Mesh item while worn, and the filled bag +returned to ordinary inventory with the same contained identity. A fresh client +reopened that same filled Small Backpack after the preview restart; native Chest +slot 0 still contained Mesh instance 187. Resource tests +seeded only the owned wearer's vitals through the control editor: with Dust +Collector worn, health/nano 1921/1554 survived a normal preview restart and +matched the native maximums exactly. A second visitor saw health 1921, without +a duplicate equipment bonus. Removal then clamped the owner's current/maximum +health and nano to 1831/1464 in the client and SQLite; the observer saw health +1831 as well. + +The fixtures retain all 30 added instances and all 156 earlier item records and +locations. `local/backpack-equipment-smoke/tmp_verify.py` compares native roots, +instantiated Chest contents, quantities, endpoint pairs and exact equipment +modifiers with paired database snapshots; 53 owner snapshots passed. It excludes +private actor fields from +observer comparisons. There were no client exceptions or unimplemented adapter +calls. Screenshots and read-only native snapshots are retained in that directory. + +Pre-Universe placement beyond its default finger slot remains unverified in the +real client. Several attempted shoulder/wrist/finger gestures emitted no matching +move, despite all six server placement tests passing. Worn use and removal worked +after reconnect. Preserve the distinction between emitted packets, native model +state and cursor/window state while investigating; these attempts do not prove +that the source slot mask or server persistence is wrong. The backpack equipment +TODO remains open for these checks. The solid magenta Notum icon also needs +comparison with its original image resource before changing rendering. diff --git a/server/armor_damage_test.go b/server/armor_damage_test.go @@ -98,13 +98,13 @@ func TestArmorDamageBonusesFollowOwnershipAcrossRemovalAndRestart(t *testing.T) player := world.characters[1] world.handleInventory(world.clients[1], inventoryMovePacket(1, 66, 30)[20:]) world.advanceEquipment(world.clients[1].equipment.readyAt) - before := [3]uint32{player.inventory.equipmentBonus(90), player.inventory.equipmentBonus(91), player.inventory.equipmentBonus(94)} + before := [3]uint32{uint32(player.inventory.equipmentBonus(90)), uint32(player.inventory.equipmentBonus(91)), uint32(player.inventory.equipmentBonus(94))} world.handleInventory(world.clients[1], itemMovePacket(1, scenario.slot, 111)[20:]) world.advanceEquipment(world.clients[1].equipment.readyAt) world.handleInventory(world.clients[1], itemMovePacket(1, scenario.slot, 111)[20:]) restarted := newTestInventoryServer(t).characters[1] - after := [3]uint32{restarted.inventory.equipmentBonus(90), restarted.inventory.equipmentBonus(91), restarted.inventory.equipmentBonus(94)} + after := [3]uint32{uint32(restarted.inventory.equipmentBonus(90)), uint32(restarted.inventory.equipmentBonus(91)), uint32(restarted.inventory.equipmentBonus(94))} if before != [3]uint32{1001, 876, 151} || after != scenario.armor || len(restarted.inventory.Items) != 4 { t.Fatalf("armor contributions were duplicated or lost: before%v after%v items%+v", before, after, restarted.inventory.Items) diff --git a/server/armor_quality_test.go b/server/armor_quality_test.go @@ -91,7 +91,7 @@ func TestMetaplastIntermediateWearRemoveAndRestart(t *testing.T) { t.Fatal("quality or identity did not persist") } for i, armor := range piece.armor { - if got := restarted.characters[1].inventory.equipmentBonus(90 + uint32(i)); got != armor { + if got := restarted.characters[1].inventory.equipmentBonus(90 + uint32(i)); got != int32(armor) { t.Fatalf("AC%d: got %d, want %d", 90+i, got, armor) } } diff --git a/server/backpack_catalog_effects_test.go b/server/backpack_catalog_effects_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "fmt" + "testing" +) + +func TestBackpackCatalogEffectsAfterWearAndRemoval(t *testing.T) { + for _, scenario := range []struct { + template, quality, slot uint32 + bonuses map[uint32]int32 + }{ + {99228, 1, 19, map[uint32]int32{}}, + {99241, 1, 19, map[uint32]int32{}}, + {143832, 1, 19, map[uint32]int32{}}, + {152039, 1, 19, map[uint32]int32{16: 1, 17: 1, 18: 1, 19: 1, 20: 1, 21: 1, 123: 10, 138: 25, 141: 150, 156: 10, 319: 1, 360: 3}}, + {156831, 1, 19, map[uint32]int32{16: 1, 17: 1, 18: 1, 19: 1, 20: 1, 21: 1, 123: 10, 138: 25, 141: 150, 156: 10, 319: 1, 360: -3}}, + {157682, 1, 19, map[uint32]int32{103: 5, 118: 5, 155: 5}}, + {157683, 1, 19, map[uint32]int32{149: 10, 221: 20}}, + {157684, 1, 19, map[uint32]int32{135: 5, 136: 5, 164: 5, 165: 5}}, + {157685, 1, 19, map[uint32]int32{119: 10, 380: 2}}, + {157686, 1, 19, map[uint32]int32{95: 280}}, + {157687, 1, 19, map[uint32]int32{138: 24}}, + {157688, 1, 19, map[uint32]int32{156: 24}}, + {157689, 1, 19, map[uint32]int32{}}, + {157690, 1, 19, map[uint32]int32{}}, + {157691, 1, 19, map[uint32]int32{}}, + {157692, 1, 19, map[uint32]int32{}}, + {157693, 1, 19, map[uint32]int32{}}, + {157694, 1, 19, map[uint32]int32{}}, + {157695, 1, 19, map[uint32]int32{}}, + {158790, 1, 19, map[uint32]int32{1: 400, 90: 900, 91: 900, 92: 900, 93: 600, 94: 900, 95: 900, 96: 900, 97: 900, 278: 60, 280: 60, 282: 60, 316: 60}}, + {164564, 140, 19, map[uint32]int32{90: 700, 91: 700, 92: 900, 93: 500, 94: 900, 95: 900, 96: 500, 97: 900, 221: 40}}, + {165201, 200, 19, map[uint32]int32{1: 45, 90: 1050, 91: 1050, 92: 950, 93: 950, 94: 950, 95: 550, 96: 950, 97: 550, 153: 15, 154: 15, 155: 15, 156: 15, 221: 45}}, + {168658, 200, 20, map[uint32]int32{92: 30, 181: 5}}, + {200461, 200, 19, map[uint32]int32{1: 90, 90: 1200, 91: 1200, 92: 1100, 93: 750, 94: 1100, 95: 1000, 96: 1000, 97: 750, 136: 15, 140: 5, 153: 30, 164: 15, 221: 90}}, + {206730, 50, 19, map[uint32]int32{90: 250, 91: 250, 92: 200, 93: 250, 94: 200, 95: 300, 96: 250, 97: 300, 136: 11}}, + {206731, 150, 19, map[uint32]int32{90: 750, 91: 750, 92: 600, 93: 750, 94: 600, 95: 900, 96: 750, 97: 900, 136: 33}}, + {207254, 1, 19, map[uint32]int32{}}, + {206730, 100, 19, map[uint32]int32{90: 500, 91: 500, 92: 400, 93: 500, 94: 400, 95: 600, 96: 500, 97: 600, 136: 22}}, + } { + t.Run(fmt.Sprintf("%d/QL%d", scenario.template, scenario.quality), func(t *testing.T) { + world, _ := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + player.stats.Body.Adventuring, player.stats.TradeRepair.ComputerLiteracy, player.stats.NanoAiding.TimeAndSpace = 1000, 1000, 1000 + player.stats.Abilities.Intelligence = 420 + player.level, player.profession = 200, 6 + world.saveUser_locked(player) + world.grantItem_locked(player, scenario.template) + player.inventory.Items[1].Quality = scenario.quality + world.saveInventory_locked(player, player.inventory) + + err := world.handleInventory(client, inventoryMovePacket(1, 65, scenario.slot)[20:]) + if client.equipment == nil { + t.Fatal("catalog wear rejected", err) + } + world.advanceEquipment(client.equipment.readyAt) + restarted := newTestInventoryServer(t).characters[1] + + for stat := uint32(0); stat <= 380; stat++ { + if player.inventory.equipmentBonus(stat) != scenario.bonuses[stat] || restarted.inventory.equipmentBonus(stat) != scenario.bonuses[stat] { + t.Fatal("catalog effect differs before or after restart", stat, scenario.bonuses[stat]) + } + } + + world.handleInventory(client, itemMovePacket(1, scenario.slot, 111)[20:]) + world.advanceEquipment(client.equipment.readyAt) + + for stat := uint32(0); stat <= 380; stat++ { + if player.inventory.equipmentBonus(stat) != 0 { + t.Fatal("removal retained a catalog effect", stat) + } + } + }) + } +} diff --git a/server/backpack_effects_test.go b/server/backpack_effects_test.go @@ -0,0 +1,197 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "math" + "reflect" + "testing" + "time" +) + +func TestPioneerBonusesIncludeSignedScaleAndAbilityTrickle(t *testing.T) { + for _, scenario := range []struct { + template uint32 + scale int32 + radius float64 + }{{152039, 3, 2.06}, {156831, -3, 1.94}} { + t.Run(fmt.Sprint(scenario.template), func(t *testing.T) { + world, conn := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + player.stats.Abilities = characterAbilitiesStats{12, 12, 12, 12, 12, 12} + player.health = player.maximumHealth() + world.saveUser_locked(player) + world.grantItem_locked(player, scenario.template) + conn.packets = nil + + err := world.handleInventory(client, inventoryMovePacket(1, 65, 19)[20:]) + if client.equipment == nil { + t.Fatal("Pioneer wear was rejected", err) + } + world.advanceEquipment(client.equipment.readyAt) + restarted := newTestInventoryServer(t).characters[1] + + if err != nil || player.inventory.equipmentBonus(360) != scenario.scale || player.inventory.equipmentBonus(319) != 1 || + math.Abs(float64(player.physicalExtent())-scenario.radius) > 0.00001 { + t.Fatal("signed scale or XP modifier was lost", err) + } + if player.effectiveAbility(16) != 13 || player.effectiveAbility(21) != 13 || player.baseStats().Abilities.Strength != 12 || + player.effectiveSkill(123, player.baseStats().NanoAiding.FirstAid, [6]uint32{0, 30, 0, 30, 40, 0}) != 18 || + player.effectiveSkill(141, player.baseStats().TradeRepair.Tutoring, [6]uint32{0, 0, 0, 100, 0, 0}) != 158 || + player.maximumHealth() != 40 || player.maximumNano() != 38 || restarted.maximumHealth() != 40 || restarted.maximumNano() != 38 { + t.Fatal("equipment abilities, skill bonuses or trickle disagree") + } + if len(conn.packets) != 5 || !bytes.Equal(conn.packets[2][29:37], []byte{0, 0, 0, 1, 0, 0, 0, 40}) || + !bytes.Equal(conn.packets[3][29:37], []byte{0, 0, 0, 221, 0, 0, 0, 38}) || + !bytes.Equal(conn.packets[4][29:37], []byte{0, 0, 0, 22, 0, 0, 0, 8}) { + t.Fatalf("native derived stat caches were not refreshed after wear: %x", conn.packets[2:]) + } + conn.packets = nil + + world.handleInventory(client, itemMovePacket(1, 19, 111)[20:]) + world.advanceEquipment(client.equipment.readyAt) + + if player.effectiveAbility(16) != 12 || player.inventory.equipmentBonus(360) != 0 || player.inventory.equipmentBonus(319) != 0 || + player.effectiveSkill(123, player.baseStats().NanoAiding.FirstAid, [6]uint32{0, 30, 0, 30, 40, 0}) != 7 || + player.maximumHealth() != 37 || player.maximumNano() != 35 { + t.Fatal("removal retained an equipment modifier") + } + if len(conn.packets) != 5 || !bytes.Equal(conn.packets[2][29:37], []byte{0, 0, 0, 1, 0, 0, 0, 37}) || + !bytes.Equal(conn.packets[3][29:37], []byte{0, 0, 0, 221, 0, 0, 0, 35}) || + !bytes.Equal(conn.packets[4][29:37], []byte{0, 0, 0, 22, 0, 0, 0, 7}) { + t.Fatal("native derived stat caches were not refreshed after removal", len(conn.packets)) + } + }) + } +} + +func TestBackpackResourceRemovalClampsMemoryAndDatabaseBeforeReply(t *testing.T) { + world, conn := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + player.stats.Body.Adventuring, player.stats.TradeRepair.ComputerLiteracy = 98, 848 + world.grantItem_locked(player, 200461) + world.handleInventory(client, inventoryMovePacket(1, 65, 19)[20:]) + world.advanceEquipment(client.equipment.readyAt) + if player.maximumHealth() != 127 || player.maximumNano() != 125 { + t.Fatal("Dust Collector resource bonuses missing") + } + player.health, player.nano = 127, 125 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + packet := targetPacket(fullCharacterPacket(player)) + shadow := targetPacket(characterPacket(player)) + if !bytes.Contains(packet, binary.BigEndian.AppendUint32(binary.BigEndian.AppendUint32(nil, 1), 37)) || + !bytes.Contains(packet, binary.BigEndian.AppendUint32(binary.BigEndian.AppendUint32(nil, 221), 35)) || + binary.BigEndian.Uint32(shadow[87+len(player.name):]) != 37 { + t.Fatal("initialization baked the direct modifiers into the base resource stats") + } + conn.packets = nil + + err := world.handleInventory(client, itemMovePacket(1, 19, 111)[20:]) + world.advanceEquipment(client.equipment.readyAt) + restarted := newTestInventoryServer(t).characters[1] + + if err != nil || player.health != 37 || player.nano != 35 || restarted.health != 37 || restarted.nano != 35 || len(conn.packets) != 4 { + t.Fatal("removal lost atomic resource clamping or its owner updates", err, len(conn.packets)) + } + if binary.BigEndian.Uint32(conn.packets[2][16:20]) != 0x3710256c || binary.BigEndian.Uint32(conn.packets[3][29:33]) != 214 { + t.Fatal("resource clamp did not update the native client") + } +} + +func TestBackpackPendingWearRechecksRequirementsAndSaveFailure(t *testing.T) { + for _, failure := range []string{"requirement changed", "database closed"} { + t.Run(failure, func(t *testing.T) { + world, conn := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + player.stats.Body.Adventuring = 19 + world.grantItem_locked(player, 99228) + before := player.inventory + world.handleInventory(client, inventoryMovePacket(1, 65, 19)[20:]) + if client.equipment == nil { + t.Fatal("qualifying initial wear was rejected") + } + if failure == "requirement changed" { + player.stats.Body.Adventuring = 18 + } else { + world.db.Close() + } + + world.advanceEquipment(client.equipment.readyAt) + restarted := newTestInventoryServer(t).characters[1] + + if client.equipment != nil || !reflect.DeepEqual(player.inventory, before) || + restarted.inventory.Items[1].Slot != 65 || len(conn.packets) != 2 { + t.Fatal("failed completion changed inventory or left the native move pending") + } + }) + } +} + +func TestBackpackResourceRemovalSaveFailureRetainsVitalsAndBonuses(t *testing.T) { + world, conn := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.stats.Body.Adventuring, player.stats.TradeRepair.ComputerLiteracy = 98, 848 + world.grantItem_locked(player, 200461) + world.handleInventory(client, inventoryMovePacket(1, 65, 19)[20:]) + world.advanceEquipment(client.equipment.readyAt) + player.health, player.nano = 127, 125 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + conn.packets = nil + world.db.Close() + + err := world.handleInventory(client, itemMovePacket(1, 19, 111)[20:]) + world.advanceEquipment(client.equipment.readyAt) + restarted := newTestInventoryServer(t).characters[1] + + expected := []ownedItem{ + {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1}, + {ID: 2, Type: 51017, Template: 200461, Quality: 200, Slot: 19, Count: 1}, + } + if err != nil || client.equipment != nil || !reflect.DeepEqual(player.inventory.Items, expected) || !reflect.DeepEqual(restarted.inventory.Items, expected) || + player.health != 127 || player.nano != 125 || restarted.health != 127 || restarted.nano != 125 || + player.maximumHealth() != 127 || player.maximumNano() != 125 || len(conn.packets) != 1 { + t.Fatal("failed removal changed equipment, resources or published success", err, len(conn.packets)) + } + if binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x47537a24 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 19 { + t.Fatal("failed removal did not restore the native equipment slot") + } +} + +func TestBackpackSpeedChangeAnchorsHeldMovement(t *testing.T) { + world, _ := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + player.stats.Body.Adventuring = 198 + player.position, player.rotation, player.running = [3]float32{}, [4]float32{0, 0, 0, 1}, true + player.health = player.maximumHealth() + world.grantItem_locked(player, 157688) + world.handleInventory(client, inventoryMovePacket(1, 65, 19)[20:]) + if client.equipment == nil { + t.Fatal("Speeder wear rejected") + } + finish := client.equipment.readyAt + client.forward, client.movementStarted = 1, finish.Add(-2*time.Second) + + world.advanceEquipment(finish) + + if player.position != [3]float32{0, 0, 9} || client.movementStarted != finish || player.inventory.equipmentBonus(156) != 24 { + t.Fatal("wear retroactively applied the new movement speed") + } + + world.handleInventory(client, itemMovePacket(1, 19, 111)[20:]) + finish = client.equipment.readyAt + client.movementStarted = finish.Add(-2 * time.Second) + world.advanceEquipment(finish) + + if math.Abs(float64(player.position[2])-18.24) > 0.00001 || client.movementStarted != finish || player.inventory.equipmentBonus(156) != 0 { + t.Fatal("removal retroactively applied the old movement speed") + } +} diff --git a/server/backpack_equipment.go b/server/backpack_equipment.go @@ -0,0 +1,55 @@ +package main + +import "ao/server/gamedata" + +func (item ownedItem) isWearableContainer() bool { + return item.isPortableContainer() && itemStat(gamedata.ItemTemplates[item.Template], 30)&4 != 0 && + (item.Quality == *gamedata.ItemTemplates[item.Template].Quality || item.isBackpackOfSurvival()) +} + +func (character *character) canWearContainer(item ownedItem) bool { + low, high := item.templateIDs() + first, second := gamedata.ItemTemplates[low], gamedata.ItemTemplates[high] + stats := character.baseStats() + for sectionIndex, section := range first.Sections { + if section.Actions == nil { + continue + } + for actionIndex, action := range *section.Actions { + if action.Type != 6 && action.Type != 8 { + continue + } + for index, requirement := range action.Requirements { + // Portable-container wear lists contain equality, strict bounds and AND. + if requirement.Operator == 4 { + continue + } + var actual uint32 + switch requirement.Stat { + case 19: + actual = character.effectiveAbility(19) + case 37: + actual = character.titleLevel() + case 54: + actual = uint32(character.level) + case 60: + actual = uint32(max(1, character.profession)) + case 131: + actual = character.effectiveSkill(131, stats.NanoAiding.TimeAndSpace, [6]uint32{0, 20, 0, 80, 0, 0}) + case 137: + actual = character.effectiveSkill(137, stats.Body.Adventuring, [6]uint32{20, 50, 30, 0, 0, 0}) + case 161: + actual = character.effectiveSkill(161, stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) + default: + return false + } + value := interpolateItemValue(requirement.Value, (*second.Sections[sectionIndex].Actions)[actionIndex].Requirements[index].Value, *first.Quality, *second.Quality, item.Quality) + if requirement.Operator == 0 && int32(actual) != value || requirement.Operator == 2 && int32(actual) <= value { + return false + } + } + return true + } + } + return false +} diff --git a/server/backpack_equipment_test.go b/server/backpack_equipment_test.go @@ -0,0 +1,130 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "net" + "reflect" + "testing" + "time" +) + +func TestBackpackWornUseThroughNativeConnection(t *testing.T) { + fixture, _ := newPortableContainerWorld(t, 99228) + fixture.characters[1].inventory.Items[2].Slot = 19 + if err := fixture.saveInventory_locked(fixture.characters[1], fixture.characters[1].inventory); err != nil { + t.Fatal(err) + } + world := newTestInventoryServer(t) + client, connection := net.Pipe() + client.SetDeadline(time.Now().Add(5 * time.Second)) + done := make(chan error, 1) + go func() { defer connection.Close(); done <- world.serveWorldConnection(connection) }() + t.Cleanup(func() { + client.Close() + if err := <-done; err != nil { + t.Error(err) + } + }) + cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) + binary.BigEndian.PutUint16(cookie, 0xdfdf) + client.Write(cookie) + for { + packet, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + if binary.BigEndian.Uint32(packet[16:20]) == 0x5f52412e { + break + } + } + client.Write(targetPacket(n3Packet(0x570c2039, 50000, 1, nil))) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } + request := backpackUseRequest(1, 19, 1) + binary.BigEndian.PutUint32(request[60:64], 102) + + client.Write(targetPacket(request)) + var replies [][]byte + for range 3 { + packet, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + replies = append(replies, packet) + } + + if binary.BigEndian.Uint32(replies[0][16:20]) != 0x52526858 || + binary.BigEndian.Uint32(replies[1][16:20]) != 0x465a5d73 || replies[1][53] != 102 || replies[1][54] != 19 || + binary.BigEndian.Uint32(replies[2][16:20]) != 0x4e536976 { + t.Fatal("native worn use did not create and open the equipped Chest") + } +} + +func TestPortableContainerWearCatalogContentsAndRestart(t *testing.T) { + for _, container := range portableContainerCatalog { + slots := []uint32{19} + if container.template == 168658 { + slots = []uint32{20, 22, 26, 28, 29, 31} + } + for _, slot := range slots { + t.Run(fmt.Sprintf("%d/slot%d", container.template, slot), func(t *testing.T) { + world, conn := newPortableContainerWorld(t, container.template) + player, client := world.characters[1], world.clients[1] + player.stats.Body.Adventuring = 1000 + player.stats.TradeRepair.ComputerLiteracy = 1000 + player.stats.NanoAiding.TimeAndSpace = 1000 + player.stats.Abilities.Intelligence = 1000 + player.level, player.profession = 200, 6 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 1)[20:]) + world.handleInventory(client, backpackMoveRequest(104, 67, 51017, 3, 111)[20:]) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + conn.packets = nil + wearable := container.template != 99302 && container.template > 23161 + + err = world.handleInventory(client, inventoryMovePacket(1, 66, slot)[20:]) + + if err != nil { + t.Fatal(err) + } + if !wearable { + after, err := readTestItemStore(world) + if err != nil || !bytes.Equal(before, after) || client.equipment != nil || len(conn.packets) != 2 { + t.Fatal("storage-only container was equipped or changed", err) + } + return + } + if client.equipment == nil { + t.Fatal("authored container wear was rejected") + } + + world.advanceEquipment(client.equipment.readyAt) + restarted := newTestInventoryServer(t) + request := backpackUseRequest(1, slot, 2) + binary.BigEndian.PutUint32(request[60:64], 102) + client.backpacks = nil + err = world.handleOwnedItemUse(client, request[20:]) + + expected := ownedItem{ID: 3, Type: 51017, Template: container.template, Quality: container.quality, Slot: slot, Count: 1} + if err != nil || restarted.characters[1].inventory.Items[2] != expected || len(conn.packets) != 5 { + t.Fatal("worn container identity, persistence or use failed", err, len(conn.packets)) + } + if !reflect.DeepEqual(player.inventory.Containers[3], []ownedItem{{ID: 4, Type: 51018, Template: 121567, Quality: 1, Slot: 0, Count: 1}}) || + !reflect.DeepEqual(restarted.characters[1].inventory.Containers[3], player.inventory.Containers[3]) { + t.Fatal("wearing the container changed its contents") + } + if conn.packets[3][53] != 102 || uint32(conn.packets[3][54]) != slot { + t.Fatal("worn Chest creation used an ordinary inventory page") + } + }) + } + } +} diff --git a/server/backpack_quality_test.go b/server/backpack_quality_test.go @@ -0,0 +1,94 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "net/http/httptest" + "net/url" + "testing" +) + +func TestBackpackOfSurvivalInterpolatesEffectsAndNativeEndpoints(t *testing.T) { + for _, scenario := range []struct { + quality, armor, energy, cold, perception uint32 + }{ + {51, 255, 204, 306, 11}, + {100, 500, 400, 600, 22}, + {101, 505, 404, 606, 22}, + {149, 745, 596, 894, 33}, + } { + for _, template := range []uint32{206730, 206731} { + t.Run(fmt.Sprintf("%d/QL%d", template, scenario.quality), func(t *testing.T) { + world, conn := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + player.stats.Body.Adventuring, player.level, player.profession = 1000, 200, 6 + world.saveUser_locked(player) + world.grantItem_locked(player, template) + player.inventory.Items[1].Quality = scenario.quality + world.saveInventory_locked(player, player.inventory) + + err := world.handleInventory(client, inventoryMovePacket(1, 65, 19)[20:]) + if client.equipment == nil { + t.Fatal("intermediate quality wear rejected", err) + } + world.advanceEquipment(client.equipment.readyAt) + restarted := newTestInventoryServer(t).characters[1] + snapshot := targetPacket(fullCharacterPacket(restarted)) + chest := backpackPacket(1, player.playfield, player.inventory.Items[1]) + + expected := [8]uint32{scenario.armor, scenario.armor, scenario.energy, scenario.armor, scenario.energy, scenario.cold, scenario.armor, scenario.cold} + for index, amount := range expected { + if restarted.inventory.equipmentBonus(90+uint32(index)) != int32(amount) { + t.Fatal("interpolated AC differs from the native rounding rule", index) + } + } + if restarted.inventory.equipmentBonus(136) != int32(scenario.perception) || len(conn.packets) != 2 || + restarted.inventory.Items[1].ID != 2 || restarted.inventory.Items[1].Quality != scenario.quality { + t.Fatal("interpolated skill, identity or quality changed") + } + var entry, action []byte + for _, value := range []uint32{2, 206730, 206731, scenario.quality, 0} { + entry = binary.BigEndian.AppendUint32(entry, value) + } + for _, value := range []uint32{206730, 206731, scenario.quality, 1, 6, 102, 19, 0, 0} { + action = binary.BigEndian.AppendUint32(action, value) + } + if !bytes.Contains(snapshot, entry) || !bytes.Equal(conn.packets[1][29:65], action) || + !bytes.Contains(chest, binary.BigEndian.AppendUint32(binary.BigEndian.AppendUint32(nil, 702), 206730)) || + !bytes.Contains(chest, binary.BigEndian.AppendUint32(binary.BigEndian.AppendUint32(nil, 703), 206731)) { + t.Fatal("one native path lost the interpolated endpoint pair") + } + }) + } + } +} + +func TestControlBackpackOfSurvivalQualityBounds(t *testing.T) { + for _, quality := range []uint32{49, 50, 51, 100, 149, 150, 151} { + t.Run(fmt.Sprint(quality), func(t *testing.T) { + useNPCData(t, testNPCData()) + world := newTestServer(t) + postControlForm(world, "/control/items", url.Values{"template": {"206730"}}) + before, _ := readTestItemStore(world) + data := fmt.Sprintf("type: 51017\ntemplate: 206730\nquality: %d\ncount: 1\n", quality) + + response := postControlForm(world, "/control/items/1", url.Values{"data": {data}}) + after, err := readTestItemStore(world) + page := httptest.NewRecorder() + world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/items/1", nil)) + + if err != nil || page.Code != 200 { + t.Fatal(err, page.Code) + } + if quality == 49 || quality == 151 { + if response.Code != 400 || !bytes.Equal(before, after) { + t.Fatal("unsupported quality changed the stored container") + } + } else if response.Code != 303 || newTestInventoryServer(t).items[1].Quality != quality { + t.Fatal("supported container quality did not persist", response.Code) + } + }) + } +} diff --git a/server/backpack_requirements_test.go b/server/backpack_requirements_test.go @@ -0,0 +1,136 @@ +package main + +import ( + "bytes" + "fmt" + "testing" + "time" +) + +func TestBackpackWearRequirementBoundaries(t *testing.T) { + for _, scenario := range []struct { + template, quality, stat uint32 + value uint16 + allowed bool + }{ + {99228, 1, 137, 18, false}, {99228, 1, 137, 19, true}, + {99241, 1, 137, 97, false}, {99241, 1, 137, 98, true}, + {143832, 1, 137, 177, false}, {143832, 1, 137, 178, true}, + {152039, 1, 137, 3, false}, {152039, 1, 137, 4, true}, + {156831, 1, 137, 3, false}, {156831, 1, 137, 4, true}, + {157682, 1, 137, 197, false}, {157682, 1, 137, 198, true}, + {158790, 1, 137, 227, false}, {158790, 1, 137, 228, true}, + {158790, 1, 54, 119, false}, {158790, 1, 54, 120, true}, + {164564, 140, 137, 72, false}, {164564, 140, 137, 73, true}, + {164564, 140, 19, 419, false}, {164564, 140, 19, 420, true}, + {165201, 200, 137, 97, false}, {165201, 200, 137, 98, true}, + {165201, 200, 161, 797, false}, {165201, 200, 161, 798, true}, + {168658, 200, 137, 47, false}, {168658, 200, 137, 48, true}, + {168658, 200, 131, 197, false}, {168658, 200, 131, 198, true}, + {168658, 200, 161, 497, false}, {168658, 200, 161, 498, true}, + {168658, 200, 54, 149, false}, {168658, 200, 54, 150, true}, + {200461, 200, 161, 847, false}, {200461, 200, 161, 848, true}, + {206730, 50, 137, 97, false}, {206730, 50, 137, 98, true}, + {206730, 50, 60, 5, false}, {206730, 50, 60, 6, true}, + {206730, 50, 54, 14, false}, {206730, 50, 54, 15, true}, + {206730, 100, 137, 197, false}, {206730, 100, 137, 198, true}, + {206730, 100, 54, 49, false}, {206730, 100, 54, 50, true}, + {206731, 150, 137, 297, false}, {206731, 150, 137, 298, true}, + {206731, 150, 54, 99, false}, {206731, 150, 54, 100, true}, + {207254, 1, 137, 97, false}, {207254, 1, 137, 98, true}, + } { + t.Run(fmt.Sprintf("%d/QL%d/stat%d/%d", scenario.template, scenario.quality, scenario.stat, scenario.value), func(t *testing.T) { + world, conn := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + player.stats.Body.Adventuring = 1000 + player.stats.TradeRepair.ComputerLiteracy = 1000 + player.stats.NanoAiding.TimeAndSpace = 1000 + player.level, player.profession = 200, 6 + if scenario.template == 164564 { + player.stats.Abilities.Intelligence = 420 + } + switch scenario.stat { + case 19: + player.stats.Abilities.Intelligence = scenario.value + case 54: + player.level = scenario.value + case 60: + player.profession = scenario.value + case 131: + player.stats.NanoAiding.TimeAndSpace = scenario.value + case 137: + player.stats.Body.Adventuring = scenario.value + case 161: + player.stats.TradeRepair.ComputerLiteracy = scenario.value + } + if granted, err := world.grantItem_locked(player, scenario.template); err != nil || !granted { + t.Fatal(granted, err) + } + player.inventory.Items[1].Quality = scenario.quality + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + slot := uint32(19) + if scenario.template == 168658 { + slot = 20 + } + + start := time.Now() + err = world.handleInventory(client, inventoryMovePacket(1, 65, slot)[20:]) + + if err != nil || (client.equipment != nil) != scenario.allowed { + t.Fatal("wear boundary disagrees with the authored requirement", err) + } + if !scenario.allowed { + after, err := readTestItemStore(world) + if err != nil || !bytes.Equal(before, after) || len(conn.packets) != 2 { + t.Fatal("rejected wear changed or lost an item", err) + } + return + } + if client.equipment.readyAt.Before(start.Add(100*time.Millisecond)) || client.equipment.readyAt.After(time.Now().Add(100*time.Millisecond)) { + t.Fatal("container did not inherit the native 10-centisecond equip delay") + } + world.advanceEquipment(client.equipment.readyAt) + if player.inventory.Items[1].Slot != slot || len(conn.packets) != 2 { + t.Fatal("qualified container wear did not complete") + } + }) + } +} + +func TestBackpackRejectsEveryUnauthoredEquipmentSlot(t *testing.T) { + for _, template := range []uint32{99228, 168658} { + t.Run(fmt.Sprint(template), func(t *testing.T) { + world, conn := newEquipmentWorld(t) + t.Cleanup(func() { world.db.Close() }) + player, client := world.characters[1], world.clients[1] + world.grantItem_locked(player, template) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + for slot := uint32(0); slot < 64; slot++ { + if template == 99228 && slot == 19 || template == 168658 && (slot == 20 || slot == 22 || slot == 26 || slot == 28 || slot == 29 || slot == 31) { + continue + } + conn.packets = nil + + err := world.handleInventory(client, inventoryMovePacket(1, 65, slot)[20:]) + + if err != nil || client.equipment != nil || len(conn.packets) != 2 || player.inventory.Items[1].Slot != 65 { + t.Fatalf("unauthored slot %d accepted or left pending: %v", slot, err) + } + } + after, err := readTestItemStore(world) + if err != nil || !bytes.Equal(before, after) { + t.Fatal("rejected slots changed durable item state", err) + } + }) + } +} diff --git a/server/backpacks.go b/server/backpacks.go @@ -25,9 +25,14 @@ func backpackPacket(owner, playfield uint32, item ownedItem) []byte { for _, value := range []uint32{11, 50000, owner, playfield, 0, 0} { body = binary.BigEndian.AppendUint32(body, value) } - body = append(body, 104, byte(item.Slot)) + page := byte(104) + if item.Slot < 64 { + page = 102 + } + body = append(body, page, byte(item.Slot)) body = binary.BigEndian.AppendUint32(body, 5*1009) - for _, value := range []uint32{23, item.Template, 701, item.Quality, 702, item.Template, 703, item.Template, 0, 2, 0, 1009, 3} { + low, high := item.templateIDs() + for _, value := range []uint32{23, item.Template, 701, item.Quality, 702, low, 703, high, 0, 2, 0, 1009, 3} { body = binary.BigEndian.AppendUint32(body, value) } return n3Packet(0x465a5d73, 51017, item.ID, body) @@ -65,7 +70,7 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 3 || binary.BigEndian.Uint32(body[28:32]) > 1 || binary.BigEndian.Uint32(body[32:36]) != 50000 || binary.BigEndian.Uint32(body[36:40]) != client.id || - (binary.BigEndian.Uint32(body[40:44]) != 104 && binary.BigEndian.Uint32(body[40:44]) != 51017) { + (binary.BigEndian.Uint32(body[40:44]) != 104 && binary.BigEndian.Uint32(body[40:44]) != 102 && binary.BigEndian.Uint32(body[40:44]) != 51017) { return nil } sequence := binary.BigEndian.Uint32(body[20:24]) @@ -95,8 +100,11 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error if page == 104 && (slot < 64 || slot >= 94) { return nil } + if page == 102 && (slot < 16 || slot >= 32) { + return nil + } item := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { - return item.isPortableContainer() && (page == 104 && item.Slot == slot || page == 51017 && item.ID == slot) + return item.isPortableContainer() && ((page == 104 || page == 102) && item.Slot == slot || page == 51017 && item.ID == slot) }) reply := append([]byte(nil), body[16:]...) if item < 0 { diff --git a/server/combat.go b/server/combat.go @@ -94,13 +94,13 @@ func (character *character) attackDelays() (time.Duration, time.Duration) { stats := character.baseStats() weapon := character.attackWeapon() if weapon != nil { - initiative := stats.effectiveSkill(stats.Speed.MeleeInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) + initiative := character.effectiveSkill(118, stats.Speed.MeleeInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) if itemStat(weapon, 420) == 2 { - initiative = stats.effectiveSkill(stats.Speed.RangedInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) + initiative = character.effectiveSkill(119, stats.Speed.RangedInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) } return weaponDelays(weapon, int32(initiative), character.aggDef) } - initiative := stats.effectiveSkill(stats.Speed.PhysicalInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) + initiative := character.effectiveSkill(120, stats.Speed.PhysicalInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) return weaponDelays(nil, int32(initiative), character.aggDef) } @@ -124,16 +124,28 @@ func (character *character) maximumHealth() uint32 { // kkr.dll FUN_10075910; breed 1000203 and profession/title 1000200 coefficients. stats := [8][3]uint32{{2, 2, 2}, {10, 6, 3}, {15, 5, 3}, {10, 5, 2}, {25, 6, 4}, {15, 8, 6}, {2, 2, 2}, {2, 2, 2}}[character.appearance>>4&7] base := character.baseStats() - bodyDevelopment := base.effectiveSkill(base.Body.BodyDevelopment, [6]uint32{0, 0, 100, 0, 0, 0}) - return stats[0] + uint32(character.level)*(stats[1]+gamedata.ProfessionTitles[max(1, character.profession)].Health[character.titleLevel()-1]) + bodyDevelopment*stats[2] + bodyDevelopment := character.effectiveSkill(152, base.Body.BodyDevelopment, [6]uint32{0, 0, 100, 0, 0, 0}) + return stats[0] + uint32(character.level)*(stats[1]+gamedata.ProfessionTitles[max(1, character.profession)].Health[character.titleLevel()-1]) + bodyDevelopment*stats[2] + uint32(character.inventory.equipmentBonus(1)) } func (character *character) maximumNano() uint32 { // kkr.dll FUN_10075910 uses real profession and stored title, as for health. stats := [8][3]uint32{{2, 2, 2}, {10, 4, 3}, {10, 3, 3}, {15, 5, 4}, {8, 2, 2}, {50, 2, 1}, {2, 2, 2}, {2, 2, 2}}[character.appearance>>4&7] base := character.baseStats() - nanoPool := base.effectiveSkill(base.Body.NanoPool, [6]uint32{0, 0, 10, 10, 10, 70}) - return stats[0] + uint32(character.level)*(stats[1]+gamedata.ProfessionTitles[max(1, character.profession)].Nano[character.titleLevel()-1]) + nanoPool*stats[2] + nanoPool := character.effectiveSkill(132, base.Body.NanoPool, [6]uint32{0, 0, 10, 10, 10, 70}) + return stats[0] + uint32(character.level)*(stats[1]+gamedata.ProfessionTitles[max(1, character.profession)].Nano[character.titleLevel()-1]) + nanoPool*stats[2] + uint32(character.inventory.equipmentBonus(221)) +} + +func (character *character) attackRating() uint32 { + stats := character.baseStats() + weapon := character.attackWeapon() + if weapon == nil { + return character.effectiveSkill(100, stats.Body.MartialArts, [6]uint32{20, 50, 0, 0, 0, 30}) + } + if itemStat(weapon, 420) == 2 { + return character.effectiveSkill(112, stats.Ranged.Pistol, [6]uint32{0, 60, 0, 0, 40, 0}) + } + return character.effectiveSkill(103, stats.Melee.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0}) } func (attacker *character) normalDamage(target *character, roll func(uint32) uint32) uint32 { @@ -154,19 +166,16 @@ func (attacker *character) normalDamage(target *character, roll func(uint32) uin // NPC attack skills remain unknown. Fractional endpoint truncation is provisional. if !attacker.npc { stats := attacker.baseStats() - rating := stats.effectiveSkill(stats.Body.MartialArts, [6]uint32{20, 50, 0, 0, 0, 30}) + rating := attacker.attackRating() if weapon != nil { - rating = stats.effectiveSkill(stats.Melee.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0}) - // Native OE checks every supported weapon requirement. // FUN_10090f10/100ab8a0: tier = trunc(5*(1-skill/requirement)). - brawling := stats.effectiveSkill(stats.Body.Brawling, [6]uint32{60, 0, 40, 0, 0, 0}) - fastAttack := stats.effectiveSkill(stats.Melee.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0}) + brawling := attacker.effectiveSkill(142, stats.Body.Brawling, [6]uint32{60, 0, 40, 0, 0, 0}) + fastAttack := attacker.effectiveSkill(147, stats.Melee.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0}) skill := min(rating, brawling, fastAttack) requirement := uint32(4) if itemStat(weapon, 420) == 2 { - rating = stats.effectiveSkill(stats.Ranged.Pistol, [6]uint32{0, 60, 0, 0, 40, 0}) - skill = min(rating, stats.effectiveSkill(stats.Ranged.FlingShot, [6]uint32{0, 100, 0, 0, 0, 0})) + skill = min(rating, attacker.effectiveSkill(150, stats.Ranged.FlingShot, [6]uint32{0, 100, 0, 0, 0, 0})) requirement = 5 } if skill < requirement { @@ -182,22 +191,23 @@ func (attacker *character) normalDamage(target *character, roll func(uint32) uin // Period AC rule: reduce the rolled hit without crossing the weapon minimum. // Truncating AC/10 before subtraction is provisional integer ordering. damage := minimum + roll(maximum-minimum+1) - return damage - min(damage-minimum, target.inventory.equipmentBonus(damageType)/10) + return damage - min(damage-minimum, uint32(target.inventory.equipmentBonus(damageType))/10) } func (character *character) physicalExtent() float32 { // FUN_1005a790 scales CharRadius421 by Scale360; Kodaik OnWear sets it to 20. - scale := uint32(100) + scale := int32(100) if character.driving() { scale = 20 } + scale += character.inventory.equipmentBonus(360) radius := uint32(2) if monster, exists := gamedata.MonsterTemplates[character.monsterData]; exists { if value, exists := monster.Stats[421]; exists { radius = value } } - return float32(int32(scale*radius)) * float32(0.01) + return float32(scale*int32(radius)) * float32(0.01) } func (server *server) combatInRange_locked(attacker, target *character, now time.Time) bool { diff --git a/server/control_items.go b/server/control_items.go @@ -10,7 +10,7 @@ type controlItemSlot struct { func controlItemSlots(inventory playerInventory, item ownedItem) []controlItemSlot { var slots []controlItemSlot for slot := uint32(1); slot < 94; slot++ { - if slot < 64 && (!item.fitsEquipmentSlot(slot) || slot >= 9 && slot <= 14 && slot-9 >= inventory.equipmentBonus(45)) { + if slot < 64 && (!item.fitsEquipmentSlot(slot) || slot >= 9 && slot <= 14 && int32(slot-9) >= inventory.equipmentBonus(45)) { continue } if !slices.ContainsFunc(inventory.Items, func(other ownedItem) bool { return other.Slot == slot }) { diff --git a/server/equipment.go b/server/equipment.go @@ -21,6 +21,9 @@ func (item ownedItem) isKineticAxe() bool { } 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 + } if item.isKodaik() || item.isYalmaha() { return slot == 1 } @@ -44,31 +47,34 @@ func (item ownedItem) fitsEquipmentSlot(slot uint32) bool { } func (character *character) canEquip(item ownedItem) bool { + if item.isWearableContainer() { + return character.canWearContainer(item) + } if item.isKodaik() { stats := character.baseStats() return gamedata.Playfields[character.playfield].Outdoor && !character.driving() && - stats.effectiveSkill(stats.Navigation.VehicleGround, [6]uint32{0, 20, 0, 20, 60, 0}) > 80 + character.effectiveSkill(166, stats.Navigation.VehicleGround, [6]uint32{0, 20, 0, 20, 60, 0}) > 80 } if item.isYalmaha() { stats := character.baseStats() return gamedata.Playfields[character.playfield].Outdoor && !character.driving() && - stats.effectiveSkill(stats.Navigation.VehicleAir, [6]uint32{0, 20, 0, 20, 60, 0}) > 80 + 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 stats.effectiveSkill(stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 5 + return character.effectiveSkill(161, stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 5 } if item.fitsEquipmentSlot(37) { stats := character.baseStats() - return stats.Abilities.Strength > 5 && stats.effectiveSkill(stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 10 + return character.effectiveAbility(16) > 5 && character.effectiveSkill(124, stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 10 } if item.isKineticAxe() { return character.canWieldKineticAxe() } if item.isFlechettePistol() { stats := character.baseStats() - return stats.effectiveSkill(stats.Ranged.Pistol, [6]uint32{0, 60, 0, 0, 40, 0}) > 5 && - stats.effectiveSkill(stats.Ranged.FlingShot, [6]uint32{0, 100, 0, 0, 0, 0}) > 5 + return character.effectiveSkill(112, stats.Ranged.Pistol, [6]uint32{0, 60, 0, 0, 40, 0}) > 5 && + character.effectiveSkill(150, stats.Ranged.FlingShot, [6]uint32{0, 100, 0, 0, 0, 0}) > 5 } if item.isMetaplast() { low, high := item.templateIDs() @@ -84,8 +90,8 @@ func (character *character) canEquip(item ownedItem) bool { } for index, requirement := range action.Requirements { value := interpolateItemValue(requirement.Value, (*second.Sections[sectionIndex].Actions)[actionIndex].Requirements[index].Value, *first.Quality, *second.Quality, item.Quality) - if requirement.Stat == 16 && int32(character.baseStats().Abilities.Strength) <= value || - requirement.Stat == 17 && int32(character.baseStats().Abilities.Agility) <= value { + if requirement.Stat == 16 && int32(character.effectiveAbility(16)) <= value || + requirement.Stat == 17 && int32(character.effectiveAbility(17)) <= value { return false } } @@ -96,9 +102,9 @@ func (character *character) canEquip(item ownedItem) bool { return false } -func (inventory playerInventory) equipmentBonus(stat uint32) uint32 { - // Supported equipment has unconditional positive OnWear Modify effects. - var bonus uint32 +func (inventory playerInventory) equipmentBonus(stat uint32) int32 { + // Supported equipment has unconditional OnWear Modify effects, including negatives. + var bonus int32 for _, item := range inventory.Items { if !item.fitsEquipmentSlot(item.Slot) { continue @@ -111,7 +117,7 @@ func (inventory playerInventory) equipmentBonus(stat uint32) uint32 { } for index, function := range *section.Functions { if function.ID == 53045 && uint32(*function.Arguments[0].Integer) == stat { - bonus += uint32(interpolateItemValue(*function.Arguments[1].Integer, *(*second.Sections[sectionIndex].Functions)[index].Arguments[1].Integer, *first.Quality, *second.Quality, item.Quality)) + bonus += interpolateItemValue(*function.Arguments[1].Integer, *(*second.Sections[sectionIndex].Functions)[index].Arguments[1].Integer, *first.Quality, *second.Quality, item.Quality) } } } @@ -120,7 +126,7 @@ func (inventory playerInventory) equipmentBonus(stat uint32) uint32 { } func (character *character) maximumNCU() uint32 { - return 8 + character.inventory.equipmentBonus(181) + return uint32(8 + character.inventory.equipmentBonus(181)) } func (character *character) canMoveEquipment(item ownedItem, destination uint32, now time.Time) bool { @@ -135,7 +141,7 @@ func (character *character) canMoveEquipment(item ownedItem, destination uint32, if item.Slot == 7 && slices.ContainsFunc(character.inventory.Items, func(other ownedItem) bool { return other.Slot >= 9 && other.Slot <= 14 }) { return false } - return destination < 9 || destination > 14 || destination-9 < character.inventory.equipmentBonus(45) + return destination < 9 || destination > 14 || int32(destination-9) < character.inventory.equipmentBonus(45) } func (character *character) attackWeapon() *gamedata.Item { @@ -162,9 +168,9 @@ func itemStat(item *gamedata.Item, stat uint32) uint32 { func (character *character) canWieldKineticAxe() bool { // Template 209283's Wield action requires all three effective skills > 4. stats := character.baseStats() - return stats.effectiveSkill(stats.Melee.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0}) >= 5 && - stats.effectiveSkill(stats.Body.Brawling, [6]uint32{60, 0, 40, 0, 0, 0}) >= 5 && - stats.effectiveSkill(stats.Melee.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0}) >= 5 + return character.effectiveSkill(103, stats.Melee.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0}) >= 5 && + character.effectiveSkill(142, stats.Body.Brawling, [6]uint32{60, 0, 40, 0, 0, 0}) >= 5 && + character.effectiveSkill(147, stats.Melee.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0}) >= 5 } func itemMovePacket(owner, source, destination uint32) []byte { @@ -233,10 +239,13 @@ func (server *server) beginEquipment_locked(client *worldClient, index int, dest } // Leave the owned item at its source until the catalog's equip delay expires. - delay := time.Duration(itemStat(gamedata.ItemTemplates[item.Template], 211)) * 10 * time.Millisecond - if item.fitsEquipmentSlot(37) { - // Beholder FUN_1008e840 defaults EquipDelay to 10; this implant has no override. - delay = 100 * time.Millisecond + // Beholder FUN_1008e840 defaults EquipDelay to 10 centiseconds. + delay := 100 * time.Millisecond + for _, stat := range gamedata.ItemTemplates[item.Template].Stats { + if stat[0] == 211 { + delay = time.Duration(stat[1]) * 10 * time.Millisecond + break + } } client.equipment = &equipmentMove{item.ID, item.Slot, destination, requestedSlot, time.Now().Add(delay)} return nil @@ -269,21 +278,26 @@ func (server *server) advanceEquipment(now time.Time) { } // Save the entire move before publishing inventory or appearance changes. - position := character.position - if move.source == 1 || move.destination == 1 { - position = predictedPosition_locked(character, client, now) - } item := character.inventory.Items[index] inventory := character.inventory inventory.Items = slices.Clone(character.inventory.Items) inventory.Items[index].Slot = move.destination + movementChanged := move.source == 1 || move.destination == 1 || inventory.equipmentBonus(156) != character.inventory.equipmentBonus(156) + position := character.position + if movementChanged { + position = predictedPosition_locked(character, client, now) + } + health, nano := character.health, character.nano + baseHealth := character.maximumHealth() - uint32(character.inventory.equipmentBonus(1)) + baseNano := character.maximumNano() - uint32(character.inventory.equipmentBonus(221)) + attackRating := character.attackRating() if err := server.saveInventory_locked(character, inventory); err != nil { log.Printf("Equipment: %v", err) updates[client] = append(updates[client], equipmentCorrectionPackets(client.id, move.source)...) continue } - if move.source == 1 || move.destination == 1 { - // Anchor held movement at the speed before the vehicle effect changed. + if movementChanged { + // Anchor held movement at the speed before the equipment effect changed. character.position = position client.movementStarted = now } @@ -305,6 +319,29 @@ func (server *server) advanceEquipment(now time.Time) { if move.source == 6 || move.destination == 6 { server.queueCombat_locked(updates, character, character, equippedWeaponPackets(character)...) } + // Ability modifiers change derived foundations that the native client caches. + for _, stat := range [][3]uint32{ + {1, baseHealth, character.maximumHealth() - uint32(character.inventory.equipmentBonus(1))}, + {221, baseNano, character.maximumNano() - uint32(character.inventory.equipmentBonus(221))}, + {22, attackRating, character.attackRating()}, + } { + if stat[1] != stat[2] { + body := binary.BigEndian.AppendUint32(nil, stat[0]) + body = binary.BigEndian.AppendUint32(body, stat[2]) + packet := n3Packet(0x2b333d6e, 50000, character.id, body) + if stat[0] == 221 { + updates[client] = append(updates[client], packet) + } else { + server.queueCombat_locked(updates, character, character, packet) + } + } + } + if character.health != health { + server.queueQuietHealth_locked(updates, character) + } + if character.nano != nano { + updates[client] = append(updates[client], nanoPointsPacket(character)) + } } server.mutex.Unlock() server.sendCombatUpdates(updates) diff --git a/server/implants.go b/server/implants.go @@ -29,7 +29,7 @@ func (server *server) useClinic_locked(client *worldClient, index int, body []by now := time.Now() accepted := client.selectedTarget == [2]uint32{50000, client.id} && slot >= 64 && slot < 94 && player.inventory.Items[index].Type == 51005 && player.inventory.Items[index].Template == 43552 && player.inventory.Items[index].Quality == 1 && - stats.effectiveSkill(stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 5 && !now.Before(player.treatmentLockedUntil) + player.effectiveSkill(124, stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 5 && !now.Before(player.treatmentLockedUntil) if accepted { // Save the cooldown and access window before acknowledging any authored effects. updated := *player diff --git a/server/insurance.go b/server/insurance.go @@ -38,7 +38,7 @@ func (server *server) handleTerminalUse(client *worldClient, body []byte) error // Borealis statel 0xc0040320 requires Computer Literacy > 90 and no combat. x, y, z := position[0]-636.4026, position[1]-66.81002, position[2]-728.8094 accepted = client.target && player.playfield == 800 && x*x+y*y+z*z <= 5*5 && player.fighting == 0 && - player.stats.effectiveSkill(player.stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 90 + player.effectiveSkill(161, player.stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 90 for _, attacker := range server.fighting { if attacker.fighting == player.id { accepted = false diff --git a/server/inventory.go b/server/inventory.go @@ -63,7 +63,7 @@ func (inventory playerInventory) validate() error { } deckSlots := inventory.equipmentBonus(45) for slot := uint32(9); slot <= 14; slot++ { - if slots[slot] && slot-9 >= deckSlots { + if slots[slot] && int32(slot-9) >= deckSlots { return fmt.Errorf("equipment in a disabled deck slot") } } @@ -101,10 +101,17 @@ func (server *server) saveInventory_locked(character *character, inventory playe if err != nil { return err } + healthMaximum, nanoMaximum := character.maximumHealth(), character.maximumNano() if err := server.writeItemStore_locked(store); err != nil { return err } character.inventory = inventory + if character.maximumHealth() < healthMaximum { + character.health = min(character.health, character.maximumHealth()) + } + if character.maximumNano() < nanoMaximum { + character.nano = min(character.nano, character.maximumNano()) + } return nil } diff --git a/server/item_pages.go b/server/item_pages.go @@ -285,8 +285,9 @@ func (server *server) editItem(w http.ResponseWriter, r *http.Request) { err = decodeUsers(strings.NewReader(r.FormValue("data")), &record) } definition := gamedata.ItemTemplates[record.Template] - if err != nil || definition == nil || definition.Quality == nil || record.Type != definition.HeaderWords[0] || record.Quality != *definition.Quality && !(ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).isMetaplast() { - http.Error(w, "Invalid item properties; use a catalog template and type, with an authored quality or supported Metaplast QL 1 through 200", http.StatusBadRequest) + item := ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality} + if err != nil || definition == nil || definition.Quality == nil || record.Type != definition.HeaderWords[0] || record.Quality != *definition.Quality && !item.isMetaplast() && !item.isBackpackOfSurvival() { + http.Error(w, "Invalid item properties; use the catalog type and authored quality, Metaplast QL 1 through 200, or Backpack of Survival QL 50 through 150", http.StatusBadRequest) return } server.updateMutex.Lock() diff --git a/server/item_quality.go b/server/item_quality.go @@ -25,15 +25,23 @@ func (item ownedItem) isMetaplast() bool { return item.Type == 51022 && low != 0 && item.Quality >= 1 && item.Quality <= 200 } +func (item ownedItem) isBackpackOfSurvival() bool { + return item.Type == 51017 && (item.Template == 206730 || item.Template == 206731) && item.Quality >= 50 && item.Quality <= 150 +} + func (item ownedItem) templateIDs() (uint32, uint32) { - if !item.isMetaplast() { + var low, high uint32 + if item.isMetaplast() { + low, high = metaplastTemplates(item.Template) + } else if item.isBackpackOfSurvival() { + low, high = 206730, 206731 + } else { return item.Template, item.Template } - low, high := metaplastTemplates(item.Template) - if item.Quality == 1 { + if item.Quality == *gamedata.ItemTemplates[low].Quality { return low, low } - if item.Quality == 200 { + if item.Quality == *gamedata.ItemTemplates[high].Quality { return high, high } return low, high diff --git a/server/main.go b/server/main.go @@ -443,7 +443,7 @@ func (server *server) serveWorldClient(client *worldClient) error { var err error if len(body) == 56 && binary.BigEndian.Uint32(body[24:28]) == 5 { err = server.handleReload(client, body) - } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 104 || binary.BigEndian.Uint32(body[40:44]) == 51017) { + } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 102 || binary.BigEndian.Uint32(body[40:44]) == 104 || binary.BigEndian.Uint32(body[40:44]) == 51017) { err = server.handleOwnedItemUse(client, body) } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 51005 || binary.BigEndian.Uint32(body[40:44]) == 51059) { err = server.handleTerminalUse(client, body) diff --git a/server/metaplast_test.go b/server/metaplast_test.go @@ -71,7 +71,7 @@ func TestMetaplastNativeWearRemoveAndRestart(t *testing.T) { t.Fatal("observer reconnect did not restore exactly one wear action") } for index, armor := range piece.armor { - if got := worn.inventory.equipmentBonus(90 + uint32(index)); got != armor { + if got := worn.inventory.equipmentBonus(90 + uint32(index)); got != int32(armor) { t.Fatalf("AC %d = %d, want %d", 90+index, got, armor) } } @@ -195,7 +195,7 @@ func TestMetaplastFullSuitKeepsSeparateSleeveContributions(t *testing.T) { } var before [8]uint32 for index := range before { - before[index] = player.inventory.equipmentBonus(90 + uint32(index)) + before[index] = uint32(player.inventory.equipmentBonus(90 + uint32(index))) } world.handleInventory(world.clients[1], itemMovePacket(1, 23, 111)[20:]) @@ -203,7 +203,7 @@ func TestMetaplastFullSuitKeepsSeparateSleeveContributions(t *testing.T) { restarted := newTestInventoryServer(t).characters[1] var after [8]uint32 for index := range after { - after[index] = restarted.inventory.equipmentBonus(90 + uint32(index)) + after[index] = uint32(restarted.inventory.equipmentBonus(90 + uint32(index))) } if before != [8]uint32{3500, 3059, 3500, 2622, 522, 522, 522, 522} || diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -36,7 +36,7 @@ func winterBiteCost() uint32 { func (player *character) winterBiteCastDelay() time.Duration { // kkr.dll 100651b4..1006526b stores initiative reduction before the final duration. stats := player.baseStats() - initiative := stats.effectiveSkill(stats.Speed.NanoInitiative, [6]uint32{0, 40, 0, 0, 60, 0}) + initiative := player.effectiveSkill(149, stats.Speed.NanoInitiative, [6]uint32{0, 40, 0, 0, 60, 0}) reduction := float32(float64(initiative) * 0.5) if initiative > 1200 { reduction = float32(600 + float64(initiative-1200)*float64(float32(1.0/6))) @@ -90,8 +90,8 @@ func (server *server) handleNanoCast(client *worldClient, body []byte) error { stats := player.baseStats() accepted := binary.BigEndian.Uint32(body[20:24]) == 50000 && binary.BigEndian.Uint32(body[28:32]) == 53019 && binary.BigEndian.Uint32(body[32:36]) == 29618 && slices.Contains(player.inventory.LearnedNanos, 29618) && - player.profession == 8 && stats.effectiveSkill(stats.NanoAiding.PsychologicalModification, [6]uint32{0, 0, 0, 80, 20, 0}) > 8 && - stats.effectiveSkill(stats.NanoAiding.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 && player.nano >= winterBiteCost() && + player.profession == 8 && player.effectiveSkill(129, stats.NanoAiding.PsychologicalModification, [6]uint32{0, 0, 0, 80, 20, 0}) > 8 && + player.effectiveSkill(130, stats.NanoAiding.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 && player.nano >= winterBiteCost() && !player.sitting && !player.driving() && client.forward == 0 && !client.strafing && !client.turning && client.equipment == nil && (player.fighting == 0 || now.Before(player.rechargeUntil)) && server.winterBiteTarget_locked(player, target, client, now) if !accepted { diff --git a/server/nano_kit.go b/server/nano_kit.go @@ -16,7 +16,7 @@ func (server *server) useNanoKit_locked(client *worldClient, index int, body []b accepted := item.Type == 51005 && item.Template == 85366 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && client.selectedTarget[0] == 50000 && target != nil && !target.npc && target.health > 0 && target.playfield == player.playfield && server.clients[target.id] != nil && server.clients[target.id].ready && !server.clients[target.id].loading && - stats.effectiveSkill(stats.NanoAiding.FirstAid, [6]uint32{0, 30, 0, 30, 40, 0}) > 7 && !now.Before(player.inventory.FirstAidLockedUntil) + player.effectiveSkill(123, stats.NanoAiding.FirstAid, [6]uint32{0, 30, 0, 30, 40, 0}) > 7 && !now.Before(player.inventory.FirstAidLockedUntil) if accepted { first := predictedPosition_locked(player, client, now) second := predictedPosition_locked(target, server.clients[target.id], now) diff --git a/server/nano_learning.go b/server/nano_learning.go @@ -11,14 +11,14 @@ func (server *server) learnNano_locked(client *worldClient, index int, body []by stats := player.baseStats() program := uint32(43324) accepted := item.Type == 51005 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && - stats.effectiveSkill(stats.NanoAiding.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 + player.effectiveSkill(130, stats.NanoAiding.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 if item.Template == 29625 { program = 29618 accepted = accepted && player.profession == 8 && - stats.effectiveSkill(stats.NanoAiding.PsychologicalModification, [6]uint32{0, 0, 0, 80, 20, 0}) > 8 + player.effectiveSkill(129, stats.NanoAiding.PsychologicalModification, [6]uint32{0, 0, 0, 80, 20, 0}) > 8 } else { accepted = accepted && player.profession == 12 && - stats.effectiveSkill(stats.NanoAiding.TimeAndSpace, [6]uint32{0, 20, 0, 80, 0, 0}) > 7 + player.effectiveSkill(131, stats.NanoAiding.TimeAndSpace, [6]uint32{0, 20, 0, 80, 0, 0}) > 7 } accepted = accepted && !slices.Contains(player.inventory.LearnedNanos, program) if accepted { diff --git a/server/regeneration.go b/server/regeneration.go @@ -38,8 +38,8 @@ func (server *server) advanceRegeneration(now time.Time) { if player.fighting != 0 { percent = 200 } - healthInterval := uint32(max(1, int((30-float64(stats.Abilities.Stamina)*float64(float32(1.0/30)))*percent*float64(float32(0.01))))) - nanoInterval := uint32(max(1, int((30-float64(stats.Abilities.Psychic)*float64(float32(1.0/30)))*percent*float64(float32(0.01))))) &^ 1 + healthInterval := uint32(max(1, int((30-float64(player.effectiveAbility(18))*float64(float32(1.0/30)))*percent*float64(float32(0.01))))) + nanoInterval := uint32(max(1, int((30-float64(player.effectiveAbility(21))*float64(float32(1.0/30)))*percent*float64(float32(0.01))))) &^ 1 rest := uint32(100) if player.sitting { rest = 25 @@ -47,7 +47,7 @@ func (server *server) advanceRegeneration(now time.Time) { healthInterval >>= 1 } } - bodyDevelopment := stats.effectiveSkill(stats.Body.BodyDevelopment, [6]uint32{0, 0, 100, 0, 0, 0}) + bodyDevelopment := player.effectiveSkill(152, stats.Body.BodyDevelopment, [6]uint32{0, 0, 100, 0, 0, 0}) breed := player.appearance >> 4 & 7 if client.regenerationSeconds%healthInterval == 0 { gain := bodyDevelopment/rest + [8]uint32{2, 3, 3, 2, 4, 6, 2, 2}[breed] diff --git a/server/stats.go b/server/stats.go @@ -142,15 +142,20 @@ func (character *character) baseStats() characterStats { return character.stats } -func (stats characterStats) effectiveSkill(base uint16, weights [6]uint32) uint32 { +func (character *character) effectiveAbility(stat uint32) uint32 { + abilities := character.baseStats().Abilities + values := [6]uint16{abilities.Strength, abilities.Agility, abilities.Stamina, abilities.Intelligence, abilities.Sense, abilities.Psychic} + return uint32(int32(values[stat-16]) + character.inventory.equipmentBonus(stat)) +} + +func (character *character) effectiveSkill(stat uint32, base uint16, weights [6]uint32) uint32 { // kkr.dll FUN_10073fa0, weights from resource type 1000204. - abilities := [6]uint16{stats.Abilities.Strength, stats.Abilities.Agility, stats.Abilities.Stamina, stats.Abilities.Intelligence, stats.Abilities.Sense, stats.Abilities.Psychic} var weighted uint32 - for index, ability := range abilities { - weighted += uint32(ability) * weights[index] + for index, weight := range weights { + weighted += character.effectiveAbility(16+uint32(index)) * weight } // Preserve the native float constants before truncating at integer boundaries. - return uint32(base) + uint32(float64(weighted)*float64(float32(0.01))*0.25) + return uint32(int32(base) + int32(float64(weighted)*float64(float32(0.01))*0.25) + character.inventory.equipmentBonus(stat)) } func (stats characterStats) nativeStats() [][2]uint32 { diff --git a/server/treatment_kit.go b/server/treatment_kit.go @@ -16,7 +16,7 @@ func (server *server) useTreatmentKit_locked(client *worldClient, index int, bod accepted := item.Type == 51005 && item.Template == 25812 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && client.selectedTarget[0] == 50000 && target != nil && !target.npc && target.health > 0 && target.sitting && target.playfield == player.playfield && server.clients[target.id] != nil && server.clients[target.id].ready && !server.clients[target.id].loading && - stats.effectiveSkill(stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 7 && !now.Before(target.treatmentLockedUntil) && + player.effectiveSkill(124, stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 7 && !now.Before(target.treatmentLockedUntil) && player.fighting == 0 && target.fighting == 0 if accepted { // InBattle includes incoming combat; its original server producer is unknown. diff --git a/server/world.go b/server/world.go @@ -99,7 +99,8 @@ func characterPacket(character *character) []byte { } else { body = append(body, byte(character.level)) } - for _, value := range []uint32{character.maximumHealth(), character.health, character.monsterData} { + // Equipment actions also reach observers, so keep direct health bonuses separate. + for _, value := range []uint32{character.maximumHealth() - uint32(character.inventory.equipmentBonus(1)), character.health, character.monsterData} { body = binary.BigEndian.AppendUint32(body, value) } body = binary.BigEndian.AppendUint16(body, 100) @@ -198,11 +199,12 @@ func fullCharacterPacket(character *character) []byte { [2]uint32{60, uint32(max(1, character.profession))}, [2]uint32{33, uint32(character.appearance >> 9 & 3)}, [2]uint32{59, uint32(character.appearance >> 7 & 3)}, - [2]uint32{27, character.health}, [2]uint32{1, character.maximumHealth()}, + // OnWear applies the direct modifiers; transmit their derived bases once. + [2]uint32{27, character.health}, [2]uint32{1, character.maximumHealth() - uint32(character.inventory.equipmentBonus(1))}, [2]uint32{37, character.titleLevel()}, [2]uint32{368, uint32(max(1, character.profession))}, [2]uint32{51, uint32(character.aggDef)}, [2]uint32{61, character.inventory.Credits}, [2]uint32{47, uint32(character.appearance >> 2 & 3)}, - [2]uint32{214, character.nano}, [2]uint32{221, character.maximumNano()}) + [2]uint32{214, character.nano}, [2]uint32{221, character.maximumNano() - uint32(character.inventory.equipmentBonus(221))}) if time.Now().Before(character.implantChangesUntil) { stats = append(stats, [2]uint32{224, 16}) } diff --git a/server/zoning.go b/server/zoning.go @@ -67,7 +67,7 @@ func (server *server) zoneDestination_locked(character *character, client *world // Grid statel 0xc04c0098 runs LineTeleport on collision with its exit beam. // Use a provisional two-metre envelope until the native mesh is recovered. if client.target && character.playfield == 152 && - character.stats.effectiveSkill(character.stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 90 { + character.effectiveSkill(161, character.stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 90 { x, y, z := character.position[0]-242.31323, character.position[1]-4.199992, character.position[2]-199.41223 if x*x+y*y+z*z <= 2*2 { destination := character.userData()