diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e126c533a..7d3e5c56b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -984,6 +984,8 @@ struct Game<'a> { /// A server's players on their way to another level, each waiting for /// the destination to load around them. server_trips: Vec, + /// Players a command sends to another level, once it has run. + level_teleports: Vec, /// A server's levels other than the one in place (game/levels.rs). levels: levels::Levels, /// Which pass of a server tick runs (`tick_server`): the first one reads @@ -10295,6 +10297,7 @@ impl<'a> Game<'a> { world_root: PathBuf::new(), travelling: None, server_trips: Vec::new(), + level_teleports: Vec::new(), levels: Default::default(), level_pass: Default::default(), portals: Default::default(), diff --git a/crates/horizon-client/src/game/command_blocks.rs b/crates/horizon-client/src/game/command_blocks.rs index 5a5fa11c8..f85be2fd3 100644 --- a/crates/horizon-client/src/game/command_blocks.rs +++ b/crates/horizon-client/src/game/command_blocks.rs @@ -357,6 +357,7 @@ impl Game<'_> { silent: false, store: None, elsewhere: false, + level: None, block: Some(pos), }; // performPrefixedCommand: a leading slash is allowed. diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 3ca938d6a..e0a0d1204 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1124,7 +1124,23 @@ impl Game<'_> { (-(dy.atan2(horizontal).to_degrees())) as f32, ]); } + // `execute in` another dimension: a server's player moves to that + // level (ServerPlayer.teleport into another level), after the command. + let level = self + .command_source + .and_then(|s| s.level) + .filter(|d| *d != self.dim && self.options.dedicated.is_some()); for &t in &targets { + if let (Some(dim), Target::Player, Some(conn)) = (level, t, self.lan_acting) { + self.level_teleports + .push(super::server_travel::LevelTeleport { + conn, + dim, + at: pos, + rotation, + }); + continue; + } self.teleport_to(t, pos, rotation); } let [x, y, z] = pos.map(|v| Text::literal(format_double(v))); diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 1fa67c8b6..01488db2c 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -26,6 +26,9 @@ pub(in crate::game) struct Source { /// `execute in` another dimension than the one Horizon has loaded: none /// of its chunks are loaded. pub elsewhere: bool, + /// The dimension `execute in` named, if any: a server teleports its + /// players there (`TeleportCommand` into the source's level). + pub level: Option, /// The command block whose output this source is /// (`BaseCommandBlock.CloseableCommandBlockSource`). pub block: Option<(i32, i32, i32)>, @@ -77,6 +80,7 @@ impl Game<'_> { silent: false, store: None, elsewhere: false, + level: None, block: None, } } @@ -90,6 +94,7 @@ impl Game<'_> { silent: true, store: None, elsewhere: false, + level: None, block: None, } } @@ -441,6 +446,7 @@ impl Game<'_> { pos: self.target_position(t)?, rot: self.target_rotation(t), elsewhere: false, + level: None, ..s }) }) @@ -544,6 +550,7 @@ impl Game<'_> { } vec![Source { elsewhere: dim != self.dim.id(), + level: Some(super::super::Dim::from_id(dim)), ..s }] } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 68b29a360..eba49f2d0 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -928,6 +928,8 @@ impl Game<'_> { .map(|t| horizon_client::lan::data::component_nbt(&t.component())) .collect::>() }); + // A teleport into another level happens before its feedback is sent. + self.run_level_teleports(host); for content in lines.unwrap_or_default() { host.hub.send_to( conn, diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index 6312254c7..6c0ec48e7 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -22,6 +22,17 @@ pub(super) struct Trip { end: bool, /// The Nether portal plan, whose exit is found or built on arrival. plan: Option, + /// Sent by a command: the player is already where it goes. + placed: bool, +} + +/// `TeleportCommand` into another level for a server's player: where, and +/// the rotation it sets (none keeps the player's). +pub(super) struct LevelTeleport { + pub conn: u32, + pub dim: Dim, + pub at: [f64; 3], + pub rotation: Option<[f32; 2]>, } /// A player's box: Player's standing dimensions. @@ -177,7 +188,8 @@ impl Game<'_> { }; let at = [destination.x, destination.y, destination.z]; let ctx = self.server_ctx(); - host.hub.change_level(i, at, yaw, &ctx); + // TeleportTransition.PLAY_PORTAL_SOUND. + host.hub.change_level(i, at, yaw, None, true, &ctx); self.as_guest(host, conn, |g| g.trigger_dimension(source, target)); self.server_trips.push(Trip { conn, @@ -185,6 +197,7 @@ impl Game<'_> { target: destination, end, plan, + placed: false, }); if let Err(e) = self.enter_level(Some(host), source) { log::error!("could not reopen {}: {e}", source.id()); @@ -214,6 +227,9 @@ impl Game<'_> { continue; } let trip = self.server_trips.remove(k); + if trip.placed { + continue; + } self.resolve_arrivals(); let yaw = host.hub.guests[i].yaw; let (position, yaw) = if trip.end { @@ -248,6 +264,43 @@ impl Game<'_> { } } + /// The players the command just run sends to another level + /// (`ServerPlayer.teleport` from TeleportCommand): a Respawn packet + /// keeping all data and the teleport, with no portal sound. The server + /// leaves the body alone until the level has loaded around it. + pub(super) fn run_level_teleports(&mut self, host: &mut LanHost) { + for t in std::mem::take(&mut self.level_teleports) { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == t.conn) else { + continue; + }; + let source = self.dim; + if let Err(e) = self.enter_level(Some(host), t.dim) { + log::error!("could not open {}: {e}", t.dim.id()); + continue; + } + let g = &mut host.hub.guests[i]; + let [yaw, pitch] = t.rotation.unwrap_or([g.yaw, g.pitch]); + // A new body there: no fall distance or motion carried over. + g.motion = None; + let ctx = self.server_ctx(); + host.hub + .change_level(i, t.at, yaw, Some(pitch), false, &ctx); + self.as_guest(host, t.conn, |g| g.trigger_dimension(source, t.dim)); + self.server_trips.retain(|trip| !trip.is(t.conn)); + self.server_trips.push(Trip { + conn: t.conn, + dim: t.dim, + target: Vec3::new(t.at[0], t.at[1], t.at[2]), + end: false, + plan: None, + placed: true, + }); + if let Err(e) = self.enter_level(Some(host), source) { + log::error!("could not reopen {}: {e}", source.id()); + } + } + } + /// The hub's view of the server for packets sent outside its own tick. pub(super) fn server_ctx(&mut self) -> TickCtx<'_> { let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b18187835..bb4eea345 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -2199,7 +2199,15 @@ impl Hub { /// names (`set_dimension`): ClientboundRespawnPacket keeping all data, /// then vanilla's packet order. Nothing tracked in the old level is /// removed one by one: the client drops its whole level. - pub fn change_level(&mut self, i: usize, at: [f64; 3], yaw: f32, ctx: &TickCtx) { + pub fn change_level( + &mut self, + i: usize, + at: [f64; 3], + yaw: f32, + pitch: Option, + portal_sound: bool, + ctx: &TickCtx, + ) { let mode = self.guests[i].game_mode; let info = self.spawn_info(mode); self.close_container_for(i); @@ -2210,6 +2218,9 @@ impl Hub { g.chunk_queue.clear(); g.center = None; g.yaw = yaw; + if let Some(pitch) = pitch { + g.pitch = pitch; + } g.position = at; g.previous_position = at; g.send(&C::Respawn(play::Respawn { @@ -2241,12 +2252,14 @@ impl Hub { // ServerPlayer.sendPostEffects. g.send(&raw(ids::POST_EFFECTS, vec![0])); // TeleportTransition.PLAY_PORTAL_SOUND. - g.send(&C::LevelEvent(play::LevelEvent { - kind: 1032, - pos: [0, 0, 0], - data: 0, - global: false, - })); + if portal_sound { + g.send(&C::LevelEvent(play::LevelEvent { + kind: 1032, + pos: [0, 0, 0], + data: 0, + global: false, + })); + } // lastSentExp, lastSentHealth and lastSentFood. g.sent_health = None; g.sent_xp = None; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java index e41c693ee..a29b95231 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java @@ -76,11 +76,16 @@ import net.minecraft.world.phys.Vec3; * line at a time: {@code step LABEL} (the label the next packets are recorded * under), {@code join NAME}, {@code cmd NAME COMMAND...}, {@code shift NAME * on|off} (the shift key, as ServerboundPlayerInputPacket), {@code fly NAME - * on|off} (ServerboundPlayerAbilitiesPacket), {@code quit NAME} and {@code - * end}, which writes each player's lines to OUT. + * on|off} (ServerboundPlayerAbilitiesPacket), {@code still NAME} (the + * position reminder LocalPlayer.sendPosition sends every 20 ticks standing + * still), {@code quit NAME}, {@code + * players on|off} (whether each player also records the other players added + * to and removed from its level, and its own respawns into a dimension) and + * {@code end}, which writes each player's lines to OUT. */ public final class LocatorBarClient { private static volatile String step = "start"; + private static volatile boolean players; private static final Map NAMES = new LinkedHashMap<>(); public static void main(String[] args) throws Exception { @@ -110,7 +115,9 @@ public final class LocatorBarClient { abilities.flying = w[2].equals("on"); players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundPlayerAbilitiesPacket(abilities)); } + case "still" -> players.get(w[1]).still(); case "quit" -> players.get(w[1]).close(); + case "players" -> LocatorBarClient.players = w[1].equals("on"); case "end" -> { try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) { for (Player p : players.values()) { @@ -166,8 +173,10 @@ public final class LocatorBarClient { private int threshold = -1; private ProtocolInfo inbound; private ProtocolInfo outbound; - private PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0); + private volatile PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0); private boolean loaded; + /** The other players this one was sent, by entity id. */ + private final Map seen = new java.util.HashMap<>(); private final Object replyLock = new Object(); private int replies; @@ -198,6 +207,14 @@ public final class LocatorBarClient { } } + void still() throws Exception { + PositionMoveRotation at = position; + // A tick of its own: the server takes one position per client tick (receivedPositionThisTick). + send(net.minecraft.network.protocol.game.ServerboundClientTickEndPacket.INSTANCE); + send(new ServerboundMovePlayerPacket.PosRot(at.position(), at.yRot(), at.xRot(), false, false)); + send(net.minecraft.network.protocol.game.ServerboundClientTickEndPacket.INSTANCE); + } + void close() throws Exception { if (socket != null) socket.close(); } @@ -266,7 +283,20 @@ public final class LocatorBarClient { while (true) { Received r = read(); Packet p = r.packet; - if (p instanceof ClientboundTrackedWaypointPacket) { + if (p instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket a + && a.getType() == net.minecraft.world.entity.EntityTypes.PLAYER) { + String who = NAMES.getOrDefault(a.getUUID(), "uuid?"); + seen.put(a.getId(), who); + if (players) record("add " + who + " at " + a.getX() + "," + a.getY() + "," + a.getZ()); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket rm) { + rm.entityIds().forEach(id -> { + String who = seen.remove(id); + if (who != null && players) record("remove " + who); + }); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundRespawnPacket rs) { + if (players) record("respawn " + rs.commonPlayerSpawnInfo().dimension().identifier()); + seen.clear(); + } else if (p instanceof ClientboundTrackedWaypointPacket) { record(waypoint(r.payload)); } else if (p instanceof ClientboundSystemChatPacket) { synchronized (replyLock) { diff --git a/tools/test_server_dimension_players_parity.py b/tools/test_server_dimension_players_parity.py new file mode 100644 index 000000000..77e1428e9 --- /dev/null +++ b/tools/test_server_dimension_players_parity.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Players in different dimensions on a dedicated server, against vanilla's, seen by vanilla clients. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat +world vanilla generated first, with Alice and Bob as operators in creative. LocatorBarClient joins them both +(players made of vanilla's protocol code) and records, step by step, the other players each is sent and loses +(ClientboundAddEntityPacket, ClientboundRemoveEntitiesPacket) and the dimensions it respawns into +(ClientboundRespawnPacket), with the locator bar's waypoints, while they change dimensions (ServerPlayer.teleport +through `execute in ... run tp`, and an End portal): Bob goes to the Nether and back, Alice to the End, Bob +follows her there, both come back to the Overworld, then Bob steps into an End portal and comes back. Between +the steps each client sends its position (the reminder a still client sends every second). Each player's lines in each step are compared exactly. +""" +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import time + +try: + from . import lab, test_rust_parity as base + from .test_dedicated_server_parity import Server + from .test_locator_bar_parity import generate_world, server_dir +except ImportError: + import lab + import test_rust_parity as base + from test_dedicated_server_parity import Server + from test_locator_bar_parity import generate_world, server_dir + +NAME = 'server-dimension-players-parity' +NETHER, END, OVERWORLD = 'minecraft:the_nether', 'minecraft:the_end', 'minecraft:overworld' +# (label, what the players do). +SCRIPT = [ + ('bob-nether', [f'cmd Bob execute in {NETHER} run tp @s 0.5 100 0.5']), + ('bob-back', [f'cmd Bob execute in {OVERWORLD} run tp @s 2.5 100 0.5']), + ('alice-end', [f'cmd Alice execute in {END} run tp @s 0.5 100 0.5']), + ('bob-end', [f'cmd Bob execute in {END} run tp @s 2.5 100 0.5']), + ('alice-back', [f'cmd Alice execute in {OVERWORLD} run tp @s 0.5 100 0.5']), + ('bob-back-again', [f'cmd Bob execute in {OVERWORLD} run tp @s 2.5 100 0.5']), + # Through an End portal (Entity.handlePortal), and back by command. + ('bob-portal', ['cmd Bob setblock 2 101 3 minecraft:end_portal', 'cmd Bob tp @s 2.5 101 3.5']), + ('bob-portal-back', [f'cmd Bob execute in {OVERWORLD} run tp @s 2.5 100 0.5']), +] +STEP_SECONDS = 5.0 + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = server_dir(directory, world) + out = build / f'{label}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], + cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + text=True) + + def tell(line): + client.stdin.write(line + '\n') + client.stdin.flush() + try: + tell('players on') + tell('step joins') + for name, x in (('Alice', 0.5), ('Bob', 2.5)): + tell(f'join {name}') + server.wait_for(rf'{name} joined the game', timeout=120) + tell(f'fly {name} on') + tell(f'cmd {name} tp @s {x} 100 0.5') + time.sleep(STEP_SECONDS) + for step, actions in SCRIPT: + tell(f'step {step}') + for action in actions: + tell(action) + # Standing still, a client still sends its position every 20 ticks + # (LocalPlayer.sendPosition): the server then tracks to it what it has sent the + # chunks of since (ChunkMap.move). + time.sleep(STEP_SECONDS / 2) + tell('still Alice') + tell('still Bob') + time.sleep(STEP_SECONDS / 2) + tell('end') + client.wait(timeout=60) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + return out.read_text(encoding='utf-8').splitlines() + + +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')] + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + import json + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] + + world = generate_world(vanilla_server, build) + vanilla_all = run_side('vanilla', vanilla_server, client, build, world) + horizon_all = run_side('horizon', horizon_server, client, build, world) + errors = [l for l in vanilla_all + horizon_all if ' error ' in f' {l} ' or 'disconnected' in l] + vanilla, horizon = shown(vanilla_all), shown(horizon_all) + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:6000]) + if sum(' respawn ' in l for l in vanilla) < 6: + raise AssertionError(f'vanilla sent too few respawns: the script did not run (see {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + 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.')) + print(f'server dimension players: {len(vanilla)} lines identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}')