aorecomp

Anarchy Online classic in the browser

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


commit 901d8affc3d95e68bfa42e3bc5e776597b723a88
parent 948e6af8f4ca36d8ff57b937990e50feef872f79
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 15:33:30 +0000

Preserve signed effective stat calculations

Diffstat:
MTODO.md | 18++++++++++++------
Mdocs/combat-client-stats.md | 3+++
Adocs/signed-stats.md | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/armor_overequipping.go | 10+++++-----
Mserver/backpack_equipment.go | 10+++++-----
Mserver/briefcase_weapon_test.go | 2+-
Mserver/combat.go | 16++++++++--------
Mserver/equipment.go | 6+++---
Mserver/ip_training.go | 4++--
Mserver/nano_casting.go | 2+-
Mserver/regeneration.go | 14+++++++-------
Mserver/shops.go | 7++++---
Aserver/signed_stats_test.go | 232+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/stats.go | 12++++++------
Mserver/weapon_stats.go | 4++--
Mserver/weapon_stats_test.go | 2+-
16 files changed, 381 insertions(+), 50 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -894,12 +894,18 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah replacement, signed effective stats, skill-buff propagation, NPC persistence, expiry/death/respawn and atomic outcomes before enabling them. Critical hits and applying the XP modifier to awarded XP remain the shared combat milestones. -- [ ] Preserve signed effective abilities and skills throughout server stat - calculations. Negative worn modifiers and Psychic debuffs must feed signed - ability trickle without unsigned wrap or an invented zero floor. Direct skill - nano modifiers must affect requirements, attack rating and derived skills. - Cover values below zero, overlapping effects, removal and restart against - the original getter chain; see [Briefcase research](docs/briefcase-weapon.md). +- [x] Preserve signed effective abilities, skill trickle and attack rating in + the shared calculators and their current consumers. Include direct skill nano + contributions, signed requirement/OE/timing comparisons, regeneration and + vendor price rounding. Cover negative inputs, overlap/removal and the native + float boundaries; see [signed stats](docs/signed-stats.md). +- [ ] Extend signed-effect verification before admitting broader debuffs or + skill nanos. Audit every transaction/cache/wire path when a final HP/nano + maximum becomes negative, extreme negative attack ratings and damage/AC + floors. Verify direct skill effect publication, persistence/restart and NPC + 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. - [ ] 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 diff --git a/docs/combat-client-stats.md b/docs/combat-client-stats.md @@ -85,6 +85,9 @@ runs of the compact ability and player/NPC weapon-layout tests passed in ## Skills and attack/defense ratings +The server's signed calculation and consumer checks are documented in +[signed effective stats](signed-stats.md), including original getter fixtures. + Ability trickle is a weighted sum divided by four, converted to integer before adding the base skill. The database supplies six integer ability percentages per skill, resource type 1000204. Defaults and exact weights for the current diff --git a/docs/signed-stats.md b/docs/signed-stats.md @@ -0,0 +1,89 @@ +# Signed effective stats + +Raw trained abilities and skills remain nonnegative stored values. Effective +abilities, effective skills and attack rating are signed calculations. The +server retains negative contributions through ability trickle, direct skill +effects, requirements, initiative, regeneration and the vendor price formula. +It converts signed attack rating to its DWORD representation when publishing +stat22, rather than converting it before damage arithmetic. + +``` +weighted = sum(signed_effective_ability * authored_percentage) +trickle = trunc(weighted * float32(.01) * .25) +effective_skill = raw_skill + trickle + worn_skill_bonus + nano_skill_bonus +``` + +Truncation is toward zero. Neither an effective ability nor a skill gets a +zero floor. The original float32 .01 is below exact .01: an ability of8 at100% +weight contributes1, and -8 contributes-1. Integer division400 changes these +boundaries. Supported stat magnitudes keep the weighted integer products +exactly representable; arbitrary overflowing modifiers are outside this check. + +Each consumer retains its own rule. Requirements compare signed stats. Armor +and weapon OE cap the deficit tier at4. Initiative retains its sign in the +timing formulas. Resource maxima use signed sums; regeneration uses signed Body +Development division, and current HP/nano are floored at0. Negative computed +recovery alone does not drain a full resource. Training ignores a nonpositive +ability-derived cap. Vendor sales preserve negative Computer Literacy through +both truncations and floor only the final line price at0. + +## Original evidence + +`local/signed-stat-research/ledger.md` binds original14.9.1 KKR SHA256 +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +The fixture runs seven maintained lifted routines, with original assembly +provenance and exact constants/tables. Getter1006dfb0 reaches10075ca0/10075c60, +signed trickle10073fa0 and modifier lookup10074a30;10074730/10074b00 add/remove +contributions. Linux and WASM produce the same15 hardcoded results, including +negative abilities/skills, overlap/removal and the8/-8 float boundary. Resource +lookup, map allocation and unrelated notifications are fixture boundaries. +This executes lifted routines, not the original Windows DLL. + +`resource-consumers.md` retains ten further original records:10075910 preserves +signed maxima,1006e030 floors current resources,1006ea50 uses signed division, +and10059bd0 caps current nano. `consumers/ledger.md` retains eight original +records for vendor finalizer100a99d0 and training cap100755c0. These establish +client formulas; the original server remains unobserved. Normal-hit damage +scaling remains the documented provisional server formula. + +The content audit hash-checks57 admitted original equipment records and212 +OnWear Modify functions. None supplies negative abilities/skills or AllOff/ +AllDef; the only negative modifier is Modified Pioneer Backpack's Scale360=-3. +The seven admitted ability nanos are positive. Tests supply authored Psychic-17 +and Psychology+52/+22 as calculation inputs; they do not admit those casts or +enable Briefcase procs. Synthetic negative skill fixtures are labeled separately. + +## Verification and remaining work + +Go regressions reproduce unsigned trickle overflow and missing direct nano skill +contributions. They check signed float boundaries, removal, overlap, real program +values feeding weapon requirements/rating, negative requirements with positive +controls, initiative, special locks, resources, regeneration and a durable sale. +Positive gear and ability nano regressions remain in place. Hardware WASM and +Go validation artifacts are under `local/signed-stat-smoke/` and +`local/signed-stat-research/`. + +The full Go suite passed in434.508 seconds. Affected stat, equipment, weapon, +bank, backpack, nano, training, regeneration and sale paths passed twice under +the race detector in274.390 seconds; process-crash cases are covered by the +full suite. The later durable signed-sale regression passed separately, including +two race runs. Vet passed with `-stdversion=false`; the existing toolchain +declaration mismatch remains in TODO. The first sandboxed full run could not +open a test socket and is retained separately; it is not counted as a pass. + +One hardware Chromium WASM client wore Modified Pioneer Backpack and cast +Psychic Boost through the native UI. Maxima progressed37/620 ->40/623 ->40/629. +A server restart retained the same item and single modifier contributions. +Native cancellation returned40/623, and native removal restored37/620 with +all backpack modifiers cleared. Native object reads,11902 decoded world packets +and SQLite snapshots verify the same identity, quantity and placement. Browser +and adapter errors were empty. The browser and owned fixtures were cleaned up; +all unrelated rows were unchanged by cleanup, and the single LAN preview was +restored. `verification.json` retains the assertions and GPU OpenGL4.5 identity. + +Before broader negative-effect admission, audit all resource transactions and +wire/cache consumers when a final maximum becomes negative. Extreme negative +attack ratings and outgoing damage/AC floors still need authoritative rules. +Direct skill effects also need cast/proc admission, NCU/replacement, publication, +persistence and NPC lifecycle coverage before enabling the Briefcase programs. +This calculation change admits no new nano or worn-item family. diff --git a/server/armor_overequipping.go b/server/armor_overequipping.go @@ -43,22 +43,22 @@ func (character *character) armorOverequippingTier(item ownedItem) uint32 { if requirement.Operator != 2 { continue } - var actual uint32 + var actual int32 switch requirement.Stat { case 16, 17, 19: actual = character.effectiveAbility(uint32(requirement.Stat)) case 37: - actual = character.titleLevel() + actual = int32(character.titleLevel()) case 54: - actual = uint32(character.level) + actual = int32(character.level) 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}) } value := interpolateItemValue(requirement.Value, (*second.Sections[sectionIndex].Actions)[actionIndex].Requirements[index].Value, *first.Quality, *second.Quality, item.Quality) - if int32(actual) < value { - tier = max(tier, min(4, (uint32(value)-actual)*5/uint32(value))) + if actual < value { + tier = max(tier, min(4, uint32((int64(value)-int64(actual))*5/int64(value)))) } } } diff --git a/server/backpack_equipment.go b/server/backpack_equipment.go @@ -24,16 +24,16 @@ func (character *character) canWearContainer(item ownedItem) bool { if requirement.Operator == 4 { continue } - var actual uint32 + var actual int32 switch requirement.Stat { case 19: actual = character.effectiveAbility(19) case 37: - actual = character.titleLevel() + actual = int32(character.titleLevel()) case 54: - actual = uint32(character.level) + actual = int32(character.level) case 60: - actual = uint32(max(1, character.profession)) + actual = int32(max(1, character.profession)) case 131: actual = character.effectiveSkill(131, stats.NanoAiding.TimeAndSpace, [6]uint32{0, 20, 0, 80, 0, 0}) case 137: @@ -44,7 +44,7 @@ func (character *character) canWearContainer(item ownedItem) bool { 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 { + if requirement.Operator == 0 && actual != value || requirement.Operator == 2 && actual <= value { return false } } diff --git a/server/briefcase_weapon_test.go b/server/briefcase_weapon_test.go @@ -112,7 +112,7 @@ func TestBriefcaseWeaponDamageUsesAuthoredSkillAndEveryOERequirement(t *testing. minimum := player.normalDamage(world.characters[1000000], func(uint32) uint32 { return 0 }) maximum := player.normalDamage(world.characters[1000000], func(limit uint32) uint32 { return limit - 1 }) - if minimum != scenario.minimum || maximum != scenario.maximum || player.attackRating() != uint32(scenario.psychology) { + if minimum != scenario.minimum || maximum != scenario.maximum || player.attackRating() != int32(scenario.psychology) { t.Fatalf("Psychology %d level %d: got %d..%d AR%d, want %d..%d", scenario.psychology, scenario.level, minimum, maximum, player.attackRating(), scenario.minimum, scenario.maximum) } } diff --git a/server/combat.go b/server/combat.go @@ -105,7 +105,7 @@ func (character *character) attackDelays() (time.Duration, time.Duration) { return weaponDelays(weapon, character.effectiveStat(initiative), character.aggDef) } initiative := character.effectiveSkill(120, stats.Speed.PhysicalInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) - return weaponDelays(nil, int32(initiative), character.aggDef) + return weaponDelays(nil, initiative, character.aggDef) } func (character *character) titleLevel() uint32 { @@ -129,7 +129,7 @@ func (character *character) maximumHealth() uint32 { 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 := 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.equipmentBonus(1)) + return uint32(int32(stats[0]) + int32(character.level)*int32(stats[1]+gamedata.ProfessionTitles[max(1, character.profession)].Health[character.titleLevel()-1]) + bodyDevelopment*int32(stats[2]) + character.equipmentBonus(1)) } func (character *character) maximumNano() uint32 { @@ -137,14 +137,14 @@ func (character *character) maximumNano() uint32 { 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 := 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)) + return uint32(int32(stats[0]) + int32(character.level)*int32(stats[1]+gamedata.ProfessionTitles[max(1, character.profession)].Nano[character.titleLevel()-1]) + nanoPool*int32(stats[2]) + character.inventory.equipmentBonus(221)) } -func (character *character) attackRating() uint32 { +func (character *character) attackRating() int32 { stats := character.baseStats() weapon := character.attackWeapon() if weapon == nil { - return uint32(int32(character.effectiveSkill(100, stats.Body.MartialArts, [6]uint32{20, 50, 0, 0, 0, 30})) + character.equipmentBonus(276)) + 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. var rating int32 @@ -163,7 +163,7 @@ func (character *character) attackRating() uint32 { if rating > 0 { rating += character.equipmentBonus(276) } - return uint32(rating) + return rating } func (attacker *character) normalDamage(target *character, roll func(uint32) uint32) uint32 { @@ -195,8 +195,8 @@ func (attacker *character) normalDamage(target *character, roll func(uint32) uin minimum -= minimum * tier / 4 maximum -= maximum * tier / 4 } - minimum += minimum * rating / 400 - maximum += maximum * rating / 400 + minimum = uint32(int64(minimum) + int64(minimum)*int64(rating)/400) + maximum = uint32(int64(maximum) + int64(maximum)*int64(rating)/400) } // Period AC rule: reduce the rolled hit without crossing the weapon minimum. diff --git a/server/equipment.go b/server/equipment.go @@ -85,8 +85,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.effectiveAbility(16)) <= value || - requirement.Stat == 17 && int32(character.effectiveAbility(17)) <= value { + if requirement.Stat == 16 && character.effectiveAbility(16) <= value || + requirement.Stat == 17 && character.effectiveAbility(17) <= value { return false } } @@ -318,7 +318,7 @@ func (server *server) advanceEquipment(now time.Time) { 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()}, + {22, uint32(attackRating), uint32(character.attackRating())}, } { if stat[1] != stat[2] { if stat[0] == 1 || stat[0] == 221 { diff --git a/server/ip_training.go b/server/ip_training.go @@ -30,7 +30,7 @@ func (character *character) trainingMaximum(stat uint32) uint32 { // FUN_10073fa0(stat, 0) includes equipment ability modifiers in this bound. var weighted int64 for index, weight := range gamedata.IPTraining.Weights[stat] { - weighted += int64(int32(character.effectiveAbility(16+uint32(index)))) * int64(weight) + weighted += int64(character.effectiveAbility(16+uint32(index))) * int64(weight) } abilityMaximum := int64(float64(weighted) * float64(float32(0.01)) * 0.25 * 8) if abilityMaximum > 0 { @@ -124,7 +124,7 @@ func (server *server) handleSkillTraining(client *worldClient, body []byte) erro for _, stat := range [][3]uint32{ {1, baseHealth, player.maximumHealth() - uint32(player.inventory.equipmentBonus(1))}, {221, baseNano, player.maximumNano() - uint32(player.inventory.equipmentBonus(221))}, - {22, attackRating, player.attackRating()}, + {22, uint32(attackRating), uint32(player.attackRating())}, } { if stat[1] != stat[2] { if stat[0] == 1 || stat[0] == 221 { diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -77,7 +77,7 @@ func (player *character) abilityNanoRequirementsMet(definition *gamedata.Item) b if requirement.Stat == 128 { base = stats.NanoAiding.BiologicalMetamorphosis } - if int32(player.effectiveSkill(uint32(requirement.Stat), base, [6]uint32{0, 0, 0, 80, 0, 20})) <= requirement.Value { + if player.effectiveSkill(uint32(requirement.Stat), base, [6]uint32{0, 0, 0, 80, 0, 20}) <= requirement.Value { return false } } diff --git a/server/regeneration.go b/server/regeneration.go @@ -51,7 +51,7 @@ func (server *server) advanceRegeneration(now time.Time) { stats := player.baseStats() healthInterval, nanoInterval := player.regenerationIntervals() nanoInterval &^= 1 - rest := uint32(100) + rest := int32(100) if player.sitting { rest = 25 if healthInterval > 1 { @@ -60,13 +60,13 @@ func (server *server) advanceRegeneration(now time.Time) { } 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] - player.health = min(player.maximumHealth(), player.health+gain) + if int32(player.health) < int32(player.maximumHealth()) && client.regenerationSeconds%healthInterval == 0 { + gain := bodyDevelopment/rest + [8]int32{2, 3, 3, 2, 4, 6, 2, 2}[breed] + player.health = uint32(max(0, min(int32(player.maximumHealth()), int32(player.health)+gain))) } - if nanoInterval == 0 || client.regenerationSeconds%nanoInterval == 0 { - gain := bodyDevelopment/rest + [8]uint32{2, 3, 3, 4, 2, 1, 2, 2}[breed] - player.nano = min(player.maximumNano(), player.nano+gain) + if int32(player.nano) < int32(player.maximumNano()) && (nanoInterval == 0 || client.regenerationSeconds%nanoInterval == 0) { + gain := bodyDevelopment/rest + [8]int32{2, 3, 3, 4, 2, 1, 2, 2}[breed] + player.nano = uint32(max(0, min(int32(player.maximumNano()), int32(player.nano)+gain))) } server.queueQuietHealth_locked(updates, player) diff --git a/server/shops.go b/server/shops.go @@ -161,15 +161,16 @@ func (item ownedItem) shopPrice() uint32 { return uint32(float64(minimum) + difference*difference/float64(maximum-minimum)) } -func shopSalePrice(item ownedItem, modifier, computerLiteracy uint32) uint64 { +func shopSalePrice(item ownedItem, modifier uint32, computerLiteracy int32) uint64 { // kkr.dll FUN_100a99d0 rounds the charge-normalized unit price to float32. price := float32(item.shopPrice()) if charges := int32(itemStat(item.templateDefinition(), 212)); item.Type != 51018 && charges > 0 { price /= float32(charges) } base := uint64(float64(item.Count) * float64(price) * float64(modifier) * 0.01) - markup := uint64(float64(computerLiteracy) * float64(float32(0.025))) - return base + uint64(float64(markup)*float64(float32(0.01))*float64(base)) + // kkr.dll 100a9b33..100a9b5f preserves signed literacy, then floors the line total. + markup := int64(float64(computerLiteracy) * float64(float32(0.025))) + return uint64(max(0, int64(base)+int64(float64(markup)*float64(float32(0.01))*float64(base)))) } func (server *server) handleShopTrade(client *worldClient, body []byte) error { diff --git a/server/signed_stats_test.go b/server/signed_stats_test.go @@ -0,0 +1,232 @@ +package main + +import ( + "ao/server/gamedata" + "testing" + "time" +) + +func syntheticNanoModifiers(t *testing.T, modifiers [][2]int32) []activeNano { + t.Helper() + var functions []gamedata.ItemFunction + for index := range modifiers { + functions = append(functions, gamedata.ItemFunction{ID: 53045, Arguments: []gamedata.ItemArgument{ + {Integer: &modifiers[index][0]}, {Integer: &modifiers[index][1]}, + }}) + } + gamedata.NanoTemplates[0] = &gamedata.Item{Sections: []gamedata.ItemSection{{Type: 2, Functions: &functions}}} + t.Cleanup(func() { delete(gamedata.NanoTemplates, 0) }) + return []activeNano{{program: 0}} +} + +func TestSignedAbilityNanoContributionsStackAndRemove(t *testing.T) { + player := &character{stats: testCharacterStats()} + player.stats.Abilities.Psychic = 6 + // These authored programs are calculation inputs, not admitted casts or procs. + player.activeNanos = []activeNano{{program: 207287}} + + negative := player.effectiveAbility(21) + player.activeNanos = append(player.activeNanos, activeNano{program: 27134}) + overlapped := player.effectiveAbility(21) + player.activeNanos = player.activeNanos[1:] + positive := player.effectiveAbility(21) + player.activeNanos = nil + + if int64(negative) != -11 || overlapped != 1 || positive != 18 || player.effectiveAbility(21) != 6 || player.stats.Abilities.Psychic != 6 { + t.Fatalf("signed contributions did not restore raw ability: %d/%d/%d/%d", negative, overlapped, positive, player.effectiveAbility(21)) + } +} + +func TestSignedSkillTrickleMatchesOriginalGetterFixture(t *testing.T) { + for _, scenario := range []struct { + name string + psychic uint16 + ability, first, next int32 + weights [6]uint32 + want int64 + }{ + {"negative ability", 6, -17, 0, 0, [6]uint32{0, 0, 0, 0, 0, 100}, 3}, + {"negative direct skill", 6, -17, -8, 0, [6]uint32{0, 0, 0, 0, 0, 100}, -5}, + {"overlapping direct skill", 6, -17, -8, 12, [6]uint32{0, 0, 0, 0, 0, 100}, 7}, + {"removed negative skill", 6, -17, 0, 12, [6]uint32{0, 0, 0, 0, 0, 100}, 15}, + {"mixed signed weights", 6, -17, 0, 0, [6]uint32{0, 0, 0, 50, 0, 50}, 5}, + {"restored abilities", 6, 0, 0, 0, [6]uint32{0, 0, 0, 50, 0, 50}, 6}, + {"positive float boundary", 8, 0, 0, 0, [6]uint32{0, 0, 0, 0, 0, 100}, 6}, + {"negative float boundary", 8, -16, 0, 0, [6]uint32{0, 0, 0, 0, 0, 100}, 4}, + } { + t.Run(scenario.name, func(t *testing.T) { + player := &character{stats: testCharacterStats()} + player.stats.Abilities = characterAbilitiesStats{6, 6, 6, 6, 6, scenario.psychic} + // Synthetic effects isolate arithmetic without claiming catalog admission. + player.activeNanos = syntheticNanoModifiers(t, [][2]int32{{21, scenario.ability}, {162, scenario.first}, {162, scenario.next}}) + + got := player.effectiveSkill(162, 5, scenario.weights) + + if int64(got) != scenario.want { + t.Fatalf("got %d, want %d", got, scenario.want) + } + }) + } +} + +func TestSignedNegativeAbilitiesDoNotPassEquipmentRequirements(t *testing.T) { + player := &character{level: 200, profession: 8, playfield: 950, stats: testCharacterStats()} + player.activeNanos = syntheticNanoModifiers(t, [][2]int32{{16, -100}, {17, -100}, {18, -100}, {19, -100}, {20, -100}, {21, -100}}) + + for _, item := range []ownedItem{ + {Type: 51018, Template: 209283, Quality: 1}, + {Type: 51018, Template: 123742, Quality: 1}, + {Type: 51022, Template: 101173, Quality: 1}, + {Type: 51022, Template: 36783, Quality: 1}, + {Type: 51022, Template: 36779, Quality: 1}, + {Type: 51022, Template: 85512, Quality: 1}, + {Type: 51022, Template: 117294, Quality: 15}, + {Type: 51022, Template: 117322, Quality: 30}, + {Type: 51017, Template: 200461, Quality: 200}, + } { + if player.canEquip(item) { + t.Fatalf("negative effective requirement admitted template %d", item.Template) + } + positive := *player + positive.activeNanos = nil + positive.stats.Abilities = characterAbilitiesStats{5000, 5000, 5000, 5000, 5000, 5000} + if !positive.canEquip(item) { + t.Fatalf("positive requirement control rejected template %d", item.Template) + } + } + if player.nanoRequirementsMet(29618) || player.nanoRequirementsMet(27169) { + t.Fatal("negative effective skills admitted a nano") + } +} + +func TestSignedNonpositiveTrickleDoesNotCreateATrainingCap(t *testing.T) { + player := &character{level: 3, stats: testCharacterStats()} + player.stats.Abilities = characterAbilitiesStats{6, 6, 6, 6, 6, 6} + player.activeNanos = []activeNano{{program: 207287}} + + maximum := player.trainingMaximum(132) + + if maximum != 17 { + t.Fatalf("negative untruncated ability bound replaced the title/level cap: %d", maximum) + } +} + +func TestSignedPsychicTrickleFeedsResourcesAndRegenerationInterval(t *testing.T) { + player := &character{appearance: 1 << 4, level: 1, stats: testCharacterStats()} + player.stats.Abilities = characterAbilitiesStats{6, 6, 6, 6, 6, 6} + player.activeNanos = []activeNano{{program: 207287}} + + health, nano := player.maximumHealth(), player.maximumNano() + healthInterval, nanoInterval := player.regenerationIntervals() + player.activeNanos = nil + restoredHealth, restoredNano := player.maximumHealth(), player.maximumNano() + + if health != 34 || nano != 26 || healthInterval != 29 || nanoInterval != 30 || restoredHealth != 34 || restoredNano != 32 { + t.Fatalf("signed Psychic resource calculations: %d/%d intervals %d/%d, restored %d/%d", health, nano, healthInterval, nanoInterval, restoredHealth, restoredNano) + } +} + +func TestSignedDirectInitiativeAndSpecialSkillKeepTheirSign(t *testing.T) { + player := &character{stats: testCharacterStats()} + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.activeNanos = syntheticNanoModifiers(t, [][2]int32{{120, -10}, {149, -10}, {150, -200}}) + + attack, recharge := player.attackDelays() + cast := player.nanoCastDelay(29618) + lock := player.flingShotLockSeconds() + + if attack != 2*time.Second || recharge != 2010*time.Millisecond || cast != 2634999990*time.Nanosecond || lock != 21 { + t.Fatalf("signed timing: %v/%v cast %v lock %d", attack, recharge, cast, lock) + } +} + +func TestSignedNegativeLiteracyFloorsOnlyFinalSaleLine(t *testing.T) { + for _, scenario := range []struct { + literacy int32 + credits uint64 + }{{-39, 605}, {-40, 599}, {-80, 593}, {-4000, 1}, {-4040, 0}} { + item := ownedItem{Type: 51018, Template: 209283, Quality: 1, Count: 1} + + credits := shopSalePrice(item, 5, scenario.literacy) + + if credits != scenario.credits { + t.Fatalf("literacy %d: got %d, want %d", scenario.literacy, credits, scenario.credits) + } + } +} + +func TestSignedLiteracyReachesDurableVendorSale(t *testing.T) { + world, _ := newShopWorld(t) + player, client := world.characters[1], world.clients[1] + player.stats.Abilities.Intelligence = 1 + player.stats.TradeRepair.ComputerLiteracy = 0 + player.activeNanos = syntheticNanoModifiers(t, [][2]int32{{161, -40}}) + + err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]) + if err != nil { + t.Fatal(err) + } + err = world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]) + restored := newTestInventoryServer(t).characters[1] + + if err != nil || player.inventory.Credits != 699 || restored.inventory.Credits != 699 || len(player.inventory.Items) != 0 || len(restored.inventory.Items) != 0 { + t.Fatalf("signed sale was not committed: %d/%d, %v", player.inventory.Credits, restored.inventory.Credits, err) + } +} + +func TestSignedNegativeBodyDevelopmentRegeneratesWithoutUnsignedWrap(t *testing.T) { + for _, full := range []bool{false, true} { + world, _, start := newRegenerationWorld() + player := world.characters[1] + player.level = 200 + player.activeNanos = syntheticNanoModifiers(t, [][2]int32{{152, -407}}) + if full { + player.health, player.nano = player.maximumHealth(), player.maximumNano() + } + + for second := 2; second <= 58; second += 2 { + world.advanceRegeneration(start.Add(time.Duration(second) * time.Second)) + } + + if !full && (player.health != 19 || player.nano != 0) { + t.Fatalf("signed recovery changed resources to %d/%d", player.health, player.nano) + } + if full && (player.health != 1010 || player.nano != 831) { + t.Fatalf("negative computed gain drained a full resource: %d/%d", player.health, player.nano) + } + } +} + +func TestSignedNegativeMartialArtsDoesNotWrapDamageScaling(t *testing.T) { + world, _ := newCombatWorld() + player := world.characters[1] + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.activeNanos = syntheticNanoModifiers(t, [][2]int32{{100, -105}}) + + rating := player.attackRating() + damage := player.normalDamage(world.characters[1000000], func(limit uint32) uint32 { return limit - 1 }) + + if rating != -100 || damage != 4 { + t.Fatalf("signed attack rating or provisional scaling wrapped: %d/%d", rating, damage) + } +} + +func TestDirectSkillNanosFeedWeaponRequirementsRatingAndRemoval(t *testing.T) { + player := &character{level: 100, profession: 8, stats: testCharacterStats(), inventory: playerInventory{ + Items: []ownedItem{{ID: 1, Type: 51018, Template: 205736, Quality: 100, Slot: 6, Count: 1}}, + }} + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.TradeRepair.Psychology = 248 + player.activeNanos = []activeNano{{program: 207284}} + + first, accepted := player.attackRating(), player.canEquip(player.inventory.Items[0]) + player.activeNanos = append(player.activeNanos, activeNano{program: 207288}) + overlapped := player.attackRating() + player.activeNanos = player.activeNanos[1:] + remaining, rejected := player.attackRating(), player.canEquip(player.inventory.Items[0]) + player.activeNanos = nil + + if first != 300 || !accepted || overlapped != 322 || remaining != 270 || rejected || player.attackRating() != 248 || player.stats.TradeRepair.Psychology != 248 { + t.Fatalf("direct skill effects did not reach weapon rules: %d/%t/%d/%d/%t/%d", first, accepted, overlapped, remaining, rejected, player.attackRating()) + } +} diff --git a/server/stats.go b/server/stats.go @@ -150,20 +150,20 @@ func (character *character) baseStats() characterStats { return character.stats } -func (character *character) effectiveAbility(stat uint32) uint32 { +func (character *character) effectiveAbility(stat uint32) int32 { 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) + character.nanoBonus(stat)) + return int32(values[stat-16]) + character.inventory.equipmentBonus(stat) + character.nanoBonus(stat) } -func (character *character) effectiveSkill(stat uint32, base uint16, weights [6]uint32) uint32 { +func (character *character) effectiveSkill(stat uint32, base uint16, weights [6]uint32) int32 { // kkr.dll FUN_10073fa0, weights from resource type 1000204. - var weighted uint32 + var weighted int32 for index, weight := range weights { - weighted += character.effectiveAbility(16+uint32(index)) * weight + weighted += character.effectiveAbility(16+uint32(index)) * int32(weight) } // Preserve the native float constants before truncating at integer boundaries. - return uint32(int32(base) + int32(float64(weighted)*float64(float32(0.01))*0.25) + character.equipmentBonus(stat)) + return int32(base) + int32(float64(weighted)*float64(float32(0.01))*0.25) + character.equipmentBonus(stat) + character.nanoBonus(stat) } type trainedStat struct { diff --git a/server/weapon_stats.go b/server/weapon_stats.go @@ -10,7 +10,7 @@ func (item ownedItem) isWieldableWeapon() bool { func (character *character) effectiveStat(stat uint32) int32 { switch stat { case 16, 17, 18, 19, 20, 21: - return int32(character.effectiveAbility(stat)) + return character.effectiveAbility(stat) case 37: return int32(character.titleLevel()) case 54: @@ -21,7 +21,7 @@ func (character *character) effectiveStat(stat uint32) int32 { stats := character.baseStats() for _, field := range stats.trainingStats() { if field.stat == stat { - return int32(character.effectiveSkill(stat, *field.value, gamedata.IPTraining.Weights[stat])) + return character.effectiveSkill(stat, *field.value, gamedata.IPTraining.Weights[stat]) } } return 0 diff --git a/server/weapon_stats_test.go b/server/weapon_stats_test.go @@ -10,7 +10,7 @@ import ( func TestWeaponRatingTruncatesEachAuthoredWeightBeforeAllOff(t *testing.T) { for _, scenario := range []struct { edged, pistol uint16 - rating uint32 + rating int32 }{{1, 1, 0}, {5, 9, 15}, {9, 5, 15}, {400, 200, 309}} { world, _ := newEquipmentWorld(t) player := world.characters[1]