aorecomp

Anarchy Online classic in the browser

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


commit 2c1c5533766f019a04a578cd7e6d54e490d59599
parent bd8826107ec281af7512e274acae2ab77989c1c0
Author: anon <anon@example.com>
Date:   Mon, 26 Oct 2026 18:40:30 +0000

Generate NPC corpse rewards atomically from combat profiles

Stage configured cash and typed item instances in the shared death outcome,
commit identity reservations with attack costs and XP, then publish caches.
Seed a clearly provisional level 1 Leet Monster Parts profile.

Cover shared attack paths, rollback/retry, concurrent deaths, cold recovery,
loot chance boundaries, pickup, full inventory and respawn without rerolls.
Full server suite: 1357 roots / 14487 results. Focused and race: 155 / 469.
Old outcome pipeline fails 11 reward roots; nonlethal control passes.
Native normal kill generated loot; record starter fight/recovery blockers
and keep full native progression acceptance open.

Diffstat:
MTODO.md | 41++++++++++++++++++++++++++++++++++-------
Adocs/npc-loot.md | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/gamedata/load.go | 9+++++++++
Mserver/gamedata/npc_combat.yaml | 6++++++
Mserver/gamedata/types.go | 21++++++++++++++-------
Aserver/npc_loot.go | 45+++++++++++++++++++++++++++++++++++++++++++++
Aserver/npc_loot_test.go | 349+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/npc_outcome.go | 35+++++++++++++++++++++++++++++++----
Mserver/special_locks.go | 2+-
9 files changed, 579 insertions(+), 19 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -43,8 +43,9 @@ The existing server already supports fighting, respawn, fixed corpse items and credits, provisional solo kill XP, leveling/IP, equipment, resurrection/reclaim, shop sales and a limited purchase subset. These are separate verified examples; they do not yet prove ordinary players can progress without admin provisioning. -Production loot tables, useful purchasable equipment and a connected native -gameplay regression are the immediate gaps. Quest and mission checkboxes below +An ordinary level 1 Leet death now generates provisional Monster Parts and cash +through a shared loot profile. Useful equipment drops, useful purchasable stock +and a connected native gameplay regression are the immediate gaps. Quest and mission checkboxes below are still open; they have not been implemented by the shop or dialogue work. Next execution order: @@ -497,6 +498,16 @@ for exact records, protocol, tests and remaining reconstruction assumptions. each value is identified as verified or provisional. - [ ] [P0] Give that species a second level. Check: the two levels have independently checked resources and combat values rather than an assumed scaling formula. +- [ ] [P0] Verify a viable starter fight and recovery route. Check: a normally + created character can train appropriate skills, equip its issued weapon, kill + a starter enemy, recover and repeat without admin changes. Audit provisional + enemy resources/damage, starting skills, attack timing and healing together + before changing balance. Include death before the first insurance save and a + reachable return to training. A native solo Enforcer attempt died; a subsequent + two-character attempt killed a Leet but its leading contributor died first, + leaving the survivor without XP or loot access. Both returns used the default + city resurrection location. These observations identify scenarios to resolve, + not historical proof of the correct balance, reward or arrival rules. - [ ] [P1] Add a second species with different behavior or equipment. Check: changing one species' profile does not change the other species. - [x] Reconcile recovery for currently unprofiled creatures. Check: a damaged @@ -605,6 +616,14 @@ are recorded in [reclaim](docs/reclaim.md). another player to loot, with an explicit relationship to corpse expiry. - [x] Award and retain credits. Check: taking a known corpse credit amount changes the balance once and survives reconnect and restart. +- [x] Generate corpse rewards through shared production death outcomes. Check: + direct weapons, specials, direct nanos and periodic damage atomically commit + configured cash/items, corpse state, XP and attack costs; failure cannot leak + instances or reserve identities. Independent concurrent deaths retain distinct + items, and checkpoint/respawn cannot reroll existing corpses. An ordinary native + Leet kill produced a durable QL 1 Monster Part and 3 credits without admin + provisioning. Its deceased leading contributor retained loot rights; native + pickup/sale remains unverified in that run. See [NPC loot](docs/npc-loot.md). - [ ] [P0] Roll loot for one creature profile. Check: controlled rolls select the documented entries and quantities, including an empty result where allowed. Wire the profile into ordinary production spawns/deaths, not only controlled @@ -613,15 +632,17 @@ are recorded in [reclaim](docs/reclaim.md). equip or sell, matching requirements, stable instance identity, repeat/restart behavior and atomic rejection with full inventory. Record the evidence and any provisional chances/cash values separately; reuse shared reward/item rules. - Initial normal-play audit confirms the production gap: `prepareDamage` - creates an empty corpse, and `item_store.go` restores existing contents; neither - generates drops or cash. The mirrored Leets page names Monster Parts but dates - to2010, so it is a research lead rather than proof of14.9.1 chances or qualities. + The first production profile now rolls QL 1 Monster Parts independently at a + provisional 50% chance and 1..5 cash. Useful equipment, broader levels/species, + original distributions/quality selection and the complete native pickup/equip/ + sale route remain open. The mirrored Leets page names Monster Parts but dates + to 2010; neither it nor the dated newbie gathering accounts establish 14.9.1 + drop chances or cash formulas. See [NPC loot](docs/npc-loot.md). - [x] Remove an expired corpse. Check: observers lose the corpse and stale loot requests cannot recover or duplicate its contents. The fixed-item checks use a controlled fixture after a real combat kill; -production drop tables remain a separate task. Native packet evidence and +broader production drop tables remain a separate task. Native packet evidence and current policy limits are recorded in [corpse and loot protocol](docs/corpse-loot.md). Known-amount credit collection and native balance limits are verified in [corpse credits](docs/corpse-credits.md); creature cash-drop formulas remain open. @@ -2266,6 +2287,12 @@ and server restarts. Turn every reproduced bug into a focused regression test. instance in slot6, with no page errors or admin edits. Combat, earned loot, leveling and purchases are not yet verified in this normal-play run. Retained evidence: `local/gameplay-loop-smoke/`; owned characters/items were cleaned up. + A subsequent normal Omni Enforcer run trained Body Development/Stamina, + equipped the issued bat/shirt and used a startup treatment lab. Solo combat + ended in death; a two-player kill generated real loot/cash but its leading + contributor died before the kill, denying the survivor loot and XP. This is + partial coverage, not completion of the loop. Native captures and cleanup: + `local/npc-loot/`. Prioritize the starter fight/recovery task above. - [ ] [P2] Audit native input across focus transitions and rapid target changes. Cover leaving/returning to the tab, opening/closing options or chat, held keys/modifiers, repeats, reconnect and slow frames. Compare the first input diff --git a/docs/npc-loot.md b/docs/npc-loot.md @@ -0,0 +1,90 @@ +# NPC corpse rewards + +Normal deaths generate rewards from the exact MonsterData/level combat profile. +The current production profile is the level 1 Leet. Each configured loot row rolls +independently, creates one item at its catalog template's authored quality, and +places it in a free corpse slot. Cash is selected inclusively from the configured +range. Unprofiled creatures do not inherit a universal loot table. + +The first table uses original Monster Parts 42640, QL 1, with a **provisional 50% +chance and 1..5 credits**. Those probabilities and cash amounts are reconstruction +values, not recovered 14.9.1 formulas. The independent-row/uniform-cash policy is +also provisional. No equipment drop, variable quantity or interpolated loot +quality is inferred from a creature's name or level. Useful equipment loot, +broader species/levels and original reward distributions remain open in TODO. + +## Evidence boundary + +The shipped item record 42640 has type 51005, QL 1, value 100 and no effect sections; +its native counterpart 42641 is QL 400. These are item facts, not a drop table. +The local Fandom mirror's Leets page lists Monster Parts and has a 2010 timestamp. +The [current Leet overview](https://wiki.aodb.us/wiki/Leets) gives the same item +association but includes later content. Neither establishes target-period drop +rates, quantities, quality selection or corpse cash. + +An [April 2002 firsthand discussion](https://forums-archive.anarchy-online.com/printthread.php?page=2&pp=20&t=18355) +describes converting newbie-area Monster Parts into plasma. Its Leet cash +anecdote describes a player deliberately giving cash to a creature; it must not +be read as an ordinary 5000-credit drop. This corroborates the early gathering +activity without establishing a species distribution. The table remains +explicitly provisional pending better period evidence. + +## Transaction and lifecycle + +All direct weapons, Fast Attack, Fling, direct nanos and periodic damage share +`server.writeNPCOutcome_locked`. It rolls only on a living-to-dead transition +that actually creates a corpse. It stages rewards on the detached outcome, +then commits NPC death, corpse cash/rights/deadlines, generated items/locations +and the item-identity reservation in the same transaction as XP and the attack's +applicable ammunition, nano cost or skill lock. Missing/ignored writes and failed +COMMIT roll back the entire outcome. Caches and the allocation counter publish +only after commit; an error can retry without leaking an item or death packet. + +XP eligibility does not control loot generation. A grey victim or a profile +with zero XP can still leave its configured rewards. Nonlethal damage, replayed +dead targets, checkpoints and respawn do not generate another reward set. A +respawn receives a fresh identity while the old corpse retains its items/cash. +Ordinary loot rights, range, full-inventory rejection, pickup, cash collection, +corpse expiry and shop sales continue through their shared handlers. + +Every generated instance enters the same item and placement caches used by +inventory, equipment, containers and shops. Catalog types and qualities are +retained; the server does not turn a weapon or bag into a generic simple item. +Typed fixture coverage does not establish those items as historical Leet drops. + +## Verification + +`server/npc_loot_test.go` covers the shared damage paths, periodic killing ticks, +probability/cash boundaries, item/placement/allocation failures and ignored writes, +deferred COMMIT failure, retry, durable pickup and cash consumption, XP-ineligible +kills, typed weapons/bags, full inventory, identity exhaustion and respawn without +reroll. Concurrent independent deaths verify distinct durable item identities. + +Exact source manifests, the old-pipeline negative baseline, automated logs and +headed GPU WASM captures are retained in `local/npc-loot/`. The normal-play +progression acceptance task stays open until earned upgrades and shop purchases, +leveling, death/reclaim and restart are verified together without admin assistance. + +The final automated run passed 1,357 server test roots (14,487 results), including +12 new reward roots (68 results). The focused and race selections each passed +155 roots (469 results). Running the reward tests against the previous outcome +pipeline failed 11 roots; the nonlethal control passed. Data-package tests and +`go vet` passed. The negative baseline replaces only the outcome integration, +retaining the new profile/schema and tests, so it isolates the missing producer. + +Two ordinary Omni Enforcers were created through Options in the headed WASM +client. Native controls equipped their issued bat and shirt, trained Body +Development/Stamina and consumed a startup lab to heal. A solo attempt died; +a two-character attempt killed Leet 1067319. SQLite retained generated instance +460, template 42640, QL 1, corpse slot 0 and 3 credits. The leading contributor +had died before the kill: neither player received XP, and the survivor's native +corpse open was rejected with "Looter is not present." This checks a real +production death and rejected access, not successful native pickup/sale or a +viable starter loop. Automated fixtures separately verify successful pickup and +exactly-once cash collection. Starter balance, contributor death/reward policy +and the default city resurrection route need further audit. + +Both owned clients closed without page errors. All nine owned characters and +35 issued items were removed with foreign-key/integrity checks and unchanged +unrelated rows. The single shared HTTPS preview remains available; generated +world corpses use their ordinary expiry lifecycle. diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -170,6 +170,15 @@ func init() { profile.AggDef < -100 || profile.AggDef > 100 { panic(fmt.Errorf("NPC combat profile %d/%d has invalid health, weapon or AggDef", monster, level)) } + if profile.Credits[0] > profile.Credits[1] || profile.Credits[1] > 100000 { + panic(fmt.Errorf("NPC combat profile %d/%d has invalid corpse cash", monster, level)) + } + for _, drop := range profile.Loot { + item := ItemTemplates[drop.Template] + if drop.Chance > 100 || item == nil || item.Quality == nil || *item.Quality == 0 { + panic(fmt.Errorf("NPC combat profile %d/%d has invalid loot %d", monster, level, drop.Template)) + } + } } } } diff --git a/server/gamedata/npc_combat.yaml b/server/gamedata/npc_combat.yaml @@ -16,3 +16,9 @@ respawn_seconds: 100 # Provisional lifetime from death; applies to empty and unlooted remains. corpse_seconds: 180 + # Provisional cash and drop probability; see docs/npc-loot.md. + # Monster Parts are documented Leet loot; the item is the original QL1 record. + credits: [1, 5] + loot: + - template: 42640 + chance: 50 diff --git a/server/gamedata/types.go b/server/gamedata/types.go @@ -23,13 +23,20 @@ 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"` - RespawnSeconds uint32 `yaml:"respawn_seconds"` - CorpseSeconds uint32 `yaml:"corpse_seconds"` + Health uint32 `yaml:"health"` + Experience uint32 `yaml:"experience"` + Weapon uint32 `yaml:"weapon"` + Initiative int32 `yaml:"initiative"` + AggDef int32 `yaml:"agg_def"` + RespawnSeconds uint32 `yaml:"respawn_seconds"` + CorpseSeconds uint32 `yaml:"corpse_seconds"` + Credits [2]uint32 `yaml:"credits,flow"` + Loot []NPCLoot `yaml:"loot"` +} + +type NPCLoot struct { + Template uint32 `yaml:"template"` + Chance uint32 `yaml:"chance"` } type NPCPlayfield struct { diff --git a/server/npc_loot.go b/server/npc_loot.go @@ -0,0 +1,45 @@ +package main + +import ( + "ao/server/gamedata" + "fmt" + "math/rand/v2" + "slices" +) + +func (server *server) rollCorpseLoot_locked(target *character) ([]ownedItem, error) { + if target.health != 0 || target.corpse == nil || target.combatProfile == nil || server.characters[target.id].health == 0 { + return nil, nil + } + roll := server.combatRoll + if roll == nil { + roll = rand.Uint32N + } + profile := target.combatProfile + if profile.Credits[1] != 0 { + target.corpse.credits += profile.Credits[0] + roll(profile.Credits[1]-profile.Credits[0]+1) + } + + // Stage new instances and retain any existing corpse contents on detached state. + target.corpse.items = slices.Clone(target.corpse.items) + var drops []ownedItem + next, slot := server.nextItem, uint32(0) + for _, drop := range profile.Loot { + if roll(100) >= drop.Chance { + continue + } + if next == ^uint32(0) { + return nil, fmt.Errorf("corpse loot item identities exhausted") + } + for slices.ContainsFunc(target.corpse.items, func(item ownedItem) bool { return item.Slot == slot }) { + slot++ + } + next++ + definition := gamedata.ItemTemplates[drop.Template] + item := ownedItem{ID: next, Type: definition.HeaderWords[0], Template: definition.ID, Quality: *definition.Quality, Slot: slot, Count: 1} + drops = append(drops, item) + target.corpse.items = append(target.corpse.items, item) + slot++ + } + return drops, nil +} diff --git a/server/npc_loot_test.go b/server/npc_loot_test.go @@ -0,0 +1,349 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "fmt" + "slices" + "sync" + "testing" + "time" +) + +func TestNPCDeathCommitsGeneratedLootAcrossAttackPaths(t *testing.T) { + for _, attack := range []string{"unarmed", "axe", "pistol", "fling", "fast", "nano"} { + t.Run(attack, func(t *testing.T) { + world, _ := newKillExperienceWorld(t, attack) + world.combatRoll = func(uint32) uint32 { return 0 } + before := world.nextItem + + attackForExperience(t, world, attack) + world.advanceCombat(time.Now().Add(time.Hour)) + world.advanceNanos(time.Now().Add(time.Hour)) + cold := newTestInventoryServer(t) + + expected := []ownedItem{{ID: before + 1, Type: 51005, Template: 42640, Quality: 1, Count: 1}} + for _, current := range []*server{world, cold} { + corpse := current.characters[1000000].corpse + if current.characters[1000000].health != 0 || corpse == nil || !slices.Equal(corpse.items, expected) || corpse.credits != 1 || corpse.looter != 1 || current.characters[1].experience != 100 || current.nextItem != before+1 { + t.Fatal("death, loot, cash, ownership, XP or allocation did not commit together", corpse, current.nextItem) + } + if current.items[before+1].Template != 42640 || current.itemPlacements[before+1] != (itemPlacement{Corpse: 1000000}) { + t.Fatal("generated instance is absent from the shared item/placement cache") + } + } + }) + } +} + +func TestNPCLootChanceAndCashBoundaries(t *testing.T) { + for _, scenario := range []struct { + roll, cash uint32 + items int + }{{0, 1, 1}, {49, 5, 1}, {50, 5, 0}, {99, 5, 0}} { + t.Run(fmt.Sprint(scenario.roll), func(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + world.combatRoll = func(limit uint32) uint32 { return min(scenario.roll, limit-1) } + before := world.nextItem + + attackForExperience(t, world, "unarmed") + cold := newTestInventoryServer(t) + + for _, current := range []*server{world, cold} { + corpse := current.characters[1000000].corpse + if corpse == nil || len(corpse.items) != scenario.items || corpse.credits != scenario.cash || current.nextItem != before+uint32(scenario.items) { + t.Fatal("chance boundary, inclusive cash range or empty-result allocation", corpse, current.nextItem) + } + } + }) + } +} + +func TestNPCLootFailedDeathPreservesStateAndRetries(t *testing.T) { + for _, attack := range []string{"unarmed", "axe", "pistol", "fling", "fast", "nano"} { + for _, failure := range []struct{ name, sql string }{ + {"item", "CREATE TRIGGER fail_loot BEFORE INSERT ON items BEGIN SELECT RAISE(FAIL,'loot item'); END"}, + {"ignored item", "CREATE TRIGGER fail_loot BEFORE INSERT ON items BEGIN SELECT RAISE(IGNORE); END"}, + {"placement", "CREATE TRIGGER fail_loot BEFORE INSERT ON item_locations BEGIN SELECT RAISE(FAIL,'loot placement'); END"}, + {"ignored placement", "CREATE TRIGGER fail_loot BEFORE INSERT ON item_locations BEGIN SELECT RAISE(IGNORE); END"}, + {"allocation", "CREATE TRIGGER fail_loot BEFORE UPDATE OF last_item_id ON world BEGIN SELECT RAISE(FAIL,'loot allocation'); END"}, + {"ignored allocation", "CREATE TRIGGER fail_loot BEFORE UPDATE OF last_item_id ON world BEGIN SELECT RAISE(IGNORE); END"}, + {"commit", "CREATE TABLE pending_loot (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_loot AFTER INSERT ON items BEGIN INSERT INTO pending_loot VALUES(999999); END"}, + } { + t.Run(attack+"/"+failure.name, func(t *testing.T) { + world, output := newKillExperienceWorld(t, attack) + world.combatRoll = func(uint32) uint32 { return 0 } + before, itemCount, placementCount := world.nextItem, len(world.items), len(world.itemPlacements) + if _, err := world.db.Exec(failure.sql); err != nil { + t.Fatal(err) + } + + switch attack { + case "fling": + if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err == nil { + t.Fatal("failed Fling loot returned success") + } + case "fast": + if err := world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, 1000000)[20:]); err == nil { + t.Fatal("failed Fast Attack loot returned success") + } + default: + attackForExperience(t, world, attack) + } + cold := newTestInventoryServer(t) + + for _, current := range []*server{world, cold} { + if current.characters[1000000].health != 1 || current.characters[1000000].corpse != nil || current.characters[1].experience != 0 || current.nextItem != before || len(current.items) != itemCount || len(current.itemPlacements) != placementCount { + t.Fatal("failed loot transaction leaked death, reward, allocation or cached item state") + } + } + for _, packet := range output.packets { + switch binary.BigEndian.Uint32(packet[16:20]) { + case 0x46002f16, 0x754f1115, 0x4727213e, 0x4f474e05, 0x7f405a16: + t.Fatal("failed loot outcome published damage, corpse or progression") + } + } + + // Retry the same public attack after removing the fault. + if _, err := world.db.Exec("DROP TRIGGER fail_loot"); err != nil { + t.Fatal(err) + } + attackForExperience(t, world, attack) + again := newTestInventoryServer(t) + if len(again.characters[1000000].corpse.items) != 1 || again.characters[1000000].corpse.credits != 1 || again.characters[1].experience != 100 || again.nextItem != before+1 { + t.Fatal("retry lost or repeated generated loot/cash/XP") + } + }) + } + } +} + +func TestNPCLootPickupUsesGeneratedInstanceAndDoesNotRepeatCash(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + world.combatRoll = func(uint32) uint32 { return 0 } + before := world.nextItem + attackForExperience(t, world, "unarmed") + + if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil { + t.Fatal(err) + } + if err := world.handleLootUse(world.clients[1], lootUseRequest(2)); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + + expected := []ownedItem{{ID: before + 1, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}} + for _, current := range []*server{world, cold} { + if !slices.Equal(current.characters[1].inventory.Items, expected) || current.characters[1].inventory.Credits != 1 || len(current.characters[1000000].corpse.items) != 0 || current.characters[1000000].corpse.credits != 0 || current.nextItem != before+1 { + t.Fatal("generated pickup changed identity, lost ownership or repeated cash", current.characters[1].inventory) + } + } +} + +func TestNPCLootDoesNotDependOnSoloExperienceEligibility(t *testing.T) { + for _, scenario := range []string{"grey", "zero XP"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + world.combatRoll = func(uint32) uint32 { return 0 } + if scenario == "grey" { + world.characters[1].level = 4 + if err := world.saveUser_locked(world.characters[1]); err != nil { + t.Fatal(err) + } + } else { + profile := *world.characters[1000000].combatProfile + profile.Experience = 0 + world.characters[1000000].combatProfile = &profile + } + + attackForExperience(t, world, "unarmed") + cold := newTestInventoryServer(t) + + if cold.characters[1].experience != 0 || len(cold.characters[1000000].corpse.items) != 1 || cold.characters[1000000].corpse.credits != 1 { + t.Fatal("XP eligibility incorrectly suppressed corpse rewards") + } + }) + } +} + +func TestNPCLootUsesSharedTypedItemRecords(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + profile := *world.characters[1000000].combatProfile + profile.Loot = []gamedata.NPCLoot{{Template: 42640, Chance: 100}, {Template: 123742, Chance: 100}, {Template: 143832, Chance: 100}} + world.characters[1000000].combatProfile = &profile + world.combatRoll = func(uint32) uint32 { return 0 } + before := world.nextItem + + attackForExperience(t, world, "unarmed") + cold := newTestInventoryServer(t) + + expected := []ownedItem{ + {ID: before + 1, Type: 51005, Template: 42640, Quality: 1, Count: 1}, + {ID: before + 2, Type: 51018, Template: 123742, Quality: 1, Slot: 1, Count: 1}, + {ID: before + 3, Type: 51017, Template: 143832, Quality: 1, Slot: 2, Count: 1}, + } + if !slices.Equal(cold.characters[1000000].corpse.items, expected) || cold.nextItem != before+3 || len(world.items[before+3].Slots) != 21 { + t.Fatal("loot generation did not retain catalog types, original qualities and durable instances", cold.characters[1000000].corpse.items) + } +} + +func TestNPCLootPeriodicKillingTickCommitsOnce(t *testing.T) { + world, _ := newPeriodicNanoWorld(t) + world.combatRoll = func(uint32) uint32 { return 0 } + target := world.characters[1000000] + target.health, target.monsterData, target.level = 1, 17655, 1 + target.combatProfile = gamedata.NPCCombatProfiles[17655][1] + before := world.nextItem + at := castPeriodicNano(t, world, 43376) + + world.advanceNanos(at.Add(7500 * time.Millisecond)) + world.advanceNanos(at.Add(7500 * time.Millisecond)) + cold := newTestInventoryServer(t) + + if cold.characters[1000000].health != 0 || len(cold.characters[1000000].corpse.items) != 1 || cold.characters[1000000].corpse.credits != 1 || cold.characters[1].experience != 100 || cold.nextItem != before+1 { + t.Fatal("periodic killing tick lost or repeated its durable rewards") + } +} + +func TestNPCLootDoesNotRollOnNonlethalDamage(t *testing.T) { + world, _ := newKillExperienceWorld(t, "pistol") + world.combatRoll = func(uint32) uint32 { return 0 } + target := world.characters[1000000] + target.health = 100 + before := world.nextItem + + attackForExperience(t, world, "pistol") + cold := newTestInventoryServer(t) + + if target.health == 0 || target.corpse != nil || cold.characters[1000000].corpse != nil || world.nextItem != before || cold.nextItem != before || len(world.items) != 2 || len(cold.items) != 2 || world.characters[1].experience != 0 { + t.Fatal("nonlethal hit allocated corpse rewards") + } +} + +func TestNPCLootIdentityExhaustionRejectsOnlyAnActualDrop(t *testing.T) { + for _, chance := range []uint32{0, 100} { + t.Run(fmt.Sprint(chance), func(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + world.combatRoll = func(uint32) uint32 { return 0 } + profile := *world.characters[1000000].combatProfile + profile.Loot = []gamedata.NPCLoot{{Template: 42640, Chance: chance}} + world.characters[1000000].combatProfile = &profile + world.nextItem = 4294967295 + if _, err := world.db.Exec("UPDATE world SET last_item_id=4294967295 WHERE id=1"); err != nil { + t.Fatal(err) + } + + attackForExperience(t, world, "unarmed") + cold := newTestInventoryServer(t) + + if world.nextItem != 4294967295 || cold.nextItem != 4294967295 || len(world.items) != 0 || len(cold.items) != 0 { + t.Fatal("loot allocation wrapped or leaked a partial item") + } + if chance == 100 { + if cold.characters[1000000].health != 1 || cold.characters[1000000].corpse != nil || cold.characters[1].experience != 0 { + t.Fatal("exhausted item identities committed part of the killing outcome") + } + } else if cold.characters[1000000].health != 0 || cold.characters[1000000].corpse.credits != 1 || cold.characters[1].experience != 100 { + t.Fatal("empty loot roll required an item identity") + } + }) + } +} + +func TestNPCLootRespawnAndCheckpointDoNotRegenerateOldRewards(t *testing.T) { + world, _ := newRespawnWorld(t) + world.combatRoll = func(uint32) uint32 { return 0 } + attackForExperience(t, world, "unarmed") + before := world.nextItem + deadline := world.npcRespawns[0].at + if len(world.characters[1000000].corpse.items) != 1 { + t.Fatal("the first life did not generate its loot") + } + item := world.characters[1000000].corpse.items[0] + + world.advanceNPCRespawns(deadline) + if err := world.checkpointWorld(deadline); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + + if cold.characters[1000001] == nil || cold.characters[1000001].corpse != nil || cold.characters[1000000].corpse.credits != 1 || !slices.Equal(cold.characters[1000000].corpse.items, []ownedItem{item}) || world.nextItem != before || cold.nextItem != before { + t.Fatal("respawn/checkpoint regenerated or lost the prior life's loot") + } +} + +func TestNPCLootFullInventoryRetainsGeneratedItem(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + world.combatRoll = func(uint32) uint32 { return 0 } + for range 30 { + if granted, err := world.grantItem_locked(world.characters[1], 42640); err != nil || !granted { + t.Fatal("fill inventory", granted, err) + } + } + attackForExperience(t, world, "unarmed") + if len(world.characters[1000000].corpse.items) != 1 { + t.Fatal("death did not generate the overflow item") + } + item := world.characters[1000000].corpse.items[0] + if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil { + t.Fatal(err) + } + + if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + + for _, current := range []*server{world, cold} { + if len(current.characters[1].inventory.Items) != 30 || current.characters[1].inventory.Credits != 1 || !slices.Equal(current.characters[1000000].corpse.items, []ownedItem{item}) || current.itemPlacements[item.ID] != (itemPlacement{Corpse: 1000000}) || current.nextItem != item.ID { + t.Fatal("full inventory lost, duplicated or transferred the generated drop") + } + } +} + +func TestNPCLootConcurrentDeathsReserveDistinctItems(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + world.combatRoll = func(uint32) uint32 { return 0 } + second := world.newCharacter() + second.playfield, second.position = 950, [3]float32{} + if err := world.saveUser_locked(second); err != nil { + t.Fatal(err) + } + npc := *world.characters[1000000] + npc.id = 1000001 + world.characters[npc.id], world.nextNPC = &npc, 1000002 + world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000001: true}} + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + for _, pair := range [][2]uint32{{1, 1000000}, {2, 1000001}} { + if err := world.handleCombat(world.clients[pair[0]], attackPacket(pair[0], pair[1])[20:]); err != nil { + t.Fatal(err) + } + } + at := world.characters[1].nextAttack + if second.nextAttack.After(at) { + at = second.nextAttack + } + before := world.nextItem + var visitors sync.WaitGroup + + for range 8 { + visitors.Go(func() { world.advanceCombat(at) }) + } + visitors.Wait() + cold := newTestInventoryServer(t) + + for _, current := range []*server{world, cold} { + first, second := current.characters[1000000].corpse, current.characters[1000001].corpse + if first == nil || second == nil || len(first.items) != 1 || len(second.items) != 1 || first.items[0].ID == second.items[0].ID || first.looter != 1 || second.looter != 2 || first.credits != 1 || second.credits != 1 || current.nextItem != before+2 || len(current.items) != 2 { + t.Fatal("concurrent deaths duplicated identities or lost independent rewards") + } + if current.characters[1].experience != 100 || current.characters[2].experience != 100 { + t.Fatal("one victim's XP was repeated or assigned to the other killer") + } + } +} diff --git a/server/npc_outcome.go b/server/npc_outcome.go @@ -7,7 +7,11 @@ import ( "time" ) -func writeNPCOutcome_locked(tx *sql.Tx, target *character, now time.Time) (npcState, error) { +func (server *server) writeNPCOutcome_locked(tx *sql.Tx, target *character, now time.Time) (npcState, error) { + drops, err := server.rollCorpseLoot_locked(target) + if err != nil { + return npcState{}, err + } state := target.worldState(true, time.Time{}) if target.health == 0 { state.Roaming.Moving, state.Roaming.Returning = false, false @@ -18,6 +22,20 @@ func writeNPCOutcome_locked(tx *sql.Tx, target *character, now time.Time) (npcSt if err := writeNPCState_locked(tx, target, &state); err != nil { return state, err } + // Death, generated ownership and identity reservation share the outcome transaction. + for _, item := range drops { + if err := insertRow(tx, "items", "id, type, template, quality, count, ammo", []any{item.ID, item.Type, item.Template, item.Quality, item.Count, item.Ammo}); err != nil { + return state, err + } + if err := insertRow(tx, "item_locations", "item_id, corpse_id, slot", []any{item.ID, target.id, item.Slot}); err != nil { + return state, err + } + } + if len(drops) != 0 { + if err := updateRecord(tx, "world", 1, "last_item_id", []any{drops[len(drops)-1].ID}); err != nil { + return state, err + } + } return state, writeActiveNanos(tx, target, now) } @@ -60,6 +78,15 @@ func (server *server) rememberNPCOutcome_locked(target *character, state npcStat nextSave = now.Add(20 * time.Second) } server.savedNPCs[target.id] = savedNPC{state, maps.Clone(target.damageContributors), nextSave} + if target.corpse != nil { + for _, item := range target.corpse.items { + if _, exists := server.items[item.ID]; !exists { + server.items[item.ID] = recordItem(item, nil) + server.itemPlacements[item.ID] = itemPlacement{Corpse: target.id, Slot: item.Slot} + server.nextItem = max(server.nextItem, item.ID) + } + } + } } func (server *server) saveDamageOutcome_locked(target *character, now time.Time) (*experienceAward, error) { @@ -74,7 +101,7 @@ func (server *server) saveDamageOutcome_locked(target *character, now time.Time) defer tx.Rollback() var state npcState if target.npc { - state, err = writeNPCOutcome_locked(tx, target, now) + state, err = server.writeNPCOutcome_locked(tx, target, now) } else { err = server.writePlayerDeath_locked(tx, target) } @@ -123,7 +150,7 @@ func (server *server) saveRangedHit_locked(gun ownedItem, target *character, now persistTarget := target.health == 0 || len(target.activeNanos) != len(server.characters[target.id].activeNanos) if persistTarget { if target.npc { - state, err = writeNPCOutcome_locked(tx, target, now) + state, err = server.writeNPCOutcome_locked(tx, target, now) } else { err = server.writePlayerDeath_locked(tx, target) } @@ -177,7 +204,7 @@ func (server *server) saveNanoOutcome_locked(player, target *character, now time var state npcState healthChanged := !target.npc && target.health != server.characters[target.id].health if target.npc { - state, err = writeNPCOutcome_locked(tx, target, now) + state, err = server.writeNPCOutcome_locked(tx, target, now) } else { err = writeActiveNanos(tx, target, now) if err == nil && healthChanged { diff --git a/server/special_locks.go b/server/special_locks.go @@ -16,7 +16,7 @@ func (server *server) saveSpecialAttack_locked(player, target *character, skill if err := writeSkillLock(tx, player.id, skill, deadline); err != nil { return nil, err } - state, err := writeNPCOutcome_locked(tx, target, now) + state, err := server.writeNPCOutcome_locked(tx, target, now) if err != nil { return nil, err }