aorecomp

Anarchy Online classic in the browser

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


server/mission_encounter_lifecycle_test.go (13422B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	"encoding/binary"
      6 	"fmt"
      7 	"reflect"
      8 	"slices"
      9 	"testing"
     10 	"time"
     11 )
     12 
     13 func killedMissionEncounterWorld(t *testing.T) (*server, *worldClient, *combatTestConn, time.Time) {
     14 	t.Helper()
     15 	world, client, output := enteredMissionEncounterWorld(t)
     16 	player, npc := world.characters[1], world.characters[2000004]
     17 	player.position = npc.position
     18 	player.position[2]--
     19 	npc.health = 1
     20 	// Keep world-lifecycle assertions independent of the production reward pool.
     21 	profile := *npc.combatProfile
     22 	profile.Loot = slices.Clone(profile.Loot[:1])
     23 	npc.combatProfile = &profile
     24 	world.combatRoll = func(uint32) uint32 { return 0 }
     25 	if err := world.saveUser(player); err != nil {
     26 		t.Fatal(err)
     27 	}
     28 	if err := world.flushWorld(); err != nil {
     29 		t.Fatal(err)
     30 	}
     31 	if err := world.handleCombat(client, attackPacket(1, npc.id)[20:]); err != nil {
     32 		t.Fatal(err)
     33 	}
     34 	killed := player.nextAttack
     35 	world.advanceCombat(killed)
     36 	if npc.health != 0 {
     37 		t.Fatal("ordinary attack did not kill the mission encounter", npc.health, player.fighting)
     38 	}
     39 	output.packets = nil
     40 	return world, client, output, killed
     41 }
     42 
     43 func TestMissionEncounterKillLootAndColdRestartDoNotCreateAnotherLife(t *testing.T) {
     44 	world, client, _, killed := killedMissionEncounterWorld(t)
     45 	before := world.nextItem
     46 	request := lootUseRequest(1)
     47 	binary.BigEndian.PutUint32(request[44:48], 2000004)
     48 
     49 	if err := world.handleLootUse(client, request); err != nil {
     50 		t.Fatal(err)
     51 	}
     52 	if err := world.handleInventory(client, lootTakeRequest()); err != nil {
     53 		t.Fatal(err)
     54 	}
     55 	world.advanceCombat(killed.Add(time.Hour))
     56 	world.advanceNPCRespawns(killed.Add(time.Hour))
     57 	cold := reloadMissionEntranceWorld(t)
     58 	cold.advanceNPCRespawns(killed.Add(time.Hour))
     59 
     60 	for _, current := range []*server{world, cold} {
     61 		player, npc := current.characters[1], current.characters[2000004]
     62 		if player.experience != 100 || player.inventory.Credits != 5 || npc.health != 0 || npc.corpse == nil ||
     63 			len(npc.corpse.items) != 0 || npc.corpse.credits != 0 || len(current.npcRespawns) != 0 || current.nextNPC != 2000005 || current.nextItem != before {
     64 			t.Fatal("mission kill, loot, XP or one-life population changed", player.experience, player.inventory, npc.corpse, current.npcRespawns)
     65 		}
     66 		if !slices.Contains(player.inventory.Items, ownedItem{ID: before, Type: 51005, Template: 42640, Quality: 1, Slot: 66, Count: 1}) {
     67 			t.Fatal("shared generated loot did not retain its identity", player.inventory.Items)
     68 		}
     69 	}
     70 }
     71 
     72 func TestMissionEncounterRetirementRemovesActorsLootAndQueuesAfterCommit(t *testing.T) {
     73 	for _, reason := range []string{"abandon", "expiry", "completed expiry"} {
     74 		t.Run(reason, func(t *testing.T) {
     75 			world, client, output, killed := killedMissionEncounterWorld(t)
     76 			mission := world.characters[1].missions[0]
     77 			drop := world.characters[2000004].corpse.items[0].ID
     78 			client.lootCorpse = 2000004
     79 			other := world.characters[2000003]
     80 			other.fighting = 1
     81 			world.fighting[other.id] = other
     82 			world.characters[1].fighting = other.id
     83 			world.fighting[1] = world.characters[1]
     84 			if reason == "completed expiry" {
     85 				mission.completed = true
     86 				world.characters[1].missions[0] = mission
     87 				world.missionExpiry[0] = mission
     88 				if _, err := world.db.Exec("UPDATE missions SET completed=1 WHERE id=?", mission.id); err != nil {
     89 					t.Fatal(err)
     90 				}
     91 			}
     92 
     93 			if reason == "abandon" {
     94 				if err := world.handleMissionRemoval(client, missionRemovalPacket(1, mission.id)[20:]); err != nil {
     95 					t.Fatal(err)
     96 				}
     97 			} else {
     98 				world.advanceMissions(mission.expiresAt.Add(time.Nanosecond))
     99 			}
    100 			world.advanceNPCRespawns(killed.Add(time.Hour))
    101 			world.advanceCorpseExpiry(killed.Add(time.Hour))
    102 			if err := world.flushWorld(); err != nil {
    103 				t.Fatal(err)
    104 			}
    105 			cold := reloadMissionEntranceWorld(t)
    106 
    107 			for _, current := range []*server{world, cold} {
    108 				if current.characters[1].playfield != 3000 || current.characters[1].experience != 100 ||
    109 					len(current.characters[1].missions) != 0 || len(current.mobileNPCs[65536]) != 0 ||
    110 					len(current.npcRespawns) != 0 || len(current.corpseExpiry) != 0 || current.characters[1000000] == nil {
    111 					t.Fatal("retirement lost player progress or retained a private world", current.characters[1], current.npcRespawns)
    112 				}
    113 				for id := uint32(2000000); id < 2000005; id++ {
    114 					if current.characters[id] != nil || current.savedNPCs[id].State.Character.Profile.ID != 0 || current.fighting[id] != nil {
    115 						t.Fatal("retired NPC was retained or recreated", id)
    116 					}
    117 				}
    118 				if _, exists := current.items[drop]; exists {
    119 					t.Fatal("unclaimed corpse loot outlived its private world", drop)
    120 				}
    121 			}
    122 			if client.lootCorpse != 0 || len(world.fighting) != 0 || world.geometry.mission(65536) != nil || len(output.packets) == 0 {
    123 				t.Fatal("committed retirement retained combat, loot or geometry")
    124 			}
    125 		})
    126 	}
    127 }
    128 
    129 func TestMissionEncounterRetirementFailurePreservesPopulationThenRetries(t *testing.T) {
    130 	for _, statement := range []string{
    131 		"CREATE TRIGGER reject_retirement BEFORE DELETE ON characters WHEN OLD.id>=2000000 BEGIN SELECT RAISE(ABORT, 'actor'); END",
    132 		"CREATE TRIGGER reject_retirement BEFORE DELETE ON characters WHEN OLD.id>=2000000 BEGIN SELECT RAISE(IGNORE); END",
    133 		"CREATE TRIGGER reject_retirement BEFORE DELETE ON npcs WHEN OLD.id>=2000000 BEGIN SELECT RAISE(IGNORE); END",
    134 		"CREATE TRIGGER reject_retirement BEFORE DELETE ON items WHEN OLD.template=42640 BEGIN SELECT RAISE(IGNORE); END",
    135 		"CREATE TRIGGER reject_retirement BEFORE DELETE ON missions BEGIN SELECT RAISE(IGNORE); END",
    136 		"CREATE TRIGGER reject_retirement AFTER DELETE ON missions BEGIN INSERT INTO characters SELECT * FROM retired_actor; INSERT INTO npcs SELECT * FROM retired_npc; END",
    137 		"CREATE TABLE pending_retirement (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_retirement AFTER DELETE ON npcs BEGIN INSERT INTO pending_retirement VALUES (999999); END",
    138 	} {
    139 		t.Run(fmt.Sprint(statement), func(t *testing.T) {
    140 			world, client, output, _ := killedMissionEncounterWorld(t)
    141 			mission := world.characters[1].missions[0]
    142 			client.lootCorpse = 2000004
    143 			before, err := readTestItemStore(world)
    144 			if err != nil {
    145 				t.Fatal(err)
    146 			}
    147 			known := len(client.npcs)
    148 			corpses := slices.Clone(world.corpseExpiry)
    149 			if _, err := world.db.Exec("CREATE TABLE retired_actor AS SELECT * FROM characters WHERE id=2000000; CREATE TABLE retired_npc AS SELECT * FROM npcs WHERE id=2000000"); err != nil {
    150 				t.Fatal(err)
    151 			}
    152 			if _, err := world.db.Exec(statement); err != nil {
    153 				t.Fatal(err)
    154 			}
    155 
    156 			failure := world.handleMissionRemoval(client, missionRemovalPacket(1, mission.id)[20:])
    157 			after, err := readTestItemStore(world)
    158 			cold := reloadMissionEntranceWorld(t)
    159 
    160 			if failure == nil || err != nil || !reflect.DeepEqual(before, after) || len(output.packets) != 0 || len(client.npcs) != known ||
    161 				client.lootCorpse != 2000004 || !slices.Equal(corpses, world.corpseExpiry) || world.geometry.mission(65536) == nil {
    162 				t.Fatal("failed retirement published partial changes", failure, err)
    163 			}
    164 			for _, current := range []*server{world, cold} {
    165 				if current.characters[1].playfield != 65536 || len(current.characters[1].missions) != 1 || current.characters[2000000] == nil ||
    166 					current.characters[2000004].corpse == nil || len(current.characters[2000004].corpse.items) != 1 {
    167 					t.Fatal("failed retirement changed durable mission actors or loot")
    168 				}
    169 			}
    170 
    171 			if _, err := world.db.Exec("DROP TRIGGER reject_retirement"); err != nil {
    172 				t.Fatal(err)
    173 			}
    174 			if err := world.handleMissionRemoval(client, missionRemovalPacket(1, mission.id)[20:]); err != nil {
    175 				t.Fatal(err)
    176 			}
    177 
    178 			if world.characters[2000000] != nil || world.characters[2000004] != nil || world.characters[1].playfield != 3000 || client.lootCorpse != 0 {
    179 				t.Fatal("retirement retry retained actors or loot")
    180 			}
    181 		})
    182 	}
    183 }
    184 
    185 func TestMissionEncounterCompletionKeepsPopulationAndClaimedLoot(t *testing.T) {
    186 	world, client, _, _ := killedMissionEncounterWorld(t)
    187 	player := world.characters[1]
    188 	mission := player.missions[0]
    189 	loot := world.nextItem
    190 	request := lootUseRequest(1)
    191 	binary.BigEndian.PutUint32(request[44:48], 2000004)
    192 	if err := world.handleLootUse(client, request); err != nil {
    193 		t.Fatal(err)
    194 	}
    195 	if err := world.handleInventory(client, lootTakeRequest()); err != nil {
    196 		t.Fatal(err)
    197 	}
    198 	player.position = world.worldItems[mission.objective].position
    199 	if err := world.handleInventory(client, worldPickupRequest(1, mission.objective)); err != nil {
    200 		t.Fatal(err)
    201 	}
    202 	destination := player.userData()
    203 	destination.Playfield, destination.Position = 3000, gamedata.MissionBooths[3221228472].Position
    204 	if err := world.updateUser(destination); err != nil {
    205 		t.Fatal(err)
    206 	}
    207 	world.clients[1], client.ready, client.loading = client, true, false
    208 
    209 	returnRequest := missionReturnRequest(2)
    210 	binary.BigEndian.PutUint32(returnRequest[44:48], 67)
    211 	if err := world.handleMissionReturn(client, returnRequest); err != nil {
    212 		t.Fatal(err)
    213 	}
    214 	cold := reloadMissionEntranceWorld(t)
    215 
    216 	for _, current := range []*server{world, cold} {
    217 		living := 0
    218 		for _, npc := range current.mobileNPCs[65536] {
    219 			if npc.health != 0 {
    220 				living++
    221 			}
    222 		}
    223 		if len(current.characters[1].missions) != 0 || living != 4 || !current.missionExpiry[0].completed ||
    224 			current.characters[2000000].health != 20 || current.characters[2000004].health != 0 || current.characters[2000004].corpse == nil ||
    225 			current.characters[1].experience != 100 || current.characters[1].inventory.Credits != 25 || current.items[loot].Template != 42640 {
    226 			t.Fatal("completion retired the population, repeated kill XP or lost claimed loot")
    227 		}
    228 	}
    229 
    230 	world.advanceMissions(mission.expiresAt)
    231 	if err := world.flushWorld(); err != nil {
    232 		t.Fatal(err)
    233 	}
    234 	cold = reloadMissionEntranceWorld(t)
    235 
    236 	if cold.characters[2000000] != nil || cold.characters[2000004] != nil || cold.items[loot].Template != 42640 ||
    237 		cold.itemPlacements[loot] != (itemPlacement{Player: 1, Slot: 66}) || cold.characters[1].experience != 100 {
    238 		t.Fatal("completed-world retirement destroyed transferred loot or recreated its source", cold.itemPlacements[loot])
    239 	}
    240 }
    241 
    242 func TestMissionEncounterDifferentWorldRejectsCombatNanoAndLoot(t *testing.T) {
    243 	for _, action := range []string{"attack", "nano", "corpse", "pickup"} {
    244 		t.Run(action, func(t *testing.T) {
    245 			world, client, _, _ := killedMissionEncounterWorld(t)
    246 			player := world.characters[1]
    247 			player.playfield = 65537
    248 			player.profession, player.nano = 8, 30
    249 			player.stats.NanoAiding.PsychologicalModification, player.stats.NanoAiding.MatterCreation = 7, 6
    250 			player.inventory.LearnedNanos = []uint32{29618}
    251 			client.lootCorpse = 2000004
    252 			// Stale known-object state must not confer authority across private worlds.
    253 			client.npcs[2000003], client.npcs[2000004] = true, true
    254 			before, err := readTestItemStore(world)
    255 			if err != nil {
    256 				t.Fatal(err)
    257 			}
    258 
    259 			switch action {
    260 			case "attack":
    261 				err = world.handleCombat(client, attackPacket(1, 2000003)[20:])
    262 				world.advanceCombat(time.Now().Add(time.Minute))
    263 			case "nano":
    264 				err = world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 2000003, 53019, 29618})[20:])
    265 				world.advanceNanos(time.Now().Add(time.Minute))
    266 			case "corpse":
    267 				client.lootCorpse = 0
    268 				request := lootUseRequest(1)
    269 				binary.BigEndian.PutUint32(request[44:48], 2000004)
    270 				err = world.handleLootUse(client, request)
    271 			case "pickup":
    272 				err = world.handleInventory(client, lootTakeRequest())
    273 			}
    274 			after, readErr := readTestItemStore(world)
    275 
    276 			if err != nil || readErr != nil || !reflect.DeepEqual(before, after) || player.fighting != 0 || client.nanoCast != nil ||
    277 				player.nano != 30 || player.nanoReserved != 0 || player.experience != 100 || world.characters[2000003].health != 20 ||
    278 				len(world.characters[2000004].corpse.items) != 1 || world.characters[2000004].corpse.credits != 1 {
    279 				t.Fatal("private-world boundary admitted a stale target, cast or loot source", err, readErr)
    280 			}
    281 		})
    282 	}
    283 }
    284 
    285 func TestMissionEncounterRetirementRemovesHiddenSourcesWithoutTouchingAnotherWorld(t *testing.T) {
    286 	world, client, _, killed := killedMissionEncounterWorld(t)
    287 	mission := world.characters[1].missions[0]
    288 	hidden := world.characters[2000004]
    289 	delete(world.characters, hidden.id)
    290 	world.npcRespawns = append(world.npcRespawns, npcRespawn{npc: hidden, at: killed.Add(time.Hour)})
    291 	other := makeNPCSpawn(gamedata.NPCGroups[hidden.npcDefinitionID], 1, hidden.position)
    292 	other.id, other.playfield = 2000005, 65537
    293 	world.characters[other.id] = &other
    294 	world.mobileNPCs[other.playfield] = []*character{&other}
    295 	world.nextNPC++
    296 	if err := world.flushWorld(); err != nil {
    297 		t.Fatal(err)
    298 	}
    299 
    300 	if err := world.handleMissionRemoval(client, missionRemovalPacket(1, mission.id)[20:]); err != nil {
    301 		t.Fatal(err)
    302 	}
    303 	world.advanceNPCRespawns(killed.Add(2 * time.Hour))
    304 	if err := world.flushWorld(); err != nil {
    305 		t.Fatal(err)
    306 	}
    307 	cold := reloadMissionEntranceWorld(t)
    308 
    309 	for _, current := range []*server{world, cold} {
    310 		if current.characters[hidden.id] != nil || len(current.npcRespawns) != 0 || current.characters[other.id] == nil ||
    311 			current.characters[other.id].playfield != 65537 || current.characters[other.id].health != 20 || len(current.mobileNPCs[65537]) != 1 {
    312 			t.Fatal("retired hidden source returned or retirement changed another world's encounter")
    313 		}
    314 	}
    315 }