aorecomp

Anarchy Online classic in the browser

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


commit a47195de7172e1c5d8764f7e00b2a10b772485b9
parent 28f6bdce2124d70b13f36ca18f816fcbe8203b8b
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 17:59:50 +0000

Award solo kill XP with atomic level and IP progression

Diffstat:
MTODO.md | 25++++++++++++++++++++-----
Mdocs/backpacks.md | 7++++---
Mdocs/character-progression.md | 20++++++++++++--------
Mdocs/combat-npc-balance.md | 1+
Mdocs/combat-rules.md | 5+++--
Mdocs/corpse-loot.md | 5+++--
Adocs/kill-experience.md | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/combat.go | 16++++++++++------
Mserver/database.go | 29+++++++++++++++++++++++++++--
Mserver/fling_crash_test.go | 19++++++++++++++++++-
Mserver/gamedata/load.go | 1+
Mserver/gamedata/npc_combat.yaml | 2++
Mserver/gamedata/profession_resources.yaml | 12++++++++++++
Mserver/gamedata/types.go | 1+
Aserver/kill_experience_outcome_test.go | 236+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/kill_experience_rules_test.go | 197+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/kill_experience_test.go | 193+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/nano_buffs.go | 6+++---
Mserver/nano_casting.go | 6++++--
Mserver/npc_outcome.go | 64++++++++++++++++++++++++++++++++++++++--------------------------
Mserver/player_death_test.go | 2+-
Aserver/progression.go | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/ranged.go | 14++++++++------
Mserver/special_locks.go | 18+++++++++++-------
Mserver/weapon_special.go | 4+++-
Mserver/world.go | 11+----------
Mtools/data/extract_profession_resources.py | 5+++--
27 files changed, 1070 insertions(+), 87 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -69,7 +69,8 @@ recorded in [inventory behavior](docs/inventory.md). passed native-client checks. Requirements, signed modifiers, ability trickle, Survival QL 50..150, resource clamping and worn-use routing have regression coverage. Normal-hit additions and weapon range are implemented below; - critical resolution and kill XP remain separate milestones. + critical resolution remains separate. The provisional solo XP path now checks + Pioneer bonus application and removal; canonical reward rules remain open. 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 @@ -231,9 +232,11 @@ Normal-hit additions and weapon-range modifiers are described in write cover living/killing hits and repeated requests after recovery. A WASM killing shot followed by SIGKILL and restart retained the native corpse and ownership. See `server/fling_crash_test.go` and [Fling Shot](docs/fling-shot.md). -- [ ] Extend forced-termination coverage to complete special reward outcomes. - Check: once kill XP/rewards exist, the killing hit, cooldown, corpse and rewards +- [x] Extend forced-termination coverage to current special reward outcomes. + Check: the killing hit, cooldown, corpse and XP/level/IP recover together exactly once; failure or replay cannot lose or repeat any part. + Eight living/lethal, before/after-commit Fling/Fast cases now check progression + alongside the corpse/lock, duplicate retries and a second database reopen. - [ ] Dual wield one verified weapon pair. Check: the actor's shared scheduling matches expected attack/recharge ordering without independent timer exploits. - [ ] Swap a weapon during combat. Check: swapping cannot bypass an existing @@ -351,10 +354,18 @@ Known-amount credit collection and native balance limits are verified in reward exactly once; the total survives restart. Include the Pioneer backpack's XPModifier, removal, rounding and eligibility rules; displaying that modifier alone does not establish correct rewards. -- [ ] Advance through one level threshold. Check: crossing it updates the native + A transactional solo prototype now covers all six supported attack paths, + including Pioneer wear/removal and crash recovery. The Leet's 100 XP, ownership, + grey cutoff and rounding remain provisional, so this canonical-rule check stays + open. See [solo kill experience](docs/kill-experience.md). +- [x] Advance through one level threshold. Check: crossing it updates the native level display and the correct derived resources without a second level-up. -- [ ] Award IP for that level. Check: the expected amount is granted once and +- [x] Award IP for that level. Check: the expected amount is granted once and the native unspent-IP value survives reconnect. +- [ ] Verify original level-up health/nano refill policy and IP selection at + title transitions. Current progression preserves current resources and grants + the reached title's IP value. Raw title-resource values are verified, but those + policies need original-server measurements. - [x] Raise one trained skill with IP. Check: the native request spends the correct amount, updates effective skill and persists the base value. - [x] Raise one ability with IP. Check: cost and ability trickle update together @@ -1180,6 +1191,10 @@ and server restarts. Turn every reproduced bug into a focused regression test. Evidence: `local/input-timing-research/native-timing-held-final.json`. Also cover Ctrl-down/click/Ctrl-up in one queued SDL batch, verifying both mouse flags and per-message keyboard state, plus rapid Enter/text batching. + The hardware XP run also saw a 150ms left click leave the Wear/Clothes tab + unchanged, while a 1500ms held click at the same location switched it. Measure + native frames and queued input/focus transitions before attributing the miss. + Captures: `local/kill-experience-smoke/clothes-window.png` and `clothes-view.png`. - [x] Keep browser message-loop wakeups out of native text input. Check: `PostMessageA` and `PostQuitMessage` produce their requested messages without spurious `WM_CHAR` NUL; explicit composed slash and NUL remain intact. diff --git a/docs/backpacks.md b/docs/backpacks.md @@ -314,9 +314,10 @@ The server's existing combat calculation consumes supported attack skills, 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. +remains separate. The [solo XP path](kill-experience.md) now consumes the Pioneer's +modifier for its provisional reward. Native XPModifier starts at 100, so wearing +the Pioneer displays 101 and the current 100-point reward becomes 101. Original +creature rewards, rounding and eligibility still need historical verification. 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/character-progression.md b/docs/character-progression.md @@ -1,7 +1,8 @@ # Character progression: 14.9.1 protocol evidence -Character XP now persists in SQLite and initializes the native experience bar. -Kill awards and automatic level advancement remain unimplemented. Native +Character XP persists in SQLite and initializes the native experience bar. +A [provisional solo kill path](kill-experience.md) now advances XP, levels and +IP atomically; original reward balance and eligibility remain unresolved. Native [IP spending](ip-training.md) persists validated skill/ability purchases. The packet replay values below are test inputs, not historical creature rewards. @@ -122,6 +123,10 @@ The original target has SHA-256 `a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. The constructor resolves `SM_Sandy_Game_Level_Complete` into its effect field. +The positive title field also triggers profession-title congratulations. Send +zero when the title is unchanged; otherwise ordinary level gains announce the +existing title again. This was reproduced and corrected in the actual WASM +kill/level-up verification described in [solo kill experience](kill-experience.md). The activation also starts animation layer 6. Helper `0x100744c0` refreshes the local XP/IP cache and open Skills view; it does not supply new health or nano maxima. The handler alone does not establish resource refill policy, XP cap, @@ -255,12 +260,11 @@ This leaves the precise 14.9.1 grey policy unresolved; later zero-XP guides are not sufficient to decide it. Later XP-pool, research and daily-mission mechanics must not be imported into this pre-Shadowlands target. -Next implementation needs an explicit creature reward and eligibility policy, -atomic persistence before publishing the award, and a single death transition -that cannot award twice. Tests must cover competing attackers, dead or departed -players, failed saves, repeat ticks, initialization, reconnect and restart. -Level advancement must coordinate XP, IP, level, title and derived resources -in one durable change rather than leaving the native bar above its threshold. +The current solo implementation has explicit provisional reward/eligibility +choices, atomic death/reward persistence and coordinated level/IP/resource +updates. Original-server evidence is still needed for reward size, ownership, +eligibility, caps, rounding, team allocation and refill policy. Current tests +and their evidence limits are described in [solo kill experience](kill-experience.md). ## Retained evidence diff --git a/docs/combat-npc-balance.md b/docs/combat-npc-balance.md @@ -65,6 +65,7 @@ and AggDef outside -100..100. | Value | Selected setting | Evidence status | | --- | --- | --- | | Maximum health | 100 | Provisional, retained pending a historical measurement | +| Solo XP reward | 100 | Provisional; the atomic [XP path](kill-experience.md) does not establish original reward size or eligibility | | Weapon | LeetBite1_001, 120910, QL 1 | Shipped definition verified; binding and choice of variant provisional | | Normal damage endpoints | 4-8 | Verified weapon values; uniform always-hit roll and omission of rating/armor remain local | | Initiative | 0 | Provisional actor value | diff --git a/docs/combat-rules.md b/docs/combat-rules.md @@ -49,8 +49,9 @@ The uniform normal-damage roll is a reconstruction choice; the item establishes the endpoints, not the historical server's random distribution. Melee range uses the recovered client predicate with catalog actor extents; see [range evidence and checks](combat-client-state-machine.md#range-line-of-sight-and-movement). -There is no server line-of-sight test. Other equipment, nanos, specials, -aggression/taunt AI and XP awards are not implemented. Player resurrection and +There is no server line-of-sight test. Other equipment, nanos, specials and +aggression/taunt AI remain incomplete. A provisional [solo XP path](kill-experience.md) +now coordinates kill rewards, level advancement and IP. Player resurrection and private reclaim have separate documented lifecycle implementations. Fixed corpse loot and the provisional level-1 Leet [respawn lifecycle](npc-respawn.md) are supported. Reload revival is a local test convenience. diff --git a/docs/corpse-loot.md b/docs/corpse-loot.md @@ -179,8 +179,9 @@ only remaining HP. Stopping and restarting attacks does not erase damage. Departure, death or a playfield change does not transfer an existing lead to another player; opening and taking still require the entitled player to be alive, connected, ready, nearby and in the same playfield. Respawn creates a -new identity with no inherited contributions. Damage credit does not imply -an XP reward; that remains unimplemented. +new identity with no inherited contributions. The provisional +[solo XP path](kill-experience.md) now uses this encounter lead, with separate +reward eligibility checks. Original XP ownership remains unverified. Ties retain the first contributor to reach the tied total. Greatest damage without a strict majority, applied-damage accounting, contribution retention diff --git a/docs/kill-experience.md b/docs/kill-experience.md @@ -0,0 +1,132 @@ +# Solo kill experience and level advancement + +Normal unarmed/axe hits, pistol shots, Fling Shot, Fast Attack and Winter Bite +share a transactional XP path. The level-1 Leet combat profile awards a +**provisional 100 XP**. This is local balance, like its provisional 100 HP; +no historical level-1 Leet reward measurement has been recovered. + +## Current reward rules and evidence limits + +The current implementation uses the encounter's leading damage contributor. +Competing solo contributors use accumulated damage, retaining the first leader +on a tie. The winner must be alive, connected, ready, in the same playfield, +and still have the creature in its interest set. A missing/ineligible winner's +reward is not reassigned to the last hitter. Team encounters and players who +have joined a team do not yet receive XP; team allocation remains TODO. + +These ownership and presence choices are provisional. Existing majority-damage +loot rights do not independently prove original XP ownership or reward range. +The current grey cutoff is a level difference greater than two, matching the +native default XPKillRange 275. That client consideration default does not +establish original server eligibility or its growth with level. Grey rewards, +per-kill caps, team shares and original creature balance remain unverified. +Unprofiled creatures have no configured reward. + +XPModifier is stat 319, with baseline 100; it is distinct from XPBonus 341. +The current calculation is: + +``` +modifier = max(0, 100 + worn equipment bonus 319 + active nano bonus 319) +reward = floor(profile experience * modifier / 100) +``` + +The Pioneer backpack and its shrinking variant each add one when worn, so +the current 100-point reward becomes 101. Carried or removed backpacks add +nothing. The original item records and a 2002 player report support a percentage +modifier; exact original rounding and cap/bonus ordering remain unverified. +Fractional tests establish the selected floor policy, not historical accuracy. +The source ledgers are retained under +`local/progression-implementation-research/content/` and `native/`. + +## Progression and native delivery + +XP is stored within the current level. An award consumes each crossed level's +requirement, preserves the remainder and grants IP. The first transition uses +the independently supported 1450-point requirement and the shipped help's +4000-IP grant at level 2. Native cumulative boundaries are described in +[character progression](character-progression.md). + +`tools/data/extract_profession_resources.py` now extracts the fourth DWORD of +all twelve professions' original 1000200 resources into the `ip` array. Each +has 4000/10000/20000/40000/80000/150000 at title starts +1/15/50/100/150/190. The raw values are verified; interpreting this field as +the per-level grant is a strong inference supported by shipped level-2/50 help +and historical tables. Selecting the reached title's grant at a title boundary +still needs original-server confirmation. + +At level 200, excess progress is discarded and no further reward is granted. +An IP balance that cannot represent the grant rejects the transaction instead +of wrapping. Artificial large-reward fixtures check coherent multiple-level +and final-level handling; they do not establish the original per-kill cap. +Higher XP thresholds remain provisional as documented in character progression. + +Health and nano maxima use the new level/title and the recovered resource +formula. Current health and nano are retained. Original level-up refill policy +is unresolved; the native level-up handler alone does not prove a refill. +Classic insurance/XP loss on death is also still TODO. + +The owner receives one absolute XP-52 update for a same-level award, or one +`NewLevelIIR_t` with the new level, IP, cumulative XP, boundaries and net gain. +A positive title field announces a profession title: unchanged titles use zero. +Sending the existing title on every level incorrectly repeats its congratulations. +Observers receive visible level/title and health-maximum changes; nano maxima +follow owner/team visibility. Private XP/IP and level-up messages stay with the +owner. Resource maxima are refreshed +after the native level event, and reconnect uses FullCharacter without replaying +award events. + +## Atomicity and verification + +The reward is staged from the detached killing result and written in the same +SQLite transaction as NPC health/corpse/ownership/respawn and the attack's +ammunition, special lock or completed nano cost/recharge. Record updates and +NPC upserts must affect their expected row; silently ignored writes fail the +transaction. Live XP/level/IP and their saved-profile cache change after commit. +Nano rewards are applied after the completed caster copy is published, preserving +both the cast debit and the new progression. + +The persisted NPC death transition prevents a second reward after repeated +ticks, requests, disconnects or restart. A respawn uses a fresh NPC identity and +starts a new encounter. No reward ledger or development-schema compatibility +path is needed. Nonlethal ticks and position checkpoints do not write XP. + +The three `server/kill_experience*_test.go` files cover 72 cases: six attack +paths, 30 rollback/retry combinations, worn/carried/removed Pioneer effects, +fractional policy, ineligible winners, competing contributions/ties, private +notifications, title/IP boundaries, cumulative XP, multiple levels, level 200, +overflow, concurrent completions and checkpoint cadence. The special-attack +process-crash suite adds eight before/after-commit living/lethal cases for +Fling and Fast Attack, now checking XP/level/IP across retry and a second reopen. +These tests establish the current implementation's consistency, not the +historical accuracy of the explicitly provisional policies above. + +Two headed hardware Chromium clients exercised the published WASM on the shared +HTTPS preview. A controlled level-1 character at 1400 XP used an axe with an +administratively raised skill to make deterministic killing hits. A normal hit +awarded 100, reached level 2 at EXP 50/2600, and changed IP from 1500 to 5500. +Max health/nano became 40/36 while current resources initially remained 34/32. +The independent observer saw level 2/max health 40, without private XP/IP. + +The first native run reproduced repeated Clerk congratulations from sending +an unchanged positive title. Repeating the threshold after the zero-title fix +retained the XP/level/IP feedback without that extra title message. Worn Pioneer +then made a Fast Attack kill worth 101; removing it restored a normal kill to +100. Native and SQLite progress matched 50, 151 and 251 within level 2. The +Skills window displayed 5500 IP, including after a cold server restart. Reconnect +and restart retained both item IDs and placements without replaying awards. + +The wire verifier found one level event with title field zero and exactly two +subsequent live XP totals, 1601 and 1701. Observer and cold-start streams contained +no private award updates. Browser/page/adapter error captures were empty. The +native/SQL/wire comparisons, screenshots and fixture cleanup are retained in +`local/kill-experience-smoke/`. This is an XP/progression smoke test with controlled +combat inputs, not evidence of canonical starter combat balance. + +Validation: `go test ./server/... -count=1`, +`go test -race ./server -run 'Test(KillExperience|Experience)' -count=2`, +`go vet -stdversion=false ./server/...`, and regeneration of profession resources +with an exact comparison against the consumed YAML. Logs are retained in +`local/kill-xp-implementation/`. An earlier combined repeated race/crash batch +exceeded the runner's 11-minute outer limit; it reported no race and left no +test subprocesses. The focused repeated race run and complete normal suite, +including all eight process-crash cases, passed separately. diff --git a/server/combat.go b/server/combat.go @@ -347,7 +347,7 @@ func (server *server) advanceCombat(now time.Time) { } damage := min(attacker.normalDamage(target, rand.Uint32N), target.health) previous := *target - fired, err := server.applyWeaponDamage_locked(attacker, target, damage, now) + fired, award, err := server.applyWeaponDamage_locked(attacker, target, damage, now) if err != nil { log.Printf("Damage: %v", err) server.cancelCombat_locked(target.id, updates) @@ -362,6 +362,7 @@ func (server *server) advanceCombat(now time.Time) { attacker.nextAttack = attacker.rechargeUntil.Add(attack) server.queueCombat_locked(updates, attacker, target, hitPacket(attacker, target, damage)) server.finishDamageEffects_locked(attacker, target, previous, now, updates) + server.applyExperienceAward_locked(award, now, updates) } server.mutex.Unlock() server.sendCombatUpdates(updates) @@ -372,16 +373,19 @@ type damageContributor struct { team uint32 } -func (server *server) applyDamage_locked(attacker, target *character, damage uint32, now time.Time) error { +func (server *server) applyDamage_locked(attacker, target *character, damage uint32, now time.Time) (*experienceAward, error) { // A lethal outcome commits before the new actor state becomes visible. candidate := prepareDamage(attacker, target, damage, now) + var award *experienceAward if candidate.health == 0 { - if err := server.saveDeath_locked(&candidate, now); err != nil { - return err + var err error + award, err = server.saveDeath_locked(&candidate, now) + if err != nil { + return nil, err } } *target = candidate - return nil + return award, nil } func prepareDamage(attacker, target *character, damage uint32, now time.Time) character { @@ -452,7 +456,7 @@ func (server *server) finishDamageEffects_locked(attacker, target *character, pr server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{65, 0, 0, effect.caster, effect.program})) } previous.position = target.position - server.finishNanoEffect_locked(updates, target, previous, now) + server.finishResourceChange_locked(updates, target, previous, now) } monster := gamedata.MonsterTemplates[target.monsterData] if target.npc && monster != nil && len(monster.DeathAnimations) != 0 { diff --git a/server/database.go b/server/database.go @@ -161,8 +161,33 @@ func upsertRecordSQL(table, columns string) string { func updateRecord(tx *sql.Tx, table string, id uint32, columns string, fields []any) error { assignments := strings.ReplaceAll(columns, ", ", " = ?, ") + " = ?" - _, err := tx.Exec("UPDATE "+table+" SET "+assignments+" WHERE id = ?", append(fields, id)...) - return err + result, err := tx.Exec("UPDATE "+table+" SET "+assignments+" WHERE id = ?", append(fields, id)...) + if err != nil { + return err + } + changed, err := result.RowsAffected() + if err != nil { + return err + } + if changed != 1 { + return fmt.Errorf("%s %d update affected %d rows", table, id, changed) + } + return nil +} + +func upsertRecord(tx *sql.Tx, table string, id uint32, columns string, fields []any) error { + result, err := tx.Exec(upsertRecordSQL(table, columns), append([]any{id}, fields...)...) + if err != nil { + return err + } + changed, err := result.RowsAffected() + if err != nil { + return err + } + if changed != 1 { + return fmt.Errorf("%s %d upsert affected %d rows", table, id, changed) + } + return nil } func insertPlayer(tx *sql.Tx, player *character) error { diff --git a/server/fling_crash_test.go b/server/fling_crash_test.go @@ -43,13 +43,17 @@ func runFlingCrashChild(t *testing.T, mode string) { } else { world, output = newRangedWorld(t) } + world.characters[1].experience = 1400 + if err := world.saveUser_locked(world.characters[1]); err != nil { + t.Fatal(err) + } target := world.characters[1000000] target.health, target.monsterData, target.level = 100, 17655, 1 target.combatProfile = gamedata.NPCCombatProfiles[17655][1] if strings.HasSuffix(mode, "/kill") { target.health = 1 } - if err := world.saveDeath_locked(target, time.Now()); err != nil { + if _, err := world.saveDeath_locked(target, time.Now()); err != nil { t.Fatal(err) } @@ -171,6 +175,13 @@ func TestFlingShotProcessCrashRecovery(t *testing.T) { if !reflect.DeepEqual(player.inventory.Items, inventory) { t.Fatal("crash changed pre-15.5 ammunition") } + level, experience, points := uint16(1), uint32(1400), uint32(1500) + if strings.HasPrefix(mode, "after/") && initialHealth == 1 { + level, experience, points = 2, 50, 5500 + } + if player.level != level || player.experience != experience || player.stats.ImprovementPoints != points { + t.Fatal("crash separated XP, level or IP from the killing special") + } if strings.HasPrefix(mode, "before/") { if target.health != initialHealth || len(player.specialAttackLocks) != 0 || len(target.damageContributors) != 0 || target.corpse != nil || len(restored.npcRespawns) != 0 { @@ -221,6 +232,12 @@ func TestFlingShotProcessCrashRecovery(t *testing.T) { len(again.characters[1000000].damageContributors) != 0 || again.characters[1000000].leadingContributor != (damageContributor{player: 1})) { t.Fatal("retried kill lost its single corpse or pending respawn") } + if initialHealth == 1 { + level, experience, points = 2, 50, 5500 + } + if again.characters[1].level != level || again.characters[1].experience != experience || again.characters[1].stats.ImprovementPoints != points { + t.Fatal("retry lost or duplicated a durable XP, level or IP outcome") + } }) } } diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -36,6 +36,7 @@ var ( ProfessionTitles map[uint16]struct { Health [6]uint32 `yaml:"health"` Nano [6]uint32 `yaml:"nano"` + IP [6]uint32 `yaml:"ip"` } IPTraining struct { TitleLevels [6]uint32 `yaml:"title_levels"` diff --git a/server/gamedata/npc_combat.yaml b/server/gamedata/npc_combat.yaml @@ -3,6 +3,8 @@ 1: # Provisional health; no historical level-1 Leet HP measurement recovered. health: 100 + # Provisional solo XP; no historical level-1 Leet reward measurement recovered. + experience: 100 # Health recovery uses the checked native NPC branch; see docs/npc-regeneration.md. # Shipped QL 1 LeetBite1_001. Choosing this variant for this spawn is provisional. # Base damage 4..8 and attack/recharge 175 cs are verified item data. diff --git a/server/gamedata/profession_resources.yaml b/server/gamedata/profession_resources.yaml @@ -2,36 +2,48 @@ 1: health: [0, 1, 2, 3, 4, 5] nano: [0, 0, 0, 0, 0, 0] + ip: [4000, 10000, 20000, 40000, 80000, 150000] 2: health: [0, 1, 1, 2, 3, 6] nano: [0, 0, 0, 0, 0, 0] + ip: [4000, 10000, 20000, 40000, 80000, 150000] 3: health: [0, 0, 0, 0, 0, 0] nano: [0, 1, 2, 3, 4, 5] + ip: [4000, 10000, 20000, 40000, 80000, 150000] 4: health: [0, 1, 1, 2, 3, 4] nano: [0, 0, 0, 0, 0, 0] + ip: [4000, 10000, 20000, 40000, 80000, 150000] 5: health: [0, 1, 1, 2, 2, 3] nano: [1, 1, 2, 2, 3, 3] + ip: [4000, 10000, 20000, 40000, 80000, 150000] 6: health: [0, 1, 2, 2, 3, 3] nano: [0, 1, 1, 2, 2, 3] + ip: [4000, 10000, 20000, 40000, 80000, 150000] 7: health: [0, 0, 1, 1, 2, 3] nano: [0, 1, 1, 1, 2, 3] + ip: [4000, 10000, 20000, 40000, 80000, 150000] 8: health: [0, 1, 1, 1, 2, 3] nano: [0, 1, 1, 1, 2, 3] + ip: [4000, 10000, 20000, 40000, 80000, 150000] 9: health: [1, 2, 3, 4, 5, 6] nano: [0, 0, 0, 0, 0, 0] + ip: [4000, 10000, 20000, 40000, 80000, 150000] 10: health: [0, 0, 0, 0, 0, 0] nano: [0, 1, 2, 3, 4, 6] + ip: [4000, 10000, 20000, 40000, 80000, 150000] 11: health: [0, 0, 0, 0, 0, 0] nano: [0, 1, 2, 3, 4, 6] + ip: [4000, 10000, 20000, 40000, 80000, 150000] 12: health: [0, 0, 0, 0, 0, 0] nano: [0, 1, 2, 3, 4, 6] + ip: [4000, 10000, 20000, 40000, 80000, 150000] diff --git a/server/gamedata/types.go b/server/gamedata/types.go @@ -16,6 +16,7 @@ type NPCData struct { type NPCCombatProfile struct { Health uint32 `yaml:"health"` + Experience uint32 `yaml:"experience"` Weapon uint32 `yaml:"weapon"` Initiative int32 `yaml:"initiative"` AggDef int32 `yaml:"agg_def"` diff --git a/server/kill_experience_outcome_test.go b/server/kill_experience_outcome_test.go @@ -0,0 +1,236 @@ +package main + +import ( + "encoding/binary" + "sync" + "testing" + "time" +) + +func TestKillExperienceKeepsCumulativeProgressAcrossThresholds(t *testing.T) { + for _, scenario := range []struct { + name string + level, nextLevel uint16 + progress, reward, nextProgress, points uint32 + total, delta uint32 + }{ + {"same level", 2, 2, 50, 100, 150, 1500, 1600, 100}, + {"multiple levels", 1, 3, 1400, 5000, 2350, 9500, 6400, 5000}, + {"last level", 199, 200, 73393850, 100, 0, 151500, 2061453150, 50}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, output := newKillExperienceWorld(t, "unarmed") + player, target := world.characters[1], world.characters[1000000] + player.level, player.experience = scenario.level, scenario.progress + target.level = scenario.level + profile := *target.combatProfile + profile.Experience = scenario.reward + target.combatProfile = &profile + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + + attackForExperience(t, world, "unarmed") + restored := newTestInventoryServer(t).characters[1] + + if player.level != scenario.nextLevel || player.experience != scenario.nextProgress || player.stats.ImprovementPoints != scenario.points || + restored.level != scenario.nextLevel || restored.experience != scenario.nextProgress || restored.stats.ImprovementPoints != scenario.points { + t.Fatalf("progression: level=%d XP=%d IP=%d", player.level, player.experience, player.stats.ImprovementPoints) + } + awards := 0 + for _, packet := range output.packets { + switch binary.BigEndian.Uint32(packet[16:20]) { + case 0x7f405a16: + awards++ + if scenario.nextLevel == scenario.level || binary.BigEndian.Uint32(packet[37:41]) != scenario.total || + binary.BigEndian.Uint32(packet[49:53]) != 0 || binary.BigEndian.Uint32(packet[57:61]) != scenario.delta { + t.Fatal("level event used the wrong cumulative XP or net gain") + } + case 0x2b333d6e: + if binary.BigEndian.Uint32(packet[29:33]) == 52 { + awards++ + if scenario.nextLevel != scenario.level || binary.BigEndian.Uint32(packet[33:37]) != scenario.total { + t.Fatal("same-level award lost its cumulative XP baseline") + } + } + } + } + if awards != 1 { + t.Fatalf("native award events: %d", awards) + } + }) + } +} + +func TestKillExperienceRejectsAnUnrepresentableIPGrant(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + player, target := world.characters[1], world.characters[1000000] + player.experience, player.stats.ImprovementPoints = 1400, 4294967295 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + + attackForExperience(t, world, "unarmed") + restored := newTestInventoryServer(t) + + if player.experience != 1400 || player.level != 1 || player.stats.ImprovementPoints != 4294967295 || target.health != 1 || target.corpse != nil || + restored.characters[1].experience != 1400 || restored.characters[1].level != 1 || restored.characters[1].stats.ImprovementPoints != 4294967295 || + restored.characters[1000000].health != 1 { + t.Fatal("IP overflow wrapped a counter or committed part of the killing action") + } +} + +func TestKillExperienceConcurrentCompletionsAwardOnce(t *testing.T) { + for _, attack := range []string{"unarmed", "fling", "fast", "nano"} { + t.Run(attack, func(t *testing.T) { + world, output := newKillExperienceWorld(t, attack) + player := world.characters[1] + player.experience = 1400 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + at := time.Now() + if attack == "unarmed" { + if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + at = player.nextAttack + } else if attack == "nano" { + if err := world.handleNanoCast(world.clients[1], characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]); err != nil { + t.Fatal(err) + } + at = world.clients[1].nanoCast.readyAt.Add(time.Nanosecond) + } + var completions sync.WaitGroup + errors := make(chan error, 2) + + for range 2 { + completions.Go(func() { + switch attack { + case "unarmed": + world.advanceCombat(at) + case "fling": + errors <- world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]) + case "fast": + errors <- world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, 1000000)[20:]) + case "nano": + world.advanceNanos(at) + } + }) + } + completions.Wait() + close(errors) + restored := newTestInventoryServer(t) + + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + if player.level != 2 || player.experience != 50 || player.stats.ImprovementPoints != 5500 || + restored.characters[1].experience != 50 || restored.characters[1].level != 2 || restored.characters[1].stats.ImprovementPoints != 5500 || + restored.characters[1000000].health != 0 { + t.Fatal("concurrent completion lost or duplicated the committed reward") + } + levels := 0 + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x7f405a16 { + levels++ + } + } + if levels != 1 { + t.Fatalf("concurrent level events: %d", levels) + } + }) + } +} + +func TestKillExperienceCreditsTheEncounterWinnerRatherThanTheLastHit(t *testing.T) { + for _, scenario := range []struct { + name string + contribution, winner uint32 + }{ + {"majority", 99, 1}, {"tie retains first", 1, 1}, {"finisher leads", 0, 2}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, firstOutput := newKillExperienceWorld(t, "unarmed") + target := world.characters[1000000] + world.nextCharacter = 1 + finisher := world.newCharacter() + finisher.playfield, finisher.position = 950, [3]float32{} + if err := world.saveUser_locked(finisher); err != nil { + t.Fatal(err) + } + lastOutput := &combatTestConn{} + world.clients[2] = &worldClient{id: 2, conn: lastOutput, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + target.damageContributors = map[damageContributor]uint32{{player: 1}: scenario.contribution} + target.leadingContributor = damageContributor{player: 1} + + if err := world.handleCombat(world.clients[2], attackPacket(2, 1000000)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(finisher.nextAttack) + restored := newTestInventoryServer(t) + + if target.corpse == nil || target.corpse.looter != scenario.winner || restored.characters[scenario.winner].experience != 100 { + t.Fatal("reward and corpse did not retain the winning contributor") + } + for index, output := range []*combatTestConn{firstOutput, lastOutput} { + owner := uint32(index + 1) + experience, notifications := uint32(0), 0 + if owner == scenario.winner { + experience, notifications = 100, 1 + } + if world.characters[owner].experience != experience || restored.characters[owner].experience != experience { + t.Fatal("reward was copied or reassigned to the last hitter") + } + awards := 0 + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 52 { + awards++ + if binary.BigEndian.Uint32(packet[24:28]) != owner || binary.BigEndian.Uint32(packet[33:37]) != 100 { + t.Fatal("private award used another player's identity or amount") + } + } + } + if awards != notifications { + t.Fatal("the winner's notification was missing or leaked to the competing player") + } + } + }) + } +} + +func TestKillExperienceDoesNotWriteRewardsOnNonlethalTicksOrCheckpoints(t *testing.T) { + world, output := newKillExperienceWorld(t, "unarmed") + player, target := world.characters[1], world.characters[1000000] + target.health = 100 + if _, err := world.db.Exec("CREATE TABLE xp_updates (player_id INTEGER); CREATE TRIGGER count_xp AFTER UPDATE OF experience ON characters WHEN NEW.id=1 BEGIN INSERT INTO xp_updates VALUES (NEW.id); END"); err != nil { + t.Fatal(err) + } + + attackForExperience(t, world, "unarmed") + world.advanceCombat(player.nextAttack) + player.position[0]++ + if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { + t.Fatal(err) + } + var writes uint32 + if err := world.db.QueryRow("SELECT count(*) FROM xp_updates").Scan(&writes); err != nil { + t.Fatal(err) + } + var savedX float32 + if err := world.db.QueryRow("SELECT position_x FROM characters WHERE id=1").Scan(&savedX); err != nil { + t.Fatal(err) + } + + if target.health == 0 || target.health == 100 || target.corpse != nil || player.experience != 0 || writes != 0 || savedX != 1 { + t.Fatalf("nonlethal damage or movement checkpoint awarded/wrote XP: health=%d XP=%d writes=%d", target.health, player.experience, writes) + } + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x7f405a16 || + binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 52 { + t.Fatal("nonlethal simulation published an award") + } + } +} diff --git a/server/kill_experience_rules_test.go b/server/kill_experience_rules_test.go @@ -0,0 +1,197 @@ +package main + +import ( + "encoding/binary" + "fmt" + "testing" +) + +func TestKillExperienceUsesWornPioneerPercentage(t *testing.T) { + for _, scenario := range []struct { + name string + template, base, expected uint32 + }{ + {"carried", 152039, 100, 100}, + {"worn", 152039, 100, 101}, + {"removed", 152039, 100, 100}, + {"shrinking", 156831, 100, 101}, + {"fraction below", 152039, 99, 99}, + {"fraction above", 152039, 101, 102}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, output := newKillExperienceWorld(t, "unarmed") + player, client := world.characters[1], world.clients[1] + profile := *world.characters[1000000].combatProfile + profile.Experience = scenario.base + world.characters[1000000].combatProfile = &profile + if granted, err := world.grantItem_locked(player, scenario.template); err != nil || !granted { + t.Fatalf("grant Pioneer: %t %v", granted, err) + } + itemID := player.inventory.Items[0].ID + if scenario.name != "carried" { + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 19)[20:]); err != nil || client.equipment == nil { + t.Fatalf("wear Pioneer: %v", err) + } + world.advanceEquipment(client.equipment.readyAt) + } + if scenario.name == "removed" { + if err := world.handleInventory(client, itemMovePacket(1, 19, 111)[20:]); err != nil || client.equipment == nil { + t.Fatalf("remove Pioneer: %v", err) + } + world.advanceEquipment(client.equipment.readyAt) + } + output.packets = nil + + attackForExperience(t, world, "unarmed") + restored := newTestInventoryServer(t).characters[1] + + if player.experience != scenario.expected || restored.experience != scenario.expected || player.level != 1 || + player.stats.ImprovementPoints != 1500 || len(player.inventory.Items) != 1 || player.inventory.Items[0].ID != itemID || + len(restored.inventory.Items) != 1 || restored.inventory.Items[0].ID != itemID || restored.inventory.Items[0].Count != 1 { + t.Fatal("XP modifier or item identity did not survive the reward") + } + awards := 0 + for _, packet := range output.packets { + key := binary.BigEndian.Uint32(packet[16:20]) + if key == 0x7f405a16 { + t.Fatal("a below-threshold award produced a level event") + } + if key == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 52 { + awards++ + if binary.BigEndian.Uint32(packet[33:37]) != scenario.expected { + t.Fatal("absolute native XP did not match the committed reward") + } + } + } + if awards != 1 { + t.Fatalf("native XP awards: %d", awards) + } + }) + } +} + +func TestKillExperienceDoesNotReassignAnIneligibleWinnersReward(t *testing.T) { + for _, reason := range []string{"dead", "offline", "loading", "other zone", "unseen", "unknown", "grey", "capped", "joined team", "team winner", "unprofiled", "no reward"} { + t.Run(reason, func(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + winner, target := world.characters[1], world.characters[1000000] + world.nextCharacter = 1 + finisher := world.newCharacter() + finisher.playfield, finisher.position = 950, [3]float32{} + if err := world.saveUser_locked(finisher); err != nil { + t.Fatal(err) + } + output := &combatTestConn{} + world.clients[2] = &worldClient{id: 2, conn: output, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + target.damageContributors = map[damageContributor]uint32{{player: 1}: 99} + target.leadingContributor = damageContributor{player: 1} + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + switch reason { + case "dead": + winner.health = 0 + case "offline": + delete(world.clients, 1) + case "loading": + world.clients[1].loading = true + case "other zone": + winner.playfield = 800 + case "unseen": + delete(world.clients[1].npcs, target.id) + case "unknown": + target.damageContributors = map[damageContributor]uint32{{player: 3}: 99} + target.leadingContributor = damageContributor{player: 3} + case "grey": + winner.level = 4 + case "capped": + winner.level = 200 + case "joined team": + winner.team = &playerTeam{id: 1, leader: 1, members: []uint32{1}} + case "team winner": + target.damageContributors = map[damageContributor]uint32{{team: 1}: 99} + target.leadingContributor = damageContributor{team: 1} + case "unprofiled": + target.combatProfile = nil + case "no reward": + profile := *target.combatProfile + profile.Experience = 0 + target.combatProfile = &profile + } + + if err := world.handleCombat(world.clients[2], attackPacket(2, 1000000)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(finisher.nextAttack) + restored := newTestInventoryServer(t) + + if target.health != 0 || target.corpse == nil || winner.experience != 0 || finisher.experience != 0 || + restored.characters[1].experience != 0 || restored.characters[2].experience != 0 { + t.Fatal("the encounter's reward was reassigned or granted to an ineligible player") + } + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x7f405a16 || + binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 52 { + t.Fatal("an ineligible kill published XP") + } + } + }) + } +} + +func TestKillExperienceUsesReachedTitleForIP(t *testing.T) { + for _, scenario := range []struct { + level uint16 + progress, title, points, announcement uint32 + }{ + {1, 1400, 1, 5500, 0}, {14, 9550, 2, 11500, 2}, {49, 101850, 3, 21500, 3}, + {99, 1519850, 4, 41500, 4}, {149, 12141850, 5, 81500, 5}, {189, 52101150, 6, 151500, 6}, + } { + t.Run(fmt.Sprint(scenario.level), func(t *testing.T) { + world, output := newKillExperienceWorld(t, "unarmed") + player, target := world.characters[1], world.characters[1000000] + player.level, player.experience = scenario.level, scenario.progress + target.level = scenario.level + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + observer := world.newCharacter() + observer.playfield = 950 + otherOutput := &combatTestConn{} + world.clients[2] = &worldClient{id: 2, conn: otherOutput, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + + attackForExperience(t, world, "unarmed") + restored := newTestInventoryServer(t).characters[1] + + if player.level != scenario.level+1 || player.experience != 50 || player.titleLevel() != scenario.title || + player.stats.ImprovementPoints != scenario.points || restored.level != scenario.level+1 || restored.experience != 50 || + restored.stats.ImprovementPoints != scenario.points { + t.Fatalf("reached-title IP: level=%d XP=%d title=%d IP=%d", player.level, player.experience, player.titleLevel(), player.stats.ImprovementPoints) + } + levels := 0 + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x7f405a16 { + levels++ + if binary.BigEndian.Uint32(packet[49:53]) != scenario.announcement || binary.BigEndian.Uint32(packet[33:37]) != scenario.points { + t.Fatal("native title/IP did not match the committed transition") + } + } + } + if levels != 1 { + t.Fatal("title transition did not produce exactly one level event") + } + titles := 0 + for _, packet := range otherOutput.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 37 { + titles++ + if binary.BigEndian.Uint32(packet[33:37]) != scenario.title { + t.Fatal("an observer received the wrong profession title") + } + } + } + if scenario.announcement == 0 && titles != 0 || scenario.announcement != 0 && titles != 1 { + t.Fatal("visible title updates did not follow actual title transitions") + } + }) + } +} diff --git a/server/kill_experience_test.go b/server/kill_experience_test.go @@ -0,0 +1,193 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "testing" + "time" +) + +func newKillExperienceWorld(t *testing.T, attack string) (*server, *combatTestConn) { + t.Helper() + var world *server + var output *combatTestConn + switch attack { + case "axe", "fast": + world, output = newFastAttackWorld(t) + case "nano": + world, output = newNanoOutcomeWorld(t, 1) + default: + world, output = newRangedWorld(t) + } + player, target := world.characters[1], world.characters[1000000] + world.nextCharacter = 1 + if attack == "unarmed" { + if err := world.saveInventory_locked(player, playerInventory{}); err != nil { + t.Fatal(err) + } + } + player.health = 25 + target.health, target.monsterData, target.level = 1, 17655, 1 + target.position = [3]float32{1, 0, 0} + target.combatProfile = gamedata.NPCCombatProfiles[17655][1] + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + output.packets = nil + return world, output +} + +func attackForExperience(t *testing.T, world *server, attack string) { + t.Helper() + client := world.clients[1] + switch attack { + case "fast": + if err := world.handleWeaponSpecial(client, fastAttackRequest(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + case "fling": + if err := world.handleWeaponSpecial(client, flingShotRequest(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + case "nano": + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]); err != nil { + t.Fatal(err) + } + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + default: + if err := world.handleCombat(client, attackPacket(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(world.characters[1].nextAttack) + } +} + +func TestKillExperienceAdvancesAllAttackPathsOnce(t *testing.T) { + for _, attack := range []string{"unarmed", "axe", "pistol", "fling", "fast", "nano"} { + t.Run(attack, func(t *testing.T) { + world, output := newKillExperienceWorld(t, attack) + player := world.characters[1] + player.experience = 1400 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + world.nextCharacter = 1 + observer := world.newCharacter() + observer.playfield = 950 + if err := world.saveUser_locked(observer); err != nil { + t.Fatal(err) + } + otherOutput := &combatTestConn{} + world.clients[2] = &worldClient{id: 2, conn: otherOutput, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + + attackForExperience(t, world, attack) + world.advanceCombat(time.Now().Add(time.Hour)) + world.advanceNanos(time.Now().Add(time.Hour)) + restored := newTestInventoryServer(t) + + if player.level != 2 || player.experience != 50 || player.stats.ImprovementPoints != 5500 || player.health != 25 || player.maximumHealth() != 43 || + restored.characters[1].level != 2 || restored.characters[1].experience != 50 || restored.characters[1].stats.ImprovementPoints != 5500 || + restored.characters[1000000].health != 0 || restored.characters[1000000].corpse == nil || restored.characters[1000000].corpse.looter != 1 { + t.Fatal("the killing action lost or duplicated XP, level, IP, resource maxima or corpse state") + } + levels := 0 + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x7f405a16 { + levels++ + for index, expected := range []uint32{2, 5500, 1500, 1450, 4050, 0, 2, 100} { + if binary.BigEndian.Uint32(packet[29+index*4:]) != expected { + t.Fatalf("native level payload field %d: %x", index, packet) + } + } + } + } + if levels != 1 || observer.level != 1 || observer.experience != 0 || restored.characters[2].experience != 0 { + t.Fatal("duplicate level event or progression granted to an observer") + } + visibleLevels := 0 + for _, packet := range otherOutput.packets { + key := binary.BigEndian.Uint32(packet[16:20]) + if key == 0x7f405a16 || key == 0x2b333d6e && (binary.BigEndian.Uint32(packet[29:33]) == 52 || binary.BigEndian.Uint32(packet[29:33]) == 53) { + t.Fatal("an observer received private XP/IP or level-up feedback") + } + if key == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 54 && binary.BigEndian.Uint32(packet[33:37]) == 2 { + visibleLevels++ + } + } + if visibleLevels != 1 { + t.Fatal("an observer did not receive the new visible level") + } + }) + } +} + +func TestKillExperienceFailedRewardRollsBackThenRetries(t *testing.T) { + for _, attack := range []string{"unarmed", "axe", "pistol", "fling", "fast", "nano"} { + for _, failure := range []struct{ name, statement string }{ + {"reward", "CREATE TRIGGER reject_xp BEFORE UPDATE OF experience ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(ABORT, 'test reward'); END"}, + {"ignored reward", "CREATE TRIGGER reject_xp BEFORE UPDATE OF experience ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(IGNORE); END"}, + {"ignored health", "CREATE TRIGGER reject_xp BEFORE UPDATE ON characters WHEN NEW.id=1000000 AND NEW.health=0 BEGIN SELECT RAISE(IGNORE); END"}, + {"ignored corpse", "CREATE TRIGGER reject_xp BEFORE UPDATE ON npcs WHEN NEW.id=1000000 AND NEW.has_corpse=1 BEGIN SELECT RAISE(IGNORE); END"}, + {"commit", "CREATE TABLE pending_xp (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_xp AFTER UPDATE OF experience ON characters WHEN NEW.id=1 BEGIN INSERT INTO pending_xp VALUES (999999); END"}, + } { + t.Run(attack+"/"+failure.name, func(t *testing.T) { + world, output := newKillExperienceWorld(t, attack) + player, target := world.characters[1], world.characters[1000000] + player.experience = 1400 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec(failure.statement); err != nil { + t.Fatal(err) + } + + // The request can report its failed transaction; ticks log and cancel it. + switch attack { + case "fling": + if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err == nil { + t.Fatal("failed Fling transaction returned success") + } + case "fast": + if err := world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, 1000000)[20:]); err == nil { + t.Fatal("failed Fast Attack transaction returned success") + } + default: + attackForExperience(t, world, attack) + } + restored := newTestInventoryServer(t) + + if player.level != 1 || player.experience != 1400 || player.stats.ImprovementPoints != 1500 || target.health != 1 || target.corpse != nil || + len(world.npcRespawns) != 0 || len(world.corpseExpiry) != 0 || len(player.specialAttackLocks) != 0 || + restored.characters[1].experience != 1400 || restored.characters[1].level != 1 || restored.characters[1].stats.ImprovementPoints != 1500 || + restored.characters[1000000].health != 1 || restored.characters[1000000].corpse != nil { + t.Fatal("failed kill committed part of its progression or corpse") + } + if attack == "pistol" && (player.inventory.Items[0].Ammo != 3 || restored.characters[1].inventory.Items[0].Ammo != 3) || + attack == "nano" && (player.nano != 30 || player.nanoReserved != 0 || !player.nanoRechargeUntil.IsZero()) { + t.Fatal("failed kill consumed ammunition, nano or recharge") + } + for _, packet := range output.packets { + key := binary.BigEndian.Uint32(packet[16:20]) + if key == 0x7f405a16 || key == 0x46002f16 || key == 0x754f1115 || key == 0x4727213e || key == 0x4f474e05 { + t.Fatal("failed kill published damage, death or progression") + } + } + + // Retry after removing the fault; another restart retains one reward. + if _, err := world.db.Exec("DROP TRIGGER reject_xp"); err != nil { + t.Fatal(err) + } + attackForExperience(t, world, attack) + again := newTestInventoryServer(t) + if player.level != 2 || player.experience != 50 || player.stats.ImprovementPoints != 5500 || + again.characters[1].level != 2 || again.characters[1].experience != 50 || again.characters[1].stats.ImprovementPoints != 5500 || + again.characters[1000000].health != 0 { + t.Fatal("retry lost or duplicated the reward") + } + }) + } + } +} diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -166,18 +166,18 @@ func (server *server) removeNano_locked(player *character, index int, now time.T previous := *player *player = candidate server.queueCombat_locked(updates, player, player, characterActionPacket(player.id, [5]uint32{65, 0, 0, effect.caster, effect.program})) - server.finishNanoEffect_locked(updates, player, previous, now) + server.finishResourceChange_locked(updates, player, previous, now) return nil } -func (server *server) finishNanoEffect_locked(updates map[*worldClient][][]byte, player *character, previous character, now time.Time) { +func (server *server) finishResourceChange_locked(updates map[*worldClient][][]byte, player *character, previous character, now time.Time) { // A maximum-health change can change a wounded player's held movement speed. if client := server.clients[player.id]; client != nil && previous.maximumHealth() != player.maximumHealth() { player.position = predictedPosition_locked(&previous, client, now) client.movementStarted = now } - // Ability modifiers do not invalidate the native client's cached resource maxima. + // Refresh the native resource caches when derived maxima change. for _, stat := range [][3]uint32{ {1, previous.maximumHealth() - uint32(previous.inventory.equipmentBonus(1)), player.maximumHealth() - uint32(player.inventory.equipmentBonus(1))}, {221, previous.maximumNano() - uint32(previous.inventory.equipmentBonus(221)), player.maximumNano() - uint32(player.inventory.equipmentBonus(221))}, diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -237,7 +237,8 @@ func (server *server) advanceNanos(now time.Time) { victim.activeNanos = append(victim.activeNanos, activeNano{program: program, caster: player.id, remaining: duration, expiresAt: now.Add(duration)}) } - if err := server.saveNanoOutcome_locked(&caster, &victim, now); err != nil { + award, err := server.saveNanoOutcome_locked(&caster, &victim, now) + if err != nil { log.Printf("Nano outcome: %v", err) server.abortNano_locked(client, now, updates) continue @@ -248,7 +249,7 @@ func (server *server) advanceNanos(now time.Time) { if program != 29618 { server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, program})) server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{177, 53019, program, player.id, itemStat(gamedata.NanoTemplates[program], 8)})) - server.finishNanoEffect_locked(updates, target, previous, now) + server.finishResourceChange_locked(updates, target, previous, now) continue } body := binary.BigEndian.AppendUint32(nil, uint32(-int32(damage))) @@ -256,6 +257,7 @@ func (server *server) advanceNanos(now time.Time) { server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, 29618})) server.queueCombat_locked(updates, target, target, n3Packet(0x4727213e, 50000, target.id, body)) server.finishDamageEffects_locked(player, target, previous, now, updates) + server.applyExperienceAward_locked(award, now, updates) if target.health == 0 { // StopFight drains pending weapon results before the explicit nano death reset. server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{153, 0, 0, 0, 5})) diff --git a/server/npc_outcome.go b/server/npc_outcome.go @@ -19,10 +19,10 @@ func writeNPCOutcome_locked(tx *sql.Tx, target *character, now time.Time) (npcSt } func writeNPCState_locked(tx *sql.Tx, target *character, state *npcState) error { - if _, err := tx.Exec(upsertRecordSQL("characters", characterColumns), append([]any{target.id}, state.Character.fields()...)...); err != nil { + if err := upsertRecord(tx, "characters", target.id, characterColumns, state.Character.fields()); err != nil { return err } - if _, err := tx.Exec(upsertRecordSQL("npcs", npcColumns), append([]any{target.id}, state.fields()...)...); err != nil { + if err := upsertRecord(tx, "npcs", target.id, npcColumns, state.fields()); err != nil { return err } if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", target.id); err != nil { @@ -51,14 +51,14 @@ func (server *server) rememberNPCOutcome_locked(target *character, state npcStat server.savedNPCs[target.id] = savedNPC{state, maps.Clone(target.damageContributors), nextSave} } -func (server *server) saveDeath_locked(target *character, now time.Time) error { +func (server *server) saveDeath_locked(target *character, now time.Time) (*experienceAward, error) { db, err := server.database() if err != nil { - return err + return nil, err } tx, err := db.Begin() if err != nil { - return err + return nil, err } defer tx.Rollback() var state npcState @@ -68,41 +68,45 @@ func (server *server) saveDeath_locked(target *character, now time.Time) error { err = server.writePlayerDeath_locked(tx, target) } if err != nil { - return err + return nil, err + } + award, err := server.writeKillReward_locked(tx, target) + if err != nil { + return nil, err } if err := tx.Commit(); err != nil { - return err + return nil, err } if target.npc { server.rememberNPCOutcome_locked(target, state, now) } else { server.rememberPlayerDeath_locked(target) } - return nil + return award, nil } -func (server *server) saveRangedHit_locked(gun ownedItem, target *character, now time.Time) error { +func (server *server) saveRangedHit_locked(gun ownedItem, target *character, now time.Time) (*experienceAward, error) { db, err := server.database() if err != nil { - return err + return nil, err } tx, err := db.Begin() if err != nil { - return err + return nil, err } defer tx.Rollback() // Nonlethal simulation remains on checkpoints; a death joins this debit. result, err := tx.Exec("UPDATE items SET ammo=? WHERE id=?", gun.Ammo, gun.ID) if err != nil { - return err + return nil, err } changed, err := result.RowsAffected() if err != nil { - return err + return nil, err } if changed != 1 { - return fmt.Errorf("weapon %d ammunition update affected %d rows", gun.ID, changed) + return nil, fmt.Errorf("weapon %d ammunition update affected %d rows", gun.ID, changed) } var state npcState if target.health == 0 { @@ -112,11 +116,15 @@ func (server *server) saveRangedHit_locked(gun ownedItem, target *character, now err = server.writePlayerDeath_locked(tx, target) } if err != nil { - return err + return nil, err } } + award, err := server.writeKillReward_locked(tx, target) + if err != nil { + return nil, err + } if err := tx.Commit(); err != nil { - return err + return nil, err } // Publish the round and durable death state only after commit. @@ -128,31 +136,31 @@ func (server *server) saveRangedHit_locked(gun ownedItem, target *character, now } else if target.health == 0 { server.rememberPlayerDeath_locked(target) } - return nil + return award, nil } -func (server *server) saveNanoOutcome_locked(player, target *character, now time.Time) error { +func (server *server) saveNanoOutcome_locked(player, target *character, now time.Time) (*experienceAward, error) { db, err := server.database() if err != nil { - return err + return nil, err } tx, err := db.Begin() if err != nil { - return err + return nil, err } defer tx.Rollback() // Commit the completed cast's cost and recharge with its authoritative effect. result, err := tx.Exec("UPDATE characters SET nano=?, nano_reserved=?, nano_recharge_until=? WHERE id=?", player.nano, player.nanoReserved, player.nanoRechargeUntil, player.id) if err != nil { - return err + return nil, err } changed, err := result.RowsAffected() if err != nil { - return err + return nil, err } if changed != 1 { - return fmt.Errorf("caster %d nano update affected %d rows", player.id, changed) + return nil, fmt.Errorf("caster %d nano update affected %d rows", player.id, changed) } var state npcState if target.npc { @@ -161,10 +169,14 @@ func (server *server) saveNanoOutcome_locked(player, target *character, now time err = writeActiveNanos(tx, target, now) } if err != nil { - return err + return nil, err + } + award, err := server.writeKillReward_locked(tx, target) + if err != nil { + return nil, err } if err := tx.Commit(); err != nil { - return err + return nil, err } player.savedVitals.Nano, player.savedVitals.NanoRechargeUntil = player.nano, player.nanoRechargeUntil @@ -174,5 +186,5 @@ func (server *server) saveNanoOutcome_locked(player, target *character, now time } else if target.id == player.id { target.savedVitals = player.savedVitals } - return nil + return award, nil } diff --git a/server/player_death_test.go b/server/player_death_test.go @@ -202,7 +202,7 @@ func TestPlayerRangedDeathCommitsTheRoundWithBuffsAndReclaim(t *testing.T) { } // Exercise the shared damage boundary; client PvP admission is disabled. - fired, err := world.applyWeaponDamage_locked(&attacker, target, 1, time.Now()) + fired, _, err := world.applyWeaponDamage_locked(&attacker, target, 1, time.Now()) restored := newTestInventoryServer(t) if fail { diff --git a/server/progression.go b/server/progression.go @@ -0,0 +1,126 @@ +package main + +import ( + "ao/server/gamedata" + "database/sql" + "encoding/binary" + "fmt" + "math" + "time" +) + +type experienceAward struct { + owner uint32 + level uint16 + experience uint32 + improvementPoints uint32 + amount uint32 +} + +func (player *character) experienceBounds() (uint32, uint32) { + // Translate current-level progress into the native cumulative boundaries. + level := max(1, player.level) + var lower uint32 + for _, required := range gamedata.ExperienceLevels[:level-1] { + lower += required + } + upper := lower + if level < 200 { + upper += gamedata.ExperienceLevels[level-1] + } + return lower, upper +} + +func (server *server) writeKillReward_locked(tx *sql.Tx, target *character) (*experienceAward, error) { + if !target.npc || target.health != 0 || server.characters[target.id].health == 0 || + target.combatProfile == nil || target.combatProfile.Experience == 0 { + return nil, nil + } + // Solo winner, grey eligibility and rounding are provisional; see docs/character-progression.md. + player := server.characters[target.leadingContributor.player] + if player == nil || player.npc || player.team != nil || player.health == 0 || player.level == 0 || player.level >= 200 || + player.playfield != target.playfield || uint32(player.level) > uint32(target.level)+2 { + return nil, nil + } + client := server.clients[player.id] + if client == nil || !client.ready || client.loading || !client.npcs[target.id] { + return nil, nil + } + modifier := max(int64(0), 100+int64(player.equipmentBonus(319))+int64(player.nanoBonus(319))) + amount := uint64(target.combatProfile.Experience) * uint64(modifier) / 100 + if amount == 0 { + return nil, nil + } + + // Stage the complete progression before writing any visible actor state. + candidate := *player + candidate.stats = player.baseStats() + progress := uint64(player.experience) + amount + points := uint64(candidate.stats.ImprovementPoints) + for candidate.level < 200 && progress >= uint64(gamedata.ExperienceLevels[candidate.level-1]) { + progress -= uint64(gamedata.ExperienceLevels[candidate.level-1]) + candidate.level++ + points += uint64(gamedata.ProfessionTitles[max(1, candidate.profession)].IP[candidate.titleLevel()-1]) + } + if candidate.level == 200 { + progress = 0 + } + if points > math.MaxUint32 { + return nil, fmt.Errorf("player %d IP exceeds uint32", player.id) + } + candidate.experience, candidate.stats.ImprovementPoints = uint32(progress), uint32(points) + before, _ := player.experienceBounds() + after, _ := candidate.experienceBounds() + award := &experienceAward{player.id, candidate.level, candidate.experience, candidate.stats.ImprovementPoints, + after + candidate.experience - before - player.experience} + if err := updateRecord(tx, "characters", player.id, "level, experience, improvement_points", + []any{award.level, award.experience, award.improvementPoints}); err != nil { + return nil, err + } + return award, nil +} + +func (server *server) applyExperienceAward_locked(award *experienceAward, now time.Time, updates map[*worldClient][][]byte) { + if award == nil { + return + } + player := server.characters[award.owner] + previous := *player + player.level, player.experience, player.stats.ImprovementPoints = award.level, award.experience, award.improvementPoints + player.savedProfile.Level, player.savedProfile.Experience, player.savedProfile.Stats.ImprovementPoints = award.level, award.experience, award.improvementPoints + lower, upper := player.experienceBounds() + client := server.clients[player.id] + if previous.level == player.level { + body := binary.BigEndian.AppendUint32(nil, 52) + body = binary.BigEndian.AppendUint32(body, lower+player.experience) + updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, player.id, body)) + return + } + + // Only the owner receives private XP/IP and native level-up feedback. + title := uint32(0) + if previous.titleLevel() != player.titleLevel() { + title = player.titleLevel() + } + var body []byte + for _, value := range []uint32{uint32(player.level), player.stats.ImprovementPoints, lower + player.experience, + lower, upper, title, 2, award.amount} { + body = binary.BigEndian.AppendUint32(body, value) + } + updates[client] = append(updates[client], n3Packet(0x7f405a16, 50000, player.id, body)) + visible := [][2]uint32{{54, uint32(player.level)}} + if title != 0 { + visible = append(visible, [2]uint32{37, title}) + } + for id, observer := range server.clients { + if id == player.id || !observer.ready || observer.loading || server.characters[id].playfield != player.playfield { + continue + } + for _, stat := range visible { + body := binary.BigEndian.AppendUint32(nil, stat[0]) + body = binary.BigEndian.AppendUint32(body, stat[1]) + updates[observer] = append(updates[observer], n3Packet(0x2b333d6e, 50000, player.id, body)) + } + } + server.finishResourceChange_locked(updates, player, previous, now) +} diff --git a/server/ranged.go b/server/ranged.go @@ -19,25 +19,27 @@ func (item ownedItem) validAmmo() bool { return item.Ammo == 0 } -func (server *server) applyWeaponDamage_locked(attacker, target *character, damage uint32, now time.Time) (bool, error) { +func (server *server) applyWeaponDamage_locked(attacker, target *character, damage uint32, now time.Time) (bool, *experienceAward, error) { for index, item := range attacker.inventory.Items { if item.Slot != 6 || !item.isFlechettePistol() { continue } if item.Ammo == 0 { - return false, nil + return false, nil, nil } // Commit the round and any resulting death before changing live actors. item.Ammo-- candidate := prepareDamage(attacker, target, damage, now) - if err := server.saveRangedHit_locked(item, &candidate, now); err != nil { - return false, err + award, err := server.saveRangedHit_locked(item, &candidate, now) + if err != nil { + return false, nil, err } attacker.inventory.Items[index] = item *target = candidate - return true, nil + return true, award, nil } - return true, server.applyDamage_locked(attacker, target, damage, now) + award, err := server.applyDamage_locked(attacker, target, damage, now) + return true, award, err } func (server *server) handleReload(client *worldClient, body []byte) error { diff --git a/server/special_locks.go b/server/special_locks.go @@ -29,27 +29,31 @@ func (server *server) loadSpecialAttackLocks() error { return rows.Err() } -func (server *server) saveSpecialAttack_locked(player, target *character, skill uint32, deadline, now time.Time) error { +func (server *server) saveSpecialAttack_locked(player, target *character, skill uint32, deadline, now time.Time) (*experienceAward, error) { db, err := server.database() if err != nil { - return err + return nil, err } tx, err := db.Begin() if err != nil { - return err + return nil, err } defer tx.Rollback() // Commit the shared lock, damage, contributions and death state together. if _, err := tx.Exec("INSERT INTO special_attack_locks (player_id, skill, locked_until) VALUES (?, ?, ?) "+ "ON CONFLICT (player_id, skill) DO UPDATE SET locked_until=excluded.locked_until", player.id, skill, deadline); err != nil { - return err + return nil, err } state, err := writeNPCOutcome_locked(tx, target, now) if err != nil { - return err + return nil, err + } + award, err := server.writeKillReward_locked(tx, target) + if err != nil { + return nil, err } if err := tx.Commit(); err != nil { - return err + return nil, err } if player.specialAttackLocks == nil { @@ -57,5 +61,5 @@ func (server *server) saveSpecialAttack_locked(player, target *character, skill } player.specialAttackLocks[skill] = deadline server.rememberNPCOutcome_locked(target, state, now) - return nil + return award, nil } diff --git a/server/weapon_special.go b/server/weapon_special.go @@ -60,7 +60,8 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro seconds := player.weaponSpecialLockSeconds(gamedata.ItemTemplates[item.Template], skill) damage := min(player.normalDamage(target, rand.Uint32N), target.health) candidate := prepareDamage(player, target, damage, now) - if err := server.saveSpecialAttack_locked(player, &candidate, skill, now.Add(time.Duration(seconds)*time.Second), now); err != nil { + award, err := server.saveSpecialAttack_locked(player, &candidate, skill, now.Add(time.Duration(seconds)*time.Second), now) + if err != nil { server.mutex.Unlock() return err } @@ -83,6 +84,7 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro server.queueCombat_locked(updates, player, target, n3Packet(0x754f1115, 50000, player.id, result)) updates[client] = append(updates[client], skillLockPacket(player.id, skill, seconds)) server.finishDamageEffects_locked(player, target, previous, now, updates) + server.applyExperienceAward_locked(award, now, updates) server.mutex.Unlock() server.sendCombatUpdates(updates) return nil diff --git a/server/world.go b/server/world.go @@ -194,16 +194,7 @@ func fullCharacterPacket(character *character) []byte { for range 4 { body = binary.BigEndian.AppendUint32(body, 1009) } - // Translate current-level progress into the native cumulative boundaries. - level := max(1, character.level) - var lowerXP uint32 - for _, required := range gamedata.ExperienceLevels[:level-1] { - lowerXP += required - } - upperXP := lowerXP - if level < 200 { - upperXP += gamedata.ExperienceLevels[level-1] - } + lowerXP, upperXP := character.experienceBounds() stats := [][2]uint32{{54, uint32(character.level)}, {52, lowerXP + character.experience}, {57, lowerXP}, {350, upperXP}} stats = append(stats, character.baseStats().nativeStats()...) stats = append(stats, diff --git a/tools/data/extract_profession_resources.py b/tools/data/extract_profession_resources.py @@ -20,9 +20,10 @@ def main(): assert [row[0] for row in rows] == [1, 15, 50, 100, 150, 190] health = [row[2] for row in rows] nano = [row[1] for row in rows] - assert all(value >= 0 for value in health + nano) + ip = [row[3] for row in rows] + assert all(value >= 0 for value in health + nano + ip) lines.extend([f'{profession}:', f' health: {json.dumps(health)}', - f' nano: {json.dumps(nano)}']) + f' nano: {json.dumps(nano)}', f' ip: {json.dumps(ip)}']) records.append(dict(profession=profession, rows=rows, payload_hex=raw.hex(), payload_sha256=hashlib.sha256(raw).hexdigest())) database.close()