aorecomp

Anarchy Online classic in the browser

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


commit 1f7e91a389f3c57e0e144a7071b355b380f6f126
parent 7126ee5cb799be6ad608a087e143d464972a972b
Author: anon <anon@example.com>
Date:   Fri, 23 Oct 2026 20:09:29 +0000

Apply combat equipment bonuses and fix observer reconnect effects

Diffstat:
MTODO.md | 24++++++++++++++++++------
Mclient/Makefile.linux | 7+++++++
Mclient/Makefile.wasm | 4++++
Aclient/tests/weapon_range.c | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/backpacks.md | 13+++++++------
Mdocs/combat-attack-rating.md | 8++++----
Adocs/combat-equipment-modifiers.md | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/combat.go | 20+++++++++++++++-----
Aserver/combat_equipment_modifiers_test.go | 236+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/main.go | 14+++++++++-----
Mserver/world_actions.go | 9+++++++++
Mserver/world_output_test.go | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12 files changed, 574 insertions(+), 26 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -68,8 +68,9 @@ recorded in [inventory behavior](docs/inventory.md). All 27 wearable templates, Survival QL 100 and all six Pre-Universe positions passed native-client checks. Requirements, signed modifiers, ability trickle, Survival QL 50..150, resource clamping and worn-use routing have regression - coverage. Damage-type additions, critical chance and kill XP still have the - separate milestones below. See [backpack verification](docs/backpacks.md). + coverage. Normal-hit additions and weapon range are implemented below; + critical resolution and kill XP remain separate milestones. + See [backpack verification](docs/backpacks.md). - [x] 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: @@ -132,12 +133,21 @@ 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. Include the Sniper's Friend - backpack's CriticalIncrease modifier and removal of that modifier. -- [ ] Apply damage-type equipment modifiers in the recovered combat order. + the expected critical damage and client feedback. Include CriticalIncrease + stat 379; Sniper's Friend modifies weapon range stat 380 instead. +- [x] Apply damage-type equipment modifiers to normal hits in the recovered 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. + armor, weapon minimum damage and the supported overequipping tiers. +- [ ] Verify damage-type modifiers with critical hits and zero-effectiveness + weapons. Check: period evidence establishes their order and whether a fully + overequipped weapon can attack; cover the resulting damage and feedback. +- [x] Apply weapon-range equipment modifiers. Check: stat 380 percentages use + the original signed product, float constant, truncation and 40-meter cap; + Sniper's Friend's +2 percent does not become a flat two-meter bonus. +- [x] Clear the observer's old actor on a live session replacement. Check: + replacing a still-visible connection replays worn effects once; Robust's + +60 damage and Sniper's Friend's +2 range do not accumulate on observers. - [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 @@ -162,6 +172,8 @@ are recorded in [fist selection research](docs/combat-fist-selection.md). Melee uses the recovered client range predicate and actual actor extents; its boundary checks and original-server evidence limits are recorded in [combat client range](docs/combat-client-state-machine.md#range-line-of-sight-and-movement). +Normal-hit additions and weapon-range modifiers are described in +[combat equipment modifiers](docs/combat-equipment-modifiers.md). ## Additional weapon actions diff --git a/client/Makefile.linux b/client/Makefile.linux @@ -170,6 +170,7 @@ test: build/linux/window build/linux/graphics build/linux/atoi build/linux/stric ./build/linux/linecrypt ./build/linux/guest-heap ./build/linux/native-input + ./build/linux/weapon-range ./build/linux/guest-crt ./build/linux/getenv ./build/linux/linux-platform @@ -646,3 +647,9 @@ build/linux/native-input: tests/native_input.c game/ccr.dll/lifted-0000.c game/c $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ test: build/linux/native-input + +build/linux/weapon-range: tests/weapon_range.c game/kkr.dll/lifted-0050.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h + @mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ + +test: build/linux/weapon-range diff --git a/client/Makefile.wasm b/client/Makefile.wasm @@ -157,6 +157,10 @@ build/wasm/native-input.js: tests/native_input.c game/ccr.dll/lifted-0000.c game @mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ +build/wasm/weapon-range.js: tests/weapon_range.c game/kkr.dll/lifted-0050.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h + @mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ + build/wasm/web/capture-test.html: tests/browser_capture.html build/wasm/web/capture-test.js cp $< $@ diff --git a/client/tests/weapon_range.c b/client/tests/weapon_range.c @@ -0,0 +1,70 @@ +#include "recomp_types.h" +#include <assert.h> + +void sub_360AAE10(void); +static int32_t item_range, range_modifier; + +static void item_stat(void) +{ + assert(MEM32(g_esp + 4) == 287 && MEM32(g_esp + 8) == 2); + g_eax = (uint32_t)item_range; + g_esp += 12; +} + +static void actor_stat(void) +{ + assert(MEM32(g_esp + 4) == 380 && MEM32(g_esp + 8) == 0); + g_eax = (uint32_t)range_modifier; + g_esp += 12; +} + +/* The tested values fit int32; retain the native truncation boundary. */ +static void integer(void) +{ + g_eax = (uint32_t)(int32_t)g_st[0]; + fp_pop_impl(g_st, &g_fp_top); + g_esp += 4; +} + +recomp_func_t recomp_lookup(uint32_t address) +{ + switch (address) { + case 0x50000300: return item_stat; + case 0x50000304: return actor_stat; + case 0x3615fd8c: return integer; + default: fprintf(stderr, "unexpected range call: %08x\n", address); abort(); + } +} +recomp_func_t recomp_lookup_manual(uint32_t address) { return NULL; } +recomp_func_t recomp_lookup_import(uint32_t address) { abort(); } + +int main(void) +{ + assert(guest_map("range fixture", 0x50000000, 0x10000)); + assert(guest_map("native range constant", 0x36170000, 0x10000)); + MEM32(0x36170894) = 0x3c23d70a; + MEM32(0x5000001c) = 0x50000100; + MEM32(0x50000100) = 0x50000180; + MEM32(0x50000184) = 0x50000300; + MEM32(0x500002e4) = 0x50000190; + MEM32(0x50000194) = 0x50000304; + const struct { int32_t range, modifier, expected; } cases[] = { + {22, 0, 22}, {22, 2, 22}, {22, 5, 23}, {10, 10, 10}, + {20, 5, 20}, {22, 50, 32}, {22, 100, 40}, {50, 0, 40}, + {2, -100, 0}, {22, -200, -21} + }; + for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + item_range = cases[i].range; + range_modifier = cases[i].modifier; + g_esp = 0x5000ff00; + g_ecx = 0x50000000; + g_fp_top = 0; + MEM32(g_esp + 4) = 0x50000200; + + sub_360AAE10(); + + assert((int32_t)g_eax == cases[i].expected); + assert(g_esp == 0x5000ff08 && g_fp_top == 0); + } + puts("native weapon range: percent modifier, float rounding, truncation and cap passed"); +} diff --git a/docs/backpacks.md b/docs/backpacks.md @@ -280,7 +280,7 @@ 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. +concealment, damage types, weapon range 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. @@ -311,11 +311,12 @@ share ownership and session checks. Contents retain their own instance identitie 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. +initiative, armor and resource modifiers. Normal-hit damage additions and weapon +range now consume the matching equipment modifiers; see +[combat equipment modifiers](combat-equipment-modifiers.md). Critical resolution +and kill XP rewards remain separate milestones. Preserving and displaying a +modifier does not establish its final reward formula. 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, diff --git a/docs/combat-attack-rating.md b/docs/combat-attack-rating.md @@ -30,7 +30,7 @@ Normal player hits follow this order, after any supported axe minimum = base_minimum + floor(base_minimum * AR / 400) maximum = base_maximum + floor(base_maximum * AR / 400) rolled = uniform_integer(minimum, maximum) -damage = rolled - min(rolled - minimum, floor(selected_AC / 10)) +damage = rolled - min(rolled - minimum, floor(selected_AC / 10)) + matching_damage_modifier ``` The scaled minimum is the AC floor. Uniform sampling of integer endpoints, @@ -57,9 +57,9 @@ at 10, rather than the unscaled minimum of 5. NPC profiles still provide their unscaled catalog damage: their attack skills and Add All Offense values are not known. Player fists receive the multiplier but remain on the fixed QL 1 3..5 record; selecting their proper QL from Martial -Arts is a separate TODO. Criticals, hit/miss rolls and damage additions -also remain separate work. These limits prevent a claim of -complete canonical damage balance. +Arts is a separate TODO. [Equipment damage additions](combat-equipment-modifiers.md) +follow the AC floor. Criticals and hit/miss rolls remain separate work. These +limits prevent a claim of complete canonical damage balance. ## Verification diff --git a/docs/combat-equipment-modifiers.md b/docs/combat-equipment-modifiers.md @@ -0,0 +1,125 @@ +# Combat equipment modifiers in 14.9.1 + +## Normal-hit added damage + +The server adds the matching worn equipment modifier after attack-rating +scaling, the roll and armor's minimum-damage floor. Robust Backpack 158790 +therefore adds 60 to projectile, energy, radiation and fire hits. It does not +add damage to fists or the supported melee axe. Inventory contents have no +combat effect; the bag must occupy an authored equipment position. + +The [July 2002 damage discussion](https://forums-archive.anarchy-online.com/printthread.php?page=1&pp=20&t=36008) +describes additions after attack-rating scaling. On July 9, Krneki explicitly +places the bonus after armor, responding to a conflicting interpretation in +the same thread. This is contemporary player evidence, not recovered server +code. The existing endpoint and AC integer truncation policies remain provisional. + +The original `kkr.dll::FUN_10031700` stat-name table identifies the modifiers: + +| Attack protection stat | Matching damage modifier | +| --- | --- | +| Projectile 90 | 278 | +| Melee 91 | 279 | +| Energy 92 | 280 | +| Chemical 93 | 281 | +| Radiation 94 | 282 | +| Cold 95 | 311 | +| Disease 96 | Poison 317 | +| Fire 97 | 316 | +| Nano 168 | 315 | + +An invalid weapon damage type already falls back to projectile, including +its matching addition. Currently accepted damage bonuses are nonnegative. +Unsupported equipment and effect interpreters are not enabled by this mapping. +The supported partial [overequipping](overequipping.md) tiers adjust weapon +endpoints before attack rating; they do not scale the flat equipment addition. +Critical resolution, signed damage debuffs, reflect/absorb ordering and the +eligibility of a weapon at zero effectiveness remain separate work. No original +critical or miss probability is inferred from this change. The current arithmetic +adds the flat bonus even if overequipping reduces both base endpoints to zero; +the original server's attack eligibility at that tier is not established. + +## Weapon range + +Sniper's Friend 157685 modifies stat 380, `RangeIncreaserWeapon`, by +2 percent. +Critical chance is the distinct stat 379, `CriticalIncrease`. The stat-name +evidence is `ev_98e4abebdc945ad44f630f266643a271f9826c40b98314ddfc955b1513b1e525` +in `local/backpack-equipment-research/native-evidence.json`. + +Original `kkr.dll::FUN_100aae10` reads weapon stat 287 and actor stat 380. It +multiplies them as signed 32-bit integers, loads that signed product into the +FPU, multiplies by the float32 constant `0x3c23d70a` at `0x10170894`, then adds +the original signed weapon range. It truncates toward zero and caps at 40. +There is no float32 store before truncation and no lower clamp. The server +then applies the existing actor extents and three-dimensional range predicate. +A negative final distance cannot become an accepted distance by squaring it. + +Assembly evidence `ev_caffa5ac96df90e71084d5f068e035270b37d97a28beb95abb889dd010d2527d` +is retained in `local/damage-modifier-research/range-evidence.json`. The original +DLL SHA-256 is `a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +The translated implementation is `client/game/kkr.dll/lifted-0050.c::sub_360AAE10`. + +| Weapon range | Percent modifier | Adjusted range before extents | +| --- | --- | --- | +| 22 | 0 | 22 | +| 22 | 2 | 22 | +| 22 | 5 | 23 | +| 10 | 10 | 10 | +| 20 | 5 | 20 | +| 22 | 50 | 32 | +| 22 | 100 | 40 | +| 50 | 0 | 40 | +| 2 | -100 | 0 | +| 22 | -200 | -21 | + +The +50 percent example yields 32 because the authored float32 constant is +slightly smaller than exact 0.01. Replacing it with an exact decimal percentage, +or rounding the sum to float32, would yield 33. Sniper's Friend alone does not +increase the adjusted range of the supported 22-meter pistol. + +## Verification + +`client/tests/weapon_range.c` calls the original translated range procedure, +with only its item/actor getters and integer-conversion boundary supplied by +the fixture. The table above passes both native Linux and WASM builds. +`server/combat_equipment_modifiers_test.go` sends public combat requests at +each resulting boundary and at the next representable float beyond it. + +The Go tests also cover every protection type with Robust, invalid-type +fallback, unchanged nonmatching damage, removal, controlled endpoint rolls, +AR 400/800, armor's minimum floor, partial overequipping, SQLite reload and +identical owner/observer damage packets with ammunition consumption. +Failed ammunition persistence cannot publish a bonus hit; failed removal keeps +the same equipped identity and bonus in memory and SQLite. + +Replacing a visible world session removes its old remote actor before sending +the new spawn. The equipment snapshot follows CharacterReady, after the native +actor has loaded; sending it with the spawn can lose the OnWear effects. Keeping +the old actor instead applies those effects twice. Repeated ready messages +acknowledge the actor without replaying equipment. Joining observers receive +equipment in their initial snapshot only for players who have finished loading; +other players' equipment follows their ready notification. + +Fresh and unfinished logins do not need the initial removal. +`server/world_output_test.go` exercises all three paths through the world +protocol, including removal/spawn/ready/equipment order and repeated ready messages. + +The published WASM client was exercised through native inventory, clothing, +Tab targeting and Q combat controls against the single HTTPS preview. Evidence +and the checking script are retained in `local/damage-modifier-research/`. +Owner and observer both display the same 9-point baseline hit, 72-point Robust +hit and 68-point Robust hit after the corrected reconnect. Loaded rounds move +20 -> 19 -> 18 -> 17; the loose stack remains 100. + +Ten native modifier captures verify Sniper's Friend and Robust on both clients +before and after replacement, including clearing Sniper's modifiers when Robust +replaces it. Maximum health stays 2876 with Robust, rather than doubling its +400-point addition or losing it. All 190 item instances are accounted for; +the 186 pre-existing instances and placements are unchanged. There are no page +errors or unimplemented adapter calls. Both test contexts close afterward, and +the existing profile editor ends their resumable combat sessions. + +The complete Go suite passes (`ao/server` 278.413s). Focused race checks pass +in 104.831s, covering combat, armor, ranged ammunition, equipment effects, +persistence failures and world-session replacement. The original range contract +also passes native Linux and WASM execution. diff --git a/server/combat.go b/server/combat.go @@ -191,7 +191,14 @@ 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, uint32(target.inventory.equipmentBonus(damageType))/10) + damage -= min(damage-minimum, uint32(target.inventory.equipmentBonus(damageType))/10) + + // Add the matching damage modifier after attack rating and the AC floor. + modifier := uint32(315) // NanoDamageModifier + if damageType >= 90 && damageType <= 97 { + modifier = [8]uint32{278, 279, 280, 281, 282, 311, 317, 316}[damageType-90] + } + return damage + uint32(attacker.inventory.equipmentBonus(modifier)) } func (character *character) physicalExtent() float32 { @@ -219,13 +226,16 @@ func (server *server) combatInRange_locked(attacker, target *character, now time second = predictedPosition_locked(target, server.clients[target.id], now) } x, y, z := first[0]-second[0], first[1]-second[1], first[2]-second[2] - itemRange := uint32(2) + itemRange := int32(2) if weapon := attacker.attackWeapon(); weapon != nil { - itemRange = itemStat(weapon, 287) + itemRange = int32(itemStat(weapon, 287)) } + // client/game/kkr.dll/lifted-0050.c::sub_360AAE10 uses a signed product + // and float32 .01, without a float32 store before truncation and the 40 cap. + itemRange = min(40, int32(float64(itemRange*attacker.inventory.equipmentBonus(380))*float64(float32(0.01))+float64(itemRange))) // FUN_10078cb0 adds the attacker's extent twice and the target's once. - distance := float32(min(40, itemRange)) + 2*attacker.physicalExtent() + target.physicalExtent() - return x*x+y*y+z*z <= distance*distance + distance := float32(itemRange) + 2*attacker.physicalExtent() + target.physicalExtent() + return distance >= 0 && x*x+y*y+z*z <= distance*distance } func (server *server) startAttack_locked(attacker, target *character, now time.Time, updates map[*worldClient][][]byte) { diff --git a/server/combat_equipment_modifiers_test.go b/server/combat_equipment_modifiers_test.go @@ -0,0 +1,236 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "fmt" + "math" + "slices" + "testing" + "time" +) + +func TestWeaponRangeMatchesOriginalClientRoundingAndBoundary(t *testing.T) { + for _, scenario := range []struct { + itemRange, modifier, expected int32 + }{ + {22, 0, 22}, {22, 2, 22}, {22, 5, 23}, {10, 10, 10}, + {20, 5, 20}, {22, 50, 32}, {22, 100, 40}, {50, 0, 40}, + {2, -100, 0}, {22, -200, -21}, + } { + t.Run(fmt.Sprintf("%d/%d", scenario.itemRange, scenario.modifier), func(t *testing.T) { + world, _ := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + originalWeapon, originalBag := gamedata.ItemTemplates[123742], gamedata.ItemTemplates[157685] + weapon, bag := *originalWeapon, *originalBag + weapon.Stats, bag.Sections = slices.Clone(weapon.Stats), slices.Clone(bag.Sections) + for index, stat := range weapon.Stats { + if stat[0] == 287 { + weapon.Stats[index][1] = uint32(scenario.itemRange) + } + } + stat := int32(380) + for index, section := range bag.Sections { + if section.Type == 2 && section.Subtype == 14 { + functions := []gamedata.ItemFunction{{ID: 53045, Arguments: []gamedata.ItemArgument{{Integer: &stat}, {Integer: &scenario.modifier}}}} + bag.Sections[index].Functions = &functions + } + } + gamedata.ItemTemplates[123742], gamedata.ItemTemplates[157685] = &weapon, &bag + t.Cleanup(func() { gamedata.ItemTemplates[123742], gamedata.ItemTemplates[157685] = originalWeapon, originalBag }) + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 157685, Quality: 1, Slot: 19, Count: 1}) + boundary := float32(scenario.expected) + 6 // Both actor radii are 2. + target.position = [3]float32{max(0, boundary), 0, 0} + world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]) + atBoundary := player.fighting == target.id + world.handleCombat(world.clients[1], stopFightPacket(1)[20:]) + target.position[0] = math.Nextafter32(max(0, boundary), float32(math.Inf(1))) + world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]) + outside := player.fighting == target.id + + if atBoundary != (boundary >= 0) || outside { + t.Fatalf("range %d modifier %d: boundary %v accepted %t outside %t", scenario.itemRange, scenario.modifier, boundary, atBoundary, outside) + } + }) + } +} + +func TestRobustDamageSelectsOnlyTheMatchingType(t *testing.T) { + for _, scenario := range []struct { + name string + kind, minimum, maximum uint32 + }{ + {"projectile", 90, 63, 72}, {"melee", 91, 3, 12}, {"energy", 92, 63, 72}, + {"chemical", 93, 3, 12}, {"radiation", 94, 63, 72}, {"cold", 95, 3, 12}, + {"disease", 96, 3, 12}, {"fire", 97, 63, 72}, {"nano", 168, 3, 12}, + {"invalid uses projectile", 0, 63, 72}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, _ := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + original := gamedata.ItemTemplates[123742] + weapon := *original + weapon.Stats = slices.Clone(weapon.Stats) + for index, stat := range weapon.Stats { + if stat[0] == 436 { + weapon.Stats[index][1] = scenario.kind + } + } + gamedata.ItemTemplates[123742] = &weapon + t.Cleanup(func() { gamedata.ItemTemplates[123742] = original }) + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 158790, Quality: 1, Slot: 19, Count: 1}) + + minimum := player.normalDamage(target, func(limit uint32) uint32 { return 0 }) + maximum := player.normalDamage(target, func(limit uint32) uint32 { return limit - 1 }) + player.inventory.Items[2].Slot = 65 + removed := player.normalDamage(target, func(limit uint32) uint32 { return limit - 1 }) + + if minimum != scenario.minimum || maximum != scenario.maximum || removed != 12 { + t.Fatalf("matching added damage: minimum %d maximum %d removed %d", minimum, maximum, removed) + } + }) + } +} + +func TestRobustDamageIsAddedAfterRatingOverequippingAndArmor(t *testing.T) { + for _, scenario := range []struct { + name string + pistol, fling uint16 + armored bool + minimum, maximum uint32 + }{ + {"rating 400", 398, 5, false, 66, 84}, + {"rating 800", 798, 5, false, 69, 96}, + {"AC minimum at rating 400", 398, 5, true, 66, 66}, + {"75 percent effectiveness", 5, 2, false, 63, 69}, + {"50 percent effectiveness", 5, 1, false, 62, 66}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, _ := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + player.stats.Ranged.Pistol, player.stats.Ranged.FlingShot = scenario.pistol, scenario.fling + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 158790, Quality: 1, Slot: 19, Count: 1}) + if scenario.armored { + target.inventory.Items = []ownedItem{{ID: 4, Type: 51022, Template: 85685, Quality: 200, Slot: 21, Count: 1}} + } + + minimum := player.normalDamage(target, func(limit uint32) uint32 { return 0 }) + maximum := player.normalDamage(target, func(limit uint32) uint32 { return limit - 1 }) + + if minimum != scenario.minimum || maximum != scenario.maximum { + t.Fatalf("modifier was scaled or reduced by armor: %d..%d", minimum, maximum) + } + }) + } +} + +func TestRobustCombatWearRemovalRestartAndObservers(t *testing.T) { + world, owner := newRangedWorld(t) + player, target, client := world.characters[1], world.characters[1000000], world.clients[1] + player.stats.Body.Adventuring = 1000 + player.level = 120 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if granted, err := world.grantItem_locked(player, 158790); !granted || err != nil { + t.Fatal("grant", granted, err) + } + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + + world.handleInventory(client, inventoryMovePacket(1, 65, 19)[20:]) + if client.equipment == nil { + t.Fatal("wear did not start") + } + world.advanceEquipment(client.equipment.readyAt) + restarted := newTestInventoryServer(t).characters[1] + owner.packets, observer.packets = nil, nil + world.handleCombat(client, attackPacket(1, target.id)[20:]) + world.advanceCombat(player.nextAttack) + healthWithBag := target.health + world.handleCombat(client, stopFightPacket(1)[20:]) + world.advanceCombat(player.rechargeUntil) // Let the distant NPC stop its reply. + time.Sleep(time.Until(player.rechargeUntil)) + world.handleInventory(client, itemMovePacket(1, 19, 111)[20:]) + if client.equipment == nil { + t.Fatal("removal did not start") + } + world.advanceEquipment(client.equipment.readyAt) + world.handleCombat(client, attackPacket(1, target.id)[20:]) + world.advanceCombat(player.nextAttack) + after := newTestInventoryServer(t).characters[1] + var ownerHits, observerHits [][]byte + for _, packet := range owner.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 { + ownerHits = append(ownerHits, packet[16:]) + } + } + for _, packet := range observer.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 { + observerHits = append(observerHits, packet[16:]) + } + } + + if healthWithBag < 928 || healthWithBag > 937 || healthWithBag-target.health < 3 || healthWithBag-target.health > 12 { + t.Fatalf("combat damage before/after removal: %d %d", healthWithBag, target.health) + } + if restarted.inventory.equipmentBonus(278) != 60 || after.inventory.equipmentBonus(278) != 0 || after.inventory.Items[0].Ammo != 1 || len(after.inventory.Items) != 3 { + t.Fatal("restart lost equipment, effects or ammunition", after.inventory) + } + if len(ownerHits) != 2 || len(observerHits) != 2 || !bytes.Equal(ownerHits[0], observerHits[0]) || !bytes.Equal(ownerHits[1], observerHits[1]) { + t.Fatalf("owner/observer damage differs: %x %x", ownerHits, observerHits) + } +} + +func TestRobustFailedAmmoSaveDoesNotDealBonusDamage(t *testing.T) { + world, conn := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 158790, Quality: 1, Slot: 19, Count: 1}) + player.inventory.LastID = 3 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]) + if _, err := world.db.Exec("CREATE TRIGGER fail_ammo BEFORE UPDATE OF ammo ON items WHEN NEW.id = 1 BEGIN SELECT RAISE(FAIL, 'test save failure'); END"); err != nil { + t.Fatal(err) + } + conn.packets = nil + + world.advanceCombat(player.nextAttack) + restarted := newTestInventoryServer(t).characters[1] + + if target.health != 1000 || player.inventory.Items[0].Ammo != 3 || restarted.inventory.Items[0].Ammo != 3 || restarted.inventory.equipmentBonus(278) != 60 { + t.Fatal("failed ammunition debit published damage or changed equipment", restarted.inventory) + } + if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x4a41203e { + t.Fatalf("failed ammunition debit published a bonus hit: %x", conn.packets) + } +} + +func TestRobustFailedRemovalRetainsDamageBonus(t *testing.T) { + world, conn := newRangedWorld(t) + player := world.characters[1] + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 158790, Quality: 1, Slot: 19, Count: 1}) + player.inventory.LastID = 3 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + world.db.Close() + + world.handleInventory(world.clients[1], itemMovePacket(1, 19, 111)[20:]) + if world.clients[1].equipment == nil { + t.Fatal("removal did not start") + } + world.advanceEquipment(world.clients[1].equipment.readyAt) + restarted := newTestInventoryServer(t).characters[1] + damage := player.normalDamage(world.characters[1000000], func(limit uint32) uint32 { return 0 }) + + if damage != 63 || player.inventory.Items[2].Slot != 19 || restarted.inventory.Items[2].Slot != 19 || restarted.inventory.equipmentBonus(278) != 60 || len(restarted.inventory.Items) != 3 { + t.Fatal("failed removal lost the item or damage bonus", damage, restarted.inventory) + } + if len(conn.packets) != 1 || 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 worn slot", conn.packets) + } +} diff --git a/server/main.go b/server/main.go @@ -317,7 +317,9 @@ func (server *server) serveWorldClient(client *worldClient) error { return fmt.Errorf("browser character requires a browser credential") } combatUpdates := make(map[*worldClient][][]byte) + replaceActor := false if previous := server.clients[character.id]; previous != nil { + replaceActor = previous.ready previous.ready = false server.cancelCombat_locked(character.id, combatUpdates) if previous.stream != nil { @@ -342,7 +344,9 @@ func (server *server) serveWorldClient(client *worldClient) error { for id, other := range server.characters { if id != character.id && other.playfield == character.playfield && server.clients[id] != nil { updates = append(updates, characterPacket(other)) - updates = append(updates, equippedItemPackets(other)...) + if !server.clients[id].loading { + updates = append(updates, equippedItemPackets(other)...) + } if other.health == 0 { updates = append(updates, deathPacket(other)) } @@ -364,10 +368,13 @@ func (server *server) serveWorldClient(client *worldClient) error { updates = append(updates, server.combatInterest_locked(client, nil)...) updates = append(updates, gameTimePacket(character.id, server.gameSeconds_locked())) spawn := characterPacket(character) - equipment := equippedItemPackets(character) playfield := character.playfield server.mutex.Unlock() server.sendCombatUpdates(combatUpdates) + // Discard the old remote actor before replaying its OnWear effects. + if replaceActor { + server.broadcast(playfield, character.id, n3Packet(0x36510078, 50000, character.id, nil)) + } for _, update := range updates { traceLog.Printf("World S2C: %x", update) if err := client.send(update); err != nil { @@ -379,9 +386,6 @@ func (server *server) serveWorldClient(client *worldClient) error { client.ready = true server.mutex.Unlock() server.broadcast(playfield, character.id, spawn) - for _, packet := range equipment { - server.broadcast(playfield, character.id, packet) - } server.updateMutex.Unlock() } case 5: diff --git a/server/world_actions.go b/server/world_actions.go @@ -34,12 +34,21 @@ func (server *server) handleCharacterReady(client *worldClient) error { server.mutex.Unlock() return nil } + // The observer's new actor must finish loading before OnWear is replayed. + // Repeated ready messages acknowledge the actor without applying effects twice. + var equipment [][]byte + if client.loading { + equipment = equippedItemPackets(server.characters[client.id]) + } client.loading = false playfield := server.characters[client.id].playfield server.mutex.Unlock() response := n3Packet(0x570c2039, 50000, client.id, nil) server.broadcast(playfield, client.id, response) + for _, packet := range equipment { + server.broadcast(playfield, client.id, packet) + } return client.send(response) } diff --git a/server/world_output_test.go b/server/world_output_test.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "errors" "net" + "slices" "sync" "testing" "time" @@ -55,6 +56,75 @@ func TestWorldReplacementDoesNotWaitForOldTransportClose(t *testing.T) { } } +func TestWorldReplacementRemovesRemoteActorBeforeReplayingEquipment(t *testing.T) { + for _, scenario := range []string{"visible previous session", "unfinished previous session", "fresh login"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newRangedWorld(t) + player := world.characters[1] + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 158790, Quality: 1, Slot: 19, Count: 1}) + player.inventory.LastID = 3 + world.clients[1].conn = &combatInterestConn{} + if scenario == "unfinished previous session" { + world.clients[1].ready = false + } else if scenario == "fresh login" { + delete(world.clients, 1) + } + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) + ready := n3Packet(0x570c2039, 50000, 1, nil) + input := append(cookie, ready...) + input = append(input, ready...) + replacement := &combatInterestConn{input: bytes.NewReader(input)} + + err := world.serveWorldClient(&worldClient{conn: replacement, loading: true}) + var keys []uint32 + for _, packet := range observer.packets { + keys = append(keys, binary.BigEndian.Uint32(packet[16:20])) + } + + expected := []uint32{0x271b3a6b, 0x570c2039, 0x3b1d2268, 0x35505644, 0x570c2039, 0x36510078} + if scenario == "visible previous session" { + expected = []uint32{0x36510078, 0x271b3a6b, 0x570c2039, 0x3b1d2268, 0x35505644, 0x570c2039, 0x36510078} + } + if err != nil || !slices.Equal(keys, expected) { + t.Fatalf("replacement must discard cached OnWear effects before replay: %x, %v", keys, err) + } + }) + } +} + +func TestWorldJoiningObserverWaitsForLoadingPlayersEquipment(t *testing.T) { + for _, scenario := range []string{"player loading", "player loaded"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newRangedWorld(t) + world.characters[1].inventory.Items = append(world.characters[1].inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 158790, Quality: 1, Slot: 19, Count: 1}) + world.clients[1].loading = scenario == "player loading" + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + cookie := systemPacket(0x1b, []byte{0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0}) + observer := &combatInterestConn{input: bytes.NewReader(cookie)} + + err := world.serveWorldClient(&worldClient{conn: observer, loading: true}) + var equipment []uint32 + for _, packet := range observer.packets { + key := binary.BigEndian.Uint32(packet[20:24]) + if key == 0x35505644 || key == 0x3b1d2268 { + equipment = append(equipment, key) + } + } + + var expected []uint32 + if scenario == "player loaded" { + expected = []uint32{0x3b1d2268, 0x35505644} + } + if err != nil || !slices.Equal(equipment, expected) { + t.Fatalf("initial snapshot must not duplicate equipment still awaiting ready: %x, %v", equipment, err) + } + }) + } +} + func (conn *shortWorldConn) SetWriteDeadline(time.Time) error { return nil } func (conn *shortWorldConn) Write(packet []byte) (int, error) { return len(packet) - 1, nil } func (conn *shortWorldConn) Close() error {