aorecomp

Anarchy Online classic in the browser

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


server/ranged_test.go (15710B)


      1 package main
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/binary"
      6 	"net/http"
      7 	"net/url"
      8 	"testing"
      9 	"time"
     10 )
     11 
     12 func newRangedWorld(t *testing.T) (*server, *combatTestConn) {
     13 	t.Helper()
     14 	t.Chdir(t.TempDir())
     15 	world, conn := newCombatWorld(t)
     16 	world.nextNPC = 1000001
     17 	player := world.characters[1]
     18 	player.name, player.level, player.appearance = "Pistol Owner", 1, 277
     19 	player.rotation[3] = 1
     20 	player.stats = testCharacterStats()
     21 	world.characters[1000000].position = [3]float32{20, 0, 0}
     22 	world.characters[1000000].health = 1000
     23 	if err := world.saveUser(player); err != nil {
     24 		t.Fatal(err)
     25 	}
     26 	inventory := playerInventory{LastID: 2, Items: []ownedItem{
     27 		{ID: 1, Type: 51018, Template: 123742, Quality: 1, Slot: 6, Count: 1, Ammo: 3},
     28 		{ID: 2, Type: 51005, Template: 21605, Quality: 1, Slot: 64, Count: 100},
     29 	}}
     30 	if err := world.saveInventory(player, inventory); err != nil {
     31 		t.Fatal(err)
     32 	}
     33 	return world, conn
     34 }
     35 
     36 func TestRangedShotConsumesOneRoundAtItsDeadlineForBothObservers(t *testing.T) {
     37 	world, conn := newRangedWorld(t)
     38 	observer := &combatTestConn{}
     39 	world.characters[2] = &character{id: 2, playfield: 950, health: 100}
     40 	world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
     41 	world.characters[1].stats.Speed.MeleeInitiative = 1200
     42 	world.characters[1].stats.Melee.OneHandEdged = 800
     43 	world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
     44 	hit := world.characters[1].nextAttack
     45 
     46 	world.advanceCombat(hit.Add(-time.Nanosecond))
     47 	if world.characters[1].inventory.Items[0].Ammo != 3 || world.characters[1000000].health != 1000 {
     48 		t.Fatal("shot preceded its deadline")
     49 	}
     50 	world.advanceCombat(hit)
     51 	world.advanceCombat(hit)
     52 	restarted := newTestInventoryServer(t)
     53 
     54 	if world.characters[1000000].health < 988 || world.characters[1000000].health > 997 || world.characters[1].inventory.Items[0].Ammo != 2 || restarted.characters[1].inventory.Items[0].Ammo != 2 || restarted.characters[1].inventory.Items[1].Count != 100 {
     55 		t.Fatal("shot used wrong damage or ammunition", world.characters[1000000].health)
     56 	}
     57 	if world.characters[1].nextAttack.Sub(hit) != 3950*time.Millisecond {
     58 		t.Fatal("pistol used the wrong initiative clock", world.characters[1].nextAttack.Sub(hit))
     59 	}
     60 	var first, second []byte
     61 	for _, packet := range conn.packets {
     62 		if binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 {
     63 			first = packet
     64 		}
     65 	}
     66 	for _, packet := range observer.packets {
     67 		if binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 {
     68 			second = packet
     69 		}
     70 	}
     71 	if first == nil || !bytes.Equal(first[16:], second[16:]) || binary.BigEndian.Uint32(first[33:37]) != 2 || binary.BigEndian.Uint32(first[37:41]) != 6 {
     72 		t.Fatalf("shot did not share its loaded count and slot: %x %x", first, second)
     73 	}
     74 }
     75 
     76 func TestRangedEmptyMagazineCannotFireOrRefillAfterRestart(t *testing.T) {
     77 	world, _ := newRangedWorld(t)
     78 	world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
     79 
     80 	for range 4 {
     81 		world.advanceCombat(world.characters[1].nextAttack)
     82 	}
     83 	health := world.characters[1000000].health
     84 	world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
     85 	world.advanceCombat(world.characters[1].nextAttack)
     86 	restarted := newTestInventoryServer(t)
     87 
     88 	if world.characters[1].fighting != 0 || world.characters[1].inventory.Items[0].Ammo != 0 || restarted.characters[1].inventory.Items[0].Ammo != 0 || world.characters[1000000].health != health || restarted.characters[1].inventory.Items[1].Count != 100 {
     89 		t.Fatal("empty weapon dealt damage or created rounds")
     90 	}
     91 }
     92 
     93 func TestRangedFailedShotSaveLeavesDamageAndAmmoUnchanged(t *testing.T) {
     94 	world, conn := newRangedWorld(t)
     95 	world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
     96 	world.db.Exec("CREATE TRIGGER fail_ammo BEFORE UPDATE OF ammo ON items WHEN NEW.id = 1 BEGIN SELECT RAISE(FAIL, 'test save failure'); END")
     97 	hit := world.characters[1].nextAttack
     98 	conn.packets = nil
     99 
    100 	world.advanceCombat(hit)
    101 	restarted := newTestInventoryServer(t)
    102 
    103 	if world.characters[1000000].health != 1000 || world.characters[1].inventory.Items[0].Ammo != 3 || restarted.characters[1].inventory.Items[0].Ammo != 3 || world.characters[1].fighting != 0 {
    104 		t.Fatal("failed debit changed damage or ammunition")
    105 	}
    106 	if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x4a41203e {
    107 		t.Fatalf("failed debit published a shot: %x", conn.packets)
    108 	}
    109 }
    110 
    111 func TestReloadTransfersRoundsAtomicallyAndRestoresItsDeadline(t *testing.T) {
    112 	world, conn := newRangedWorld(t)
    113 	request := explicitReloadRequest(1, 64, 1)
    114 	before := time.Now()
    115 
    116 	err := world.handleReload(world.clients[1], request)
    117 	world.handleReload(world.clients[1], request)
    118 	restarted := newTestInventoryServer(t)
    119 
    120 	if err != nil || world.characters[1].inventory.Items[0].Ammo != 20 || world.characters[1].inventory.Items[1].Count != 83 || restarted.characters[1].inventory.Items[0].Ammo != 20 || restarted.characters[1].inventory.Items[1].Count != 83 {
    121 		t.Fatal("reload failed or changed the total rounds", err)
    122 	}
    123 	if restarted.characters[1].rechargeUntil.Before(before.Add(1250*time.Millisecond)) || restarted.characters[1].rechargeUntil.After(time.Now().Add(1250*time.Millisecond)) {
    124 		t.Fatal("reload deadline did not survive restart")
    125 	}
    126 	if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x26515e61 || !bytes.Equal(conn.packets[1][29:57], []byte{0, 0, 0, 104, 0, 0, 0, 48, 0, 0, 0xc7, 0x4a, 0, 0, 0, 1, 0, 0, 0, 83, 0, 0, 0, 20, 0, 0, 0, 0}) {
    127 		t.Fatalf("reload wire fields: %x", conn.packets)
    128 	}
    129 }
    130 
    131 func TestReloadPausesRemainingRechargeBeforeAnotherAttack(t *testing.T) {
    132 	world, _ := newRangedWorld(t)
    133 	world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
    134 	world.advanceCombat(world.characters[1].nextAttack)
    135 	next, recharge := world.characters[1].nextAttack, world.characters[1].rechargeUntil
    136 	health := world.characters[1000000].health
    137 
    138 	err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1))
    139 	world.advanceCombat(next)
    140 	world.advanceCombat(next.Add(1250*time.Millisecond - time.Nanosecond))
    141 
    142 	if err != nil || world.characters[1].nextAttack != next.Add(1250*time.Millisecond) || world.characters[1].rechargeUntil != recharge.Add(1250*time.Millisecond) || world.characters[1000000].health != health {
    143 		t.Fatal("reload shortened the active weapon cycle", err)
    144 	}
    145 }
    146 
    147 func TestReloadUsesOnlyAvailableRoundsAndRemovesAnEmptyStack(t *testing.T) {
    148 	world, conn := newRangedWorld(t)
    149 	world.characters[1].inventory.Items[1].Count = 5
    150 	if err := world.saveInventory(world.characters[1], world.characters[1].inventory); err != nil {
    151 		t.Fatal(err)
    152 	}
    153 
    154 	err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1))
    155 	restarted := newTestInventoryServer(t)
    156 
    157 	if err != nil || len(restarted.characters[1].inventory.Items) != 1 || restarted.characters[1].inventory.Items[0].Ammo != 8 || len(restarted.items) != 1 {
    158 		t.Fatal("partial reload lost or created ammunition", err)
    159 	}
    160 	if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[1][45:49]) != 0 || binary.BigEndian.Uint32(conn.packets[1][49:53]) != 8 || binary.BigEndian.Uint32(conn.packets[1][53:57]) != 1 {
    161 		t.Fatalf("empty-stack reply: %x", conn.packets)
    162 	}
    163 }
    164 
    165 func explicitReloadRequest(sequence, source, weapon uint32) []byte {
    166 	var body []byte
    167 	for _, value := range []uint32{0, sequence, 5, 0, 50000, 1, 104, source, 51018, weapon} {
    168 		body = binary.BigEndian.AppendUint32(body, value)
    169 	}
    170 	return n3Packet(0x52526858, 50000, 1, body)[20:]
    171 }
    172 
    173 func TestReloadExplicitAmmoUseAcknowledgesOnceAndTranslatesItsSlot(t *testing.T) {
    174 	world, conn := newRangedWorld(t)
    175 	request := explicitReloadRequest(1, 48, 1)
    176 	decodeInventory1491(request)
    177 
    178 	err := world.handleReload(world.clients[1], request)
    179 	world.handleReload(world.clients[1], request)
    180 
    181 	if err != nil || world.characters[1].inventory.Items[0].Ammo != 20 || world.characters[1].inventory.Items[1].Count != 83 || len(conn.packets) != 2 {
    182 		t.Fatal("explicit reload repeated or failed", err)
    183 	}
    184 	if binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x52526858 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 || binary.BigEndian.Uint32(conn.packets[0][33:37]) != 1 || binary.BigEndian.Uint32(conn.packets[0][57:61]) != 48 || binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x26515e61 {
    185 		t.Fatalf("explicit reload acknowledgement: %x", conn.packets)
    186 	}
    187 }
    188 
    189 func TestReloadAcceptsNativeEquippedWeaponSlot(t *testing.T) {
    190 	world, conn := newRangedWorld(t)
    191 	request := explicitReloadRequest(1, 48, 6)
    192 	binary.BigEndian.PutUint32(request[48:52], 101)
    193 	decodeInventory1491(request)
    194 
    195 	err := world.handleReload(world.clients[1], request)
    196 	restarted := newTestInventoryServer(t)
    197 
    198 	if err != nil || restarted.characters[1].inventory.Items[0].Ammo != 20 || restarted.characters[1].inventory.Items[1].Count != 83 || len(conn.packets) != 2 {
    199 		t.Fatal("native wear-slot reload did not conserve rounds", err)
    200 	}
    201 	if binary.BigEndian.Uint32(conn.packets[0][33:37]) != 1 || binary.BigEndian.Uint32(conn.packets[1][37:41]) != 51018 || binary.BigEndian.Uint32(conn.packets[1][41:45]) != 1 {
    202 		t.Fatalf("reload did not resolve the owned weapon instance: %x", conn.packets)
    203 	}
    204 }
    205 
    206 func TestReloadRestartsAnInterruptedAttackAfterItsDelay(t *testing.T) {
    207 	world, _ := newRangedWorld(t)
    208 	world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
    209 	attack, _ := world.characters[1].attackDelays()
    210 	health := world.characters[1000000].health
    211 
    212 	err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1))
    213 	ready := world.clients[1].reloadUntil
    214 	world.advanceCombat(ready.Add(attack - time.Nanosecond))
    215 	before := world.characters[1000000].health
    216 	world.advanceCombat(ready.Add(attack))
    217 
    218 	if err != nil || before != health || world.characters[1000000].health >= health || world.characters[1].inventory.Items[0].Ammo != 19 {
    219 		t.Fatal("interrupted attack did not restart after reload", err)
    220 	}
    221 }
    222 
    223 func TestReloadRejectsInvalidRequestsWithoutChangingRounds(t *testing.T) {
    224 	for _, scenario := range []string{"foreign owner", "foreign actor", "foreign weapon", "wrong ammo page", "wrong ammo slot", "missing ammo", "unsupported weapon", "full", "dead", "loading", "not ready", "stale", "equipment", "nano", "reloading"} {
    225 		t.Run(scenario, func(t *testing.T) {
    226 			world, _ := newRangedWorld(t)
    227 			player, client := world.characters[1], world.clients[1]
    228 			request := explicitReloadRequest(1, 64, 1)
    229 			expected := uint32(3)
    230 			switch scenario {
    231 			case "foreign owner":
    232 				binary.BigEndian.PutUint32(request[8:12], 2)
    233 			case "foreign actor":
    234 				binary.BigEndian.PutUint32(request[36:40], 2)
    235 			case "foreign weapon":
    236 				binary.BigEndian.PutUint32(request[52:56], 2)
    237 			case "wrong ammo page":
    238 				binary.BigEndian.PutUint32(request[40:44], 107)
    239 			case "wrong ammo slot":
    240 				binary.BigEndian.PutUint32(request[44:48], 65)
    241 			case "missing ammo":
    242 				player.inventory.Items[1].Template = 85366
    243 			case "unsupported weapon":
    244 				player.inventory.Items[0].Template = 209283
    245 				player.inventory.Items[0].Ammo = 0
    246 				expected = 0
    247 			case "full":
    248 				player.inventory.Items[0].Ammo = 20
    249 				expected = 20
    250 			case "dead":
    251 				player.health = 0
    252 			case "loading":
    253 				client.loading = true
    254 			case "not ready":
    255 				client.ready = false
    256 			case "stale":
    257 				world.clients[1] = &worldClient{}
    258 			case "equipment":
    259 				client.equipment = &equipmentMove{}
    260 			case "nano":
    261 				client.nanoCast = &nanoCast{}
    262 			case "reloading":
    263 				client.reloadUntil = time.Now().Add(time.Second)
    264 			}
    265 
    266 			err := world.handleReload(client, request)
    267 
    268 			if err != nil || player.inventory.Items[0].Ammo != expected || player.inventory.Items[1].Count != 100 {
    269 				t.Fatal("invalid reload changed ammunition", err)
    270 			}
    271 		})
    272 	}
    273 }
    274 
    275 func TestReloadFailedTransactionKeepsBothSidesAndDeadline(t *testing.T) {
    276 	world, conn := newRangedWorld(t)
    277 	if _, err := world.db.Exec("CREATE TRIGGER fail_ammo BEFORE UPDATE OF ammo ON items WHEN NEW.id = 1 BEGIN SELECT RAISE(FAIL, 'test save failure'); END"); err != nil {
    278 		t.Fatal(err)
    279 	}
    280 
    281 	err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1))
    282 	restarted := newTestInventoryServer(t)
    283 
    284 	if err == nil || len(conn.packets) != 0 || world.characters[1].inventory.Items[0].Ammo != 3 || world.characters[1].inventory.Items[1].Count != 100 || !world.characters[1].rechargeUntil.IsZero() || !world.clients[1].reloadUntil.IsZero() {
    285 		t.Fatal("failed reload published or modified live state")
    286 	}
    287 	if restarted.characters[1].inventory.Items[0].Ammo != 3 || restarted.characters[1].inventory.Items[1].Count != 100 || !restarted.characters[1].rechargeUntil.IsZero() {
    288 		t.Fatal("failed transfer persisted partially")
    289 	}
    290 }
    291 
    292 func TestPistolEquipmentUsesItsRequirementsAndPreservesLoadedRounds(t *testing.T) {
    293 	world, _ := newRangedWorld(t)
    294 	player, client := world.characters[1], world.clients[1]
    295 
    296 	err := world.handleInventory(client, itemMovePacket(1, 6, 111)[20:])
    297 	world.advanceEquipment(client.equipment.readyAt)
    298 	if err != nil || player.inventory.Items[0].Slot != 65 {
    299 		t.Fatal("pistol did not leave the equipped slot", err)
    300 	}
    301 	player.stats.Abilities.Agility, player.stats.Abilities.Sense = 1, 1
    302 	player.stats.Ranged.Pistol = 5
    303 	player.stats.Ranged.FlingShot = 6
    304 	world.handleInventory(client, inventoryMovePacket(1, 65, 6)[20:])
    305 	if client.equipment != nil {
    306 		t.Fatal("pistol equipped below its requirement")
    307 	}
    308 	player.stats.Ranged.Pistol = 6
    309 	world.handleInventory(client, inventoryMovePacket(1, 65, 6)[20:])
    310 	if client.equipment == nil {
    311 		t.Fatal("qualifying pistol request was rejected")
    312 	}
    313 	world.advanceEquipment(client.equipment.readyAt)
    314 	restarted := newTestInventoryServer(t)
    315 
    316 	if player.inventory.Items[0].Ammo != 3 || restarted.characters[1].inventory.Items[0].Ammo != 3 || restarted.characters[1].inventory.Items[0].Slot != 6 {
    317 		t.Fatal("equip or restart changed loaded rounds")
    318 	}
    319 	packet := targetPacket(equippedWeaponPackets(player)[0])
    320 	if binary.BigEndian.Uint32(packet[55:59]) != 6054 ||
    321 		binary.BigEndian.Uint32(packet[75:79]) != 702 || binary.BigEndian.Uint32(packet[79:83]) != 123742 ||
    322 		binary.BigEndian.Uint32(packet[83:87]) != 703 || binary.BigEndian.Uint32(packet[87:91]) != 123742 ||
    323 		binary.BigEndian.Uint32(packet[91:95]) != 26 || binary.BigEndian.Uint32(packet[95:99]) != 3 {
    324 		t.Fatalf("weapon instance did not initialize its magazine: %x", packet)
    325 	}
    326 }
    327 
    328 func TestPistolControlAssignmentPreservesLoadedRounds(t *testing.T) {
    329 	world, _ := newRangedWorld(t)
    330 	world.baseURL = "/"
    331 	created := postControlForm(world, "/admin/items", url.Values{"template": {"123742"}})
    332 	if created.Code != http.StatusSeeOther {
    333 		t.Fatal("could not create pistol", created.Code)
    334 	}
    335 	fields := url.Values{"ammo": {"9"}}
    336 
    337 	edited := postControlForm(world, "/admin/items/3", fields)
    338 	assigned := postControlForm(world, "/admin/items/3", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:65"}})
    339 	restarted := newTestInventoryServer(t)
    340 
    341 	if edited.Code != http.StatusSeeOther || assigned.Code != http.StatusSeeOther || restarted.items[3].Ammo != 9 || len(restarted.characters[1].inventory.Items) != 3 || restarted.characters[1].inventory.Items[2].Ammo != 9 {
    342 		t.Fatal("control assignment lost loaded rounds", edited.Code, assigned.Code)
    343 	}
    344 }
    345 
    346 func TestPistolControlRejectsAmmoAboveCapacity(t *testing.T) {
    347 	world, _ := newRangedWorld(t)
    348 	world.baseURL = "/"
    349 	fields := url.Values{"ammo": {"21"}}
    350 
    351 	response := postControlForm(world, "/admin/items/1", fields)
    352 	restarted := newTestInventoryServer(t)
    353 
    354 	if response.Code != http.StatusBadRequest || world.characters[1].inventory.Items[0].Ammo != 3 || restarted.items[1].Ammo != 3 {
    355 		t.Fatal("invalid loaded count replaced the item", response.Code)
    356 	}
    357 }