commit 5ff3f06bf33acb9bcb13601012d0bdee9266c38e
parent a4f32cc1d201d2b482d65cecc43de4133374b7cd
Author: anon <anon@example.com>
Date: Wed, 28 Oct 2026 21:27:43 +0000
Resolve ordinary weapon hit and miss outcomes
Diffstat:
23 files changed, 777 insertions(+), 39 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -439,12 +439,19 @@ capacity checks are recorded in [belts and NCU](docs/belts-ncu.md).
## Combat calculations
-- [ ] [P0] Resolve hit versus miss. Check: controlled test rolls produce the matching
- native outcomes; a miss does not reduce health.
+- [x] Implement provisional ordinary weapon hit/miss outcomes. Check: controlled
+ test rolls produce the matching native outcomes; a miss does not reduce health.
Include starter player/NPC ratings and evades in the normal fight/recovery
- audit. Current ordinary weapon hits only roll critical selection and damage;
- training evades cannot yet prevent a hit. Resolve this missing combat rule
- alongside First Aid before treating the starter deaths as proof of enemy HP.
+ audit. Ordinary attacks now check authored weighted attack/defense skills,
+ all-off/all-def modifiers and defender Agg/Def, using a documented later
+ empirical probability curve provisionally. Misses preserve health/control,
+ spend finite ammo atomically, advance the normal clock and start retaliation
+ without damage/kill credit. Native rating contracts run on Linux and WASM.
+ See [hit/miss evidence and limits](docs/weapon-hit-chance.md).
+- [ ] [P2] Establish the original 14.9.1 hit probability curve, caps/zero cases
+ and relationship to critical chance before claiming canonical balance.
+ Authentic NPC raw skill growth remains part of the P0 early-profile task;
+ the working hit/miss framework does not establish historical enemy HP.
- [ ] [P2] Resolve a critical hit. Check: a known weapon and controlled roll produce
the expected critical damage and client feedback. Include CriticalIncrease
stat 379; Sniper's Friend modifies weapon range stat 380 instead.
@@ -639,6 +646,8 @@ for exact records, protocol, tests and remaining reconstruction assumptions.
XP and useful loot for the next progression levels, keeping balance explicitly
provisional where historical measurements are missing. Prefer shared growth
rules supported by evidence over a separate bespoke profile for every level.
+ Include raw attack/evade skills and all-off/all-def foundations; the current
+ five-point NPC skill default does not establish level growth.
Verify ordinary earned equipment, healing costs, mission completion and the next
level without admin grants. Preserve authored outdoor level ranges.
- [x] Make the next supported enemy level available through ordinary starter
@@ -2678,6 +2687,9 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah
lifecycle with the original program and proc rules above. Current admitted
equipment has no negative ability/skill modifiers; synthetic arithmetic
fixtures must not be described as canonical negative gear.
+ Include weaponDamage's uint32 endpoint, AC and added-damage conversions:
+ negative ratings or modifiers must use evidenced floors instead of wrapping
+ into large damage values, including Fast/Fling's defensive-check exemption.
- [ ] [P3] Research bank CASH/XP semantics and the original server's filled-backpack
deletion policy; current zero fields and recursive deletion are reconstruction
policies. Also establish the original combat-state producer/expiry and remote
@@ -2889,6 +2901,10 @@ and server restarts. Turn every reproduced bug into a focused regression test.
Include special animations, each client's recovery phase and target/controller
changes in the remaining audit; matching result packets alone do not prove
matching displayed HP or safe correction during combat.
+ The ordinary hit/miss mission trace also showed native NPC HP0 1.757 seconds
+ before the authoritative final three-damage/death packet, after a server
+ combat recovery tick. Preserve that concrete case in the recovery-phase
+ audit; see [hit/miss native verification](docs/weapon-hit-chance.md#native-verification).
- [ ] [P1] Audit ranged ammunition and reload. Cover empty/partial/full magazines,
matching/wrong/missing ammunition, insufficient stacks, repeated reloads,
reload during each attack phase, failed saves and round conservation across
diff --git a/client/Makefile.linux b/client/Makefile.linux
@@ -179,6 +179,7 @@ test: build/linux/window build/linux/graphics build/linux/atoi build/linux/stric
./build/linux/ip-training
./build/linux/fling-result
./build/linux/critical-result
+ ./build/linux/weapon-rating
./build/linux/guest-crt
./build/linux/getenv
./build/linux/linux-platform
@@ -694,6 +695,12 @@ build/linux/critical-result: tests/critical_result.c game/kkr.dll/lifted-0034.c
test: build/linux/critical-result
+build/linux/weapon-rating: tests/weapon_rating.c game/kkr.dll/lifted-0042.c game/kkr.dll/lifted-0033.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-rating
+
build/linux/character-reference: tests/character_reference.c game/ddr.dll/lifted-0030.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 $@
diff --git a/client/tests/weapon_rating.c b/client/tests/weapon_rating.c
@@ -0,0 +1,139 @@
+#include "recomp_types.h"
+#include <assert.h>
+
+void sub_3608F1F0(void);
+void sub_3608F2F0(void);
+void sub_3606DFB0(void);
+
+static int32_t effective[1200];
+static unsigned section, section_calls, lazy_probes, effective_calls;
+
+static void item_section(void)
+{
+ assert(g_ecx == 0x50000100 && MEM32(g_esp + 4) == section);
+ section_calls++;
+ g_eax = 0x50000800;
+ g_esp += 8;
+}
+
+static void has_section(void)
+{
+ assert(g_ecx == 0x50000100);
+ assert(MEM32(g_esp + 4) == ++lazy_probes);
+ g_eax = 0;
+ g_esp += 8;
+}
+
+/* Effective values isolate the native getter's mode-0 branch. */
+static void effective_stat(void)
+{
+ assert(g_ecx == 0x50000700 && MEM32(g_esp + 4) < 1200);
+ effective_calls++;
+ g_eax = (uint32_t)effective[MEM32(g_esp + 4)];
+ g_esp += 8;
+}
+
+recomp_func_t recomp_lookup(uint32_t address)
+{
+ switch (address) {
+ case 0x3608f810: return item_section;
+ case 0x3608f8e0: return has_section;
+ case 0x3606dfb0: return sub_3606DFB0;
+ case 0x36075ca0: return effective_stat;
+ default: fprintf(stderr, "unexpected rating 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(); }
+
+static void weighted_ratings(void)
+{
+ const struct {
+ unsigned defense, npc;
+ int32_t first, second, first_weight, second_weight, modifier, expected;
+ } cases[] = {
+ {0, 0, 125, 125, 50, 50, 7, 131},
+ {1, 0, 125, 125, 50, 50, 7, 131},
+ {0, 0, 3, 3, 33, 33, 99, 0},
+ {1, 0, 3, 3, 33, 33, 99, 0},
+ {0, 0, -3, 1, 50, 50, 99, -1},
+ {1, 0, -3, 1, 50, 50, 99, -1},
+ {0, 0, -3, 3, 50, 50, 99, 0},
+ {1, 0, -3, 3, 50, 50, 99, 0},
+ {0, 0, 3, 3, 50, 50, -7, -5},
+ {1, 0, 3, 3, 50, 50, -7, -5},
+ {0, 1, 5, 5, 50, 50, 7, 11},
+ {1, 1, 5, 5, 50, 50, 7, 11},
+ {0, 1, -3, 1, 50, 50, 99, -1},
+ {1, 1, -3, 1, 50, 50, 99, -1}
+ };
+ for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
+ unsigned first_stat = cases[i].defense ? 155 : 100;
+ unsigned second_stat = cases[i].defense ? 154 : 102;
+ unsigned modifier_stat = cases[i].defense ? 277 : 276;
+ section = cases[i].defense ? 13 : 12;
+ section_calls = lazy_probes = effective_calls = 0;
+ MEM8(0x500003b4) = cases[i].npc;
+ MEM32(0x50000804) = 0x50000900;
+ MEM32(0x50000808) = 0x50000910;
+ MEM32(0x50000900) = first_stat;
+ MEM32(0x50000904) = (uint32_t)cases[i].first_weight;
+ MEM32(0x50000908) = second_stat;
+ MEM32(0x5000090c) = (uint32_t)cases[i].second_weight;
+ MEM32(0x50001000 + first_stat * 4) = (uint32_t)cases[i].first;
+ MEM32(0x50001000 + second_stat * 4) = (uint32_t)cases[i].second;
+ MEM32(0x50001000 + modifier_stat * 4) = 999;
+ effective[first_stat] = cases[i].first + (cases[i].npc ? 100 : 0);
+ effective[second_stat] = cases[i].second + (cases[i].npc ? 100 : 0);
+ effective[modifier_stat] = cases[i].modifier;
+ g_esp = 0x5000ff00;
+ g_ecx = 0x50000100;
+ MEM32(g_esp + 4) = 0x50000200;
+
+ if (cases[i].defense) sub_3608F2F0();
+ else sub_3608F1F0();
+
+ assert((int32_t)g_eax == cases[i].expected);
+ assert(g_esp == 0x5000ff08 && lazy_probes == 0);
+ assert(section_calls == 5);
+ unsigned weighted_reads = cases[i].npc ? 0 : 2;
+ unsigned modifier_reads = cases[i].expected > 0 || cases[i].modifier == -7;
+ assert(effective_calls == weighted_reads + modifier_reads);
+ }
+}
+
+static void missing_and_empty_ratings(void)
+{
+ for (unsigned defense = 0; defense < 2; defense++) {
+ for (unsigned missing = 0; missing < 2; missing++) {
+ section = defense ? 13 : 12;
+ section_calls = lazy_probes = effective_calls = 0;
+ MEM32(0x50000804) = MEM32(0x50000808) = 0x50000900;
+ g_esp = 0x5000ff00;
+ g_ecx = 0x50000100;
+ MEM32(g_esp + 4) = missing ? 0 : 0x50000200;
+
+ if (defense) sub_3608F2F0();
+ else sub_3608F1F0();
+
+ assert(g_eax == 0 && g_esp == 0x5000ff08);
+ assert(effective_calls == 0);
+ assert(lazy_probes == (missing ? 0 : 35));
+ assert(section_calls == (missing ? 0 : 3));
+ }
+ }
+}
+
+int main(void)
+{
+ assert(guest_map("weapon rating fixture", 0x50000000, 0x10000));
+ MEM32(0x500002e4) = 0x50000400;
+ MEM32(0x50000404) = 0x3606dfb0;
+ MEM32(0x500002e8) = 0x50000600;
+ MEM32(0x50000604) = 0x50001000;
+ MEM32(0x50000354) = 0x50000700;
+ weighted_ratings();
+ missing_and_empty_ratings();
+ puts("native weapon ratings: 18 signed, section, modifier and getter-mode cases passed");
+}
diff --git a/docs/combat-rules.md b/docs/combat-rules.md
@@ -39,8 +39,10 @@ Its three skill requirements, 1.5-second equip delay, persistent right-hand slot
and native owner/observer replication are described in
[inventory and equipment](inventory.md). Combat swapping is not implemented.
-The server still selects QL 1 regardless of MA skill and omits hit/miss
-rolls. Supported Metaplast armor now reduces normal hits using the weapon's
+The server still selects QL 1 regardless of MA skill. Ordinary attacks now
+use authored attack/defense ratings and a provisional hit probability curve;
+see [weapon hit and miss evidence](weapon-hit-chance.md). Supported Metaplast
+armor now reduces normal hits using the weapon's
damage type and minimum floor; [armor notes](armor.md) distinguish sourced
rules from provisional integer ordering. Level-1 Leets use an explicit
catalog-weapon profile; other NPCs retain 100 health, 5 damage and 1s/1s timing. Profile settings
diff --git a/docs/weapon-hit-chance.md b/docs/weapon-hit-chance.md
@@ -0,0 +1,137 @@
+# Ordinary weapon hits and misses
+
+Ordinary attacks now check the attacker's rating against the defense selected
+by the attacking weapon. A failed check emits the native miss message, spends
+a fired round, and advances the same attack/recharge cycle as a hit. It does
+not damage health, roll a critical or damage amount, break control nanos, or
+grant damage contribution, XP, loot or kill credit. It still starts NPC
+retaliation. Fast Attack and Fling retain their pre-15.5.5 defensive-check
+exemption; this change does not add a nano-resist rule.
+
+## Recovered rating ingredients
+
+The original 14.9.1 `kkr.dll` SHA-256 is
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+Functions `1008f1f0` and `1008f2f0` read item sections 12 and 13 respectively.
+Both calculate each signed skill-times-percentage term with integer division
+by 100 before summing. A strictly positive sum receives AddAllOff276 or
+AddAllDef277; a zero or negative sum does not. There is no floor after adding
+that modifier. Equipment and active nano modifiers participate.
+
+The NPC flag at actor offset `1b4` requests getter mode 2 for the weighted
+skills. Original getter `1006dfb0` reads raw stored stats in that mode, without
+player ability trickle or direct skill modifiers. The final all-off/all-def
+modifier still uses effective mode 0. Players use effective skills, including
+ability trickle, equipment and nanos. The server shares this calculation
+between attack and defense instead of assigning evade skills by weapon name.
+
+The three original Martial Arts Item records use attack MartialArts100 and
+defense EvadeClose155, each at 100 percent. That also supplies the current
+unarmed fallback. Other weapons use their authored section 13: DodgeRanged154,
+EvadeClose155, DuckExplosions153, or a weighted combination as supplied.
+
+`client/tests/weapon_rating.c` exercises the maintained native rating bodies
+and the native raw/effective getter branch. Eighteen hardcoded cases cover
+separate signed truncation, positive-sum gating, negative final values,
+NPC raw skills, effective modifiers, missing actors and empty sections.
+Linux and WASM results agree. Item section lookup and the mode-0 effective
+provider are fixture boundaries. Assembly and source provenance are retained
+in `local/hit-miss-research/native/ledger.md` and `rating-evidence.json`.
+
+## Provisional probability curve
+
+The original server's probability calculation has not been recovered.
+Period sources establish the relevance of attack skills, evades and Agg/Def,
+but do not establish a numerical curve. The current implementation uses the
+weapon formula in [Ebag333's calculator, preserved in a May 2018 repost](https://forums.funcom.com/t/ebag333s-ar-and-nr-hit-chance-calculator/4340).
+The raw post, unlike the rendered page, preserves its JavaScript:
+
+```
+chance = (3.75 + 0.0075 * defenderAggDef)
+ * (attackRating / (attackRating + defenseRating)) ^ 2.25
+```
+
+This is a later empirical model, not proof of the 14.9.1 server. Its author
+reports approximate accuracy at full defense, with weaker evidence elsewhere.
+The attack/defense ratio is an intermediate value, not the final hit chance.
+The separate nano calculator uses different coefficients and is not applied.
+The original thread's date was not established from its numeric thread ID.
+
+The server clamps defense to zero, effective defender Agg/Def to -100..100,
+and the resulting chance to 100 percent. Nonpositive attack ratings miss,
+including zero against zero. A positive attack against nonpositive defense
+lands. A uniform integer draw in 0..9999 is compared with the truncated chance
+times 10000. These bounds, zero handling and precision are reconstruction
+choices; no historical minimum or maximum hit-rate cap is claimed. At equal
+ratings the current thresholds are 6306, 7883 and 9460 for full defense,
+neutral and full aggression. NPCs use their combat profile's base Agg/Def;
+players use their slider, with effective stat51 modifiers added before clamp.
+
+NPC raw skill values remain a separate gap. Existing unspecified NPC stats
+retain the provisional five-point foundation. This implementation does not
+turn that default into a measured creature rating or fit a level curve to
+the reconstructed 100-HP Leet profiles. NPC stat growth, authentic population
+levels, and the exact historical hit/critical relationship remain open.
+
+## Protocol and durable outcomes
+
+The native MissedAttackInfo message is `5c654b28`. Its envelope actor is the
+attacker, and the payload is remaining ammo, weapon slot, attacker identity,
+then target identity. Identities have type 50000. The original activation
+queues zero damage/result 3 on the weapon animation path and displays miss
+feedback for a local attacker or defender. Observers receive the animation
+without the same local chat. See [combat protocol](combat-client-protocol.md).
+
+The same finite-ammo transaction handles hits and misses. The updated round
+must commit before live ammo, the attack clock or a result packet changes.
+A failed debit cancels combat without publishing a miss or granting threat
+or rewards. Nonlethal health and encounter state continue to use periodic
+checkpoints; a miss adds no damage contribution. Zero-damage hostility can
+retain zero threat to establish retaliation without earning a kill share.
+
+Go tests cover probability boundaries, zero/extreme ratings, authored evade
+selection, native weighted arithmetic, owner/observer payloads, unchanged
+health and rewards, exact cycle timing, one round per due swing, cold ammo
+restoration, failed debits, control preservation and special exemptions.
+Unrelated damage/loot fixtures explicitly force landed ordinary attacks;
+the hit-chance tests exercise both sides of each threshold independently.
+
+## Native verification
+
+The retained Atrox Enforcer completed a new, unmodified five-Leet level-2
+mission through the ordinary WASM UI. Training Evade Close from raw 5 to 13
+spent 102 earned IP; the native effective display became 15 and survived a
+server restart. Across the five fights, 28 NPC misses carried zero damage.
+The player's final native HP in each fight matched starting HP minus all
+received real hit damage. Recovery consumed five purchased lab charges.
+The character earned 500 kill XP, collected one corpse credit, and returned
+the book for 20 credits and a QL-2 glove. Cold native inventory retained all
+14 old instances, with only the lab count changing from 14 to 9, plus the
+new reward instance. Completion XP remains separately unresolved.
+
+A separate controlled visitor, with zero attack rating and a three-round
+pistol, delivered misses to its native owner and another native observer.
+Both heaps queued zero damage/result 3 and saw ammunition 2, 1, then 0.
+Player and target HP stayed unchanged, while the local participant displayed
+miss chat and the observer did not. Page reload and server restart retained
+zero ammo; trying the empty weapon produced no further result. No XP or
+damage contribution was granted. These deliberate fixture stats establish
+protocol behavior rather than historical NPC balance. All browser checks used
+the GPU and reported no page errors or unimplemented adapters.
+
+The ordinary trace also preserves the existing NPC recovery-phase limitation.
+Four targets required 103 authoritative damage, including a three-point combat
+recovery tick. One target displayed zero native HP 1.757 seconds before the
+server's final three-damage/death packet. This does not establish NPC HP
+agreement during combat; the broader [recovery audit](npc-regeneration.md)
+remains open. Player HP agreement and controlled zero-damage miss delivery
+were checked independently. Evidence is under `local/hit-miss-smoke/` and
+`local/hit-miss-controlled/`, including `native-verified.json`.
+
+The complete maintained Go suite passed: 1,664 top-level tests and 16,385
+results, with no skips, using `go test ./server/... ./tools/data/... -count=1
+-timeout 90m`. The final focused race run passed 11 top-level tests and 43
+results. All 113 Linux client contract programs passed on an isolated virtual
+display; the 18 rating cases also passed in WASM. The server build and Go vet
+passed. Test logs, source hashes and the completed verification checkpoint are
+retained in `local/hit-miss-research/` and `local/hit-miss-smoke/`.
diff --git a/server/aggdef_nano_test.go b/server/aggdef_nano_test.go
@@ -226,7 +226,7 @@ func TestAggDefNanoDamageCompanionsReachOrdinaryHits(t *testing.T) {
world, _ := newCombatNanoWorld(t, combatNanoFixture{})
player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
- player.stats.Body.MartialArts = 0
+ player.stats.Body.MartialArts = 1
player.inventory.LearnedNanos = []uint32{fixture.program}
target.health = 1000
castTestBuff(t, world, 1, 1, fixture.program)
diff --git a/server/combat.go b/server/combat.go
@@ -6,6 +6,7 @@ import (
"fmt"
"log"
"maps"
+ "math"
"math/rand/v2"
"slices"
"sort"
@@ -155,32 +156,79 @@ func (character *character) maximumNano() uint32 {
}
func (character *character) attackRating() int32 {
- stats := character.baseStats()
- weapon := character.attackWeapon()
- if weapon == nil {
- return character.effectiveSkill(100, stats.Body.MartialArts, [6]uint32{20, 50, 0, 0, 0, 30}) + character.equipmentBonus(276)
- }
- // kkr.dll 1008f1f0 divides each authored skill contribution separately.
+ return character.weaponRating(character.attackWeapon(), 12)
+}
+
+func (character *character) weaponRating(weapon *gamedata.Item, kind uint32) int32 {
+ // kkr.dll 1008f1f0/1008f2f0 use sections 12/13 and divide each term separately.
var rating int32
- for _, section := range weapon.Sections {
- if section.Type != 4 || section.Subtype != 4 || section.Entries == nil {
- continue
+ if weapon == nil {
+ // Martial Arts Item43712: attack MA100, defense EvadeClose155, both 100%.
+ stat := uint32(100)
+ if kind == 13 {
+ stat = 155
}
- for _, entry := range *section.Entries {
- if entry.Type != nil && *entry.Type == 12 {
- for _, weight := range *entry.Stats {
- value, _ := character.effectiveStat(weight[0])
- rating += value * int32(weight[1]) / 100
+ rating = character.combatSkill(stat)
+ } else {
+ for _, section := range weapon.Sections {
+ if section.Type != 4 || section.Subtype != 4 || section.Entries == nil {
+ continue
+ }
+ for _, entry := range *section.Entries {
+ if entry.Type != nil && *entry.Type == kind {
+ for _, weight := range *entry.Stats {
+ rating += character.combatSkill(weight[0]) * int32(weight[1]) / 100
+ }
}
}
}
}
if rating > 0 {
- rating += character.equipmentBonus(276)
+ modifier := uint32(276)
+ if kind == 13 {
+ modifier = 277
+ }
+ rating += character.equipmentBonus(modifier) + character.nanoBonus(modifier)
}
return rating
}
+func (character *character) combatSkill(stat uint32) int32 {
+ if character.npc {
+ // kkr.dll 1006dfb0 mode 2 reads NPC raw skills, without player trickle/modifiers.
+ stats := character.baseStats()
+ for _, field := range stats.trainingStats() {
+ if field.stat == stat {
+ return int32(*field.value)
+ }
+ }
+ return 0
+ }
+ value, _ := character.effectiveStat(stat)
+ return value
+}
+
+func (server *server) weaponLands_locked(attacker, target *character) bool {
+ attack := float64(attacker.attackRating())
+ defense := float64(max(0, target.weaponRating(attacker.attackWeapon(), 13)))
+ aggDef := target.aggDef
+ if target.npc && target.combatProfile != nil {
+ aggDef = target.combatProfile.AggDef
+ }
+ aggDef += target.equipmentBonus(51) + target.nanoBonus(51)
+
+ // Ebag333's later empirical weapon curve is provisional for 14.9.1.
+ chance := float64(0)
+ if attack > 0 {
+ chance = min(1, (3.75+0.0075*float64(min(100, max(-100, aggDef))))*math.Pow(attack/(attack+defense), 2.25))
+ }
+ roll := server.combatRoll
+ if roll == nil {
+ roll = rand.Uint32N
+ }
+ return roll(10000) < uint32(chance*10000)
+}
+
func (server *server) weaponHit_locked(attacker, target *character) (uint32, bool) {
roll := server.combatRoll
if roll == nil {
@@ -401,7 +449,15 @@ func (server *server) advanceCombat(now time.Time) {
if now.Before(attacker.nextAttack) {
continue
}
- damage, critical := server.weaponHit_locked(attacker, target)
+ damage, result := uint32(0), uint32(3)
+ if server.weaponLands_locked(attacker, target) {
+ var critical bool
+ damage, critical = server.weaponHit_locked(attacker, target)
+ result = 4
+ if critical {
+ result = 5
+ }
+ }
previous := *target
fired, award, err := server.applyWeaponDamage_locked(attacker, target, damage, now)
if err != nil {
@@ -416,7 +472,7 @@ func (server *server) advanceCombat(now time.Time) {
attack, recharge := attacker.attackDelays()
attacker.rechargeUntil = now.Add(recharge)
attacker.nextAttack = attacker.rechargeUntil.Add(attack)
- server.queueCombat_locked(updates, attacker, target, hitPacket(attacker, target, damage, critical))
+ server.queueCombat_locked(updates, attacker, target, weaponResultPacket(attacker, target, damage, result))
server.finishDamageEffects_locked(attacker, target, previous, now, updates)
server.applyExperienceAward_locked(award, now, updates)
}
@@ -468,7 +524,7 @@ func prepareDamage(attacker, target *character, damage uint32, now time.Time) ch
candidate.corpse = &corpse
}
// Credit the player or team present at each hit for this NPC life.
- if candidate.npc && !attacker.npc {
+ if candidate.npc && !attacker.npc && damage != 0 {
if candidate.threat == nil {
candidate.threat = make(map[uint32]int64)
}
@@ -596,9 +652,7 @@ func (server *server) sendCombatUpdates(updates map[*worldClient][][]byte) {
}
}
-func hitPacket(attacker, target *character, damage uint32, critical bool) []byte {
- // kkr.dll 0x100aec00: damage, ammo, slot, target identity, death reason and result.
- body := binary.BigEndian.AppendUint32(nil, damage)
+func weaponResultPacket(attacker, target *character, damage, result uint32) []byte {
slot := uint32(0)
ammo := uint32(0xffffffff)
if !attacker.npc && attacker.attackWeapon() != nil {
@@ -609,10 +663,16 @@ func hitPacket(attacker, target *character, damage uint32, critical bool) []byte
ammo = item.Ammo
}
}
- result := uint32(4)
- if critical {
- result = 5
+ if result == 3 {
+ // kkr.dll 100b1460/100b14f0: miss queues zero damage and the same ammo/slot.
+ var body []byte
+ for _, value := range []uint32{ammo, slot, 50000, attacker.id, 50000, target.id} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x5c654b28, 50000, attacker.id, body)
}
+ // kkr.dll 100aec00: damage, ammo, slot, target identity, death reason and result.
+ body := binary.BigEndian.AppendUint32(nil, damage)
for _, value := range []uint32{ammo, slot, 50000, target.id, 0, result} {
body = binary.BigEndian.AppendUint32(body, value)
}
diff --git a/server/combat_test.go b/server/combat_test.go
@@ -21,6 +21,13 @@ func (conn *combatTestConn) Write(packet []byte) (int, error) {
return len(packet), nil
}
+func landedCombatRoll(limit uint32) uint32 {
+ if limit == 10000 {
+ return 0
+ }
+ return limit - 1
+}
+
func newCombatWorld() (*server, *combatTestConn) {
conn := &combatTestConn{}
return &server{
@@ -32,7 +39,7 @@ func newCombatWorld() (*server, *combatTestConn) {
1: {id: 1, conn: conn, target: true, ready: true, npcs: map[uint32]bool{1000000: true}},
},
fighting: make(map[uint32]*character),
- combatRoll: func(limit uint32) uint32 { return limit - 1 },
+ combatRoll: landedCombatRoll,
}, conn
}
diff --git a/server/combat_visibility_test.go b/server/combat_visibility_test.go
@@ -80,7 +80,7 @@ func TestCombatVisibilityRechecksBeforeShotAndRetainsNPCThreat(t *testing.T) {
npcDeadline := target.nextAttack
target.position[0] = 16
rolls := 0
- world.combatRoll = func(limit uint32) uint32 { rolls++; return limit - 1 }
+ world.combatRoll = func(limit uint32) uint32 { rolls++; return landedCombatRoll(limit) }
world.advanceCombat(deadline.Add(time.Minute))
world.advanceCombat(deadline.Add(2 * time.Minute))
diff --git a/server/critical_hit_test.go b/server/critical_hit_test.go
@@ -43,6 +43,9 @@ func TestCriticalDamageRatingArmorOverequippingAndAddedDamage(t *testing.T) {
player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 158790, Quality: 1, Slot: 19, Count: 1})
}
world.combatRoll = func(limit uint32) uint32 {
+ if limit == 10000 {
+ return 0
+ }
if limit != 100 {
t.Fatal("a critical must not roll the ordinary damage range", limit)
}
@@ -90,6 +93,9 @@ func TestCriticalChanceBoundariesUseSignedWornModifiers(t *testing.T) {
player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 158790, Quality: 1, Slot: 19, Count: 1})
var bounds []uint32
world.combatRoll = func(limit uint32) uint32 {
+ if limit == 10000 {
+ return 0
+ }
bounds = append(bounds, limit)
if len(bounds) == 1 {
return scenario.roll
diff --git a/server/critical_nano_test.go b/server/critical_nano_test.go
@@ -57,6 +57,9 @@ func TestCriticalNanosChangeOrdinaryFastAttackAndFlingThresholds(t *testing.T) {
}
castTestBuff(t, world, 1, 1, fixture.Program)
world.combatRoll = func(limit uint32) uint32 {
+ if limit == 10000 {
+ return 0
+ }
if limit == 100 {
return roll
}
@@ -325,6 +328,9 @@ func TestCriticalNanoAddsToWornChance(t *testing.T) {
castTestBuff(t, world, 1, 1, 32065)
target.position, target.health = [3]float32{1, 0, 0}, 1000
world.combatRoll = func(limit uint32) uint32 {
+ if limit == 10000 {
+ return 0
+ }
if limit == 100 {
return roll
}
diff --git a/server/early_melee_test.go b/server/early_melee_test.go
@@ -132,6 +132,9 @@ func TestAdvancedBaseballbatUsesSelectedNormalAndFastDamageWithoutAmmunition(t *
t.Fatal(err)
}
world.combatRoll = func(bound uint32) uint32 {
+ if bound == 10000 {
+ return 0
+ }
if critical {
return 0
}
diff --git a/server/inventory_test.go b/server/inventory_test.go
@@ -165,7 +165,7 @@ func TestInventoryNativeMoveDeleteAndRestart(t *testing.T) {
func newTestInventoryServer(t *testing.T) *server {
t.Helper()
- world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character), combatRoll: func(limit uint32) uint32 { return limit - 1 }}
+ world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character), combatRoll: landedCombatRoll}
if _, err := world.loadNPCs(); err != nil {
t.Fatal(err)
}
diff --git a/server/mission_levels_test.go b/server/mission_levels_test.go
@@ -35,7 +35,7 @@ func TestMissionScalableRewardsFollowEveryDifficultyAndFamilyBoundary(t *testing
definition := gamedata.MissionTemplates[3221228472]
definition.RewardItems = []uint32{85596, 122691}
gamedata.MissionTemplates[3221228472] = definition
- world.combatRoll = func(bound uint32) uint32 { return bound - 1 }
+ world.combatRoll = landedCombatRoll
request := missionOffersRequest()
request[17] = byte(index + 1)
output.packets = nil
diff --git a/server/nano_control_break_test.go b/server/nano_control_break_test.go
@@ -260,7 +260,7 @@ func TestZeroDamageWeaponOutcomeDoesNotRollControlBreak(t *testing.T) {
t.Fatal(err)
}
player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
- player.stats.Ranged.Pistol, player.stats.Ranged.FlingShot = 0, 0
+ player.stats.Ranged.Pistol, player.stats.Ranged.FlingShot = 1, 0
if err := world.handleCombat(client, attackPacket(1, target.id)[20:]); err != nil {
t.Fatal(err)
diff --git a/server/nano_damage_test.go b/server/nano_damage_test.go
@@ -44,6 +44,8 @@ func newDirectDamageWorld(t *testing.T, fixture directDamageNanoFixture) (*serve
for _, field := range player.stats.trainingStats() {
*field.value = 2000
}
+ // Keep incoming weapon events viable against this spell fixture's evades.
+ world.characters[1000000].stats.Body.MartialArts = 2000
player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
player.stats.Speed.NanoInitiative = 5
player.stats.Body.NanoPool, player.nano = 30000, 50000
diff --git a/server/npcs_test.go b/server/npcs_test.go
@@ -37,7 +37,7 @@ func newTestServer(t *testing.T) *server {
t.Helper()
t.Chdir(t.TempDir())
world := newServer()
- world.combatRoll = func(limit uint32) uint32 { return limit - 1 }
+ world.combatRoll = landedCombatRoll
t.Cleanup(func() { world.db.Close() })
return world
}
diff --git a/server/reclaim_test.go b/server/reclaim_test.go
@@ -50,6 +50,8 @@ func defeatReclaimPlayer(t *testing.T, world *server) time.Time {
t.Helper()
player, npc := world.characters[1], world.characters[1000000]
player.health = 1
+ // Death fixtures require the killing attack to pass even against trained evades.
+ npc.stats.Body.MartialArts = 60000
npc.playfield, npc.position = player.playfield, player.position
if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
t.Fatal(err)
diff --git a/server/skill_nano_test.go b/server/skill_nano_test.go
@@ -37,6 +37,8 @@ func newSkillNanoWorld(t *testing.T) (*server, *combatTestConn) {
for _, field := range player.stats.trainingStats() {
*field.value = 900
}
+ // Keep combat events viable against this fixture's highly trained player.
+ world.characters[1000000].stats.Body.MartialArts = 900
player.stats.Body.NanoPool, player.nano = 30000, 50000
if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
diff --git a/server/weapon_miss_test.go b/server/weapon_miss_test.go
@@ -0,0 +1,287 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "slices"
+ "testing"
+ "time"
+)
+
+func TestOrdinaryWeaponHitThresholdUsesDefenderAggDef(t *testing.T) {
+ for _, scenario := range []struct {
+ aggDef int32
+ chance uint32
+ }{{-100, 6306}, {0, 7883}, {100, 9460}} {
+ for _, landed := range []bool{true, false} {
+ t.Run(fmt.Sprintf("%d/%t", scenario.aggDef, landed), func(t *testing.T) {
+ world, conn := newRangedWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
+ player.stats.Ranged.Pistol = 100
+ target.stats.Speed.DodgeRanged = 100
+ target.aggDef = scenario.aggDef
+ var bounds []uint32
+ world.combatRoll = func(limit uint32) uint32 {
+ bounds = append(bounds, limit)
+ if limit == 10000 {
+ if landed {
+ return scenario.chance - 1
+ }
+ return scenario.chance
+ }
+ return limit - 1
+ }
+
+ if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(player.nextAttack)
+
+ wantKey, wantBounds := uint32(0x5c654b28), []uint32{10000}
+ if landed {
+ wantKey, wantBounds = 0x46002f16, []uint32{10000, 100, 13}
+ }
+ if !slices.Equal(bounds, wantBounds) || binary.BigEndian.Uint32(conn.packets[1][16:20]) != wantKey ||
+ (target.health < 1000) != landed || player.inventory.Items[0].Ammo != 2 {
+ t.Fatal("hit threshold or draw sequence", bounds, target.health, conn.packets)
+ }
+ })
+ }
+ }
+}
+
+func TestOrdinaryWeaponHitChanceHandlesZeroAndExtremeRatings(t *testing.T) {
+ for _, scenario := range []struct {
+ attack, defense uint16
+ roll uint32
+ landed bool
+ }{{0, 0, 0, false}, {0, 100, 0, false}, {100, 0, 9999, true}, {100, 1, 9999, true}, {1, 60000, 0, false}} {
+ t.Run(fmt.Sprint(scenario), func(t *testing.T) {
+ world, conn := newRangedWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
+ player.stats.Ranged.Pistol = scenario.attack
+ target.stats.Speed.DodgeRanged = scenario.defense
+ world.combatRoll = func(limit uint32) uint32 {
+ if limit == 10000 {
+ return scenario.roll
+ }
+ return limit - 1
+ }
+
+ world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:])
+ world.advanceCombat(player.nextAttack)
+
+ key := uint32(0x5c654b28)
+ if scenario.landed {
+ key = 0x46002f16
+ }
+ if binary.BigEndian.Uint32(conn.packets[1][16:20]) != key || (target.health < 1000) != scenario.landed || player.inventory.Items[0].Ammo != 2 {
+ t.Fatal("nonpositive or extreme rating outcome", conn.packets)
+ }
+ })
+ }
+}
+
+func TestTrainedEvadeChangesIncomingOutcomeAndSurvivesRestart(t *testing.T) {
+ world, conn := newTrainingWorld(t)
+ player, npc := world.characters[1], world.characters[1000000]
+ npc.position = [3]float32{1, 0, 0}
+ npc.fighting, npc.nextAttack = 1, time.Now()
+ world.fighting[npc.id] = npc
+ world.combatRoll = func(limit uint32) uint32 { return min(5000, limit-1) }
+ world.advanceCombat(npc.nextAttack)
+ health := player.health
+ if health != player.maximumHealth()-5 {
+ t.Fatal("untrained baseline did not land the controlled attack", health)
+ }
+ trained := player.baseStats()
+ trained.Speed.EvadeClose = 6
+
+ err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(trained)[20:])
+ conn.packets = nil
+ world.advanceCombat(npc.nextAttack)
+ cold := newTestInventoryServer(t).characters[1]
+
+ if err != nil || player.health != health || player.stats.Speed.EvadeClose != 6 || cold.stats.Speed.EvadeClose != 6 ||
+ player.stats.ImprovementPoints >= 1500 || cold.stats.ImprovementPoints != player.stats.ImprovementPoints ||
+ len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x5c654b28 {
+ t.Fatal("trained evade did not change the same incoming roll or persist", health, player.health, player.stats, err)
+ }
+}
+
+func TestRangedMissSaveFailureDoesNotPublishOrSpendTheRound(t *testing.T) {
+ world, conn := newRangedWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ target.stats.Speed.DodgeRanged = 100
+ world.combatRoll = func(limit uint32) uint32 { return limit - 1 }
+ if _, err := world.db.Exec("CREATE TRIGGER fail_miss BEFORE UPDATE OF ammo ON items BEGIN SELECT RAISE(FAIL, 'test miss save failure'); END"); err != nil {
+ t.Fatal(err)
+ }
+ world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:])
+ conn.packets = nil
+
+ world.advanceCombat(player.nextAttack)
+ cold := newTestInventoryServer(t)
+
+ if target.health != 1000 || len(target.threat) != 0 || len(target.damageContributors) != 0 || target.fighting != 0 ||
+ player.inventory.Items[0].Ammo != 3 || cold.characters[1].inventory.Items[0].Ammo != 3 || player.fighting != 0 ||
+ !player.rechargeUntil.IsZero() || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x4a41203e {
+ t.Fatal("failed miss debit published state or feedback", conn.packets, player.inventory)
+ }
+}
+
+func TestOrdinaryMissDoesNotBreakControlEffects(t *testing.T) {
+ world, conn := newRootedControlWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ player.stats.Body.MartialArts = 5
+ target.stats.Speed.EvadeClose = 100
+ world.combatRoll = func(limit uint32) uint32 {
+ if limit != 10000 {
+ t.Fatal("a miss rolled damage or a control break", limit)
+ }
+ return limit - 1
+ }
+ before := slices.Clone(target.activeNanos)
+ world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:])
+
+ world.advanceCombat(player.nextAttack)
+ cold := newTestInventoryServer(t).characters[target.id]
+
+ if !slices.Equal(before, target.activeNanos) || !target.movementRestricted() || !cold.movementRestricted() || len(target.damageContributors) != 0 {
+ t.Fatal("miss broke a control nano or granted damage credit", target.activeNanos, cold.activeNanos)
+ }
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 65 {
+ t.Fatal("miss emitted a control-removal action")
+ }
+ }
+}
+
+func TestPre1555FastAndFlingBypassTheOrdinaryDefenseCheck(t *testing.T) {
+ for _, special := range []uint32{147, 150} {
+ t.Run(fmt.Sprint(special), func(t *testing.T) {
+ var world *server
+ var conn *combatTestConn
+ var request []byte
+ if special == 147 {
+ world, conn = newFastAttackWorld(t)
+ request = fastAttackRequest(1, 1000000)
+ } else {
+ world, conn = newRangedWorld(t)
+ request = flingShotRequest(1, 1000000)
+ }
+ target := world.characters[1000000]
+ target.stats.Speed.EvadeClose, target.stats.Speed.DodgeRanged = 60000, 60000
+ world.combatRoll = func(limit uint32) uint32 {
+ if limit == 10000 {
+ t.Fatal("period Fast/Fling made an ordinary defensive check")
+ }
+ return limit - 1
+ }
+
+ err := world.handleWeaponSpecial(world.clients[1], request[20:])
+
+ if err != nil || target.health >= 1000 || len(world.characters[1].skillLocks) != 1 {
+ t.Fatal("special did not land or retain its lock", target.health, err)
+ }
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5c654b28 {
+ t.Fatal("special emitted ordinary miss feedback")
+ }
+ }
+ })
+ }
+}
+
+func TestWeaponDefenseUsesTheAttackingWeaponAuthoredSkill(t *testing.T) {
+ for _, stat := range []uint32{153, 154, 155} {
+ t.Run(fmt.Sprint(stat), func(t *testing.T) {
+ world, conn := newRangedWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
+ player.stats.Ranged.Pistol = 100
+ target.stats.Speed.DuckExplosions, target.stats.Speed.DodgeRanged, target.stats.Speed.EvadeClose = 1, 1, 1
+ for _, field := range target.stats.trainingStats() {
+ if field.stat == stat {
+ *field.value = 100
+ }
+ }
+ original := gamedata.ItemTemplates[123742]
+ weapon := *original
+ weapon.Sections = slices.Clone(original.Sections)
+ kind := uint32(13)
+ weights := [][2]uint32{{stat, 100}}
+ for index, section := range weapon.Sections {
+ if section.Type == 4 && section.Subtype == 4 {
+ entries := slices.Clone(*section.Entries)
+ for index := range entries {
+ if entries[index].Type != nil && *entries[index].Type == kind {
+ entries[index].Stats = &weights
+ }
+ }
+ weapon.Sections[index].Entries = &entries
+ }
+ }
+ gamedata.ItemTemplates[123742] = &weapon
+ t.Cleanup(func() { gamedata.ItemTemplates[123742] = original })
+ world.combatRoll = func(limit uint32) uint32 { return min(7883, limit-1) }
+
+ world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:])
+ world.advanceCombat(player.nextAttack)
+
+ if target.health != 1000 || binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x5c654b28 {
+ t.Fatal("defense ignored the weapon's authored skill", stat, target.health)
+ }
+ })
+ }
+}
+
+func TestRangedMissPreservesHealthCreditsAndClockAndCommitsAmmunition(t *testing.T) {
+ world, conn := newRangedWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ target.health = 1
+ target.stats.Speed.DodgeRanged = 100
+ target.position = [3]float32{1, 0, 0}
+ 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{target.id: true}}
+ world.combatRoll = func(limit uint32) uint32 { return limit - 1 }
+ if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ now := player.nextAttack
+
+ world.advanceCombat(now)
+ world.advanceCombat(now)
+ cold := newTestInventoryServer(t)
+
+ if target.health != 1 || target.corpse != nil || len(target.damageContributors) != 0 ||
+ player.experience != 0 || player.inventory.Credits != 0 || player.inventory.Items[0].Ammo != 2 || cold.characters[1].inventory.Items[0].Ammo != 2 ||
+ player.nextAttack != now.Add(3950*time.Millisecond) || player.rechargeUntil != now.Add(1970*time.Millisecond) {
+ t.Fatal("miss changed health, rewards, ammunition or cycle", target, player)
+ }
+ if target.fighting != 1 || len(target.threat) != 1 || target.threat[1] != 0 {
+ t.Fatal("miss did not begin retaliation without damage credit", target.threat)
+ }
+ var miss, observed []byte
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5c654b28 {
+ miss = packet[29:53]
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 || binary.BigEndian.Uint32(packet[16:20]) == 0x3710256c {
+ t.Fatal("miss also emitted damage", packet)
+ }
+ }
+ for _, packet := range observer.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5c654b28 {
+ observed = packet[29:53]
+ }
+ }
+ if !bytes.Equal(miss, []byte{0, 0, 0, 2, 0, 0, 0, 6, 0, 0, 195, 80, 0, 0, 0, 1, 0, 0, 195, 80, 0, 15, 66, 64}) || !bytes.Equal(miss, observed) {
+ t.Fatalf("miss payload or observer mismatch: %x %x", miss, observed)
+ }
+}
diff --git a/server/weapon_quality_lifecycle_test.go b/server/weapon_quality_lifecycle_test.go
@@ -169,7 +169,7 @@ func TestWeaponQualityFailedShotAndReloadPreserveBothSides(t *testing.T) {
player, client := world.characters[1], world.clients[1]
player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
player.stats.Ranged.Pistol, player.stats.Ranged.FlingShot = 400, 100
- world.combatRoll = func(limit uint32) uint32 { return limit - 1 }
+ world.combatRoll = landedCombatRoll
player.inventory.Items[0].Quality = 5
if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
diff --git a/server/weapon_quality_test.go b/server/weapon_quality_test.go
@@ -152,6 +152,9 @@ func TestWeaponQualityNormalAndFlingDamageAmmoAndReloadRecover(t *testing.T) {
t.Fatal(err)
}
world.combatRoll = func(limit uint32) uint32 {
+ if limit == 10000 {
+ return 0
+ }
if limit == 100 && critical {
return 0
}
diff --git a/server/weapon_rating_test.go b/server/weapon_rating_test.go
@@ -0,0 +1,59 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "fmt"
+ "testing"
+)
+
+func TestWeaponRatingsMatchNativeWeightedSkillContract(t *testing.T) {
+ for _, kind := range []uint32{12, 13} {
+ for _, scenario := range []struct {
+ npc bool
+ first, second uint16
+ weight uint32
+ skillBonus, modifier int32
+ want int32
+ }{
+ {false, 125, 125, 50, 0, 7, 131},
+ {true, 125, 125, 50, 100, 7, 131},
+ {false, 125, 125, 50, 100, 7, 231},
+ {false, 3, 3, 33, 0, 99, 0},
+ {false, 125, 129, 50, -128, 99, -1},
+ {false, 125, 131, 50, -128, 99, 0},
+ {false, 3, 3, 50, 0, -7, -5},
+ {true, 3, 3, 50, -128, -7, -5},
+ } {
+ t.Run(fmt.Sprintf("%d/%+v", kind, scenario), func(t *testing.T) {
+ actor := &character{npc: scenario.npc, stats: testCharacterStats()}
+ actor.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
+ first, second, modifier := int32(100), int32(102), int32(276)
+ actor.stats.Body.MartialArts, actor.stats.Melee.OneHandBlunt = scenario.first, scenario.second
+ if kind == 13 {
+ first, second, modifier = 155, 154, 277
+ actor.stats.Speed.EvadeClose, actor.stats.Speed.DodgeRanged = scenario.first, scenario.second
+ }
+ weights := [][2]uint32{{uint32(first), scenario.weight}, {uint32(second), scenario.weight}}
+ entries := []gamedata.ItemEntry{{Type: &kind, Stats: &weights}}
+ weapon := &gamedata.Item{Sections: []gamedata.ItemSection{{Type: 4, Subtype: 4, Entries: &entries}}}
+ functions := []gamedata.ItemFunction{
+ {ID: 53045, Arguments: []gamedata.ItemArgument{{Integer: &first}, {Integer: &scenario.skillBonus}}},
+ {ID: 53045, Arguments: []gamedata.ItemArgument{{Integer: &second}, {Integer: &scenario.skillBonus}}},
+ {ID: 53045, Arguments: []gamedata.ItemArgument{{Integer: &modifier}, {Integer: &scenario.modifier}}},
+ }
+ original := gamedata.NanoTemplates[43371]
+ program := *original
+ program.Sections = []gamedata.ItemSection{{Type: 2, Subtype: 0, Functions: &functions}}
+ gamedata.NanoTemplates[43371] = &program
+ t.Cleanup(func() { gamedata.NanoTemplates[43371] = original })
+ actor.activeNanos = []activeNano{{program: 43371}}
+
+ rating := actor.weaponRating(weapon, kind)
+
+ if rating != scenario.want {
+ t.Fatalf("native weighted rating: got %d want %d", rating, scenario.want)
+ }
+ })
+ }
+ }
+}