aorecomp

Anarchy Online classic in the browser

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


commit 62e78389af3b6481b6977ca6111f1272657397b1
parent 8f91215af0a9b97a8cd3f6d1944c07fe93428f12
Author: anon <anon@example.com>
Date:   Sat,  7 Nov 2026 21:31:37 +0000

Bound player visibility and measure native network load

Diffstat:
MDEVELOPERS.md | 9+++++++++
Mserver/actor_speed_test.go | 2+-
Mserver/admin_live.go | 2+-
Mserver/admin_live_test.go | 2+-
Mserver/aggdef_nano_test.go | 2+-
Mserver/armor_damage_test.go | 2+-
Mserver/armor_test.go | 2+-
Mserver/attack_rating_test.go | 2+-
Mserver/backpack_uploads_test.go | 2+-
Mserver/belts_test.go | 2+-
Aserver/browser_player_interest_test.go | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/browser_social_swimming_test.go | 2+-
Mserver/character_info.go | 2+-
Mserver/character_info_test.go | 4+++-
Mserver/clothing_test.go | 2+-
Mserver/combat.go | 2+-
Mserver/combat_equipment_modifiers_test.go | 2+-
Mserver/combat_interest.go | 2+-
Mserver/combat_interest_test.go | 4++--
Mserver/combat_lifecycle_test.go | 2+-
Mserver/combat_stress_test.go | 7++++---
Mserver/combat_test.go | 4++--
Mserver/consumable_outcome_test.go | 3++-
Mserver/critical_hit_test.go | 4++--
Mserver/electronicum_quality_test.go | 2+-
Mserver/equipment.go | 2+-
Mserver/equipment_conservation_test.go | 2+-
Mserver/equipment_replacement_test.go | 4++--
Mserver/equipment_test.go | 6+++---
Mserver/fast_attack_test.go | 2+-
Mserver/fling_shot_test.go | 2+-
Mserver/flying_vehicle_test.go | 4++--
Mserver/implant_catalog_test.go | 2+-
Mserver/information_test.go | 2+-
Mserver/insurance_experience_test.go | 2+-
Mserver/interest.go | 2+-
Mserver/ip_training_test.go | 2+-
Mserver/kill_experience_rules_test.go | 2+-
Mserver/kill_experience_test.go | 2+-
Mserver/map_upload_test.go | 2+-
Mserver/metaplast_test.go | 2+-
Mserver/mission_boundaries_test.go | 2++
Mserver/mission_entrance_test.go | 2+-
Mserver/mouse_movement_test.go | 4++--
Mserver/movement_yaw_test.go | 2+-
Mserver/nano_buffs_test.go | 9++++++---
Mserver/nano_casting_test.go | 2+-
Mserver/nano_control_movement_test.go | 2+-
Mserver/nano_healing_test.go | 2+-
Mserver/nano_kit_test.go | 8+++++---
Mserver/nano_learning_test.go | 2+-
Mserver/ncu_hacker_interface_test.go | 2+-
Mserver/npc_combat_test.go | 2+-
Mserver/npc_levels_test.go | 2+-
Mserver/npc_navigation_test.go | 2+-
Mserver/npc_pursuit_test.go | 2+-
Mserver/npc_threat_test.go | 3++-
Mserver/overequipping_test.go | 2+-
Mserver/owned_item_use_test.go | 2+-
Mserver/pet_dismiss_test.go | 4++--
Mserver/pet_messages.go | 2+-
Mserver/pet_retreat_test.go | 2+-
Mserver/pet_wait_test.go | 2+-
Mserver/pets.go | 17+++++++++++++----
Mserver/player_altitude_test.go | 2+-
Mserver/player_death_test.go | 2+-
Mserver/player_flight_input_test.go | 4++--
Mserver/player_flight_modes_test.go | 4++--
Mserver/player_flight_test.go | 4++--
Mserver/player_follow.go | 20++++++++++++++------
Mserver/player_follow_test.go | 14+++++++++-----
Aserver/player_interest.go | 127+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/player_interest_test.go | 177+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/player_movement_mode_test.go | 2+-
Mserver/player_movement_test.go | 2+-
Mserver/player_posture_test.go | 2+-
Mserver/player_sneak_test.go | 2+-
Mserver/progression.go | 2+-
Mserver/ranged_test.go | 2+-
Mserver/regeneration_nano_test.go | 2+-
Mserver/regeneration_test.go | 4++--
Mserver/remote_combat_stats_test.go | 6+++---
Mserver/remote_reload_test.go | 2+-
Mserver/resource_kit_test.go | 2+-
Mserver/resurrection_reconnect_test.go | 4++--
Mserver/resurrection_test.go | 2+-
Mserver/roaming.go | 1+
Mserver/sixth_level_training_test.go | 2+-
Mserver/social_actions_test.go | 8++++----
Mserver/social_swimming_test.go | 2+-
Mserver/stale_equipment_resources_test.go | 2+-
Mserver/starter_weapons_test.go | 2+-
Mserver/state.go | 35+++++++++++++++++++++++++++++++----
Mserver/stationary_clinic_test.go | 2+-
Mserver/team_resources.go | 4++--
Mserver/team_resources_test.go | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/teams_test.go | 10++++++++++
Mserver/token_upload_test.go | 2+-
Mserver/tradeskills_test.go | 2+-
Mserver/treatment_kit_test.go | 3++-
Mserver/utility_equipment_test.go | 2+-
Mserver/vehicle_test.go | 2+-
Mserver/vektor_quality_test.go | 2+-
Mserver/weapon_miss_test.go | 2+-
Mserver/weapon_quality_test.go | 2+-
Mserver/weapon_special_animation_test.go | 4++--
Mserver/weapon_wear_admission_test.go | 2+-
Mserver/world_actions.go | 2+-
Mserver/world_loading_test.go | 4++--
Mserver/world_output_test.go | 34++++++++++++++++++++++++++++++++--
Mserver/world_session.go | 32+++++++++++++++++---------------
Mserver/zone_movement_test.go | 2+-
Atools/client/test_player_interest.mjs | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/stress/README.md | 39+++++++++++++++++++++++++++------------
Atools/stress/distributed.json | 24++++++++++++++++++++++++
Mtools/stress/hotspot.json | 6+++---
Mtools/stress/main.go | 6+++++-
Mtools/stress/protocol.go | 88+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Mtools/stress/protocol_test.go | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
119 files changed, 976 insertions(+), 215 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -84,6 +84,15 @@ Bank, reclaim and bag contents follow their player; corpses, pets, resource stat and mission floor items belong to their physical zone. Unassigned items remain in SQLite and are imported only through a transaction that claims ownership. +Each zone refreshes player visibility every 250 ms using a temporary spatial +grid of its connected players. Actors enter at 180 metres and leave beyond +200 metres, matching NPC interest. Entry sends a complete snapshot before +movement, combat and follow controllers; departure stops dependent controllers +before removing the actor. Subsequent actor updates reach only observers that +know it. Team resource messages remain available outside actor visibility and +across zones. Health reconciliation retains its existing cadence. Broadcasts +encode the native packet once, then copy it for each recipient's output queue. + Zone activation restores its NPC checkpoint or creates its authored population in one transaction. Concurrent arrivals share that owner's activation, while the directory continues routing other zones. NPC identities are reserved before diff --git a/server/actor_speed_test.go b/server/actor_speed_test.go @@ -82,7 +82,7 @@ func TestLateActorSpawnKeepsTrainedSpeedSeparateFromEquipmentAndNanos(t *testing } world.advanceEquipment(client.equipment.readyAt) observer := world.newCharacter() - observer.playfield = player.playfield + observer.playfield, observer.position = player.playfield, player.position if err := world.saveUser(observer); err != nil { t.Fatal(err) } diff --git a/server/admin_live.go b/server/admin_live.go @@ -107,7 +107,7 @@ func (server *server) teleportWithinPlayfield(player *character, destination use } client.lootCorpse, client.dialogue = 0, nil for _, observer := range server.clients { - if observer.ready && !observer.loading && server.characters[observer.id].playfield == player.playfield { + if observer.ready && observer.sees(player) && !observer.loading && server.characters[observer.id].playfield == player.playfield { updates[observer] = append(updates[observer], playerFollowPacket(player.id, 0), npcMovementPacket(player, 0x94)) } } diff --git a/server/admin_live_test.go b/server/admin_live_test.go @@ -65,7 +65,7 @@ func TestAdminSameZoneTeleportPreservesConnectionAndNotifiesObservers(t *testing ownerConnection, observerConnection := &combatInterestConn{}, &combatInterestConn{} client := &worldClient{id: player.id, ready: true, conn: ownerConnection, target: true, npcs: make(map[uint32]bool)} world.clients[player.id] = client - world.clients[observer.id] = &worldClient{id: observer.id, ready: true, conn: observerConnection, target: true} + world.clients[observer.id] = &worldClient{id: observer.id, ready: true, conn: observerConnection, target: true, players: map[uint32]bool{player.id: true}} player.rotation = [4]float32{0, 0.70710677, 0, 0.70710677} player.movement = heldPlayerMovement(player, 1, time.Now()) rotation := player.rotation diff --git a/server/aggdef_nano_test.go b/server/aggdef_nano_test.go @@ -49,7 +49,7 @@ func TestAggDefNanosUploadCastRestoreAndExpireCompleteEffects(t *testing.T) { trained := player.baseStats() observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true} + world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true, players: map[uint32]bool{1: true}} if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil { t.Fatal(err) diff --git a/server/armor_damage_test.go b/server/armor_damage_test.go @@ -138,7 +138,7 @@ func TestArmorDamageNativeCombatMatchesBothObservers(t *testing.T) { npc.combatProfile = &gamedata.NPCCombatProfile{Weapon: [2]uint32{120910, 120910}} observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, players: map[uint32]bool{1: true}, npcs: map[uint32]bool{1000000: true}} owner.packets = nil world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]) diff --git a/server/armor_test.go b/server/armor_test.go @@ -26,7 +26,7 @@ func TestArmorNativeMoveDelayAndRestart(t *testing.T) { world, conn := newArmorWorld(t) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, players: map[uint32]bool{1: true}} before, err := readTestItemStore(world) if err != nil { t.Fatal(err) diff --git a/server/attack_rating_test.go b/server/attack_rating_test.go @@ -111,7 +111,7 @@ func TestAttackRatingNativeDamageMatchesBothObservers(t *testing.T) { world.advanceEquipment(world.clients[1].equipment.readyAt) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, players: map[uint32]bool{1: true}, npcs: map[uint32]bool{1000000: true}} owner.packets = nil world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]) diff --git a/server/backpack_uploads_test.go b/server/backpack_uploads_test.go @@ -99,7 +99,7 @@ func TestBackpackUploadsCommitExactChildAndMetadataBeforeSuccess(t *testing.T) { client.conn = output observer := &combatTestConn{} world.characters[2] = &character{id: 2, health: 100, playfield: player.playfield} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true, target: true} err := world.handleOwnedItemUse(client, request) world.handleOwnedItemUse(client, request) diff --git a/server/belts_test.go b/server/belts_test.go @@ -30,7 +30,7 @@ func TestBeltNCUEquipDelaysAndRestart(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, players: map[uint32]bool{1: true}} for _, move := range []struct { source, destination uint32 diff --git a/server/browser_player_interest_test.go b/server/browser_player_interest_test.go @@ -0,0 +1,83 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserPlayerInterestReentry(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for native player visibility reentry") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/player-interest", time.Now().Format("20060102-150405")) + t.Chdir(t.TempDir()) + world := newDormantServerForTest(t) + for i := 0; i < 2; i++ { + player := world.newCharacter() + player.name, player.level, player.profession = fmt.Sprint("Interest ", i), 10, 9 + player.position, player.rotation = [3]float32{52 + float32(i)*2, 14, 56}, [4]float32{0, 0, 0, 1} + player.stats.Melee.OneHandBlunt, player.stats.Melee.SneakAttack, player.stats.Melee.FastAttack = 20, 20, 20 + player.stats.Body.Brawling, player.stats.Body.Dimach = 20, 20 + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("interest-", i)))) + if err := world.saveUser(player); err != nil { + t.Fatal(err) + } + } + if granted, err := world.grantItem(world.characters[1], 121564); !granted || err != nil { + t.Fatal("grant fixture weapon", err) + } + shutdown := startTestService(t, world) + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("POST /test-place/{place}", testPlayerHTTP(world, 2, func(state *server, w http.ResponseWriter, r *http.Request) { + position := [3]float32{54, 14, 56} + if r.PathValue("place") == "far" { + position[0] = 292 + } + // Place the controlled observer across the interest boundary without a + // collision sweep through the backyard walls or any synthetic game input. + player := state.characters[2] + player.position, player.movement = position, playerMovement{} + if err := state.savePosition(player); err != nil { + http.Error(w, err.Error(), 500) + return + } + if err := state.clients[2].send(npcMovementPacket(player, 0x94)); err != nil { + http.Error(w, err.Error(), 500) + return + } + w.WriteHeader(http.StatusNoContent) + })) + mux.HandleFunc("GET /test-state", testPlayerHTTP(world, 1, func(state *server, w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(map[string]any{"position": state.characters[1].position, + "sitting": state.characters[1].sitting, "inventory": state.characters[1].inventory, + "known": state.clients[2].players[1]}) + })) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_player_interest.mjs"), host.URL, output) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + host.Close() + if failure := shutdown(); failure != nil { + t.Fatal(failure) + } + t.Logf("Browser artifacts: %s", output) + if err != nil { + t.Fatal(err) + } +} diff --git a/server/browser_social_swimming_test.go b/server/browser_social_swimming_test.go @@ -38,7 +38,7 @@ func TestBrowserSocialSwimmingRefusal(t *testing.T) { } } observer := &combatTestConn{} - peerClient := &worldClient{id: 2, target: true, ready: true, conn: observer} + peerClient := &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer} world.clients[2] = peerClient shutdown := startTestService(t, world) mux := http.NewServeMux() diff --git a/server/character_info.go b/server/character_info.go @@ -62,7 +62,7 @@ func (server *server) handleCharacterInfo(client *worldClient, body []byte) erro represented := client.npcs[target.id] && target.corpse == nil if !target.npc { recipient := server.clients[target.id] - represented = recipient != nil && recipient.ready && !recipient.loading + represented = client.seesPlayer(target.id) && recipient != nil && recipient.ready && !recipient.loading } if !represented { return nil diff --git a/server/character_info_test.go b/server/character_info_test.go @@ -76,12 +76,14 @@ func TestCharacterInfoRetainsVisitorTitleSeparatelyFromName(t *testing.T) { } func TestCharacterInfoRejectsUnrepresentedOrUnauthenticatedRequests(t *testing.T) { - for _, scenario := range []string{"missing", "unseen npc", "other zone", "offline", "foreign owner", "sender type", "target type", "argument", "action", "key", "legacy", "not ready", "loading", "target not ready", "target loading", "replaced"} { + for _, scenario := range []string{"missing", "unseen npc", "unseen player", "other zone", "offline", "foreign owner", "sender type", "target type", "argument", "action", "key", "legacy", "not ready", "loading", "target not ready", "target loading", "replaced"} { t.Run(scenario, func(t *testing.T) { world, connections := newTeamWorld(t) client := world.clients[1] request := teamRequest(1, 105, 2, 0) switch scenario { + case "unseen player": + delete(client.players, 2) case "missing": binary.BigEndian.PutUint32(request[24:28], 90) case "unseen npc": diff --git a/server/clothing_test.go b/server/clothing_test.go @@ -29,7 +29,7 @@ func TestStarterClothingWearRestrictionsAndColdRecovery(t *testing.T) { before, _ := readTestItemStore(world) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, players: map[uint32]bool{1: true}} slot, bonus := uint32(17), int32(0) if template == 29426 { slot, bonus = 21, 10 diff --git a/server/combat.go b/server/combat.go @@ -650,7 +650,7 @@ func (server *server) queueCombat(updates map[*worldClient][][]byte, character, // even while the observer's own character is still finishing native loading. for id, client := range server.clients { if client.ready && server.characters[id].playfield == character.playfield && - (!character.npc || client.npcs[character.id]) && (!target.npc || client.npcs[target.id]) { + client.sees(character) && client.sees(target) { updates[client] = append(updates[client], packets...) } } diff --git a/server/combat_equipment_modifiers_test.go b/server/combat_equipment_modifiers_test.go @@ -141,7 +141,7 @@ func TestRobustCombatWearRemovalRestartAndObservers(t *testing.T) { } observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, players: map[uint32]bool{1: true}, npcs: map[uint32]bool{1000000: true}} world.handleInventory(client, inventoryMovePacket(1, 65, 19)[20:]) if client.equipment == nil { diff --git a/server/combat_interest.go b/server/combat_interest.go @@ -7,7 +7,7 @@ func (server *server) combatInterest(client *worldClient, spawned map[uint32]boo target := server.characters[attacker.fighting] if target == nil || attacker.playfield != server.characters[client.id].playfield || target.playfield != attacker.playfield || - (attacker.npc && !client.npcs[attacker.id]) || (target.npc && !client.npcs[target.id]) { + !client.sees(attacker) || !client.sees(target) { continue } if spawned != nil && !spawned[attacker.id] && !spawned[target.id] { diff --git a/server/combat_interest_test.go b/server/combat_interest_test.go @@ -69,7 +69,7 @@ func TestCombatNPCInterestReplaysTargetsOnceAfterSpawning(t *testing.T) { world.advanceCombat(world.characters[1].nextAttack) world.characters[2] = &character{id: 2, playfield: 950, health: 100} conn := &combatTestConn{} - world.clients[2] = &worldClient{id: 2, conn: conn, ready: true, npcs: make(map[uint32]bool)} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: conn, ready: true, npcs: make(map[uint32]bool)} now := time.Now() world.advanceNPCs(now) @@ -116,7 +116,7 @@ func TestCombatSessionReplacementCancelsBeforeInitialization(t *testing.T) { world.advanceCombat(world.characters[1].nextAttack) world.characters[2] = &character{id: 2, playfield: 950, health: 100} observer := &combatTestConn{} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true, npcs: map[uint32]bool{1000000: true}} activeAtInitialization := -1 conn := &combatInterestConn{ input: bytes.NewReader(systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})), diff --git a/server/combat_lifecycle_test.go b/server/combat_lifecycle_test.go @@ -63,7 +63,7 @@ func TestCombatProfileEditStopsBothActorsInTheirOriginalPlayfield(t *testing.T) world.advanceCombat(world.characters[1].nextAttack) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} destination := world.characters[1].userData() destination.Playfield = 705 diff --git a/server/combat_stress_test.go b/server/combat_stress_test.go @@ -35,7 +35,8 @@ func TestCombatSharedNPCKillingBlowIsResolvedOnce(t *testing.T) { world, first := newCombatWorld(t) second := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: second, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: second, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[1].players = map[uint32]bool{2: true} world.characters[1000000].health = 6 for _, id := range []uint32{1, 2} { if err := world.handleCombat(world.clients[id], attackPacket(id, 1000000)[20:]); err != nil { @@ -143,7 +144,7 @@ func TestCombatFailedObserverDoesNotSuppressOtherObservers(t *testing.T) { world, healthy := newCombatWorld(t) failed := &failingCombatConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: failed, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: failed, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil { t.Fatal(err) @@ -163,7 +164,7 @@ func TestCombatLateObserverReceivesInjuredNPCBeforeFight(t *testing.T) { world.advanceCombat(world.characters[1].nextAttack) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: make(map[uint32]bool)} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: make(map[uint32]bool)} world.advanceNPCs(time.Now()) diff --git a/server/combat_test.go b/server/combat_test.go @@ -217,7 +217,7 @@ func TestCombatPacketsOnlyReachObserversWhoKnowTheNPC(t *testing.T) { world.characters[2] = &character{id: 2, playfield: 950, health: 100} world.characters[3] = &character{id: 3, playfield: 950, health: 100} world.characters[4] = &character{id: 4, playfield: 952, health: 100} - world.clients[2] = &worldClient{id: 2, conn: near, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: near, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} world.clients[3] = &worldClient{id: 3, conn: hidden, target: true, ready: true} world.clients[4] = &worldClient{id: 4, conn: elsewhere, target: true, ready: true} world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) @@ -317,7 +317,7 @@ func TestCombatLateObserverSeesDeadNPC(t *testing.T) { world.advanceCombat(world.characters[1].nextAttack) world.characters[2] = &character{id: 2, playfield: 950, health: 100} conn := &combatTestConn{} - world.clients[2] = &worldClient{id: 2, conn: conn, target: true, ready: true, npcs: make(map[uint32]bool)} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: conn, target: true, ready: true, npcs: make(map[uint32]bool)} world.advanceNPCs(time.Now()) diff --git a/server/consumable_outcome_test.go b/server/consumable_outcome_test.go @@ -72,7 +72,8 @@ func newConsumableOutcomeWorld(t *testing.T, template uint32, other bool) (*serv conn := &combatTestConn{} world.clients[player.id] = &worldClient{id: player.id, conn: conn, target: true, ready: true, selectedTarget: [2]uint32{50000, target.id}} if other { - world.clients[target.id] = &worldClient{id: target.id, conn: &combatTestConn{}, target: true, ready: true} + world.clients[player.id].players = map[uint32]bool{target.id: true} + world.clients[target.id] = &worldClient{id: target.id, conn: &combatTestConn{}, target: true, ready: true, players: map[uint32]bool{player.id: true}} } return world, target, conn } diff --git a/server/critical_hit_test.go b/server/critical_hit_test.go @@ -175,7 +175,7 @@ func TestCriticalWeaponSpecialsPersistDamageLockAndUnchangedAmmunition(t *testin world.combatRoll = func(uint32) uint32 { return 0 } observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} if err := world.handleWeaponSpecial(world.clients[1], request[20:]); err != nil { t.Fatal(err) @@ -300,7 +300,7 @@ func TestCriticalKillingShotCommitsAmmoCorpseAndExperienceTogether(t *testing.T) target.combatProfile = gamedata.NPCCombatProfiles[17655][1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} world.combatRoll = func(uint32) uint32 { return 0 } world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]) diff --git a/server/electronicum_quality_test.go b/server/electronicum_quality_test.go @@ -30,7 +30,7 @@ func TestElectronicumQualitiesWearRemoveAndRecover(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} player.stats.Ranged.Pistol = scenario.threshold player.aggDef = 75 diff --git a/server/equipment.go b/server/equipment.go @@ -344,7 +344,7 @@ func (server *server) advanceEquipment(now time.Time) { server.queueCombat(updates, character, character, weaponUnequipPacket(client.id)) // The owner's live inventory row still needs its detached weapon dynel. for id, observer := range server.clients { - if id != client.id && observer.ready && !observer.loading && server.characters[id].playfield == character.playfield { + if id != client.id && observer.sees(character) && observer.ready && !observer.loading && server.characters[id].playfield == character.playfield { updates[observer] = append(updates[observer], n3Packet(0x36510078, removed.Type, removed.ID, nil)) } } diff --git a/server/equipment_conservation_test.go b/server/equipment_conservation_test.go @@ -14,7 +14,7 @@ func TestEquipmentPlacementFailurePreservesEveryItemThenRetries(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} if granted, err := world.grantItem(player, 121567); err != nil || !granted { t.Fatal("grant unrelated item", granted, err) } diff --git a/server/equipment_replacement_test.go b/server/equipment_replacement_test.go @@ -71,7 +71,7 @@ func TestEquipmentReplacementFailureRetainsBothItemsAndRetries(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} before, _ := readTestItemStore(world) items := slices.Clone(player.inventory.Items) statement := fmt.Sprintf("CREATE TRIGGER reject_swap BEFORE DELETE ON item_locations WHEN OLD.item_id=%d BEGIN SELECT RAISE(FAIL, 'swap delete'); END", id) @@ -173,7 +173,7 @@ func TestEquipmentArmorReplacementRemovesOnlyTheDisplacedEffects(t *testing.T) { before := player.equipmentBonus(90) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} world.handleInventory(client, inventoryMovePacket(1, 65, 21)[20:]) if client.equipment == nil { diff --git a/server/equipment_test.go b/server/equipment_test.go @@ -47,7 +47,7 @@ func TestEquipmentDelayedNativeMoveAndRestart(t *testing.T) { world, conn := newEquipmentWorld(t) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} request := inventoryMovePacket(1, 64, 6)[20:] before, err := readTestItemStore(world) if err != nil { @@ -103,7 +103,7 @@ func TestWeaponReequipRetiresOwnerInstanceAfterItsNativeRequest(t *testing.T) { world, owner := newEquipmentWorld(t) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} if err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:]); err != nil { t.Fatal(err) } @@ -289,7 +289,7 @@ func TestEquipmentRejectedWearRestoresFullNativeInventory(t *testing.T) { } observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} request := inventoryMovePacket(1, source-16, 18)[20:] decodeInventory1491(request) diff --git a/server/fast_attack_test.go b/server/fast_attack_test.go @@ -37,7 +37,7 @@ func TestFastAttackPublishesWeaponDamageAndPersistsItsOwnLock(t *testing.T) { player.stats.Melee.OneHandEdged = 400 observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true, target: true, npcs: map[uint32]bool{1000000: true}} inventory := player.inventory inventory.Items = append([]ownedItem(nil), player.inventory.Items...) started := time.Now() diff --git a/server/fling_shot_test.go b/server/fling_shot_test.go @@ -24,7 +24,7 @@ func TestFlingShotDamagesOnceWithoutConsumingPre155Ammunition(t *testing.T) { player, target := world.characters[1], world.characters[1000000] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} started := time.Now() err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, target.id)[20:]) diff --git a/server/flying_vehicle_test.go b/server/flying_vehicle_test.go @@ -33,7 +33,7 @@ func TestFlyingVehicleEquipRemovalAndRestart(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 800, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} started := time.Now() if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { @@ -247,7 +247,7 @@ func TestFlyingVehicleCapturedAltitudeReachesObserverAndRestart(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 800, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} compact, err := hex.DecodeString("021c20041714efd6c60000000030f30000") if err != nil { t.Fatal(err) diff --git a/server/implant_catalog_test.go b/server/implant_catalog_test.go @@ -69,7 +69,7 @@ func TestCatalogImplantsUseEveryAnatomicalSlotAndPreserveIdentity(t *testing.T) player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} before := slices.Clone(player.inventory.Items) started := time.Now() diff --git a/server/information_test.go b/server/information_test.go @@ -38,7 +38,7 @@ func TestInformationUseAuthorizesEveryOriginalPlacement(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} request := shopUseRequest(1) binary.BigEndian.PutUint32(request[40:44], 51005) auditCheckpointWrites(t, world) diff --git a/server/insurance_experience_test.go b/server/insurance_experience_test.go @@ -141,7 +141,7 @@ func TestInsuranceExperienceDeathPreservesProtectedProgress(t *testing.T) { } observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 705, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} output.packets = nil fatal := defeatReclaimPlayer(t, world) diff --git a/server/interest.go b/server/interest.go @@ -93,7 +93,7 @@ func (server *server) updateNPCInterest(client *worldClient, now time.Time) [][] updates = append(updates, deathPacket(other)) } } - if other.pet != nil && other.followTarget != 0 && !other.pet.paused { + if other.pet != nil && other.followTarget != 0 && !other.pet.paused && client.seesPlayer(other.followTarget) { updates = append(updates, petFollowPacket(other, other.followTarget)) } else if other.motion != nil && other.motion.moving { updates = append(updates, npcRoutePacket(other, other.position)) diff --git a/server/ip_training_test.go b/server/ip_training_test.go @@ -73,7 +73,7 @@ func TestSkillTrainingAppliesAbilityDependenciesTogetherWithoutFreeHealing(t *te health, nano := player.health, player.nano observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:]) restored := newTestInventoryServer(t).characters[1] diff --git a/server/kill_experience_rules_test.go b/server/kill_experience_rules_test.go @@ -158,7 +158,7 @@ func TestKillExperienceUsesReachedTitleForIP(t *testing.T) { observer := world.newCharacter() observer.playfield = 950 otherOutput := &combatTestConn{} - world.clients[2] = &worldClient{id: 2, conn: otherOutput, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, conn: otherOutput, target: true, ready: true, players: map[uint32]bool{1: true}, npcs: map[uint32]bool{1000000: true}} attackForExperience(t, world, "unarmed") restored := newTestInventoryServer(t).characters[1] diff --git a/server/kill_experience_test.go b/server/kill_experience_test.go @@ -82,7 +82,7 @@ func TestKillExperienceAdvancesAllAttackPathsOnce(t *testing.T) { t.Fatal(err) } otherOutput := &combatTestConn{} - world.clients[2] = &worldClient{id: 2, conn: otherOutput, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, conn: otherOutput, target: true, ready: true, players: map[uint32]bool{1: true}, npcs: map[uint32]bool{1000000: true}} attackForExperience(t, world, attack) world.advanceCombat(time.Now().Add(time.Hour)) diff --git a/server/map_upload_test.go b/server/map_upload_test.go @@ -290,7 +290,7 @@ func TestMapUploadEffectiveSkillBoundaryAndOwnerOnlyDelivery(t *testing.T) { player.stats.Navigation.MapNavigation = scenario.raw observer := &combatTestConn{} world.characters[2] = &character{id: 2, health: 100, playfield: player.playfield} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) diff --git a/server/metaplast_test.go b/server/metaplast_test.go @@ -45,7 +45,7 @@ func TestMetaplastNativeWearRemoveAndRestart(t *testing.T) { } observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} original := player.inventory.Items[1] request := inventoryMovePacket(1, 49, piece.slot)[20:] diff --git a/server/mission_boundaries_test.go b/server/mission_boundaries_test.go @@ -67,6 +67,8 @@ func newMissionBoundaryWorld(t *testing.T) (*server, [3]*combatTestConn) { } world.updateNPCInterest(client, time.Now()) } + world.clients[1].players = map[uint32]bool{3: true} + world.clients[3].players = map[uint32]bool{1: true} for _, output := range outputs { output.packets = nil } diff --git a/server/mission_entrance_test.go b/server/mission_entrance_test.go @@ -294,7 +294,7 @@ func TestMissionMovementCorrectsRejectedReportsForOwnerAndObservers(t *testing.T owner, observer := &combatTestConn{}, &combatTestConn{} client.conn = owner world.characters[2] = &character{id: 2, playfield: 9000001, health: 100} - world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer} before := player.position requester := *player requester.position = [3]float32{5, .011, 16} diff --git a/server/mouse_movement_test.go b/server/mouse_movement_test.go @@ -34,7 +34,7 @@ func TestMouseMovementRelaysFacingAndCheckpointsWithoutPerPacketWrites(t *testin client := &worldClient{id: 1, target: true, ready: true, conn: owner} world.clients[1] = client world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer} now := time.Now() player.nextPositionSave = now.Add(20 * time.Second) auditCheckpointWrites(t, world) @@ -189,7 +189,7 @@ func TestMouseMovementNativeTransportAndLateObserver(t *testing.T) { } } observer := &combatTestConn{} - observerClient := &worldClient{id: 2, conn: observer, target: true, ready: true} + observerClient := &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} world.newCharacter().playfield = 950 world.newCharacter().playfield = 950 shutdown := startTestService(t, world) diff --git a/server/movement_yaw_test.go b/server/movement_yaw_test.go @@ -75,7 +75,7 @@ func TestMovementYawOffsetRelayKeepsTheOriginalPoseAndScalar(t *testing.T) { player.rotation = [4]float32{0, 0, 0, 1} observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer} request := playerMovementRequest(player, 20) binary.BigEndian.PutUint16(request[len(request)-2:], 2048) diff --git a/server/nano_buffs_test.go b/server/nano_buffs_test.go @@ -82,7 +82,8 @@ func TestNanoBuffFriendlyTargetAndObserverReceiveRecipientEffect(t *testing.T) { recipient.id, recipient.name, recipient.position = 2, "Recipient", [3]float32{0, 0, 12} world.characters[2], world.nextCharacter = &recipient, 2 recipientConn := &combatTestConn{} - world.clients[2] = &worldClient{id: 2, conn: recipientConn, ready: true, target: true} + world.clients[1].players = map[uint32]bool{2: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: recipientConn, ready: true, target: true} if err := world.saveUser(&recipient); err != nil { t.Fatal(err) } @@ -109,7 +110,8 @@ func TestNanoBuffRejectsInvalidAdmission(t *testing.T) { recipient := *player recipient.id = 2 world.characters[2] = &recipient - world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true} + world.clients[1].players = map[uint32]bool{2: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: &combatTestConn{}, ready: true, target: true} target := uint32(2) targetType := uint32(50000) switch scenario { @@ -340,7 +342,8 @@ func TestNanoBuffReadyBroadcastReplaysOnceToObservers(t *testing.T) { castTestBuff(t, world, 1, 1, 27169) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 1} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true} + world.clients[1].players = map[uint32]bool{2: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true, target: true} world.clients[1].loading = true conn.packets = nil diff --git a/server/nano_casting_test.go b/server/nano_casting_test.go @@ -35,7 +35,7 @@ func TestWinterBiteTimesOneResultAndRecharge(t *testing.T) { request := characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true, npcs: map[uint32]bool{npc.id: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true, target: true, npcs: map[uint32]bool{npc.id: true}} if err := world.handleNanoCast(client, request); err != nil { t.Fatal(err) diff --git a/server/nano_control_movement_test.go b/server/nano_control_movement_test.go @@ -211,7 +211,7 @@ func TestControlRootLateObserverReplaysEffectWithoutARoute(t *testing.T) { at := castTestBuff(t, world, 1, target.id, 42110) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: make(map[uint32]bool)} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: make(map[uint32]bool)} world.lastNPCUpdate = at world.advanceNPCs(at.Add(250 * time.Millisecond)) diff --git a/server/nano_healing_test.go b/server/nano_healing_test.go @@ -28,7 +28,7 @@ func TestHealingCrystalUploadCommitsProgramAndConsumption(t *testing.T) { world, conn := newHealingCrystalWorld(t) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true, target: true} err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) restored := newTestInventoryServer(t).characters[1] diff --git a/server/nano_kit_test.go b/server/nano_kit_test.go @@ -99,7 +99,8 @@ func TestNanoKitRejectsInvalidUseAndFailedSave(t *testing.T) { player, client := world.characters[1], world.clients[1] target := &character{id: 2, playfield: player.playfield, level: 1, appearance: 277, health: 10} world.characters[2] = target - world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true} + world.clients[1].players = map[uint32]bool{2: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: &combatTestConn{}, ready: true} client.selectedTarget = [2]uint32{50000, 2} request := backpackUseRequest(1, 64, 1)[20:] switch scenario { @@ -150,10 +151,11 @@ func TestNanoKitRestoresFriendAtNativeRangeDuringCombat(t *testing.T) { t.Fatal(err) } friendConn := &combatTestConn{} - world.clients[2] = &worldClient{id: 2, conn: friendConn, target: true, ready: true} + world.clients[1].players = map[uint32]bool{2: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: friendConn, target: true, ready: true} observerConn := &combatTestConn{} world.characters[3] = &character{id: 3, playfield: player.playfield} - world.clients[3] = &worldClient{id: 3, conn: observerConn, target: true, ready: true} + world.clients[3] = &worldClient{id: 3, players: map[uint32]bool{1: true, 2: true}, conn: observerConn, target: true, ready: true} client.selectedTarget = [2]uint32{50000, 2} player.fighting = 1000000 diff --git a/server/nano_learning_test.go b/server/nano_learning_test.go @@ -89,7 +89,7 @@ func TestNanoCrystalLearnsAndConsumesOnceAcrossRestart(t *testing.T) { client := world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) restored := newTestInventoryServer(t).characters[1] diff --git a/server/ncu_hacker_interface_test.go b/server/ncu_hacker_interface_test.go @@ -34,7 +34,7 @@ func TestNCUHackerInterfaceQualityWearRemoveAndRestart(t *testing.T) { } observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} if err := world.handleInventory(client, inventoryMovePacket(1, 64, 15)[20:]); err != nil || client.equipment == nil { t.Fatal("HUD2 wear rejected", err) diff --git a/server/npc_combat_test.go b/server/npc_combat_test.go @@ -104,7 +104,7 @@ func TestNPCProfileCombatUsesCatalogTimingAndDamageForBothObservers(t *testing.T observer := world.newCharacter() first, second := &combatTestConn{}, &combatTestConn{} world.clients[player.id] = &worldClient{id: player.id, conn: first, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} - world.clients[observer.id] = &worldClient{id: observer.id, conn: second, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[observer.id] = &worldClient{id: observer.id, conn: second, target: true, ready: true, players: map[uint32]bool{player.id: true}, npcs: map[uint32]bool{1000000: true}} npc := world.characters[1000000] if err := world.handleCombat(world.clients[player.id], attackPacket(player.id, npc.id)[20:]); err != nil { diff --git a/server/npc_levels_test.go b/server/npc_levels_test.go @@ -67,7 +67,7 @@ func TestNPCLevelTwoUsesInterpolatedBiteForBothObservers(t *testing.T) { player, observer := world.newCharacter(), world.newCharacter() first, second := &combatTestConn{}, &combatTestConn{} world.clients[player.id] = &worldClient{id: player.id, conn: first, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} - world.clients[observer.id] = &worldClient{id: observer.id, conn: second, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[observer.id] = &worldClient{id: observer.id, conn: second, target: true, ready: true, players: map[uint32]bool{player.id: true}, npcs: map[uint32]bool{1000000: true}} npc := world.characters[1000000] if err := world.handleCombat(world.clients[player.id], attackPacket(player.id, npc.id)[20:]); err != nil { diff --git a/server/npc_navigation_test.go b/server/npc_navigation_test.go @@ -253,7 +253,7 @@ func TestMissionNPCNewObserverReceivesTheRemainingDetourAfterSpawn(t *testing.T) advanceNavigationForTest(t, world, start.Add(250 * time.Millisecond), world.advanceNPCs) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 65536, position: player.position} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: make(map[uint32]bool)} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: make(map[uint32]bool)} advanceNavigationForTest(t, world, start.Add(500 * time.Millisecond), world.advanceNPCs) diff --git a/server/npc_pursuit_test.go b/server/npc_pursuit_test.go @@ -171,7 +171,7 @@ func TestNPCPursuitJoiningObserverGetsSpawnBeforeRouteAndAttack(t *testing.T) { world.advanceNPCs(start.Add(250 * time.Millisecond)) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: make(map[uint32]bool)} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: make(map[uint32]bool)} world.advanceNPCs(start.Add(500 * time.Millisecond)) diff --git a/server/npc_threat_test.go b/server/npc_threat_test.go @@ -10,7 +10,8 @@ func newThreatWorld(t *testing.T) (*server, *combatTestConn) { t.Helper() world, conn := newCombatWorld(t) world.characters[2] = &character{id: 2, playfield: 950, health: 100, stats: testCharacterStats()} - world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[1].players = map[uint32]bool{2: true} + world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, players: map[uint32]bool{1: true}, npcs: map[uint32]bool{1000000: true}} return world, conn } diff --git a/server/overequipping_test.go b/server/overequipping_test.go @@ -124,7 +124,7 @@ func TestOverequippingNativeDamageMatchesBothObservers(t *testing.T) { player.stats.Body.Brawling = 1 observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} owner.packets = nil world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]) diff --git a/server/owned_item_use_test.go b/server/owned_item_use_test.go @@ -69,7 +69,7 @@ func TestUnsupportedWornItemUseRepliesWithoutChangingEquipment(t *testing.T) { world.advanceEquipment(client.equipment.readyAt) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} before, err := readTestItemStore(world) if err != nil { t.Fatal(err) diff --git a/server/pet_dismiss_test.go b/server/pet_dismiss_test.go @@ -102,7 +102,7 @@ func TestPetDismissRejectsForeignOwnerAndSelectors(t *testing.T) { switch scenario { case "foreign actor", "other owner": world.characters[2] = &character{id: 2, playfield: 950, health: 100} - client = &worldClient{id: 2, target: true, ready: true, conn: &combatTestConn{}} + client = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: &combatTestConn{}} world.clients[2] = client if scenario == "other owner" { binary.BigEndian.PutUint32(request[8:], 2) @@ -136,7 +136,7 @@ func TestPetDismissNotifiesAnObserverStillLoadingItsSnapshot(t *testing.T) { world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, target: true, ready: true, loading: true, conn: observer, npcs: map[uint32]bool{1000001: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, loading: true, conn: observer, npcs: map[uint32]bool{1000001: true}} err := world.handlePetCommand(client, petDismissRequest(1)[20:]) diff --git a/server/pet_messages.go b/server/pet_messages.go @@ -31,7 +31,7 @@ func (command petRetired) execute(state *server) error { delete(owner.pets, command.pet) updates := make(map[*worldClient][][]byte) for id, client := range state.clients { - if client.ready && state.characters[id].playfield == owner.playfield { + if client.ready && client.sees(owner) && state.characters[id].playfield == owner.playfield { updates[client] = append(updates[client], petIdentityPacket(0x58742a0f, owner.id, command.pet), petCounterPacket(owner)) } } diff --git a/server/pet_retreat_test.go b/server/pet_retreat_test.go @@ -22,7 +22,7 @@ func TestPetRetreatAndWaitCancelOnlyOwnedOutgoingCombat(t *testing.T) { target := &character{id: 2, playfield: owner.playfield, position: pet.position, health: 100, stats: testCharacterStats()} peerOutput := &combatTestConn{} world.characters[2] = target - world.clients[2] = &worldClient{id: 2, conn: peerOutput, ready: true, target: true, npcs: map[uint32]bool{pet.id: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: peerOutput, ready: true, target: true, npcs: map[uint32]bool{pet.id: true}} updates := make(map[*worldClient][][]byte) now := time.Now() pet.rechargeUntil = now.Add(time.Second) diff --git a/server/pet_wait_test.go b/server/pet_wait_test.go @@ -63,7 +63,7 @@ func TestPetOwnerReadyReplaysMembershipAfterActorLoading(t *testing.T) { world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: observer, npcs: map[uint32]bool{1000001: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer, npcs: map[uint32]bool{1000001: true}} client.loading = true output.packets = nil diff --git a/server/pets.go b/server/pets.go @@ -79,14 +79,21 @@ func petCounterPacket(owner *character) []byte { return n3Packet(0x2b333d6e, 50000, owner.id, body) } -func (server *server) petOwnerPackets(owner *character) [][]byte { +func petMembershipPackets(owner *character) [][]byte { if len(owner.pets) == 0 { return nil } packets := [][]byte{petCounterPacket(owner)} for id := range owner.pets { - pet := server.characters[id] packets = append(packets, petIdentityPacket(0x194e4f76, owner.id, id)) + } + return packets +} + +func (server *server) petOwnerPackets(owner *character) [][]byte { + packets := petMembershipPackets(owner) + for id := range owner.pets { + pet := server.characters[id] if pet != nil && pet.followTarget != 0 && pet.playfield == owner.playfield && !pet.pet.paused { packets = append(packets, petFollowPacket(pet, owner.id)) } @@ -215,8 +222,10 @@ func (server *server) removePet(pet *character, updates map[*worldClient][][]byt if !client.ready || client.id != pet.pet.owner && server.characters[client.id].playfield != pet.playfield { continue } - updates[client] = append(updates[client], petIdentityPacket(0x58742a0f, pet.pet.owner, pet.id)) - if owner != nil { + if client.seesPlayer(pet.pet.owner) { + updates[client] = append(updates[client], petIdentityPacket(0x58742a0f, pet.pet.owner, pet.id)) + } + if owner != nil && client.sees(owner) { updates[client] = append(updates[client], petCounterPacket(owner)) } if client.npcs[pet.id] { diff --git a/server/player_altitude_test.go b/server/player_altitude_test.go @@ -80,7 +80,7 @@ func TestPlayerAltitudeRunsBeforeCharacterReadyAndReplicatesOnce(t *testing.T) { observer, elsewhere, unready := &combatTestConn{}, &combatTestConn{}, &combatTestConn{} for id, connection := range map[uint32]*combatTestConn{2: observer, 3: elsewhere, 4: unready} { world.characters[id] = &character{id: id, playfield: 705, health: 100} - world.clients[id] = &worldClient{id: id, ready: id != 4, loading: true, target: true, conn: connection} + world.clients[id] = &worldClient{id: id, ready: id != 4, loading: true, target: true, conn: connection, players: map[uint32]bool{1: true}} } world.characters[3].playfield = 1001 started := time.Now() diff --git a/server/player_death_test.go b/server/player_death_test.go @@ -38,7 +38,7 @@ func TestPlayerDeathRemovesBuffsAndCommitsReclaimBeforeCheckpoint(t *testing.T) player := world.characters[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 705, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} owner.packets = nil fatal := defeatReclaimPlayer(t, world) diff --git a/server/player_flight_input_test.go b/server/player_flight_input_test.go @@ -14,7 +14,7 @@ func TestPlayerMovementRejectsEquipmentAndUnknownEvents(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 705, health: 100} - world.clients[2] = &worldClient{id: 2, ready: true, target: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, target: true, conn: observer} world.characters[1000000].playfield = 705 player.followTarget = 1000000 player.nextPositionSave = time.Time{} @@ -44,7 +44,7 @@ func TestPlayerMovementProcessesValidInputAfterAnUnsupportedNativePacket(t *test player := world.characters[1] position := player.position world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, ready: true, target: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, target: true, conn: observer} forged := *player forged.position[0] = 70 invalid := targetPacket(npcMovementPacket(&forged, 27)) diff --git a/server/player_flight_modes_test.go b/server/player_flight_modes_test.go @@ -27,7 +27,7 @@ func TestPlayerFlightWalkAndRunPreserveUnrelatedMotionAndEquipment(t *testing.T) body, item := player.body, player.inventory.Items[0] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 705, health: 100} - world.clients[2] = &worldClient{id: 2, ready: true, target: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, target: true, conn: observer} if err := world.handleMovement(client, playerMovementRequest(player, action)); err != nil { t.Fatal(err) @@ -185,7 +185,7 @@ func TestPlayerFlightGroundModeReplayedAfterWearForNewObserver(t *testing.T) { } world.nextCharacter = 1 observer := world.newCharacter() - observer.playfield = 705 + observer.playfield, observer.position = 705, player.position if following { player.followTarget = observer.id } diff --git a/server/player_flight_test.go b/server/player_flight_test.go @@ -153,7 +153,7 @@ func TestPlayerFlightReadyAnchorsOwnerAndObserversWithoutAnotherLift(t *testing. player.position, player.movement = [3]float32{961.625, 60, 510.75}, playerMovement{} observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 705, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true} owner := client.conn.(*combatTestConn) client.target = false owner.packets = nil @@ -308,7 +308,7 @@ func TestPlayerFlightLateObserverReceivesAnIdlePositionAnchor(t *testing.T) { world.advanceEquipment(client.equipment.readyAt) world.characters[2] = &character{id: 2, playfield: 705, health: 100} connection := &combatTestConn{} - world.clients[2] = &worldClient{id: 2, conn: connection, ready: true, loading: true} + world.clients[2] = &worldClient{id: 2, conn: connection, ready: true, loading: true, players: map[uint32]bool{1: true}} if err := world.handleCharacterReady(world.clients[2]); err != nil { t.Fatal(err) diff --git a/server/player_follow.go b/server/player_follow.go @@ -51,7 +51,7 @@ func (server *server) playerFollowTargetAvailable(client *worldClient, target *c return client.npcs[target.id] } other := server.clients[target.id] - return other != nil && other.ready && !other.loading + return client.seesPlayer(target.id) && other != nil && other.ready && !other.loading } func playerFollowPacket(id, target uint32) []byte { @@ -70,12 +70,12 @@ func (server *server) playerFollowReplay(observer *worldClient, spawned map[uint var packets [][]byte for id, client := range server.clients { player := server.characters[id] - if player.followTarget == 0 || !client.ready || client.loading || server.characters[id].playfield != server.characters[observer.id].playfield { + if !observer.seesPlayer(id) || player.followTarget == 0 || !client.ready || client.loading || server.characters[id].playfield != server.characters[observer.id].playfield { continue } target := server.characters[player.followTarget] - if !server.playerFollowTargetAvailable(client, target) || target.npc && !observer.npcs[target.id] || - spawned != nil && !spawned[target.id] { + if !server.playerFollowTargetAvailable(client, target) || !observer.sees(target) || + spawned != nil && !spawned[target.id] && !spawned[id] { continue } packets = append(packets, playerMovementMassPackets(player)...) @@ -86,15 +86,23 @@ func (server *server) playerFollowReplay(observer *worldClient, spawned map[uint } packets = append(packets, packet) } + // A known pet can regain its controller when its owner enters visibility. + for id := range observer.npcs { + pet := server.characters[id] + if pet != nil && pet.pet != nil && !pet.pet.paused && pet.followTarget != 0 && observer.seesPlayer(pet.followTarget) && + spawned != nil && spawned[pet.followTarget] && !spawned[id] { + packets = append(packets, petFollowPacket(pet, pet.followTarget)) + } + } return packets } -func (server *server) playerMovementReplay(observer *worldClient, now time.Time) [][]byte { +func (server *server) playerMovementReplay(observer *worldClient, now time.Time, spawned map[uint32]bool) [][]byte { // Refresh pose and initialize direction omitted by the native vehicle reader. var packets [][]byte for id, client := range server.clients { player := server.characters[id] - if id == observer.id || !client.ready || client.loading || player.playfield != server.characters[observer.id].playfield { + if id == observer.id || !observer.players[id] || spawned != nil && !spawned[id] || !client.ready || client.loading || player.playfield != server.characters[observer.id].playfield { continue } // Worn flight effects replay after the snapshot and can replace its ground mode. diff --git a/server/player_follow_test.go b/server/player_follow_test.go @@ -17,9 +17,10 @@ func TestPlayerFollowNativeWorldRequestReachesOwnerAndObserver(t *testing.T) { startTestService(t, world) client := connectZoningClient(t, world, true) observer := &combatTestConn{} - observerClient := &worldClient{id: 2, target: true, ready: true, conn: observer} + observerClient := &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer} callTestZone(t, world, 1, zoneTestCommand(func(state *server) error { state.clients[2] = observerClient + state.clients[1].players = map[uint32]bool{2: true} return nil })) // Captured /follow: owned subject, selected target, distance2.5, no correction/path. @@ -170,7 +171,8 @@ func TestPlayerFollowAcceleratesAndArrivesWithoutNativeMovementSnapshots(t *test func TestPlayerFollowChainsUseOneTargetSnapshot(t *testing.T) { world, _ := newCombatWorld(t) world.characters[2] = &character{id: 2, playfield: 950, health: 100, position: [3]float32{10, 0, 0}} - world.clients[2] = &worldClient{id: 2, ready: true, target: true, conn: &combatTestConn{}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, target: true, conn: &combatTestConn{}} + world.clients[1].players = map[uint32]bool{2: true} if err := world.handlePlayerFollow(world.clients[1], playerFollowRequest(2)); err != nil { t.Fatal(err) } @@ -236,9 +238,10 @@ func TestPlayerFollowTargetLossClearsNativeController(t *testing.T) { func TestPlayerFollowMovementCheckpointsWithoutTickDatabaseWrites(t *testing.T) { world := newCheckpointWorld(t) world.characters[2] = &character{id: 2, playfield: 950, health: 100, position: [3]float32{80, 14, 56}} - world.clients[2] = &worldClient{id: 2, ready: true, conn: &combatTestConn{}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, conn: &combatTestConn{}} client := &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}} world.clients[1] = client + client.players = map[uint32]bool{2: true} if err := world.handlePlayerFollow(client, playerFollowRequest(2)); err != nil { t.Fatal(err) } @@ -462,8 +465,9 @@ func TestPlayerFollowRetargetingPreservesVelocity(t *testing.T) { world.advancePlayerMovement(world.characters[client.id].movement.updatedAt.Add(100 * time.Millisecond)) velocity := world.characters[client.id].movement.velocity world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, ready: true, conn: &combatTestConn{}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, conn: &combatTestConn{}} + client.players = map[uint32]bool{2: true} err := world.handlePlayerFollow(client, playerFollowRequest(2)) if err != nil || world.characters[client.id].followTarget != 2 || world.characters[client.id].movement.velocity != velocity { @@ -495,7 +499,7 @@ func TestPlayerFollowChecksTradeRangeAfterBothTradersMove(t *testing.T) { world.characters[1000000].position = [3]float32{0, 0, 30} world.characters[2] = &character{id: 2, playfield: 950, health: 100, position: [3]float32{4.99999, 0, 0}} world.characters[1000001] = &character{id: 1000001, npc: true, playfield: 950, health: 100, position: [3]float32{4.99999, 0, 30}} - world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: &combatTestConn{}, npcs: map[uint32]bool{1000001: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: &combatTestConn{}, npcs: map[uint32]bool{1000001: true}} playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{}) if world.clients[1].trade == nil { t.Fatal("trade was not admitted") diff --git a/server/player_interest.go b/server/player_interest.go @@ -0,0 +1,127 @@ +package main + +import ( + "math" + "time" +) + +func (client *worldClient) seesPlayer(id uint32) bool { + return client.id == id || client.players[id] +} + +func (client *worldClient) sees(actor *character) bool { + if actor.npc { + return client.npcs[actor.id] + } + return client.seesPlayer(actor.id) +} + +func (server *server) playerSnapshot(observer *worldClient, player *character, now time.Time) [][]byte { + // Fresh actors apply their equipment modifiers after the snapshot. + observer.players[player.id] = true + delete(observer.absorbedBonuses, player.id) + snapshot := player.predictedMovement(now) + packets := [][]byte{characterPacket(&snapshot), characterTitlePacket(player)} + if !server.clients[player.id].loading { + packets = append(packets, playerCombatStatPackets(player)...) + packets = append(packets, equippedItemPackets(player)...) + packets = append(packets, activeNanoPackets(player, now)...) + } + packets = append(packets, petMembershipPackets(player)...) + if player.health == 0 { + packets = append(packets, deathPacket(player)) + } + return append(packets, n3Packet(0x570c2039, 50000, player.id, nil)) +} + +func (server *server) forgetPlayer(observer *worldClient, id uint32) [][]byte { + // Stop controllers that reference the departing actor before deleting it. + var packets [][]byte + for _, attacker := range server.fighting { + if attacker.fighting == id && observer.sees(attacker) { + packets = append(packets, stopFightPacket(attacker.id)) + } + } + for other := range server.clients { + if observer.seesPlayer(other) && server.characters[other].followTarget == id { + packets = append(packets, playerFollowPacket(other, 0)) + } + } + for other := range observer.npcs { + pet := server.characters[other] + if pet != nil && pet.pet != nil && pet.followTarget == id { + packets = append(packets, petFollowPacket(pet, 0)) + } + } + delete(observer.players, id) + delete(observer.absorbedBonuses, id) + return append(packets, n3Packet(0x36510078, 50000, id, nil)) +} + +func (server *server) refreshPlayerInterest(now time.Time) { + // Build once per interest pass. Cells exclude offline characters and are owned + // by this zone; teleports and ordinary movement need no separate index writes. + type cell struct { + playfield uint32 + x, z int + } + cells := make(map[cell][]*worldClient) + for id, client := range server.clients { + if client.ready { + player := server.characters[id] + key := cell{player.playfield, int(math.Floor(float64(player.position[0]) / 200)), int(math.Floor(float64(player.position[2]) / 200))} + cells[key] = append(cells[key], client) + } + } + updates := make(map[*worldClient][][]byte) + for id, observer := range server.clients { + if !observer.ready || observer.loading { + continue + } + player := server.characters[id] + if observer.players == nil { + observer.players = make(map[uint32]bool) + } + for other := range observer.players { + peer := server.clients[other] + actor := server.characters[other] + if peer != nil && peer.ready && actor.playfield == player.playfield { + x, z := player.position[0]-actor.position[0], player.position[2]-actor.position[2] + if x*x+z*z <= 200*200 { + continue + } + } + updates[observer] = append(updates[observer], server.forgetPlayer(observer, other)...) + } + + // Hysteresis matches NPC interest. Queue all snapshots before controllers + // so combat and follow never reference a participant that has not spawned. + var spawned map[uint32]bool + x, z := int(math.Floor(float64(player.position[0])/200)), int(math.Floor(float64(player.position[2])/200)) + for dx := -1; dx <= 1; dx++ { + for dz := -1; dz <= 1; dz++ { + for _, peer := range cells[cell{player.playfield, x + dx, z + dz}] { + if observer.seesPlayer(peer.id) { + continue + } + actor := server.characters[peer.id] + x, z := player.position[0]-actor.position[0], player.position[2]-actor.position[2] + if x*x+z*z > 180*180 { + continue + } + if spawned == nil { + spawned = make(map[uint32]bool) + } + spawned[peer.id] = true + updates[observer] = append(updates[observer], server.playerSnapshot(observer, actor, now)...) + } + } + } + if len(spawned) != 0 { + updates[observer] = append(updates[observer], server.playerMovementReplay(observer, now, spawned)...) + updates[observer] = append(updates[observer], server.combatInterest(observer, spawned)...) + updates[observer] = append(updates[observer], server.playerFollowReplay(observer, spawned)...) + } + } + server.sendCombatUpdates(updates) +} diff --git a/server/player_interest_test.go b/server/player_interest_test.go @@ -0,0 +1,177 @@ +package main + +import ( + "encoding/binary" + "testing" + "time" +) + +func joinInterestPlayer(t *testing.T, world *server, id uint32, x float32) (*worldClient, *combatInterestConn) { + t.Helper() + player := world.characters[id] + if player == nil { + player = world.newCharacter() + if player.id != id { + t.Fatal("unexpected fixture identity", player.id) + } + } + player.playfield, player.position, player.rotation = 950, [3]float32{x, 14, 56}, [4]float32{0, 0, 0, 1} + if err := world.saveUser(player); err != nil { + t.Fatal(err) + } + output := &combatInterestConn{} + client := &worldClient{conn: output, loading: true} + if err := world.joinWorldClient(client, id); err != nil { + t.Fatal(err) + } + if err := world.handleCharacterReady(client); err != nil { + t.Fatal(err) + } + return client, output +} + +func actorPacketCount(output *combatInterestConn, opcode, actor uint32) int { + count := 0 + for _, packet := range output.packets { + if binary.BigEndian.Uint16(packet[2:4]) == 10 && binary.BigEndian.Uint32(packet[20:24]) == opcode && binary.BigEndian.Uint32(packet[28:32]) == actor { + count++ + } + } + return count +} + +func TestPlayerInterestBoundaryAndDistantBroadcasts(t *testing.T) { + world := newCheckpointWorld(t) + first, output := joinInterestPlayer(t, world, 1, 500) + second, _ := joinInterestPlayer(t, world, 2, 681) + if first.players[2] || second.players[1] || actorPacketCount(output, 0x271b3a6b, 2) != 0 { + t.Fatal("distant player was included in login") + } + output.packets = nil + + world.characters[2].position[0] = 680 + world.advanceActions(time.Now()) + if !first.players[2] || !second.players[1] || actorPacketCount(output, 0x271b3a6b, 2) != 1 { + t.Fatal("player did not enter at 180 metres") + } + world.characters[2].position[0] = 700 + world.advanceActions(time.Now()) + if !first.players[2] || actorPacketCount(output, 0x36510078, 2) != 0 { + t.Fatal("boundary margin removed a visible player") + } + world.characters[2].position[0] = 701 + world.advanceActions(time.Now()) + if first.players[2] || second.players[1] || actorPacketCount(output, 0x36510078, 2) != 1 { + t.Fatal("player did not leave beyond 200 metres") + } + output.packets = nil + if err := world.handlePosture(second, characterActionPacket(2, [5]uint32{86})[20:]); err != nil { + t.Fatal(err) + } + second.regenerationAt = time.Now().Add(-2 * time.Second) + world.advanceRegeneration(time.Now()) + if actorPacketCount(output, 0x5e477770, 2) != 0 || actorPacketCount(output, 0x3710256c, 2) != 0 { + t.Fatal("distant posture or health reached an observer", output.packets) + } + + world.characters[2].position[0] = 680 + world.advanceActions(time.Now()) + if actorPacketCount(output, 0x271b3a6b, 2) != 1 || actorPacketCount(output, 0x570c2039, 2) != 1 { + t.Fatal("returning player did not receive a complete fresh actor") + } + world.leaveWorldClient(second) + if first.players[2] || actorPacketCount(output, 0x36510078, 2) != 1 { + t.Fatal("departure retained a visible actor") + } +} + +func TestPlayerInterestReplaysFollowAfterBothSnapshots(t *testing.T) { + world := newCheckpointWorld(t) + follower, _ := joinInterestPlayer(t, world, 1, 590) + _, _ = joinInterestPlayer(t, world, 2, 670) + observer, output := joinInterestPlayer(t, world, 3, 500) + follower.target = true + if err := world.handlePlayerFollow(follower, playerFollowRequest(2)); err != nil { + t.Fatal(err) + } + output.packets = nil + + world.characters[2].position[0] = 701 + world.advanceActions(time.Now()) + if observer.players[2] || !follower.players[2] || world.characters[1].followTarget != 2 { + t.Fatal("observer visibility changed the owner's follow") + } + stop, removed := -1, -1 + for index, packet := range output.packets { + if binary.BigEndian.Uint32(packet[20:24]) == 0x260f3671 && binary.BigEndian.Uint32(packet[28:32]) == 1 && binary.BigEndian.Uint32(packet[40:44]) == 0 { + stop = index + } + if binary.BigEndian.Uint32(packet[20:24]) == 0x36510078 && binary.BigEndian.Uint32(packet[28:32]) == 2 { + removed = index + } + } + if stop < 0 || removed <= stop { + t.Fatal("follow target disappeared before its observer controller stopped", stop, removed) + } + output.packets = nil + world.characters[2].position[0] = 680 + world.advanceActions(time.Now()) + spawn, follow := -1, -1 + for index, packet := range output.packets { + if binary.BigEndian.Uint32(packet[20:24]) == 0x271b3a6b && binary.BigEndian.Uint32(packet[28:32]) == 2 { + spawn = index + } + if binary.BigEndian.Uint32(packet[20:24]) == 0x260f3671 && binary.BigEndian.Uint32(packet[28:32]) == 1 && binary.BigEndian.Uint32(packet[40:44]) == 2 { + follow = index + } + } + if spawn < 0 || follow <= spawn { + t.Fatal("follow did not resume after its target snapshot", spawn, follow) + } +} + +func TestPlayerInterestPetFollowWaitsForActorSnapshots(t *testing.T) { + for _, reentry := range []bool{false, true} { + t.Run(map[bool]string{false: "login", true: "reentry"}[reentry], func(t *testing.T) { + world, _ := newPetSummonWorld(t) + client := world.clients[1] + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]); err != nil { + t.Fatal(err) + } + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + if err := world.handlePetCommand(client, petFollowRequest(1)[20:]); err != nil { + t.Fatal(err) + } + world.nextCharacter = 1 + observer, output := joinInterestPlayer(t, world, 2, 50) + if reentry { + world.characters[1].position[0] = 251 + world.advanceActions(time.Now()) + if observer.players[1] || !observer.npcs[1000001] { + t.Fatal("fixture did not retain the pet while its owner left") + } + output.packets = nil + world.characters[1].position[0] = 0 + world.advanceActions(time.Now()) + } + + ownerSeen, petSeen, followed := false, reentry, 0 + for _, packet := range output.packets { + key, id := binary.BigEndian.Uint32(packet[20:24]), binary.BigEndian.Uint32(packet[28:32]) + if key == 0x271b3a6b { + ownerSeen = ownerSeen || id == 1 + petSeen = petSeen || id == 1000001 + } + if key == 0x260f3671 && id == 1000001 { + followed++ + if !ownerSeen || !petSeen { + t.Fatal("pet controller preceded a required actor snapshot") + } + } + } + if followed != 1 { + t.Fatal("pet controller was omitted or replayed twice", followed) + } + }) + } +} diff --git a/server/player_movement_mode_test.go b/server/player_movement_mode_test.go @@ -132,7 +132,7 @@ func TestPlayerRejectedSeatedControlStillPlacesAndRelaysPose(t *testing.T) { player.inventory, player.sitting = playerInventory{}, true observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, ready: true, target: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, target: true, conn: observer} player.followTarget = 1000000 reported := *player reported.position = [3]float32{2, 14, 4} diff --git a/server/player_movement_test.go b/server/player_movement_test.go @@ -318,7 +318,7 @@ func TestLateReverseFollowInitializesDirectionBeforeController(t *testing.T) { world.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: &combatTestConn{}, npcs: map[uint32]bool{1000000: true}} world.newCharacter().playfield = player.playfield connection := &combatTestConn{} - observer := &worldClient{id: 2, ready: true, loading: true, target: true, conn: connection, npcs: map[uint32]bool{1000000: true}} + observer := &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, loading: true, target: true, conn: connection, npcs: map[uint32]bool{1000000: true}} world.clients[2] = observer if err := world.handleCharacterReady(observer); err != nil { diff --git a/server/player_posture_test.go b/server/player_posture_test.go @@ -33,7 +33,7 @@ func TestPlayerSitUsesComponentAdmissionBeforeChangingRest(t *testing.T) { player.movement.deepWater = scenario.components[0] == 4 observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, ready: true, target: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, ready: true, target: true, conn: observer} request := make([]byte, 36) binary.BigEndian.PutUint32(request[16:], 86) diff --git a/server/player_sneak_test.go b/server/player_sneak_test.go @@ -94,7 +94,7 @@ func TestSneakEndsWhenAnAttackOrCastStarts(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true, target: true, npcs: map[uint32]bool{1000000: true}} if err := world.handleSneak(client, characterActionPacket(1, [5]uint32{163})[20:]); err != nil { t.Fatal(err) } diff --git a/server/progression.go b/server/progression.go @@ -120,7 +120,7 @@ func (server *server) applyExperienceAward(award *experienceAward, now time.Time visible = append(visible, [2]uint32{37, title}) } for id, observer := range server.clients { - if id == player.id || !observer.ready || observer.loading || server.characters[id].playfield != player.playfield { + if id == player.id || !observer.sees(player) || !observer.ready || observer.loading || server.characters[id].playfield != player.playfield { continue } for _, stat := range visible { diff --git a/server/ranged_test.go b/server/ranged_test.go @@ -37,7 +37,7 @@ func TestRangedShotConsumesOneRoundAtItsDeadlineForBothObservers(t *testing.T) { world, conn := newRangedWorld(t) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} world.characters[1].stats.Speed.MeleeInitiative = 1200 world.characters[1].stats.Melee.OneHandEdged = 800 world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) diff --git a/server/regeneration_nano_test.go b/server/regeneration_nano_test.go @@ -109,7 +109,7 @@ func TestRegenerationNanoDeathRemovesEffectsBeforeFurtherRecovery(t *testing.T) castTestBuff(t, world, 1, 1, fixture.program) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} owner.packets = nil fatal := defeatReclaimPlayer(t, world) diff --git a/server/regeneration_test.go b/server/regeneration_test.go @@ -101,7 +101,7 @@ func TestRegenerationIncomingCombatPublishesRecoveryWithoutChangingAttack(t *tes npc.regenerationAt = start.Add(time.Hour) peer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: peer, target: true, ready: true, regenerationAt: start.Add(time.Hour)} + world.clients[2] = &worldClient{id: 2, conn: peer, target: true, ready: true, players: map[uint32]bool{1: true}, regenerationAt: start.Add(time.Hour)} updates := make(map[*worldClient][][]byte) world.startAttack(npc, player, start, updates) world.sendCombatUpdates(updates) @@ -142,7 +142,7 @@ func TestRegenerationCorrectsAbsoluteIdleResourcesForOwnerAndObserver(t *testing world, conn, start := newRegenerationWorld(t) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} world.advanceRegeneration(start.Add(2 * time.Second)) diff --git a/server/remote_combat_stats_test.go b/server/remote_combat_stats_test.go @@ -30,7 +30,7 @@ func TestRemotePlayerSpawnCarriesUnmodifiedCombatFoundations(t *testing.T) { world.clients[1].loading = true } else if scenario == "new player" || scenario == "replacing player" { observer = &combatInterestConn{} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true, target: true} if scenario == "new player" { delete(world.clients, 1) } else { @@ -51,7 +51,7 @@ func TestRemotePlayerSpawnCarriesUnmodifiedCombatFoundations(t *testing.T) { return fmt.Errorf("loading actor received foundations before its ready notification") } } - state.clients[2] = &worldClient{id: 2, conn: observer, ready: true} + state.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true} return state.handleCharacterReady(state.clients[1]) })) } @@ -101,7 +101,7 @@ func TestRemoteAggDefChangesReachOnlyReadySamePlayfieldObservers(t *testing.T) { for index, conn := range connections { id := uint32(index + 2) world.characters[id] = &character{id: id, playfield: 950, health: 100} - world.clients[id] = &worldClient{id: id, conn: conn, target: true, ready: true} + world.clients[id] = &worldClient{id: id, conn: conn, target: true, ready: true, players: map[uint32]bool{1: true}} } world.clients[3].ready = false world.characters[4].playfield = 705 diff --git a/server/remote_reload_test.go b/server/remote_reload_test.go @@ -30,7 +30,7 @@ func newRemoteReloadWorld(t *testing.T) (*server, [3]*combatTestConn) { outsider := world.newCharacter() outsider.playfield = 952 connections := [3]*combatTestConn{owner, {}, {}} - world.clients[2] = &worldClient{id: 2, conn: connections[1], target: true, ready: true} + world.clients[2] = &worldClient{id: 2, conn: connections[1], target: true, ready: true, players: map[uint32]bool{1: true}} world.clients[3] = &worldClient{id: 3, conn: connections[2], target: true, ready: true} owner.packets = nil return world, connections diff --git a/server/resource_kit_test.go b/server/resource_kit_test.go @@ -331,7 +331,7 @@ func TestStartupLaboratoryPatientCooldownRangeBoundaryAndPrivateNano(t *testing. target.position[0] += 7 observer := &combatTestConn{} world.characters[3] = &character{id: 3, playfield: player.playfield, position: player.position, health: 100} - world.clients[3] = &worldClient{id: 3, conn: observer, target: true, ready: true} + world.clients[3] = &worldClient{id: 3, conn: observer, target: true, ready: true, players: map[uint32]bool{1: true, 2: true}} err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) deadline := target.skillLocks[124] diff --git a/server/resurrection_reconnect_test.go b/server/resurrection_reconnect_test.go @@ -62,8 +62,8 @@ func TestResurrectionReconnectResumesPendingDeath(t *testing.T) { belongings := player.inventory durableBelongings := newTestInventoryServer(t).characters[1].inventory observer := &combatTestConn{} - world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.characters[2] = &character{id: 2, playfield: 950, position: player.position, health: 100} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} if _, err := world.db.Exec("CREATE TABLE resurrection_writes (health INTEGER); CREATE TRIGGER record_resurrection AFTER UPDATE OF health ON characters WHEN NEW.id=1 AND OLD.health=0 AND NEW.health>0 BEGIN INSERT INTO resurrection_writes VALUES (NEW.health); END"); err != nil { t.Fatal(err) } diff --git a/server/resurrection_test.go b/server/resurrection_test.go @@ -89,7 +89,7 @@ func TestResurrectionOnlyOnceAndClearsCombatForBothObservers(t *testing.T) { } observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) world.advanceCombat(player.nextAttack) player.health = 0 diff --git a/server/roaming.go b/server/roaming.go @@ -21,6 +21,7 @@ type npcMotion struct { } func (server *server) advanceActions(now time.Time) { + server.refreshPlayerInterest(now) server.advanceMissions(now) server.advanceCorpseExpiry(now) server.advanceNPCRespawns(now) diff --git a/server/sixth_level_training_test.go b/server/sixth_level_training_test.go @@ -35,7 +35,7 @@ func TestEarnedSixthLevelUnlocksMeleeAndBodyDevelopmentTraining(t *testing.T) { t.Fatal(err) } otherOutput := &combatTestConn{} - world.clients[observer.id] = &worldClient{id: observer.id, conn: otherOutput, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + world.clients[observer.id] = &worldClient{id: observer.id, conn: otherOutput, target: true, ready: true, players: map[uint32]bool{player.id: true}, npcs: map[uint32]bool{1000000: true}} // The one-hit boss isolates level, IP and health bookkeeping. world.combatRoll = func(uint32) uint32 { return 0 } trained := player.baseStats() diff --git a/server/social_actions_test.go b/server/social_actions_test.go @@ -23,7 +23,7 @@ func TestSocialActionNativeDispatchDoesNotReplayGesturesToLateObservers(t *testi startTestService(t, world) client := connectZoningClient(t, world, true) observer := &combatTestConn{} - observerClient := &worldClient{id: 2, target: true, ready: true, conn: observer} + observerClient := &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer} callTestZone(t, world, 1, zoneTestCommand(func(state *server) error { state.clients[2] = observerClient return nil @@ -88,7 +88,7 @@ func TestSocialActionCompletesNativeCommandsWithoutDatabaseWrites(t *testing.T) client := &worldClient{id: 1, target: true, ready: true, conn: owner} world.clients[1] = client world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer} auditCheckpointWrites(t, world) for index, action := range []uint32{1, 61, 61, 63} { @@ -126,7 +126,7 @@ func TestSocialActionRejectsMalformedUnauthorizedAndUnsupportedRequests(t *testi client := world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer} body := socialActionRequest(61) malformed := false switch scenario { @@ -186,7 +186,7 @@ func TestSocialActionExcludesOtherPlayfieldsAndUnreadyObservers(t *testing.T) { world, owner := newCombatWorld(t) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer} if scenario == "other playfield" { world.characters[2].playfield = 705 } else { diff --git a/server/social_swimming_test.go b/server/social_swimming_test.go @@ -23,7 +23,7 @@ func TestSocialActionSwimmingRefusalPreservesMovementAndPendingReference(t *test owner, observer := &combatTestConn{}, &combatTestConn{} client.conn = owner world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer} before, vitals := player.movement, player.vitals() auditCheckpointWrites(t, world) diff --git a/server/stale_equipment_resources_test.go b/server/stale_equipment_resources_test.go @@ -37,7 +37,7 @@ func TestStaleWornSourceRefreshesDerivedResourcesOnce(t *testing.T) { } observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} before, err := readTestItemStore(world) if err != nil { t.Fatal(err) diff --git a/server/starter_weapons_test.go b/server/starter_weapons_test.go @@ -31,7 +31,7 @@ func TestStarterWeaponsEquipWithCatalogRequirementsAndRecover(t *testing.T) { before, _ := readTestItemStore(world) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} for profession := uint16(1); profession <= 12; profession++ { if scenario.profession == 0 || uint32(profession) == scenario.profession { diff --git a/server/state.go b/server/state.go @@ -86,6 +86,7 @@ type worldClient struct { regenerationAt time.Time regenerationSeconds uint32 npcs map[uint32]bool + players map[uint32]bool dialogue *npcDialogue equipment *equipmentMove wornRemoval [46][]byte @@ -107,12 +108,16 @@ type worldClient struct { } func (client *worldClient) send(packet []byte) error { - // Broadcasts and connection replies must not interleave on the TCP stream. - client.mutex.Lock() - defer client.mutex.Unlock() if client.target && binary.BigEndian.Uint16(packet[2:4]) == 10 { packet = targetPacket(append([]byte(nil), packet...)) } + return client.sendEncoded(packet) +} + +func (client *worldClient) sendEncoded(packet []byte) error { + // Copy before stamping the recipient; a broadcast shares its encoded bytes. + client.mutex.Lock() + defer client.mutex.Unlock() if client.writeWake == nil { packet = append([]byte(nil), packet...) binary.BigEndian.PutUint32(packet[12:16], client.id) @@ -259,13 +264,35 @@ func newPlayerCharacter(id uint32) *character { func (server *server) broadcast(playfield, exclude uint32, packet []byte) { // The zone owns the recipients; sending only enqueues bytes for their writers. key := binary.BigEndian.Uint32(packet[20:24]) + var native []byte for id, client := range server.clients { if id != exclude && client.ready && server.characters[id].playfield == playfield { + actor := binary.BigEndian.Uint32(packet[28:32]) + if binary.BigEndian.Uint32(packet[24:28]) == 50000 && !client.seesPlayer(actor) && !client.npcs[actor] { + continue + } + if key == 0x36510078 && binary.BigEndian.Uint32(packet[24:28]) == 50000 && client.players[actor] { + for _, removal := range server.forgetPlayer(client, actor) { + if err := client.send(removal); err != nil { + client.ready = false + client.disconnect(client.conn) + break + } + } + continue + } // A new or removed actor no longer has its previous resource snapshot basis. if (key == 0x271b3a6b || key == 0x36510078) && binary.BigEndian.Uint32(packet[24:28]) == 50000 { delete(client.absorbedBonuses, binary.BigEndian.Uint32(packet[28:32])) } - if err := client.send(packet); err != nil { + encoded := packet + if client.target { + if native == nil { + native = targetPacket(append([]byte(nil), packet...)) + } + encoded = native + } + if err := client.sendEncoded(encoded); err != nil { log.Printf("World broadcast: %v", err) client.ready = false client.disconnect(client.conn) diff --git a/server/stationary_clinic_test.go b/server/stationary_clinic_test.go @@ -338,7 +338,7 @@ func TestStationaryClinicLostReplyKeepsCommittedObserverOutcome(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 1183, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true, target: true} client.conn = &failingCombatConn{} failed := world.handleTerminalUse(client, stationaryClinicUseRequest(1)) diff --git a/server/team_resources.go b/server/team_resources.go @@ -48,7 +48,7 @@ func (server *server) queueTeamResources(updates map[*worldClient][][]byte, memb if id == member.id || client == nil || !client.ready || client.loading || server.characters[id].playfield != member.playfield { continue } - if !server.characterInCombat(member) { + if !server.characterInCombat(member) || !client.sees(member) { updates[client] = append(updates[client], server.teamResourcePacket(id, member)) continue } @@ -70,7 +70,7 @@ func (server *server) queueTeamResources(updates map[*worldClient][][]byte, memb func (server *server) queueResourceMaximum(updates map[*worldClient][][]byte, actor *character, stat, base uint32) { for id, client := range server.clients { - if !client.ready || server.characters[id].playfield != actor.playfield || + if !client.ready || !client.sees(actor) || server.characters[id].playfield != actor.playfield || stat == 221 && id != actor.id && (actor.team == nil || server.characters[id].team == nil || actor.team.id != server.characters[id].team.id) { continue } diff --git a/server/team_resources_test.go b/server/team_resources_test.go @@ -447,3 +447,56 @@ func TestTeamResourcesSkipUnavailableOrUnrelatedRecipients(t *testing.T) { }) } } + +func TestTeamResourcesOutsidePlayerInterestDoNotRequireAnActor(t *testing.T) { + world, connections := newTeamWorld(t) + formTestTeam(t, world, 1, 2) + delete(world.clients[2].players, 1) + world.characters[1].health, world.characters[1].fighting = 20, 1000000 + now := time.Now() + world.clients[1].regenerationAt = now.Add(-2 * time.Second) + connections[1].packets = nil + + world.advanceRegeneration(now) + + if len(teamResourceUpdates(connections[1].packets)) != 1 { + t.Fatal("hidden teammate did not receive its roster resource update", connections[1].packets) + } + for _, packet := range connections[1].packets { + if binary.BigEndian.Uint32(packet[24:28]) == 1 { + t.Fatal("hidden teammate received a world-actor update", packet) + } + } +} + +func TestTeamResourceMaximumBasisResetsOnPlayerInterestReentry(t *testing.T) { + world, connections := newResourceBackpackTeam(t) + player, client := world.characters[1], world.clients[1] + now := time.Now() + player.position[0] = 400 + world.advanceActions(now) + client.regenerationAt = now.Add(-2 * time.Second) + world.advanceRegeneration(now) + if world.clients[2].absorbedBonuses[1].health != 90 { + t.Fatal("hidden team snapshot did not establish its resource basis") + } + player.position[0] = 0 + world.advanceActions(now) + connections[1].packets = nil + stats := player.baseStats() + stats.Body.BodyDevelopment = 6 + + if err := world.handleSkillTraining(client, skillTrainingRequest(stats)[20:]); err != nil { + t.Fatal(err) + } + + var maximum uint32 + for _, packet := range connections[1].packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[24:28]) == 1 && binary.BigEndian.Uint32(packet[29:33]) == 1 { + maximum = binary.BigEndian.Uint32(packet[33:37]) + } + } + if maximum != 52 { + t.Fatal("fresh actor retained the hidden team snapshot's modifier basis", maximum) + } +} diff --git a/server/teams_test.go b/server/teams_test.go @@ -26,6 +26,16 @@ func newTeamWorld(t *testing.T) (*server, []*combatTestConn) { world.clients[id] = &worldClient{id: id, conn: conn, target: true, ready: true} connections = append(connections, conn) } + // These connected fixtures have already received each other's actor snapshots. + for id, client := range world.clients { + client.players = make(map[uint32]bool) + for other := range world.clients { + if id != other { + client.players[other] = true + } + } + } + return world, connections } diff --git a/server/token_upload_test.go b/server/token_upload_test.go @@ -65,7 +65,7 @@ func TestTokenUploadOriginalLevelBoundariesAndVariants(t *testing.T) { world, conn := newTokenUploadWorld(t, scenario.template, level, scenario.side) observer := &combatTestConn{} world.characters[2] = &character{id: 2, health: 100, playfield: world.characters[1].playfield} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true, target: true} wantClan, wantOmni, stat := uint32(10), uint32(20), uint32(75) if scenario.side == 1 { wantClan += scenario.gains[index] diff --git a/server/tradeskills_test.go b/server/tradeskills_test.go @@ -38,7 +38,7 @@ func TestItemCombinationConsumesBothIngredientsAndPersistsOneResult(t *testing.T world, conn := newCombinationWorld(t) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} if err := world.handleItemCombination(world.clients[1], combinationRequest(1, 65, 66)); err != nil { t.Fatal(err) diff --git a/server/treatment_kit_test.go b/server/treatment_kit_test.go @@ -116,11 +116,12 @@ func TestTreatmentKitStandingHealerTreatsDistinctPatientsAndRestoresLocks(t *tes player, client := world.characters[1], world.clients[1] player.sitting = false player.setSkillLock(124, time.Now().Add(600*time.Second)) + client.players = map[uint32]bool{2: true, 3: true} connections := make(map[uint32]*combatTestConn) for _, id := range []uint32{2, 3} { world.characters[id] = &character{id: id, name: fmt.Sprintf("Patient%d", id), playfield: player.playfield, position: [3]float32{7, 0, 0}, rotation: [4]float32{0, 0, 0, 1}, level: 1, appearance: 277, stats: testCharacterStats(), health: 1, sitting: true} connections[id] = &combatTestConn{} - world.clients[id] = &worldClient{id: id, conn: connections[id], target: true, ready: true} + world.clients[id] = &worldClient{id: id, conn: connections[id], target: true, ready: true, players: map[uint32]bool{1: true, 2: true, 3: true}} if err := world.saveUser(world.characters[id]); err != nil { t.Fatal(err) } diff --git a/server/utility_equipment_test.go b/server/utility_equipment_test.go @@ -30,7 +30,7 @@ func TestUtilityWearAndRemovalPreserveIdentityAndSkillAcrossRestart(t *testing.T player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: player.playfield, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} if err := world.handleInventory(client, inventoryMovePacket(1, 64, slot)[20:]); err != nil { t.Fatal(err) diff --git a/server/vehicle_test.go b/server/vehicle_test.go @@ -150,7 +150,7 @@ func TestGroundVehicleRemovalRestoresEffectsAndAllowsCombat(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 800, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} if err := world.handleInventory(client, inventoryMovePacket(1, 64, 1)[20:]); err != nil { t.Fatal(err) } diff --git a/server/vektor_quality_test.go b/server/vektor_quality_test.go @@ -44,7 +44,7 @@ func TestVektorQualitiesWearRemoveAndRecover(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} player.stats.Ranged.Shotgun = scenario.threshold player.aggDef = 75 diff --git a/server/weapon_miss_test.go b/server/weapon_miss_test.go @@ -248,7 +248,7 @@ func TestRangedMissPreservesHealthCreditsAndClockAndCommitsAmmunition(t *testing target.position = [3]float32{1, 0, 0} observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{target.id: true}} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: map[uint32]bool{target.id: true}} world.combatRoll = func(limit uint32) uint32 { return limit - 1 } if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil { t.Fatal(err) diff --git a/server/weapon_quality_test.go b/server/weapon_quality_test.go @@ -51,7 +51,7 @@ func TestWeaponQualityEquipRequiresInterpolatedSkillsAndRecovers(t *testing.T) { player, client := world.characters[1], world.clients[1] observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} player.stats.Ranged.Pistol, player.stats.Ranged.FlingShot = scenario.pistol-1, scenario.fling player.inventory.Items[0].Template, player.inventory.Items[0].Quality = template, scenario.quality diff --git a/server/weapon_special_animation_test.go b/server/weapon_special_animation_test.go @@ -29,7 +29,7 @@ func TestWeaponSpecialQueuesActionBeforeResultAndLockOnlyForVisibleClients(t *te id := uint32(index + 2) observers[index] = &combatTestConn{} world.characters[id] = &character{id: id, playfield: 950, health: 100} - world.clients[id] = &worldClient{id: id, conn: observers[index], ready: true, target: true, npcs: map[uint32]bool{1000000: true}} + world.clients[id] = &worldClient{id: id, conn: observers[index], ready: true, target: true, players: map[uint32]bool{1: true}, npcs: map[uint32]bool{1000000: true}} } world.clients[3].loading = true delete(world.clients[4].npcs, 1000000) @@ -89,7 +89,7 @@ func TestWeaponSpecialRecoveryWaitsForBothCombatantsToStop(t *testing.T) { world.clients[1].regenerationAt = start.Add(time.Hour) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}, regenerationAt: start.Add(time.Hour)} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}, regenerationAt: start.Add(time.Hour)} if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil { t.Fatal(err) } diff --git a/server/weapon_wear_admission_test.go b/server/weapon_wear_admission_test.go @@ -30,7 +30,7 @@ func TestConditionalWeaponWearRejectsWithoutChangingOwnershipOrBonuses(t *testin } observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, ready: true} owner.packets = nil if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil { diff --git a/server/world_actions.go b/server/world_actions.go @@ -43,7 +43,7 @@ func (server *server) handleCharacterReady(client *worldClient) error { player.body = playerCollisionBody{} player.movement.prepare(player, time.Now()) player.alignSurface([3]float32{}, true) - motion = server.playerMovementReplay(client, time.Now()) + motion = server.playerMovementReplay(client, time.Now(), nil) motion = append(motion, server.playerFollowReplay(client, nil)...) replay = playerCombatStatPackets(server.characters[client.id]) replay = append(replay, equippedItemPackets(server.characters[client.id])...) diff --git a/server/world_loading_test.go b/server/world_loading_test.go @@ -55,7 +55,7 @@ func TestWorldLoadingObserverReceivesPeriodicLifecycleAfterActorSnapshot(t *test world, owner := newPeriodicNanoWorld(t) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, loading: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, loading: true, players: map[uint32]bool{1: true}, npcs: map[uint32]bool{1000000: true}} if lethal { world.characters[1000000].health = 7 } @@ -97,7 +97,7 @@ func TestWorldLoadingObserverReceivesWeaponTimelineWithoutBecomingATarget(t *tes world, owner := newCombatWorld(t) observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, loading: true, npcs: map[uint32]bool{1000000: true}} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, loading: true, players: map[uint32]bool{1: true}, npcs: map[uint32]bool{1000000: true}} if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil { t.Fatal(err) diff --git a/server/world_output_test.go b/server/world_output_test.go @@ -67,8 +67,9 @@ func TestWorldBroadcastRetiresFailedRecipientAndPreservesDeparture(t *testing.T) world, observer := newCombatWorld(t) failed := &failingCombatConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - client := &worldClient{id: 2, conn: failed, ready: true} + client := &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: failed, ready: true} world.clients[2] = client + world.clients[1].players = map[uint32]bool{2: true} packet := stopFightPacket(1) world.broadcast(950, 0, packet) @@ -167,7 +168,7 @@ func TestWorldReplacementRemovesRemoteActorBeforeReplayingEquipment(t *testing.T } observer := &combatTestConn{} world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) ready := n3Packet(0x570c2039, 50000, 1, nil) input := append(cookie, ready...) @@ -403,3 +404,32 @@ func TestWorldOutputDrainsAcceptedPacketsWhenSessionEnds(t *testing.T) { t.Fatalf("session shutdown dropped accepted output: %x", conn.packets) } } + +func TestWorldBroadcastSharesEncodingWithoutSharingRecipientHeaders(t *testing.T) { + world, first := newCombatWorld(t) + second, legacy := &combatTestConn{}, &combatTestConn{} + for id, output := range map[uint32]*combatTestConn{2: second, 3: legacy} { + world.characters[id] = &character{id: id, playfield: 950} + world.clients[id] = &worldClient{id: id, ready: true, target: id == 2, conn: output, players: map[uint32]bool{1: true}} + } + packet := npcMovementPacket(world.characters[1], 1) + original := append([]byte(nil), packet...) + + world.broadcast(950, 0, packet) + + if !bytes.Equal(packet, original) { + t.Fatal("broadcast changed its source packet") + } + for index, output := range []*combatTestConn{first, second, legacy} { + if len(output.packets) != 1 || binary.BigEndian.Uint32(output.packets[0][12:16]) != uint32(index+1) { + t.Fatal("shared packet retained another recipient's header", index, output.packets) + } + length := 48 + if index == 2 { + length = 76 + } + if len(output.packets[0]) != length { + t.Fatal("recipient received the wrong protocol layout", index, output.packets[0]) + } + } +} diff --git a/server/world_session.go b/server/world_session.go @@ -68,6 +68,7 @@ func (server *server) joinWorldClient(client *worldClient, id uint32) error { client.regenerationSeconds = 0 client.id = character.id client.npcs = make(map[uint32]bool) + client.players = make(map[uint32]bool) client.lootCorpse = 0 client.shop = nil client.bank = nil @@ -76,24 +77,18 @@ func (server *server) joinWorldClient(client *worldClient, id uint32) error { return err } updates := [][]byte{playfieldUpdate, characterPacket(character), characterTitlePacket(character)} - for id, other := range server.characters { - if id != character.id && other.playfield == character.playfield && server.clients[id] != nil { - snapshot := other.predictedMovement(time.Now()) - updates = append(updates, characterPacket(&snapshot)) - updates = append(updates, characterTitlePacket(other)) - if !server.clients[id].loading { - updates = append(updates, playerCombatStatPackets(other)...) - updates = append(updates, equippedItemPackets(other)...) - updates = append(updates, activeNanoPackets(other, time.Now())...) - } - if other.health == 0 { - updates = append(updates, deathPacket(other)) - } - updates = append(updates, n3Packet(0x570c2039, 50000, other.id, nil)) + for id, peer := range server.clients { + other := server.characters[id] + if id == character.id || !peer.ready || other.playfield != character.playfield { + continue + } + x, z := other.position[0]-character.position[0], other.position[2]-character.position[2] + if x*x+z*z <= 180*180 { + updates = append(updates, server.playerSnapshot(client, other, now)...) } } updates = append(updates, server.updateNPCInterest(client, time.Now())...) - updates = append(updates, server.playerMovementReplay(client, time.Now())...) + updates = append(updates, server.playerMovementReplay(client, time.Now(), nil)...) updates = append(updates, server.playerFollowReplay(client, nil)...) if client.target { updates = append(updates, server.chatServerPacket(client.conn)) @@ -146,6 +141,13 @@ func (server *server) joinWorldClient(client *worldClient, id uint32) error { } } client.ready = true + for id := range client.players { + peer := server.clients[id] + if peer.players == nil { + peer.players = make(map[uint32]bool) + } + peer.players[character.id] = true + } server.broadcast(playfield, character.id, spawn) server.broadcast(playfield, character.id, title) for _, update := range petUpdates { diff --git a/server/zone_movement_test.go b/server/zone_movement_test.go @@ -26,7 +26,7 @@ func TestZoneMovementReplaysShopAndCheckpointsWithoutPerPacketWrites(t *testing. client := &worldClient{id: 1, target: true, ready: true, conn: owner} world.clients[1] = client world.characters[2] = &character{id: 2, playfield: 950, health: 100} - world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: observer} + world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, target: true, ready: true, conn: observer} now := time.Now() player.nextPositionSave = now.Add(20 * time.Second) before := world.nextItem diff --git a/tools/client/test_player_interest.mjs b/tools/client/test_player_interest.mjs @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output] = process.argv.slice(2); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [ + '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +const games = []; +const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id && !actor.deleting); +try { + for (let index = 0; index < 2; index++) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'interest-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + } + const [owner, observer] = games; + const state = async () => (await owner.page.request.get(url + '/test-state')).json(); + await Promise.all(games.map(game => game.wait('both nearby players visible', () => actor(game, 1) && actor(game, 2)))); + + // The controlled teleport isolates interest from long travel; gameplay uses real input. + assert.equal((await observer.page.request.post(url + '/test-place/far')).status(), 204); + await Promise.all([owner.wait('distant observer removed', () => !actor(owner, 2)), + observer.wait('distant owner removed', () => !actor(observer, 1))]); + assert.equal((await state()).known, false); + const hidden = observer.sequence; + await owner.key('KeyI'); + await owner.click(681, 65, 'right'); + await owner.wait('weapon equipped while unobserved', () => owner.local().inventory.some(item => item.slot === 6)); + await owner.key('KeyX'); + await owner.wait('owner seated while unobserved', () => owner.local().stats[430] === 2); + assert.equal((await state()).sitting, true); + assert.equal((await state()).inventory.Items.find(item => item.Slot === 6).Template, 121564); + await observer.snapshot(); + assert(!observer.events.some(event => event.sequence > hidden && event.direction === 'framereceived' && + event.actor?.[0] === 50000 && event.actor[1] === 1), 'hidden actor updates leaked to observer'); + + const reentry = observer.sequence; + assert.equal((await observer.page.request.post(url + '/test-place/near')).status(), 204); + await observer.wait('fresh seated owner after reentry', () => actor(observer, 1)?.stats[430] === 2); + assert.equal((await state()).known, true); + const received = observer.events.filter(event => event.sequence > reentry && event.direction === 'framereceived'); + const spawn = received.findIndex(event => event.opcode === '271b3a6b' && event.actor?.[1] === 1); + const weapon = received.findIndex(event => event.opcode === '3b1d2268'); + assert(spawn >= 0 && weapon > spawn, 'equipped weapon must replay after the owner snapshot'); + await owner.key('KeyX'); + await observer.wait('visible owner stands', () => actor(observer, 1)?.stats[430] !== 2); + await owner.key('KeyI'); + const before = owner.local().position[2]; + await owner.hold('KeyW', 'owner walks after reentry', snapshot => owner.local(snapshot).position[2] > before + 2); + await observer.wait('observer receives resumed movement', () => actor(observer, 1)?.position[2] > before + 1); + assert((await state()).position[2] > before + 1); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: distance retirement, hidden equipment/posture isolation, complete reentry and real movement'); +} finally { + try { await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); } + finally { await browser.close(); } +} diff --git a/tools/stress/README.md b/tools/stress/README.md @@ -9,22 +9,37 @@ go build -o /tmp/ao-stress ./tools/stress /tmp/ao-stress -url http://127.0.0.1:PORT -clients 100 -ramp 30s -duration 2m ``` -The default scenario puts 70% of clients in Omni-1 Entertainment (705), 20% in -Newland City (800), and 10% in the starter backyard (950). `-scenario` accepts a -JSON array of weighted spawn positions in the format of `hotspot.json`. Weights -are assigned deterministically in client order. Add positions to spread clients -within a zone; use equal weights for a balanced comparison. The supplied points -concentrate players together and deliberately exercise dense scene broadcasts. +The default `distributed.json` puts 70% of clients in Omni-1 Entertainment (705), +20% in Newland City (800), and 10% in the starter backyard (950). The cities each +use five separated locations. At each location 80% of clients are idle and 20% +walk for two seconds, rest for eight, and reverse on the next leg. Walking poses +describe a controlled two-metre leg, not a full native physics implementation. +These are synthetic placements, not measured production player behavior. + +Use `-scenario tools/stress/hotspot.json` for the dense crowd: everyone is active, +with one location per zone. Keep this worst case separate from distributed load. +`-scenario` accepts weighted spawn locations with `Activity` set to `idle`, `walk` +or `crowd`. Weights are assigned deterministically in client order. Both supplied +scenarios retain the same 70/20/10 zone split. Provisioning completes before measurement. The client then schedules connections throughout the ramp, authenticates through `/browser-world`, waits for the world snapshot, sends CharacterReady, and waits for its acknowledgement. It continuously -reads the actual game byte stream. Each ready client alternates sitting/standing -once per second and walks forward/backward while standing. Movement inputs precede -the posture probe, so its acknowledgement measures work through the simulation -owner. This is a movement/visibility/recovery workload, not combat, inventory, -team, chat or zone-transfer coverage. It uses the full-width protocol accepted by -the server, without browsers or rendering. +reads the actual game byte stream using the compact 14.9.1 protocol, including +quantized movement, native N3 headers and packet alignment. No browser or renderer +is involved. Received byte counts include packet alignment but exclude WebSocket, +TCP/IP and TLS overhead; older full-width results excluded alignment. + +Crowd clients alternate sitting/standing once per second and walk forward/backward +while standing. They deliberately send both directional stops before each posture +probe. Its acknowledgement passes through the simulation owner. Idle and walking +clients instead use a private one-second protocol ping: these measure transport +round trips, including ordered movement processing when a walker sends a command +first. Idle pings alone do not demonstrate simulation responsiveness. The report's +`action` and `steady_actions` fields count completed probes in either scenario; +do not compare CPU/probe across different activity mixes as if the work were equal. +These are movement/visibility/recovery workloads, not combat, inventory, team, +chat or zone-transfer coverage. JSON lines report cumulative admission and action latency, steady-period action latency, scheduled-action latency including client scheduling delay, received diff --git a/tools/stress/distributed.json b/tools/stress/distributed.json @@ -0,0 +1,24 @@ +[ + {"Activity": "idle", "Weight": 28, "Playfield": 705, "Position": [960, 16.5, 510], "Rotation": [0, 0, 0, 1]}, + {"Activity": "walk", "Weight": 7, "Playfield": 705, "Position": [960, 16.5, 510], "Rotation": [0, 0, 0, 1]}, + {"Activity": "idle", "Weight": 28, "Playfield": 705, "Position": [500, 16.5, 510], "Rotation": [0, 0, 0, 1]}, + {"Activity": "walk", "Weight": 7, "Playfield": 705, "Position": [500, 16.5, 510], "Rotation": [0, 0, 0, 1]}, + {"Activity": "idle", "Weight": 28, "Playfield": 705, "Position": [1420, 16.5, 510], "Rotation": [0, 0, 0, 1]}, + {"Activity": "walk", "Weight": 7, "Playfield": 705, "Position": [1420, 16.5, 510], "Rotation": [0, 0, 0, 1]}, + {"Activity": "idle", "Weight": 28, "Playfield": 705, "Position": [960, 16.5, 970], "Rotation": [0, 0, 0, 1]}, + {"Activity": "walk", "Weight": 7, "Playfield": 705, "Position": [960, 16.5, 970], "Rotation": [0, 0, 0, 1]}, + {"Activity": "idle", "Weight": 28, "Playfield": 705, "Position": [500, 16.5, 970], "Rotation": [0, 0, 0, 1]}, + {"Activity": "walk", "Weight": 7, "Playfield": 705, "Position": [500, 16.5, 970], "Rotation": [0, 0, 0, 1]}, + {"Activity": "idle", "Weight": 8, "Playfield": 800, "Position": [680, 74.75, 538], "Rotation": [0, 0, 0, 1]}, + {"Activity": "walk", "Weight": 2, "Playfield": 800, "Position": [680, 74.75, 538], "Rotation": [0, 0, 0, 1]}, + {"Activity": "idle", "Weight": 8, "Playfield": 800, "Position": [220, 74.75, 538], "Rotation": [0, 0, 0, 1]}, + {"Activity": "walk", "Weight": 2, "Playfield": 800, "Position": [220, 74.75, 538], "Rotation": [0, 0, 0, 1]}, + {"Activity": "idle", "Weight": 8, "Playfield": 800, "Position": [1140, 74.75, 538], "Rotation": [0, 0, 0, 1]}, + {"Activity": "walk", "Weight": 2, "Playfield": 800, "Position": [1140, 74.75, 538], "Rotation": [0, 0, 0, 1]}, + {"Activity": "idle", "Weight": 8, "Playfield": 800, "Position": [680, 74.75, 998], "Rotation": [0, 0, 0, 1]}, + {"Activity": "walk", "Weight": 2, "Playfield": 800, "Position": [680, 74.75, 998], "Rotation": [0, 0, 0, 1]}, + {"Activity": "idle", "Weight": 8, "Playfield": 800, "Position": [220, 74.75, 998], "Rotation": [0, 0, 0, 1]}, + {"Activity": "walk", "Weight": 2, "Playfield": 800, "Position": [220, 74.75, 998], "Rotation": [0, 0, 0, 1]}, + {"Activity": "idle", "Weight": 20, "Playfield": 950, "Position": [52, 14, 56], "Rotation": [0, 0, 0, 1]}, + {"Activity": "walk", "Weight": 5, "Playfield": 950, "Position": [52, 14, 56], "Rotation": [0, 0, 0, 1]} +] diff --git a/tools/stress/hotspot.json b/tools/stress/hotspot.json @@ -1,5 +1,5 @@ [ - {"Weight": 7, "Playfield": 705, "Position": [960, 16.5, 510], "Rotation": [0, 0, 0, 1]}, - {"Weight": 2, "Playfield": 800, "Position": [679.625, 74.75, 537.875], "Rotation": [0, 0, 0, 1]}, - {"Weight": 1, "Playfield": 950, "Position": [52, 14, 56], "Rotation": [0, 0, 0, 1]} + {"Activity": "crowd", "Weight": 7, "Playfield": 705, "Position": [960, 16.5, 510], "Rotation": [0, 0, 0, 1]}, + {"Activity": "crowd", "Weight": 2, "Playfield": 800, "Position": [679.625, 74.75, 537.875], "Rotation": [0, 0, 0, 1]}, + {"Activity": "crowd", "Weight": 1, "Playfield": 950, "Position": [52, 14, 56], "Rotation": [0, 0, 0, 1]} ] diff --git a/tools/stress/main.go b/tools/stress/main.go @@ -19,6 +19,7 @@ import ( ) type placement struct { + Activity string Weight int Playfield uint32 Position [3]float32 @@ -46,7 +47,7 @@ func main() { clients := flag.Int("clients", 100, "number of clients, up to 20000") ramp := flag.Duration("ramp", time.Minute, "time over which connections are scheduled") duration := flag.Duration("duration", time.Minute, "steady load duration after the ramp") - scenario := flag.String("scenario", "tools/stress/hotspot.json", "JSON file of weighted spawn locations") + scenario := flag.String("scenario", "tools/stress/distributed.json", "JSON file of weighted spawn locations and activities") flag.Parse() if *address == "" || *clients < 1 || *clients > 20000 || *ramp <= 0 || *duration <= 0 || flag.NArg() != 0 { fmt.Fprintln(os.Stderr, "provide -url, 1..20000 clients, and positive ramp/duration") @@ -71,6 +72,9 @@ func run(ctx context.Context, address string, count int, ramp, duration time.Dur } weight := 0 for _, place := range places { + if place.Activity != "crowd" && place.Activity != "idle" && place.Activity != "walk" { + return fmt.Errorf("each placement needs Activity crowd, idle or walk") + } if place.Weight <= 0 || place.Playfield == 0 || place.Rotation == [4]float32{} { return fmt.Errorf("each placement needs positive Weight, Playfield and a nonzero Rotation") } diff --git a/tools/stress/protocol.go b/tools/stress/protocol.go @@ -5,7 +5,6 @@ import ( "encoding/binary" "fmt" "io" - "math" "net/http" "strings" "time" @@ -16,7 +15,7 @@ import ( func packet(kind uint16, opcode uint32, body []byte) []byte { length := 20 + len(body) result := make([]byte, (length+3)&^3) - binary.BigEndian.PutUint16(result, 1) + binary.BigEndian.PutUint16(result, 0xdfdf) binary.BigEndian.PutUint16(result[2:], kind) binary.BigEndian.PutUint16(result[4:], 1) binary.BigEndian.PutUint16(result[6:], uint16(length)) @@ -27,22 +26,22 @@ func packet(kind uint16, opcode uint32, body []byte) []byte { } func command(id, opcode uint32, body []byte) []byte { - prefix := binary.BigEndian.AppendUint32(nil, opcode) - prefix = binary.BigEndian.AppendUint32(prefix, 50000) + prefix := binary.BigEndian.AppendUint32(nil, 50000) prefix = binary.BigEndian.AppendUint32(prefix, id) - prefix = binary.BigEndian.AppendUint32(prefix, 0) - return packet(10, 0, append(prefix, body...)) + prefix = append(prefix, 0) + return packet(10, opcode, append(prefix, body...)) } func movement(person visitor, action uint32) []byte { - body := binary.BigEndian.AppendUint32(nil, action) - for _, value := range person.Place.Position { - body = binary.BigEndian.AppendUint32(body, math.Float32bits(value)) + // 14.9.1 quantizes XYZ and the quaternion into a 17-byte movement body. + body := []byte{byte(action)} + for axis, scale := range [3]float32{8, 16, 8} { + body = binary.BigEndian.AppendUint16(body, uint16(int32(person.Place.Position[axis]*scale))) } for _, value := range person.Place.Rotation { - body = binary.BigEndian.AppendUint32(body, math.Float32bits(value)) + body = binary.BigEndian.AppendUint16(body, uint16(int16(value*16384))) } - body = append(body, make([]byte, 8)...) + body = binary.BigEndian.AppendUint16(body, 0) return command(person.ID, 0x54111123, body) } @@ -95,21 +94,26 @@ func exercise(ctx context.Context, address string, person visitor, scheduled tim return } traffic.packets++ - traffic.bytes += len(body) + traffic.bytes += (len(body) + 3) &^ 3 if time.Since(reported) >= time.Second { events <- traffic traffic = event{playfield: person.Place.Playfield, kind: "traffic"} reported = time.Now() } - if binary.BigEndian.Uint16(body[2:4]) != 10 || len(body) < 36 || binary.BigEndian.Uint32(body[28:32]) != person.ID { - continue - } - ack := acknowledgement{opcode: binary.BigEndian.Uint32(body[20:24])} - if ack.opcode == 0x5e477770 && len(body) >= 40 { - ack.action = binary.BigEndian.Uint32(body[36:40]) - } - if ack.opcode != 0x5f52412e && ack.opcode != 0x570c2039 && (ack.opcode != 0x5e477770 || ack.action != 86 && ack.action != 87) { - continue + ack := acknowledgement{} + if binary.BigEndian.Uint16(body[2:4]) == 11 && binary.BigEndian.Uint32(body[16:20]) == 2 { + ack.opcode = 2 + } else { + if binary.BigEndian.Uint16(body[2:4]) != 10 || len(body) < 29 || binary.BigEndian.Uint32(body[24:28]) != person.ID { + continue + } + ack.opcode = binary.BigEndian.Uint32(body[16:20]) + if ack.opcode == 0x5e477770 && len(body) >= 33 { + ack.action = binary.BigEndian.Uint32(body[29:33]) + } + if ack.opcode != 0x5f52412e && ack.opcode != 0x570c2039 && (ack.opcode != 0x5e477770 || ack.action != 86 && ack.action != 87) { + continue + } } select { case acks <- ack: @@ -174,24 +178,46 @@ func exercise(ctx context.Context, address string, person visitor, scheduled tim for step := 0; waitUntil(ctx, next); step++ { sent := time.Now() pending = true - for _, action := range []uint32{2, 4} { - if err := write(movement(person, action)); err != nil { + want := acknowledgement{opcode: 2} + if person.Place.Activity == "crowd" { + for _, action := range []uint32{2, 4} { + if err := write(movement(person, action)); err != nil { + return err + } + } + want = acknowledgement{opcode: 0x5e477770, action: uint32(86 + step%2)} + body := binary.BigEndian.AppendUint32(nil, want.action) + body = append(body, make([]byte, 16)...) + if err := write(command(person.ID, want.opcode, body)); err != nil { + return err + } + } else { + // Walkers move for two seconds, then rest for eight, reversing each leg. + if person.Place.Activity == "walk" && (step%10 == 0 || step%10 == 2) { + action := uint32(1 + 2*(step/10%2)) + if step%10 == 2 { + distance := float32(2) + if action == 3 { + distance = -distance + } + person.Place.Position[2] += distance + action++ + } + if err := write(movement(person, action)); err != nil { + return err + } + } + if err := write(packet(11, 1, nil)); err != nil { return err } } - action := uint32(86 + step%2) - body := binary.BigEndian.AppendUint32(nil, action) - body = append(body, make([]byte, 16)...) - if err := write(command(person.ID, 0x5e477770, body)); err != nil { - return err - } - if err := await(acknowledgement{opcode: 0x5e477770, action: action}); err != nil { + if err := await(want); err != nil { return err } pending = false events <- event{playfield: person.Place.Playfield, kind: "action", elapsed: time.Since(sent), at: time.Now()} events <- event{playfield: person.Place.Playfield, kind: "scheduled_action", elapsed: time.Since(next)} - if action == 87 { + if want.opcode == 0x5e477770 && want.action == 87 { if err := write(movement(person, uint32(1+2*(step/2%2)))); err != nil { return err } diff --git a/tools/stress/protocol_test.go b/tools/stress/protocol_test.go @@ -1,8 +1,10 @@ package main import ( + "bytes" "context" "encoding/binary" + "encoding/hex" "io" "net/http" "net/http/httptest" @@ -43,16 +45,16 @@ func TestExerciseWaitsForItsOwnGameAcknowledgementAndStopsReader(t *testing.T) { } conn.Write(command(42, 0x5f52412e, make([]byte, 12))) case 10: - key := binary.BigEndian.Uint32(body[20:24]) + key := binary.BigEndian.Uint32(body[16:20]) if key == 0x570c2039 { - conn.Write(body) + conn.Write(append(body, make([]byte, (-len(body))&3)...)) } if key == 0x5e477770 { - action := binary.BigEndian.Uint32(body[36:40]) + action := binary.BigEndian.Uint32(body[29:33]) actions <- action // An unrelated actor's acknowledgement cannot complete this action. - conn.Write(command(99, key, body[36:])) - conn.Write(body) + conn.Write(command(99, key, body[29:])) + conn.Write(append(body, make([]byte, (-len(body))&3)...)) } } } @@ -61,7 +63,7 @@ func TestExerciseWaitsForItsOwnGameAcknowledgementAndStopsReader(t *testing.T) { events := make(chan event, 100) done := make(chan error, 1) go func() { - done <- exercise(ctx, server.URL, visitor{ID: 42, Cookie: "ao_client=test", Place: placement{Playfield: 705, Rotation: [4]float32{0, 0, 0, 1}}}, time.Now(), events) + done <- exercise(ctx, server.URL, visitor{ID: 42, Cookie: "ao_client=test", Place: placement{Activity: "crowd", Playfield: 705, Rotation: [4]float32{0, 0, 0, 1}}}, time.Now(), events) }() ready, acknowledged := false, false for !acknowledged { @@ -112,3 +114,78 @@ func TestReadPacketHandlesFragmentedAlignmentAndTruncation(t *testing.T) { t.Fatal("truncated header was accepted", err) } } + +func TestMovementUsesNativeCompactWireLayout(t *testing.T) { + person := visitor{ID: 1, Place: placement{Position: [3]float32{52, 14, 56}, Rotation: [4]float32{0, 0, 0, 1}}} + actual := movement(person, 1) + // Native header, N3 identity/pass-on, quantized pose, angle and alignment. + want, err := hex.DecodeString("dfdf000a0001002e0000000100000000541111230000c35000000001000101a000e001c0000000000000400000000000") + if err != nil || !bytes.Equal(actual, want) { + t.Fatalf("native movement packet: %x, expected %x (%v)", actual, want, err) + } +} + +func TestExerciseIdleAndWalkingUsePrivatePingProbes(t *testing.T) { + for _, activity := range []string{"idle", "walk"} { + t.Run(activity, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var moves []byte + serverDone := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer close(serverDone) + socket, err := websocket.Accept(w, r, nil) + if err != nil { + t.Error(err) + return + } + defer socket.CloseNow() + conn := websocket.NetConn(ctx, socket, websocket.MessageBinary) + for { + body, err := readPacket(conn) + if err != nil { + return + } + switch binary.BigEndian.Uint16(body[2:4]) { + case 1: + conn.Write(command(42, 0x5f52412e, make([]byte, 12))) + case 10: + switch binary.BigEndian.Uint32(body[16:20]) { + case 0x570c2039: + conn.Write(command(42, 0x570c2039, nil)) + case 0x54111123: + moves = append(moves, body[29]) + default: + t.Error("mixed activity sent a broadcast posture probe") + } + case 11: + conn.Write(packet(11, 2, nil)) + } + } + })) + defer server.Close() + events := make(chan event, 100) + done := make(chan error, 1) + go func() { + done <- exercise(ctx, server.URL, visitor{ID: 42, Place: placement{Activity: activity, Rotation: [4]float32{0, 0, 0, 1}}}, time.Now(), events) + }() + acknowledged := false + for !acknowledged { + select { + case result := <-events: + acknowledged = result.kind == "action" + case err := <-done: + t.Fatal("client ended before its probe", err) + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } + cancel() + <-done + <-serverDone + if activity == "idle" && len(moves) != 0 || activity == "walk" && !bytes.Equal(moves, []byte{1}) { + t.Fatal("unexpected movement before probe", moves) + } + }) + } +}