aorecomp

Anarchy Online classic in the browser

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


commit c3c9e1c93b9b261f529e0d6c84876a5da0e7d69d
parent 74b15b292e700ff6a2bcb0dd18ebd7bceb4acff8
Author: anon <anon@example.com>
Date:   Tue, 27 Oct 2026 11:29:33 +0000

Add isolated Clan training boss combat and QL4 loot

Diffstat:
MTODO.md | 32+++++++++++++++++++++++++++++++-
Adocs/starter-boss.md | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/gamedata/load.go | 14++++++++++++++
Mserver/gamedata/npc_combat.yaml | 25+++++++++++++++++++++++++
Mserver/gamedata/types.go | 1+
Mserver/npcs.go | 6+++++-
Aserver/starter_boss_test.go | 404+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 589 insertions(+), 2 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -634,12 +634,29 @@ for exact records, protocol, tests and remaining reconstruction assumptions. unsaved death still uses a provisional destination. Establish the original rules before replacing these policies. The shipped training grounds contain no reclaim placement; do not invent one. +- [ ] [P0] Keep unsaved Clan/neutral deaths on a usable faction-appropriate return + route. A fresh Clan Atrox NT's ordinary Salamander Boss defeat used the current + Omni Entertainment fallback, retaining items and XP but stranding its training + progression across factions. Recover the original initial checkpoint policy + and reuse authored starter/scanner destinations; test all three sides, saved + overrides, failed writes, reconnect and a normal return to training. - [ ] [P1] Deliver the authored explanation when a backyard city exit rejects a player. Check: the original level-2-or-1,000-credit message appears once per entry, without moving the player, charging credits or repeating every simulation tick. Reuse the statel/criteria behavior; do not add per-backyard special cases. -- [ ] [P1] Add a second species with different behavior or equipment. Check: changing +- [x] Add a second species with different behavior or equipment. Check: changing one species' profile does not change the other species. + The authored Clan Training Salamander Boss uses its original QL4 bite family, + separately from Leet equipment, with code/species/level/evidence admission and + native verification on two clients. Broader Salamander populations and full + boss behavior remain outside this restricted profile. +- [ ] [P0] Extend shared combat pursuit to admitted encounters without idle roaming, + including the fixed Clan Training Salamander Boss. A fixed spawn point is not + evidence that a creature should stand still during combat. Verify approach, + melee range, retreat, target loss, return, roots/snares and reconnect for both + fixed and roaming profiles. Keep idle placement separate from combat movement; + do not add species-specific pursuit branches. Until this is implemented, + ranged kills of the stationary boss do not establish normal encounter balance. - [ ] [P1] Connect successive outdoor hunting areas to early progression. Use original district/species level ranges for mutants and other encounters, rather than scaling the outdoor world to the visiting player. Check reachable @@ -777,6 +794,19 @@ are recorded in [reclaim](docs/reclaim.md). 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] Connect selected-quality regular equipment to an authored training boss. + The original level-4 Clan Training BSML placement now admits a code-restricted + Salamander profile with original bite endpoints and explicit QL4 gloves/pistol + loot. Ordinary salamanders sharing its appearance cannot inherit this profile. + The pool, chances and combat/reward baseline are provisional reconstruction + policy, not recovered historical boss balance. Tests cover killing paths, + independent/empty rolls, atomic failure/retry, full and partial pickup, wear, + sale and cold replacement. Native acquisition and the complete ordinary + earned-income progression gate remain separate. See [starter boss](docs/starter-boss.md). + Two native clients verified the selected bite contract. An ordinary Atrox NT + defeated four full-health lives for 400 XP and collected one four-credit corpse; + three QL4 glove drops expired while still corpse-owned during interaction checks. + No native boss-drop pickup, wear or sale is claimed by this milestone. - [ ] [P0] Generate loot at suitable supported qualities. Separate item-family membership/chance from quality selection; establish period-supported QL ranges relative to creature level, allowing fixed-QL exceptions. Use shared endpoint diff --git a/docs/starter-boss.md b/docs/starter-boss.md @@ -0,0 +1,109 @@ +# Clan Training Salamander Boss + +The original 14.9.1 population places template code BSML at level 4 in Clan +Training (952), at (186.06424, 13.7, 182.79846). Its stable definition is +`952/district/5/fixed/0`, in the authored Dyna Boss district. The selected +Salamander appearance 30354 is an inferred species assignment from the original +named Salamander camp contexts; the historical complete boss template and +unique name remain unresolved. + +## Production profile and evidence boundary + +The profile is restricted to MonsterData 30354, level 4 and template code BSML. +A profile's optional `template_code` narrows the existing species/level rule: +ordinary salamanders sharing its body do not acquire boss rewards. Startup +requires a matching admitted original population. Spawn, cold load and replacement +all resolve through the same evidence and code checks. Existing Leet profiles +retain their species-based admission. + +Original SalamanderBite1 definitions 121063/121064 span QL1..400, with base +attack/recharge 235 centiseconds, melee damage, two-meter range, Martial Arts +attack and Evade Close defense. At actor QL4 their damage endpoints are 7..16 +and critical bonus 8. The shared NPC weapon path supplies interpolation and +native initialization. Choosing this variant for the boss, initiative 0 and +AggDef 75 are reconstruction choices, not a recovered server equipment binding. +Its original CharRadius stat 421 is 4. The shared range rule adds actor extents: +the two-meter bite reaches twelve meters against the default-size player. + +Health 100, XP 100, cash 1..5, 100-second respawn and 180-second corpse lifetime +use the current early-profile baseline. These are provisional values. No +historical boss multiplier, aura, special resistance or aggression rule is +inferred. The existing combat, XP, corpse rights, respawn and transaction rules +apply; fuller boss behavior remains separate work. + +The small regular-equipment pool is also explicit reconstruction policy: + +| Drop | Selected QL | Independent chance | +| --- | --- | --- | +| Metaplast gloves 85596/85595 | 4 | 50% | +| Rusty OT M-10 Flechette Pistol 123742/123743 | 4 | 25% | + +The original records establish these families' values, requirements and effects, +not this boss's exact historical membership or probabilities. A +[later backyard description](https://wiki.aodb.us/wiki/Backyards) identifies a +useful-loot Salamander boss, but mixes later starting areas and does not enumerate +its items. It is corroborating context, not a target-period loot table. The +fixed supported subset creates an early equipment source while historical +selection and wider content remain open. No universal NPC-level QL formula is +introduced; both selected QLs are declared in the production profile. + +The gloves require Strength 15 and Agility 16 and grant ACs 5/4/5/4/2/2/2/2 in +stat 90..97 order. The finite pistol retains the ordinary empty loaded clip; +bullets and reload remain necessary before using it. No ammo is invented to +make a pickup immediately usable. It can be sold through shared item prices. +Actual ordinary skill training, income, recovery and upgrade purchases are +separate from controlled handler fixtures. + +## Verification + +The handler tests cover the actual authored spawn and exclude the same body +under another code, wrong level/species and unresolved evidence. Production +rewards pass through six killing actions, independent chance boundaries, +empty rolls, second-item SQL failure/ignore/COMMIT failure and retry. Cold load +and replacement recheck the template code while retaining committed corpse +contents and XP. Full inventory rejects pickup without losing either drop; +one freed slot admits one item while the other remains on the corpse. + +A generated pair survives cold pickup restoration, rejected below-threshold +wear, qualified armor wear, a cancelled weapon sale and one accepted sale. +Cancellation follows native first-free restoration while preserving identity. +The Clan starter terminal credits 97 for the QL4 pistol at the fixture's low +Computer Literacy; worn gloves retain their identity and effects. These tests +isolate mechanics and do not establish normal-play acquisition or balance. + +Original payloads, parsed records, maintained-data comparisons, population and +mapping evidence, test logs and native artifacts are retained under +`local/starter-boss/`. Native ordinary-play outcomes are recorded separately +as they are verified; this document does not claim the full P0 loop is complete. + +## Ordinary native check + +Two hardware-rendered WASM clients received the same QL4 bite endpoints, damage +7..16, critical bonus 8 and 235-centisecond delays. A normally created and trained +level-1 Atrox NT lost its first attempt inside the effective bite range. Issued +items and its previous 100 XP survived automatic resurrection. The provisional +unsaved destination sent this Clan character to Omni Entertainment; a +faction-appropriate initial return remains a P0 TODO. + +A second normally created Atrox NT defeated four full-health boss lives using +its issued solar pistol, uploaded nanos, ordinary skill training and recovery. +It earned 400 XP. One corpse opening credited four cash exactly once. The item +rolls produced three QL4 glove instances and one empty result; no pistol dropped +in these four kills. The gloves expired while still corpse-owned during the +interaction checks. None entered player inventory, so this run establishes no +native boss-drop pickup, wear or sale. Those acceptance checks remain open. +A clean server restart retained the earned XP/cash, learned nanos and all sixteen +issued instances across the owned characters. Both live native inventories +matched SQLite identities, qualities, charges and slots afterward. No browser +exceptions occurred; the owned clients closed after verification. + +The fixed boss can retaliate inside its effective range but does not yet pursue +a retreating player. Ranged acquisition outside that range therefore cannot +establish canonical encounter balance. Shared pursuit for fixed encounters is +another P0 TODO; no per-species movement exception was added here. + +The complete Go suite passed 15,084 results across server and gamedata, including +31 results in eight focused boss tests. Ten related race-test roots passed, +as did vet. A resolver negative control fails ordinary-salamander isolation and +changed-code cold replacement checks, demonstrating that the restriction is +required rather than merely documented. diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -210,6 +210,20 @@ func init() { loadYAML("npc_combat.yaml", &NPCCombatProfiles) for monster, levels := range NPCCombatProfiles { for level, profile := range levels { + // Template-specific encounters must match an admitted original population. + if profile.TemplateCode != "" { + matched := false + for _, group := range NPCGroups { + if group.TemplateCode == profile.TemplateCode && group.MonsterData == monster && group.AppearanceStatus == "inferred_species" && + level >= group.Levels[0] && level <= group.Levels[1] { + matched = true + break + } + } + if !matched { + panic(fmt.Errorf("NPC combat profile %d/%d has no admitted population for %s", monster, level, profile.TemplateCode)) + } + } first, second := ItemTemplates[profile.Weapon[0]], ItemTemplates[profile.Weapon[1]] if MonsterTemplates[monster] == nil || level == 0 || profile.Health == 0 || first == nil || second == nil || first.HeaderWords[0] != 51018 || second.HeaderWords[0] != 51018 || diff --git a/server/gamedata/npc_combat.yaml b/server/gamedata/npc_combat.yaml @@ -40,3 +40,28 @@ - template: 42640 quality: 1 chance: 50 + +30354: + 4: + # The original Clan Training fixed boss; ordinary salamanders do not inherit it. + template_code: BSML + # Provisional early-profile baseline; no historical boss multipliers recovered. + health: 100 + experience: 100 + credits: [1, 5] + # Original SalamanderBite1 endpoints; choosing variant 1 for this boss is provisional. + weapon: [121063, 121064] + initiative: 0 + agg_def: 75 + respawn_seconds: 100 + corpse_seconds: 180 + # Provisional regular equipment subset, not a recovered boss loot table. + # Explicit QL4 uses reviewed families; no universal NPC-level loot formula. + # See docs/starter-boss.md for original placement, item facts and evidence limits. + loot: + - template: 85596 + quality: 4 + chance: 50 + - template: 123742 + quality: 4 + chance: 25 diff --git a/server/gamedata/types.go b/server/gamedata/types.go @@ -51,6 +51,7 @@ type NPCData struct { } type NPCCombatProfile struct { + TemplateCode string `yaml:"template_code"` Health uint32 `yaml:"health"` Experience uint32 `yaml:"experience"` Weapon [2]uint32 `yaml:"weapon,flow"` diff --git a/server/npcs.go b/server/npcs.go @@ -10,7 +10,11 @@ func npcCombatProfile(definition string, monster uint32, level uint16) *gamedata if group == nil || group.AppearanceStatus != "inferred_species" || group.MonsterData != monster { return nil } - return gamedata.NPCCombatProfiles[monster][level] + profile := gamedata.NPCCombatProfiles[monster][level] + if profile != nil && profile.TemplateCode != "" && profile.TemplateCode != group.TemplateCode { + return nil + } + return profile } func readNPCSpawns() ([]character, error) { diff --git a/server/starter_boss_test.go b/server/starter_boss_test.go @@ -0,0 +1,404 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "fmt" + "reflect" + "slices" + "testing" + "time" +) + +func TestStarterBossAuthoredSpawnHasUsefulSelectedQualityLoot(t *testing.T) { + spawns, err := readNPCSpawns() + if err != nil { + t.Fatal(err) + } + for _, spawn := range spawns { + if spawn.npcDefinitionID != "952/district/5/fixed/0" { + continue + } + + if spawn.monsterData != 30354 || spawn.level != 4 || spawn.position != [3]float32{186.06424, 13.7, 182.79846} || spawn.combatProfile == nil || + spawn.combatProfile.Health != 100 || spawn.combatProfile.Experience != 100 || spawn.combatProfile.Weapon != [2]uint32{121063, 121064} || + !reflect.DeepEqual(spawn.combatProfile.Loot, []gamedata.NPCLoot{{Template: 85596, Quality: 4, Chance: 50}, {Template: 123742, Quality: 4, Chance: 25}}) { + t.Fatal("authored starter boss has no isolated, level-appropriate equipment profile", spawn.combatProfile) + } + return + } + t.Fatal("authored Clan Training boss missing") +} + +func newStarterBossKillWorld(t *testing.T, attack string) (*server, *combatTestConn) { + t.Helper() + world, conn := newKillExperienceWorld(t, attack) + target := world.characters[1000000] + target.monsterData, target.level, target.playfield = 30354, 4, 952 + target.npcDefinitionID = "952/district/5/fixed/0" + target.combatProfile = gamedata.NPCCombatProfiles[30354][4] + world.characters[1].playfield = 952 + if err := world.saveUser_locked(world.characters[1]); err != nil { + t.Fatal(err) + } + if err := world.savePosition_locked(world.characters[1]); err != nil { + t.Fatal(err) + } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + return world, conn +} + +func TestStarterBossProductionLootAcrossKillingActions(t *testing.T) { + for _, attack := range []string{"unarmed", "axe", "pistol", "fling", "fast", "nano"} { + t.Run(attack, func(t *testing.T) { + world, _ := newStarterBossKillWorld(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) + t.Cleanup(func() { cold.db.Close() }) + + want := []ownedItem{ + {ID: before + 1, Type: 51022, Template: 85596, Quality: 4, Count: 1}, + {ID: before + 2, Type: 51018, Template: 123742, Quality: 4, Count: 1, Slot: 1}, + } + for _, current := range []*server{world, cold} { + corpse := current.characters[1000000].corpse + if corpse == nil || !slices.Equal(corpse.items, want) || corpse.credits != 1 || current.characters[1].experience != 100 || current.nextItem != before+2 { + t.Fatal("production boss death lost or repeated typed, selected-quality rewards", corpse) + } + for _, item := range want { + if current.items[item.ID].Template != item.Template || current.items[item.ID].Quality != 4 || current.items[item.ID].Type != item.Type || + current.itemPlacements[item.ID] != (itemPlacement{Corpse: 1000000, Slot: item.Slot}) { + t.Fatal("boss loot was not published through shared ownership") + } + } + } + }) + } +} + +func TestStarterBossIndependentLootChanceBoundaries(t *testing.T) { + for _, scenario := range []struct { + roll uint32 + templates []uint32 + }{ + {0, []uint32{85596, 123742}}, {24, []uint32{85596, 123742}}, + {25, []uint32{85596}}, {49, []uint32{85596}}, {50, nil}, {99, nil}, + } { + t.Run(fmt.Sprint(scenario.roll), func(t *testing.T) { + world, _ := newStarterBossKillWorld(t, "unarmed") + world.combatRoll = func(limit uint32) uint32 { return min(scenario.roll, limit-1) } + before := world.nextItem + + attackForExperience(t, world, "unarmed") + + corpse := world.characters[1000000].corpse + if corpse == nil || len(corpse.items) != len(scenario.templates) || world.nextItem != before+uint32(len(scenario.templates)) { + t.Fatal("boss chance boundary changed allocation or lost an empty result") + } + for index, template := range scenario.templates { + if corpse.items[index].Template != template || corpse.items[index].Quality != 4 { + t.Fatal("boss loot selected an endpoint quality or wrong row") + } + } + }) + } +} + +func TestStarterBossSecondDropFailureRetainsLivingStateAndRetries(t *testing.T) { + for _, fault := range []struct{ name, sql string }{ + {"insert", "CREATE TRIGGER fail_boss BEFORE INSERT ON items WHEN NEW.template=123742 BEGIN SELECT RAISE(FAIL,'boss second item'); END"}, + {"ignored insert", "CREATE TRIGGER fail_boss BEFORE INSERT ON items WHEN NEW.template=123742 BEGIN SELECT RAISE(IGNORE); END"}, + {"commit", "CREATE TABLE pending_boss (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_boss AFTER INSERT ON items WHEN NEW.template=123742 BEGIN INSERT INTO pending_boss VALUES(999999); END"}, + } { + t.Run(fault.name, func(t *testing.T) { + world, conn := newStarterBossKillWorld(t, "unarmed") + world.combatRoll = func(uint32) uint32 { return 0 } + before := world.nextItem + if _, err := world.db.Exec(fault.sql); err != nil { + t.Fatal(err) + } + + attackForExperience(t, world, "unarmed") + cold := newTestInventoryServer(t) + t.Cleanup(func() { cold.db.Close() }) + + 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 { + t.Fatal("failed second boss drop committed a partial death or reward") + } + } + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 { + t.Fatal("failed boss death published its attack result") + } + } + + if _, err := world.db.Exec("DROP TRIGGER fail_boss"); err != nil { + t.Fatal(err) + } + attackForExperience(t, world, "unarmed") + again := newTestInventoryServer(t) + t.Cleanup(func() { again.db.Close() }) + + if len(again.characters[1000000].corpse.items) != 2 || again.nextItem != before+2 || again.characters[1].experience != 100 { + t.Fatal("retry did not commit both boss drops exactly once") + } + }) + } +} + +func TestStarterBossCodeRecheckedOnColdLoadAndReplacement(t *testing.T) { + for _, changed := range []bool{false, true} { + t.Run(fmt.Sprint(changed), func(t *testing.T) { + data := testNPCData() + group := &data.Playfields[0].Districts[0].Groups[0] + group.TemplateCode, group.MonsterData, group.Levels, group.AppearanceStatus = "BSML", 30354, [2]uint16{4, 4}, "inferred_species" + useNPCData(t, data) + world := newTestServer(t) + t.Cleanup(func() { world.db.Close() }) + world.combatRoll = func(uint32) uint32 { return 0 } + player := world.newCharacter() + player.position = group.Positions[0] + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + world.characters[1000000].health = 1 + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + client := &worldClient{id: player.id, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[player.id] = client + if err := world.handleCombat(client, attackPacket(player.id, 1000000)[20:]); err != nil { + t.Fatal(err) + } + death := player.nextAttack + world.advanceCombat(death) + if changed { + group.TemplateCode = "SM01" + } + + cold := newTestInventoryServer(t) + t.Cleanup(func() { cold.db.Close() }) + cold.advanceNPCRespawns(death.Add(100 * time.Second)) + respawned := newTestInventoryServer(t) + t.Cleanup(func() { respawned.db.Close() }) + + for _, current := range []*server{cold, respawned} { + if len(current.characters[1000000].corpse.items) != 2 || current.characters[player.id].experience != 100 || current.nextItem != 2 || + (current.characters[1000000].combatProfile != nil) == changed || (current.characters[1000001].combatProfile != nil) == changed || current.characters[1000001].health != 100 { + t.Fatal("code change leaked a boss profile or erased already committed rewards") + } + } + }) + } +} + +func TestStarterBossLootPickupWearSaleAndRestore(t *testing.T) { + world, conn := newStarterBossKillWorld(t, "unarmed") + world.combatRoll = func(uint32) uint32 { return 0 } + player, client := world.characters[1], world.clients[1] + player.stats.Abilities.Strength, player.stats.Abilities.Agility = 14, 16 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + before := world.nextItem + attackForExperience(t, world, "unarmed") + if err := world.handleLootUse(client, lootUseRequest(1)); err != nil { + t.Fatal(err) + } + for _, slot := range []uint32{0, 1} { + request := lootTakeRequest() + binary.BigEndian.PutUint32(request[20:24], slot) + if err := world.handleInventory(client, request); err != nil { + t.Fatal(err) + } + } + world = newTestInventoryServer(t) + t.Cleanup(func() { world.db.Close() }) + player = world.characters[1] + client = &worldClient{id: 1, conn: conn, target: true, ready: true} + world.clients[1] = client + + err := world.handleInventory(client, inventoryMovePacket(1, 64, 24)[20:]) + + if err != nil || client.equipment != nil || len(player.inventory.Items) != 2 || player.inventory.Items[0].Slot != 64 || player.inventory.Items[1].Slot != 65 { + t.Fatal("below-threshold boss-drop wear lost either item", err, player.inventory) + } + + player.stats.Abilities.Strength = 15 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + conn.packets = nil + err = world.handleInventory(client, inventoryMovePacket(1, 64, 24)[20:]) + if err != nil || client.equipment == nil { + t.Fatal("qualified generated gloves could not equip", err, player.inventory) + } + world.advanceEquipment(client.equipment.readyAt) + cold := newTestInventoryServer(t) + t.Cleanup(func() { cold.db.Close() }) + + want := []ownedItem{ + {ID: before + 1, Type: 51022, Template: 85596, Quality: 4, Count: 1, Slot: 24}, + {ID: before + 2, Type: 51018, Template: 123742, Quality: 4, Count: 1, Slot: 65}, + } + if !slices.Equal(cold.characters[1].inventory.Items, want) || cold.characters[1].inventory.Credits != 1 || len(cold.characters[1000000].corpse.items) != 0 { + t.Fatal("boss pickup/wear/restoration lost the selected QL or stable instances", cold.characters[1].inventory) + } + for stat, expected := range []int32{5, 4, 5, 4, 2, 2, 2, 2} { + if cold.characters[1].inventory.equipmentBonus(90+uint32(stat)) != expected { + t.Fatal("generated armor used endpoint effects", stat) + } + } + var wear []byte + for _, value := range []uint32{85596, 85595, 4, 1, 6, 102, 24, 0, 0} { + wear = binary.BigEndian.AppendUint32(wear, value) + } + if len(conn.packets) != 2 || !bytes.Equal(conn.packets[1][29:65], wear) { + t.Fatal("native boss-drop wear lost the selected family endpoints") + } + + machine := gamedata.ShopMachines[3221226424] + player.position, player.appearance = machine.Position, 0x315 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + request := shopUseRequest(2) + binary.BigEndian.PutUint32(request[44:48], 3221226424) + if err := world.handleShopUse(client, request); err != nil { + t.Fatal(err) + } + if client.shop == nil { + t.Fatal("training sale booth rejected its fixture", player.playfield, player.position, player.health, machine) + } + offer := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})[20:] + if err := world.handleTrade(client, offer); err != nil { + t.Fatal(err) + } + if len(client.shop.items) != 1 { + t.Fatal("boss weapon was not staged for sale", client.shop) + } + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + cancelled := newTestInventoryServer(t) + t.Cleanup(func() { cancelled.db.Close() }) + + want[1].Slot = 64 + if !slices.Equal(cancelled.characters[1].inventory.Items, want) || cancelled.characters[1].inventory.Credits != 1 { + t.Fatal("cancelled boss-loot sale changed cash or either instance") + } + + request = shopUseRequest(3) + binary.BigEndian.PutUint32(request[44:48], 3221226424) + if err := world.handleShopUse(client, request); err != nil { + t.Fatal(err) + } + offer = shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:] + if err := world.handleTrade(client, offer); err != nil { + t.Fatal(err) + } + for range 2 { + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + } + sold := newTestInventoryServer(t) + t.Cleanup(func() { sold.db.Close() }) + + if !slices.Equal(sold.characters[1].inventory.Items, want[:1]) || sold.characters[1].inventory.Credits != 98 || sold.nextItem != before+2 || sold.characters[1].inventory.equipmentBonus(90) != 5 { + t.Fatal("boss-loot sale lost worn gear or duplicated the selected-quality proceeds", sold.characters[1].inventory) + } +} + +func TestStarterBossFullInventoryPreservesBothDropsAndPartialPickup(t *testing.T) { + world, _ := newStarterBossKillWorld(t, "unarmed") + world.combatRoll = func(uint32) uint32 { return 0 } + player, client := world.characters[1], world.clients[1] + before := world.nextItem + for slot := uint32(64); slot < 94; slot++ { + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: before + slot - 63, Type: 51005, Template: 95577, Quality: 1, Slot: slot, Count: 1}) + } + player.inventory.LastID = before + 30 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + before = world.nextItem + attackForExperience(t, world, "unarmed") + if err := world.handleLootUse(client, lootUseRequest(1)); err != nil { + t.Fatal(err) + } + stored, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + + if err := world.handleInventory(client, lootTakeRequest()); err != nil { + t.Fatal(err) + } + after, err := readTestItemStore(world) + + if err != nil || !bytes.Equal(stored, after) || len(world.characters[1000000].corpse.items) != 2 || player.inventory.Credits != 1 { + t.Fatal("full inventory lost or changed either generated boss item", err) + } + + if err := world.handleInventory(client, characterActionPacket(1, [5]uint32{112, 104, 64, 95577, 95577})[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, lootTakeRequest()); err != nil { + t.Fatal(err) + } + request := lootTakeRequest() + binary.BigEndian.PutUint32(request[20:24], 1) + if err := world.handleInventory(client, request); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + t.Cleanup(func() { cold.db.Close() }) + + if len(cold.characters[1].inventory.Items) != 30 || !slices.Contains(cold.characters[1].inventory.Items, ownedItem{ID: before + 1, Type: 51022, Template: 85596, Quality: 4, Slot: 64, Count: 1}) || + !slices.Equal(cold.characters[1000000].corpse.items, []ownedItem{{ID: before + 2, Type: 51018, Template: 123742, Quality: 4, Slot: 1, Count: 1}}) || cold.nextItem != before+2 || cold.characters[1].inventory.Credits != 1 { + t.Fatal("partial pickup consumed the uncollected drop, repeated cash or changed ownership", cold.characters[1].inventory, cold.characters[1000000].corpse.items, before, cold.nextItem) + } +} + +func TestStarterBossProfileRequiresItsCodeSpeciesLevelAndEvidence(t *testing.T) { + for _, scenario := range []struct { + name, code, evidence string + monster uint32 + level uint16 + accepted bool + }{ + {"boss", "BSML", "inferred_species", 30354, 4, true}, + {"ordinary salamander", "SM01", "inferred_species", 30354, 4, false}, + {"unresolved salamander", "BSML", "placeholder_creature", 30354, 4, false}, + {"other species", "BSML", "inferred_species", 17655, 4, false}, + {"other level", "BSML", "inferred_species", 30354, 3, false}, + {"existing Leet", "TEST", "inferred_species", 17655, 1, true}, + } { + t.Run(scenario.name, func(t *testing.T) { + data := testNPCData() + group := &data.Playfields[0].Districts[0].Groups[0] + group.TemplateCode, group.AppearanceStatus, group.MonsterData = scenario.code, scenario.evidence, scenario.monster + group.Levels = [2]uint16{scenario.level, scenario.level} + useNPCData(t, data) + + spawns, err := readNPCSpawns() + + if err != nil || len(spawns) != 1 || (spawns[0].combatProfile != nil) != scenario.accepted { + t.Fatal("boss profile leaked across its binding or lost the existing species rule", err, spawns) + } + }) + } +}