server/combat_test.go (17615B)
1 package main 2 3 import ( 4 "bytes" 5 "encoding/binary" 6 "encoding/hex" 7 "fmt" 8 "net" 9 "testing" 10 "time" 11 ) 12 13 type combatTestConn struct { 14 net.Conn 15 packets [][]byte 16 pending []byte 17 } 18 19 func (conn *combatTestConn) RemoteAddr() net.Addr { 20 return &net.TCPAddr{IP: net.IPv4(192, 0, 2, 1), Port: 4321} 21 } 22 23 func (conn *combatTestConn) SetWriteDeadline(time.Time) error { return nil } 24 25 func (conn *combatTestConn) Write(packet []byte) (int, error) { 26 // TCP writes may contain multiple packets or part of one packet. 27 conn.pending = append(conn.pending, packet...) 28 for len(conn.pending) >= 16 { 29 length := (int(binary.BigEndian.Uint16(conn.pending[6:8])) + 3) &^ 3 30 if length < 20 { 31 return 0, fmt.Errorf("invalid test world packet length %d", length) 32 } 33 if len(conn.pending) < length { 34 break 35 } 36 conn.packets = append(conn.packets, append([]byte(nil), conn.pending[:length]...)) 37 conn.pending = conn.pending[length:] 38 } 39 return len(packet), nil 40 } 41 42 func landedCombatRoll(limit uint32) uint32 { 43 if limit == 10000 { 44 return 0 45 } 46 return limit - 1 47 } 48 49 func newCombatWorld(t *testing.T) (*server, *combatTestConn) { 50 t.Helper() 51 t.Chdir(t.TempDir()) 52 conn := &combatTestConn{} 53 world := &server{ 54 worldServices: worldServices{combatRoll: landedCombatRoll}, 55 characters: map[uint32]*character{ 56 1: {id: 1, playfield: 950, health: 100, stats: testCharacterStats()}, 57 1000000: {id: 1000000, playfield: 950, position: [3]float32{1, 0, 0}, appearance: 229, npc: true, health: 100, stats: testCharacterStats()}, 58 }, 59 clients: map[uint32]*worldClient{ 60 1: {id: 1, conn: conn, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}, 61 }, 62 fighting: make(map[uint32]*character), 63 } 64 65 openTestDatabase(t, world) 66 return world, conn 67 } 68 69 func TestCombatTimesSwingsAndRetaliation(t *testing.T) { 70 world, conn := newCombatWorld(t) 71 player, npc := world.characters[1], world.characters[1000000] 72 73 if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil { 74 t.Fatal(err) 75 } 76 first := player.nextAttack 77 world.advanceCombat(first.Add(-time.Nanosecond)) 78 if npc.health != 100 || len(conn.packets) != 1 { 79 t.Fatal("attack landed before its attack phase ended") 80 } 81 world.advanceCombat(first) 82 world.advanceCombat(first.Add(time.Second)) 83 world.advanceCombat(first.Add(3950 * time.Millisecond)) 84 85 if npc.health < 90 || npc.health > 94 || player.health != 90 || player.fighting != 1000000 || npc.fighting != 1 { 86 t.Fatalf("combat state: player=%+v npc=%+v", player, npc) 87 } 88 if len(conn.packets) != 6 || hex.EncodeToString(conn.packets[1][33:57]) != "ffffffff000000000000c350000f42400000000000000004" { 89 t.Fatalf("unarmed hit layout or cycle: %x", conn.packets) 90 } 91 } 92 93 func TestCombatStartingAttackStandsTheAttacker(t *testing.T) { 94 world, _ := newCombatWorld(t) 95 world.characters[1].sitting = true 96 97 err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) 98 99 if err != nil || world.characters[1].sitting || world.characters[1].fighting != 1000000 { 100 t.Fatalf("attack did not leave the sitting posture: %v", err) 101 } 102 } 103 104 func TestCombatRepeatedRequestsDoNotResetClockOrCatchUpTicks(t *testing.T) { 105 world, conn := newCombatWorld(t) 106 request := attackPacket(1, 1000000)[20:] 107 world.handleCombat(world.clients[1], request) 108 first := world.characters[1].nextAttack 109 110 world.handleCombat(world.clients[1], request) 111 if world.characters[1].nextAttack != first || len(conn.packets) != 1 { 112 t.Fatal("repeated attack changed the clock or replayed the acknowledgement") 113 } 114 world.advanceCombat(first.Add(time.Hour)) 115 116 if world.characters[1000000].health < 95 || world.characters[1000000].health > 97 || world.characters[1].nextAttack != first.Add(time.Hour+3950*time.Millisecond) { 117 t.Fatal("a late tick replayed missed attacks") 118 } 119 } 120 121 func TestCombatRejectsInvalidTargetsAndSessions(t *testing.T) { 122 for _, scenario := range []string{"player", "human NPC", "dead", "other zone", "unknown", "hidden", "far", "loading", "replaced"} { 123 t.Run(scenario, func(t *testing.T) { 124 world, _ := newCombatWorld(t) 125 npc, client := world.characters[1000000], world.clients[1] 126 switch scenario { 127 case "player": 128 npc.npc = false 129 case "human NPC": 130 npc.appearance = 789 131 case "dead": 132 npc.health = 0 133 case "other zone": 134 npc.playfield = 952 135 case "unknown": 136 delete(world.characters, 1000000) 137 case "hidden": 138 delete(client.npcs, 1000000) 139 case "far": 140 npc.position[0] = 9 141 case "loading": 142 client.loading = true 143 case "replaced": 144 world.clients[1] = &worldClient{id: 1} 145 } 146 147 err := world.handleCombat(client, attackPacket(1, 1000000)[20:]) 148 149 if err != nil || len(world.fighting) != 0 || world.characters[1].fighting != 0 { 150 t.Fatalf("invalid attack accepted: %s, %v", scenario, err) 151 } 152 }) 153 } 154 } 155 156 func TestCombatStopLeavesRetaliatingNPCActive(t *testing.T) { 157 world, conn := newCombatWorld(t) 158 world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) 159 first := world.characters[1].nextAttack 160 world.advanceCombat(first) 161 162 world.handleCombat(world.clients[1], stopFightPacket(1)[20:]) 163 world.advanceCombat(first.Add(3 * time.Second)) 164 165 if world.characters[1].fighting != 0 || world.characters[1000000].fighting != 1 || world.characters[1000000].health < 95 || world.characters[1000000].health > 97 || world.characters[1].health != 95 { 166 t.Fatal("stopping an attack also pacified the opponent") 167 } 168 if hex.EncodeToString(conn.packets[3][16:33]) != "4a41203e0000c350000000010000000001" { 169 t.Fatalf("stop layout: %x", conn.packets[3]) 170 } 171 } 172 173 func TestCombatRangeUsesPredictedPlayerPosition(t *testing.T) { 174 world, _ := newCombatWorld(t) 175 world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) 176 first := world.characters[1].nextAttack 177 world.characters[1].rotation = [4]float32{0, 0, 0, 1} 178 started := first.Add(-8 * time.Second) 179 world.characters[1].movement = heldPlayerMovement(world.characters[1], 1, started) 180 181 for frame := 1; frame <= 80; frame++ { 182 world.advancePlayerMovement(started.Add(time.Duration(frame) * 100 * time.Millisecond)) 183 } 184 world.advanceCombat(first) 185 186 if len(world.fighting) != 0 || world.characters[1000000].health != 100 { 187 t.Fatal("an out-of-range predicted position still dealt damage") 188 } 189 } 190 191 func TestCombatKillingHitClampsHealthAndCancelsEveryAttacker(t *testing.T) { 192 world, conn := newCombatWorld(t) 193 world.characters[1000000].health = 3 194 world.characters[1000000].motion = &npcMotion{roaming: true, moving: true} 195 world.characters[2] = &character{id: 2, playfield: 950, health: 100, fighting: 1000000} 196 world.fighting[2] = world.characters[2] 197 world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) 198 first := world.characters[1].nextAttack 199 200 world.advanceCombat(first) 201 world.advanceCombat(first.Add(time.Hour)) 202 203 if world.characters[1000000].health != 0 || world.characters[1000000].motion.moving || len(world.fighting) != 0 || world.characters[2].fighting != 0 { 204 t.Fatal("death did not release every opponent") 205 } 206 if hex.EncodeToString(conn.packets[1][29:57]) != "00000003ffffffff000000000000c350000f42400000000400000004" { 207 t.Fatalf("killing hit: %x", conn.packets[1]) 208 } 209 if hex.EncodeToString(conn.packets[len(conn.packets)-1][29:49]) != "0000006300000000000000000000000000001770" { 210 t.Fatal("NPC death animation was not announced after the final hit") 211 } 212 } 213 214 func TestCombatPacketsOnlyReachObserversWhoKnowTheNPC(t *testing.T) { 215 world, _ := newCombatWorld(t) 216 near, hidden, elsewhere := &combatTestConn{}, &combatTestConn{}, &combatTestConn{} 217 world.characters[2] = &character{id: 2, playfield: 950, health: 100} 218 world.characters[3] = &character{id: 3, playfield: 950, health: 100} 219 world.characters[4] = &character{id: 4, playfield: 952, health: 100} 220 world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: near, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} 221 world.clients[3] = &worldClient{id: 3, conn: hidden, target: true, ready: true} 222 world.clients[4] = &worldClient{id: 4, conn: elsewhere, target: true, ready: true} 223 world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) 224 225 world.advanceCombat(world.characters[1].nextAttack) 226 227 if len(near.packets) != 3 || len(hidden.packets) != 0 || len(elsewhere.packets) != 0 { 228 t.Fatalf("combat visibility: near=%d hidden=%d elsewhere=%d", len(near.packets), len(hidden.packets), len(elsewhere.packets)) 229 } 230 for _, packet := range hidden.packets { 231 if binary.BigEndian.Uint32(packet[24:28]) == 1000000 { 232 t.Fatal("hidden NPC announced before its spawn") 233 } 234 } 235 } 236 237 func TestCombatAcceptsNativeWorldMessagesAndCancelsOnDisconnect(t *testing.T) { 238 useNPCData(t, testNPCData()) 239 world := newTestServer(t) 240 world.newCharacter() 241 shutdown := startTestService(t, world) 242 client := connectZoningClient(t, world, true) 243 244 if _, err := client.Write(targetPacket(attackPacket(1, 1000000))); err != nil { 245 t.Fatal(err) 246 } 247 ack, err := readPacket(client) 248 if err != nil { 249 t.Fatal(err) 250 } 251 callTestZone(t, world, 1, zoneTestCommand(func(state *server) error { 252 state.advanceCombat(state.characters[1].nextAttack) 253 return nil 254 })) 255 for range 2 { 256 if _, err := readPacket(client); err != nil { 257 t.Fatal(err) 258 } 259 } 260 client.Close() 261 deadline := time.Now().Add(time.Second) 262 for { 263 var disconnected bool 264 callTestZone(t, world, 1, zoneTestCommand(func(state *server) error { 265 disconnected = state.clients[1] == nil && len(state.fighting) == 0 266 return nil 267 })) 268 if disconnected { 269 break 270 } 271 if time.Now().After(deadline) { 272 t.Fatal("disconnect retained its session or combat participants") 273 } 274 time.Sleep(time.Millisecond) 275 } 276 if err := shutdown(); err != nil { 277 t.Fatal(err) 278 } 279 cold := newTestInventoryServer(t) 280 if !bytes.Equal(ack[16:38], targetPacket(attackPacket(1, 1000000))[16:38]) || cold.characters[1000000].health < 95 || cold.characters[1000000].health > 97 { 281 t.Fatalf("native attack/disconnect: ack=%x health=%d", ack, cold.characters[1000000].health) 282 } 283 } 284 285 func TestCombatPlayerDeathStopsMovementAndFurtherAttacks(t *testing.T) { 286 t.Chdir(t.TempDir()) 287 world, conn := newCombatWorld(t) 288 if err := world.saveUser(world.characters[1]); err != nil { 289 t.Fatal(err) 290 } 291 world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) 292 first := world.characters[1].nextAttack 293 world.advanceCombat(first) 294 world.characters[1].health = 3 295 world.characters[1].rotation = [4]float32{0, 0, 0, 1} 296 world.characters[1].movement = heldPlayerMovement(world.characters[1], 1, first) 297 298 world.advanceCombat(first.Add(time.Second)) 299 world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) 300 world.advanceCombat(first.Add(time.Hour)) 301 302 if world.characters[1].health != 0 || world.characters[1].movement.forward != 0 || world.characters[1].position != [3]float32{0, 0, 1.5} || len(world.fighting) != 0 { 303 t.Fatal("dead player kept moving or fighting") 304 } 305 if hex.EncodeToString(conn.packets[3][29:57]) != "00000003ffffffff000000000000c350000000010000000400000004" { 306 t.Fatalf("lethal NPC strike: %x", conn.packets[3]) 307 } 308 if hex.EncodeToString(conn.packets[len(conn.packets)-1][29:49]) != "00000063000000000000000000000000000001f4" { 309 t.Fatal("player death animation was not announced after the final hit") 310 } 311 } 312 313 func TestCombatLateObserverSeesDeadNPC(t *testing.T) { 314 world, _ := newCombatWorld(t) 315 world.characters[1000000].health = 3 316 world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) 317 world.advanceCombat(world.characters[1].nextAttack) 318 world.characters[2] = &character{id: 2, playfield: 950, health: 100} 319 conn := &combatTestConn{} 320 world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: conn, target: true, ready: true, npcs: make(map[uint32]bool)} 321 322 world.advanceNPCs(time.Now()) 323 324 if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x271b3a6b || hex.EncodeToString(conn.packets[1][29:49]) != "0000006300000000000000000000000000001770" { 325 t.Fatalf("late observer did not receive the NPC corpse: %x", conn.packets) 326 } 327 } 328 329 func TestCombatZoningCancelsOpponentsAndPreservesHealth(t *testing.T) { 330 t.Chdir(t.TempDir()) 331 world, _ := newCombatWorld(t) 332 world.characters[1].appearance = 0x315 333 world.characters[1].level = 1 334 world.characters[1].health = 37 335 world.characters[1].aggDef = 75 336 world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) 337 first := world.characters[1].nextAttack 338 world.advanceCombat(first) 339 world.advanceCombat(first.Add(time.Second)) 340 destination := world.characters[1].userData() 341 destination.Playfield = 952 342 343 err := world.updateUser(destination) 344 world.advanceCombat(first.Add(time.Hour)) 345 346 if err != nil || world.characters[1].playfield != 952 || world.characters[1].health != 32 || world.characters[1].aggDef != 75 || world.characters[1].rechargeUntil != first.Add(1220*time.Millisecond) || world.characters[1000000].fighting != 0 || len(world.fighting) != 0 { 347 t.Fatalf("combat survived zoning or health reset: %v", err) 348 } 349 } 350 351 func TestCombatMalformedPacketsAreRejected(t *testing.T) { 352 for _, packet := range [][]byte{attackPacket(1, 1000000)[:44], stopFightPacket(1)[:39], n3Packet(0x76793f0d, 50000, 1, []byte{0, 0, 0})[:39]} { 353 if !t.Run("packet", func(t *testing.T) { 354 world, _ := newCombatWorld(t) 355 356 err := world.handleCombat(world.clients[1], packet[20:]) 357 358 if err == nil || len(world.fighting) != 0 { 359 t.Fatal("short combat packet was accepted") 360 } 361 }) { 362 return 363 } 364 } 365 } 366 367 func TestCombatAggDefControlsNativeFistTimings(t *testing.T) { 368 for _, scenario := range []struct { 369 name string 370 value int32 371 attack time.Duration 372 recharge time.Duration 373 }{ 374 {"center", 0, 1980 * time.Millisecond, 1970 * time.Millisecond}, 375 {"base speed", 75, 1230 * time.Millisecond, 1220 * time.Millisecond}, 376 {"full aggression", 100, time.Second, time.Second}, 377 {"full defense", -100, 2980 * time.Millisecond, 2970 * time.Millisecond}, 378 } { 379 t.Run(scenario.name, func(t *testing.T) { 380 world, conn := newCombatWorld(t) 381 request := n3Packet(0x76793f0d, 50000, 1, binary.BigEndian.AppendUint32(nil, uint32(scenario.value))) 382 383 if err := world.handleCombat(world.clients[1], request[20:]); err != nil { 384 t.Fatal(err) 385 } 386 before := time.Now() 387 world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) 388 after := time.Now() 389 first := world.characters[1].nextAttack 390 world.advanceCombat(first) 391 392 if first.Before(before.Add(scenario.attack)) || first.After(after.Add(scenario.attack)) || 393 world.characters[1].nextAttack != first.Add(scenario.attack+scenario.recharge) || 394 world.characters[1].rechargeUntil != first.Add(scenario.recharge) { 395 t.Fatal("attack/recharge differs from native centisecond calculation") 396 } 397 if world.characters[1].aggDef != scenario.value || binary.BigEndian.Uint16(conn.packets[0][6:8]) != 37 || 398 binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x2b333d6e || 399 binary.BigEndian.Uint32(conn.packets[0][29:33]) != 51 || 400 int32(binary.BigEndian.Uint32(conn.packets[0][33:37])) != scenario.value { 401 t.Fatal("slider value was not acknowledged through the native stat layout") 402 } 403 }) 404 } 405 } 406 407 func TestCombatAggDefRejectsInvalidValuesAndReplacedSessions(t *testing.T) { 408 for _, value := range []int32{-101, 101, -2147483648, 2147483647, 75} { 409 if !t.Run(fmt.Sprint(value), func(t *testing.T) { 410 world, conn := newCombatWorld(t) 411 client := world.clients[1] 412 if value == 75 { 413 world.clients[1] = &worldClient{id: 1} 414 } 415 request := n3Packet(0x76793f0d, 50000, 1, binary.BigEndian.AppendUint32(nil, uint32(value))) 416 417 err := world.handleCombat(client, request[20:]) 418 419 if err != nil || world.characters[1].aggDef != 0 || len(conn.packets) != 0 { 420 t.Fatalf("invalid slider request accepted: %d, %v", value, err) 421 } 422 }) { 423 return 424 } 425 } 426 } 427 428 func TestCombatAggDefUsesNativeWorldRequest(t *testing.T) { 429 useNPCData(t, testNPCData()) 430 world := newTestServer(t) 431 world.newCharacter() 432 startTestService(t, world) 433 client := connectZoningClient(t, world, true) 434 request := n3Packet(0x76793f0d, 50000, 1, []byte{0xff, 0xff, 0xff, 0x9c}) 435 436 if _, err := client.Write(targetPacket(request)); err != nil { 437 t.Fatal(err) 438 } 439 ack, err := readPacket(client) 440 441 if err != nil { 442 t.Fatal(err) 443 } 444 if hex.EncodeToString(ack[16:37]) != "2b333d6e0000c350000000010000000033ffffff9c" { 445 t.Fatalf("native slider reply: %x", ack) 446 } 447 var aggDef int32 448 callTestZone(t, world, 1, zoneTestCommand(func(state *server) error { 449 aggDef = state.characters[1].aggDef 450 return nil 451 })) 452 if aggDef != -100 { 453 t.Fatal("native request did not reach the player's combat state") 454 } 455 } 456 457 func TestCombatDeadPlayerCannotCrossZoneTriggers(t *testing.T) { 458 world, _ := newCombatWorld(t) 459 world.characters[1].health = 0 460 world.characters[1].rotation = [4]float32{0, 0, 0, 1} 461 world.characters[1].movement.forward = 1 462 now := time.Now() 463 world.characters[1].movement.updatedAt = now 464 world.zoneLinks = map[string]map[uint32]zoneLinks{"target": { 465 950: {Doors: []zoneDoor{{ID: 1, Destination: 952, DestinationDoor: 2}}}, 466 952: {Doors: []zoneDoor{{ID: 2, Position: [3]float32{10, 0, 10}}}}, 467 }} 468 469 world.advanceZoneCrossings(now) 470 471 if world.characters[1].playfield != 950 || !world.clients[1].ready { 472 t.Fatal("dead player crossed a zone trigger") 473 } 474 } 475 476 func TestCombatReconnectKeepsDefeatedPlayerDead(t *testing.T) { 477 useNPCData(t, testNPCData()) 478 world := newTestServer(t) 479 world.newCharacter().health = 0 480 481 reconnectResurrectionPlayer(t, world, n3Packet(0x570c2039, 50000, 1, nil)) 482 if world.characters[1].health != 0 || world.characters[1].fighting != 0 { 483 t.Fatal("reconnecting bypassed the pending resurrection") 484 } 485 }