diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index eafa9d22b..f9ea1262b 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -61,9 +61,10 @@ pub(super) struct LanHost { pub mob_players: HashMap, /// An integrated server's owner (game/integrated.rs). pub owner: Option, - /// The players' locator bars (game/lan_waypoints.rs), and the guests who - /// are dead, whose respawn replaces their waypoint. - pub waypoints: lan::waypoints::Waypoints, + /// The players' locator bars, one waypoint manager per level by + /// dimension id (game/lan_waypoints.rs), and the guests who are dead, + /// whose respawn replaces their waypoint. + pub waypoints: std::collections::HashMap, pub waypoint_dead: std::collections::HashSet, /// Guests' commands waiting for the hub to be back in `self.lan`, where /// a command can reach every player (game/lan_actions.rs). diff --git a/crates/horizon-client/src/game/lan_waypoints.rs b/crates/horizon-client/src/game/lan_waypoints.rs index 0d0ab69e4..ba1512a00 100644 --- a/crates/horizon-client/src/game/lan_waypoints.rs +++ b/crates/horizon-client/src/game/lan_waypoints.rs @@ -1,5 +1,5 @@ //! The locator bar of the players on a served world (lan/waypoints.rs): what -//! each player looks like to the waypoint manager this tick. +//! each player looks like to their level's waypoint manager this tick. use super::{Game, lan::LanHost}; use horizon_client::{ items::ItemStack, @@ -27,8 +27,12 @@ impl Game<'_> { Some((team.name.clone(), color)) } + /// Each level's `ServerWaypointManager` ticked with the players in that + /// level: a player who changes level leaves the old one's manager + /// (`ServerLevel.removePlayerImmediately`: untracked for everyone there) + /// and joins the new one's (`addDuringTeleport`). pub(super) fn lan_update_waypoints(&mut self, host: &mut LanHost, state: Option<&HostState>) { - let mut players = Vec::new(); + let mut players: Vec<(&str, waypoints::Player)> = Vec::new(); if let Some(h) = state { let icon = self .cmds @@ -39,22 +43,25 @@ impl Game<'_> { color: i.color, }) .unwrap_or_default(); - players.push(waypoints::Player { - uuid: h.uuid, - conn: None, - position: h.position, - spectator: self.spectator(), - transmit_range: transmit_range( - h.sneaking, - self.potions.effects.get("invisibility").is_some(), - h.equipment[5].as_ref(), - ), - receive_range: PLAYER_RANGE, - first_tick: false, - view_distance: host.hub.config.view_distance, - team: self.waypoint_team(&h.name), - icon, - }); + players.push(( + self.dim.id(), + waypoints::Player { + uuid: h.uuid, + conn: None, + position: h.position, + spectator: self.spectator(), + transmit_range: transmit_range( + h.sneaking, + self.potions.effects.get("invisibility").is_some(), + h.equipment[5].as_ref(), + ), + receive_range: PLAYER_RANGE, + first_tick: false, + view_distance: host.hub.config.view_distance, + team: self.waypoint_team(&h.name), + icon, + }, + )); } let mut respawned = Vec::new(); for g in host.hub.guests.iter().filter(|g| g.placed) { @@ -66,27 +73,56 @@ impl Game<'_> { } // Player.updatePlayerPose: the shift key crouches unless flying. let crouching = g.sneaking && !g.flying && !g.fall_flying && !g.sleeping; - players.push(waypoints::Player { - uuid: g.uuid, - conn: Some(g.conn), - position: g.position, - spectator: g.spectator(), - transmit_range: transmit_range( - crouching, - g.effects.get("invisibility").is_some(), - g.armor[0].as_ref(), - ), - receive_range: PLAYER_RANGE, - first_tick: g.ticks == 0, - view_distance: g.view_distance, - team: self.waypoint_team(&g.name), - icon: Icon::default(), - }); + players.push(( + &g.dimension, + waypoints::Player { + uuid: g.uuid, + conn: Some(g.conn), + position: g.position, + spectator: g.spectator(), + transmit_range: transmit_range( + crouching, + g.effects.get("invisibility").is_some(), + g.armor[0].as_ref(), + ), + receive_range: PLAYER_RANGE, + first_tick: g.ticks == 0, + view_distance: g.view_distance, + team: self.waypoint_team(&g.name), + icon: Icon::default(), + }, + )); } host.waypoint_dead - .retain(|uuid| players.iter().any(|p| p.uuid == *uuid)); + .retain(|uuid| players.iter().any(|(_, p)| p.uuid == *uuid)); let locator_bar = self.ui.rules.bool("locator_bar"); - for (conn, packet) in host.waypoints.tick(&players, &respawned, locator_bar) { + let mut levels: Vec = host.waypoints.keys().cloned().collect(); + for (level, _) in &players { + if !levels.iter().any(|l| l == level) { + levels.push((*level).to_owned()); + } + } + levels.sort(); + let mut out = Vec::new(); + for level in levels { + let here: Vec = players + .iter() + .filter(|(l, _)| *l == level) + .map(|(_, p)| p.clone()) + .collect(); + let away: Vec<(u128, u32)> = players + .iter() + .filter(|(l, _)| *l != level) + .filter_map(|(_, p)| Some((p.uuid, p.conn?))) + .collect(); + let manager = host.waypoints.entry(level.clone()).or_default(); + out.extend(manager.tick_level(&here, &away, &respawned, locator_bar)); + // Nobody left in the level: nothing to remember there. + if here.is_empty() { + host.waypoints.remove(&level); + } + } + for (conn, packet) in out { if let Some(g) = host.hub.guest(conn) { g.send(&packet); } diff --git a/crates/horizon-client/src/lan/waypoints.rs b/crates/horizon-client/src/lan/waypoints.rs index 852cfc4fb..3e92d820d 100644 --- a/crates/horizon-client/src/lan/waypoints.rs +++ b/crates/horizon-client/src/lan/waypoints.rs @@ -153,6 +153,9 @@ pub struct Waypoints { /// One tick's players, and the packets for their connections. struct Tick<'a> { players: HashMap, + /// The connections of the players in other levels: one who just left this level is + /// still told of the waypoints it loses (`removePlayer` disconnects them). + away: &'a [(u128, u32)], view: HashMap, /// Players a respawn replaced this tick: a new ServerPlayer, on its first tick. fresh: &'a [u128], @@ -169,7 +172,17 @@ impl<'a> Tick<'a> { icon: &Icon, target: WaypointTarget, ) { - let Some(conn) = self.players.get(&receiver).and_then(|p| p.conn) else { + let Some(conn) = self + .players + .get(&receiver) + .and_then(|p| p.conn) + .or_else(|| { + self.away + .iter() + .find(|(uuid, _)| *uuid == receiver) + .map(|&(_, conn)| conn) + }) + else { return; }; self.out @@ -449,9 +462,22 @@ impl Waypoints { players: &[Player], respawned: &[u128], locator_bar: bool, + ) -> Vec<(u32, C)> { + self.tick_level(players, &[], respawned, locator_bar) + } + + /// [`Self::tick`] for one level of several: `away` are the connections of the players + /// in the other levels, for the untracks owed to one who has just left this one. + pub fn tick_level( + &mut self, + players: &[Player], + away: &[(u128, u32)], + respawned: &[u128], + locator_bar: bool, ) -> Vec<(u32, C)> { let mut t = Tick { players: players.iter().map(|p| (p.uuid, p)).collect(), + away, view: HashMap::default(), fresh: respawned, enabled: locator_bar, @@ -632,6 +658,29 @@ mod tests { assert_eq!(to(&out, 20), [(1, WaypointTarget::Empty)]); } + #[test] + fn a_player_leaving_the_level_loses_its_waypoints() { + let (a, b) = ( + player(1, 10, [0.5, 64.0, 0.5]), + player(2, 20, [4.5, 64.0, 0.5]), + ); + let mut w = Waypoints::default(); + w.tick(&[a.clone(), b.clone()], &[], true); + let mut moved = b.clone(); + moved.position = [5.5, 64.0, 0.5]; + w.tick(&[a.clone(), moved], &[], true); + // B goes to another level: A loses B, and B (reached through `away`) loses A. + let out = w.tick_level(std::slice::from_ref(&a), &[(2, 20)], &[], true); + assert_eq!( + to(&out, 10), + vec![(waypoint_operation::UNTRACK, WaypointTarget::Empty)] + ); + assert_eq!( + to(&out, 20), + vec![(waypoint_operation::UNTRACK, WaypointTarget::Empty)] + ); + } + #[test] fn team_colours() { assert_eq!(team_rgb("red"), Some(0xFF5555)); diff --git a/tools/test_server_dimension_players_parity.py b/tools/test_server_dimension_players_parity.py index 77e1428e9..8453d14af 100644 --- a/tools/test_server_dimension_players_parity.py +++ b/tools/test_server_dimension_players_parity.py @@ -93,9 +93,29 @@ def run_side(label, server_command, client_command, build, world): return out.read_text(encoding='utf-8').splitlines() +SHOWN = ('add', 'remove', 'respawn', 'track', 'untrack', 'update') + + +def settled(lines): + """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: + what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more + than once on the way there; the packet by packet order is test_locator_bar_parity's.""" + def waypoint(line): + parts = line.split(' ') + return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None + last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} + return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] + + def shown(lines): - """Each player's adds, removes and respawns, without the waypoints (the locator bar harness has those).""" - return [l for l in lines if l.split(' ', 2)[2:3] and l.split(' ', 2)[2].split(' ')[0] in ('add', 'remove', 'respawn')] + """Each player's adds, removes, respawns and waypoints (as the step leaves them), step by step; sorted within a + step (the packets of one step may leave in another order within the tick).""" + steps = {} + for line in lines: + parts = line.split(' ', 2) + if len(parts) == 3 and parts[2].split(' ')[0] in SHOWN: + steps.setdefault((parts[0], parts[1]), []).append(line) + return [l for key in steps for l in sorted(settled(steps[key]))] def main(): @@ -139,7 +159,7 @@ def main(): java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), scope='Two players on a dedicated server changing dimensions (Nether, End, back): the other players each ' - 'is sent and loses, and the dimensions it respawns into.')) + 'is sent and loses, the dimensions it respawns into and its locator bar waypoints.')) print(f'server dimension players: {len(vanilla)} lines identical') diff --git a/tools/test_server_player_targets_parity.py b/tools/test_server_player_targets_parity.py index f8f457143..71416223b 100644 --- a/tools/test_server_player_targets_parity.py +++ b/tools/test_server_player_targets_parity.py @@ -11,8 +11,9 @@ vanilla generated first, with Alice and Bob as operators in creative. LocatorBar of vanilla's protocol code) and records, step by step, the system chat each receives and what the server changes about it: game mode events, teleports, inventory slots, effects, its death (with the death message), the other players it is sent or loses and the levels it respawns into. Each player's lines in each step are compared exactly, -in sorted order (the packets of one step may leave in another order within the tick). The locator bar's waypoints -and what a death does besides its messages are left to their own harnesses. +in sorted order (the packets of one step may leave in another order within the tick), with the locator bar's +waypoints as each step leaves them (one manager per level: a player in another level is untracked). What a death does besides its messages +is left to its own harness. """ import hashlib import os @@ -78,11 +79,21 @@ SCRIPT = [ ] # What the players' locator bars show has its own harness (test_locator_bar_parity), and what a death does # besides its messages (drops, the body leaving) the player combat ones: here only the messages of `kill`. -WAYPOINTS = ('track ', 'untrack ', 'update ') DEATH_STEP = 'step=console-kill' STEP_SECONDS = 2.5 +def settled(lines): + """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: + what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more + than once on the way there; the packet by packet order is test_locator_bar_parity's.""" + def waypoint(line): + parts = line.split(' ') + return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None + last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} + return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] + + def run_side(label, server_command, client_command, build, world): directory = build / label port = server_dir(directory, world) @@ -134,13 +145,13 @@ def run_side(label, server_command, client_command, build, world): # At the death, Alice picks up Bob's drops (and gets their advancements) in vanilla. death_side = step == DEATH_STEP and (not rest.startswith(('chat ', 'killed ')) or 'chat.type.advancement' in rest) - if rest.startswith(WAYPOINTS) or death_side: + if death_side: continue if step != 'step=start': steps.setdefault((who, step), []).append(line) order = {f'step={s}': i for i, (s, _, _) in enumerate(SCRIPT)} keys = sorted(steps, key=lambda k: (k[0], order.get(k[1], -1))) - return [l for k in keys for l in sorted(steps[k])], errors + return [l for k in keys for l in sorted(settled(steps[k]))], errors def main():