diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index f8e6e8fa9..1ae82b0f1 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -13,6 +13,7 @@ use horizon_client::{ items::ItemStack, lan::{ guest::SPECTATOR, + hub::TickCtx, menu::{Rules, Slots}, }, motion::{MotionEvent, MotionWorld, PlayerMotion}, @@ -281,6 +282,14 @@ impl Game<'_> { "container.enderchest", Slots::Ender, ) + } else if let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get(&pos) { + // AbstractFurnaceBlock.openContainer: FurnaceMenu, BlastFurnaceMenu, SmokerMenu. + let (menu, title) = match f.kind.recipe_type() { + "minecraft:blasting" => ("minecraft:blast_furnace", "container.blast_furnace"), + "minecraft:smoking" => ("minecraft:smoker", "container.smoker"), + _ => ("minecraft:furnace", "container.furnace"), + }; + (menu, title, Slots::Block(pos)) } else if let Some((other, right)) = self.chest_partner(pos) { // ChestBlock.combine: the right half's slots come first. let halves = if right { @@ -486,6 +495,7 @@ impl Game<'_> { S::ContainerClick(p) if self.lan_merchant_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_furnace_click(host, conn, &p) => {} S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item), S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => { let g = &mut host.hub.guests[gi]; @@ -720,9 +730,14 @@ impl Game<'_> { return; } let command = command.trim_start_matches('/').to_owned(); + // The guest's own level (Commands.performCommand with the player's source): an + // operator's on a dedicated server, never the host's. + let permission = host.hub.guest(conn).map_or(0, |g| g.permission); let lines = self.as_guest(host, conn, |g| { g.chat_capture = Some(Vec::new()); + let level = std::mem::replace(&mut g.ui.registries.permission, permission); g.run_command(&command); + g.ui.registries.permission = level; g.chat_capture .take() .unwrap_or_default() @@ -800,7 +815,23 @@ impl Game<'_> { if let Some(play) = host.play.get_mut(&conn) { play.potions = Default::default(); } - host.hub.respawn(i, spawn); + let ctx = TickCtx { + world: &mut self.world, + host: None, + entities: &[], + next_entity: &mut self.next_entity, + spawn, + difficulty: i32::from(self.ui.difficulty), + difficulty_locked: self.level.difficulty_locked, + clock_rate: if self.ui.rules.bool("advance_time") { + self.ui.clock.rate + } else { + 0.0 + }, + tick_rate: self.clock.rate(), + tick_frozen: self.clock.frozen(), + }; + host.hub.respawn(i, spawn, &ctx); } /// Per tick, for every guest: dig, use items, pick up drops, die. @@ -853,14 +884,15 @@ impl Game<'_> { let g = &mut host.hub.guests[gi]; if g.health <= 0.0 && !g.dead { g.dead = true; + g.last_death = Some(g.position.map(|v| v.floor() as i32)); + let (id, at) = (g.entity_id, g.position); let message = literal(&format!("{} died", g.name)); host.hub.send_to( conn, - &C::PlayerCombatKill(play::PlayerCombatKill { - id: host.hub.guests[gi].entity_id, - message, - }), + &C::PlayerCombatKill(play::PlayerCombatKill { id, message }), ); + // LivingEntity.die: the death animation, the dying player included. + host.hub.entity_event(id, 3, at); } } } diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 02db51586..9841fa879 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -6,8 +6,9 @@ //! closes (`AbstractContainerMenu.clearContainer`). use super::{Game, lan::LanHost}; use horizon_client::{ + containers::BlockEntity, items::ItemStack, - lan::guest::Guest, + lan::{guest::Guest, menu::Slots}, menu::{Env, Input, Kind, Menu}, }; use horizon_protocol::packets::play::{self, Clientbound as C}; @@ -20,6 +21,9 @@ pub(super) struct GuestCrafting { inventory: Option>, /// The open crafting table: its window, state id and menu. table: Option<(i32, i32, Box)>, + /// The open furnace's window and menu (`AbstractFurnaceMenu`); its slots live in + /// the furnace block entity and the hub's container menu keeps the client in sync. + furnace: Option<(i32, Box)>, } /// ServerboundContainerClickPacket's input. @@ -153,6 +157,74 @@ impl Game<'_> { true } + /// A click on the guest's open furnace, blast furnace or smoker: the host's + /// `AbstractFurnaceMenu` (fuel slot, take-only result, quick moves by recipe and + /// fuel) over the block entity's slots. False for other windows. + pub(super) fn lan_furnace_click( + &mut self, + host: &mut LanHost, + conn: u32, + p: &play::ContainerClick, + ) -> bool { + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return false; + }; + let Some(pos) = host.hub.guests[gi] + .menu + .as_ref() + .filter(|m| p.container != 0 && m.window == p.container) + .and_then(|m| match m.slots { + Slots::Block(pos) => Some(pos), + _ => None, + }) + else { + return false; + }; + let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get(&pos) else { + return false; + }; + let recipe = match f.kind.recipe_type() { + "minecraft:blasting" => "blasting", + "minecraft:smoking" => "smoking", + _ => "smelting", + }; + let items = f.items.clone(); + if host.hub.guests[gi].spectator() { + return true; + } + let mut menu = host + .play + .entry(conn) + .or_default() + .crafting + .furnace + .take() + .filter(|(window, _)| *window == p.container) + .map_or_else(|| Box::new(Menu::new(Kind::Furnace(recipe))), |(_, m)| m); + let changed = self.guest_menu_op(host, gi, &mut menu, |menu, env| { + for (k, s) in items.iter().enumerate() { + menu.set_slot(env, k, s.clone()); + } + let before: Vec<_> = (0..menu.slot_count()) + .map(|s| menu.slot(s).cloned()) + .collect(); + let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input)); + (0..menu.slot_count()) + .filter(|&s| menu.slot(s) != before[s].as_ref()) + .collect::>() + }); + if let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&pos) { + for k in 0..3 { + f.items[k] = menu.slot(k).cloned(); + } + // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. + f.input_clicked(&self.res.recipes, items[0].clone()); + } + host.play.entry(conn).or_default().crafting.furnace = Some((p.container, menu)); + host.hub.inventory_clicked(conn, p, &self.world, &changed); + true + } + /// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`). pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) { self.lan_crafting_closed(host, conn, None); diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index e9bfe7fbe..0fa47510a 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -4,7 +4,7 @@ use super::{ hub::Hub, menu::{self, Menu, Rules, Slots, View}, }; -use crate::{items::ItemStack, world::World}; +use crate::{containers::BlockEntity, items::ItemStack, world::World}; use horizon_protocol::{ item::Hashed, packets::play::{self, Clientbound as C}, @@ -175,6 +175,7 @@ impl Hub { state: 0, sent: Vec::new(), drag: None, + sent_data: Vec::new(), }); self.send_menu_content(i, items); } @@ -416,6 +417,47 @@ impl Hub { } } + /// AbstractContainerMenu.broadcastChanges' data slots: a furnace's + /// AbstractFurnaceBlockEntity.dataAccess (lit time left, lit total, cooking + /// timer, cooking total), each sent when it changes. + fn sync_container_data(&mut self, i: usize, world: &World) { + let g = &mut self.guests[i]; + let Some(m) = g.menu.as_mut() else { + return; + }; + let Slots::Block(pos) = m.slots else { + return; + }; + let Some(BlockEntity::Furnace(f)) = world.block_entities.get(&pos) else { + return; + }; + let data = [ + f.lit_remaining, + f.lit_total, + f.cooking_timer, + f.cooking_total, + ] + .map(|v| v as i16); + m.sent_data.resize(data.len(), i16::MIN); + let window = m.window; + let changed: Vec<(usize, i16)> = data + .iter() + .enumerate() + .filter(|&(k, v)| m.sent_data[k] != *v) + .map(|(k, &v)| (k, v)) + .collect(); + for &(k, value) in &changed { + m.sent_data[k] = value; + } + for (k, value) in changed { + g.send(&C::ContainerSetData(play::ContainerSetData { + container: window, + id: k as i16, + value, + })); + } + } + /// Slot changes of open containers (AbstractContainerMenu.broadcastChanges). pub fn sync_containers(&mut self, world: &World) { for i in 0..self.guests.len() { @@ -457,6 +499,8 @@ impl Hub { })); } } + // Then the data slots, as broadcastChanges does. + self.sync_container_data(i, world); } } } diff --git a/crates/horizon-client/src/lan/data.rs b/crates/horizon-client/src/lan/data.rs index 85c4894a9..8de0e53d3 100644 --- a/crates/horizon-client/src/lan/data.rs +++ b/crates/horizon-client/src/lan/data.rs @@ -109,24 +109,14 @@ pub fn json_to_nbt(v: &Value) -> Tag { } } -/// A component's JSON as NbtOps writes it: a list whose elements differ in -/// type (translation arguments mixing numbers and components) holds each -/// element that isn't a compound wrapped in one under the empty key. +/// A component's JSON as NbtOps writes it. A list whose elements differ in type +/// (translation arguments mixing numbers and components) stays one list: the NBT +/// writer wraps each element that isn't a compound under the empty key, as +/// `ListTag.wrapIfNeeded` does, so wrapping it here too would leave the client a +/// `{"": 1}` argument it cannot read. pub fn component_nbt(v: &Value) -> Tag { match v { - Value::Array(a) => { - let kind = |v: &Value| std::mem::discriminant(&json_to_nbt(v)); - let mixed = a.windows(2).any(|w| kind(&w[0]) != kind(&w[1])); - Tag::List( - a.iter() - .map(|e| match component_nbt(e) { - t @ Tag::Compound(_) => t, - t if mixed => Tag::compound([("", t)]), - t => t, - }) - .collect(), - ) - } + Value::Array(a) => Tag::List(a.iter().map(component_nbt).collect()), Value::Object(o) => Tag::compound(o.iter().map(|(k, v)| (k.as_str(), component_nbt(v)))), other => json_to_nbt(other), } @@ -313,3 +303,27 @@ mod tests { assert!(matches!(t.get("b"), Some(Tag::List(l)) if l.len() == 2)); } } + +#[cfg(test)] +mod component_tests { + use super::*; + use horizon_world::nbt::{Limits, read_network, write_network}; + + /// `/give`'s reply: a count, then components. On the wire each element is wrapped + /// once, and read back (ListTag.addAndUnwrap) it is the number again. + #[test] + fn mixed_translation_arguments_are_wrapped_once() { + let json = serde_json::json!({ + "translate": "commands.give.success.single", + "with": [1, {"text": "Raw Iron"}, {"text": "Tester"}], + }); + let tag = component_nbt(&json); + let Some(Tag::List(args)) = tag.get("with") else { + panic!("no arguments: {tag:?}"); + }; + assert_eq!(args[0], Tag::Int(1)); + // Read back as ListTag.addAndUnwrap does: a wrapper wrapped twice stays a compound. + let bytes = write_network(&tag, Limits::default()).unwrap(); + assert_eq!(read_network(&bytes, Limits::default()).unwrap().0, tag); + } +} diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 243c90d18..50d6b74a9 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -113,6 +113,8 @@ pub struct Guest { pub menu_state: i32, pub sent_health: Option<(f32, i32, f32)>, pub sent_xp: Option<(f32, i32, i32)>, + /// Where the player last died (Player.lastDeathLocation), sent with the respawn. + pub last_death: Option<[i32; 3]>, pub sent_selected: usize, pub inbox: VecDeque, pub joined_tick: u64, @@ -196,6 +198,7 @@ impl Guest { menu_state: 0, sent_health: None, sent_xp: None, + last_death: None, sent_selected: 0, inbox: VecDeque::new(), joined_tick: 0, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index cb438508e..d5ccef495 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -731,6 +731,22 @@ impl Hub { })); } + /// ClientboundSetDefaultSpawnPositionPacket for the level's respawn data. + fn default_spawn(&self, spawn: [f64; 3]) -> C { + C::SetDefaultSpawnPosition(play::SetDefaultSpawnPosition { + pos: play::GlobalPos { + dimension: self.config.dimension.clone(), + pos: [ + spawn[0].floor() as i32, + spawn[1].floor() as i32, + spawn[2].floor() as i32, + ], + }, + yaw: 0.0, + pitch: 0.0, + }) + } + /// PlayerList.sendLevelInfo. fn send_level_info(&mut self, i: usize, ctx: &TickCtx) { let spawn = ctx.spawn; @@ -747,18 +763,7 @@ impl Hub { warning_time: 300, })); g.send(&self.time_packet(ctx.world, ctx.clock_rate)); - g.send(&C::SetDefaultSpawnPosition(play::SetDefaultSpawnPosition { - pos: play::GlobalPos { - dimension: self.config.dimension.clone(), - pos: [ - spawn[0].floor() as i32, - spawn[1].floor() as i32, - spawn[2].floor() as i32, - ], - }, - yaw: 0.0, - pitch: 0.0, - })); + g.send(&self.default_spawn(spawn)); let w = &ctx.world.weather; if w.raining { g.send(&C::GameEvent(play::GameEvent { @@ -1408,7 +1413,8 @@ impl Hub { let g = &self.guests[i]; (g.health, g.food, g.saturation) }; - if self.guests[i].sent_health != Some(health) { + // A dead player's health isn't sent (the death screen shows from the combat kill). + if self.guests[i].sent_health != Some(health) && !self.guests[i].dead { let g = &mut self.guests[i]; g.send(&C::SetHealth(play::SetHealth { health: health.0, @@ -1658,12 +1664,38 @@ impl Hub { .map(str::to_owned) } - /// ServerPlayer.respawn: back to `at` with a fresh start. - pub fn respawn(&mut self, i: usize, at: [f64; 3]) { + /// PlayerList.respawn: back to `at` with a fresh start. The vanilla client waits on its + /// level loading screen from the Respawn packet until the level info's "level chunks load + /// start" event and the chunk under the player, so the packets follow vanilla's order. + pub fn respawn(&mut self, i: usize, at: [f64; 3], ctx: &TickCtx) { let mode = self.guests[i].game_mode; - let info = self.spawn_info(mode); + let mut info = self.spawn_info(mode); + // Player.getLastDeathLocation, set where the player died. + info.last_death = self.guests[i].last_death.map(|pos| play::GlobalPos { + dimension: self.config.dimension.clone(), + pos, + }); self.close_container_for(i); let g = &mut self.guests[i]; + // ServerLevel.removePlayerImmediately: every entity paired with the dead player is + // removed (ServerEntity.removePairing, one packet each). Its chunks are dropped + // without ForgetLevelChunk (PlayerChunkSender.dropChunk skips dead players): the + // client keeps them and they are all sent again. + for id in g.tracker.ids() { + g.send(&C::RemoveEntities(play::RemoveEntities { ids: vec![id] })); + } + g.tracker.clear(); + g.sent_chunks.clear(); + g.chunk_queue.clear(); + // ServerPlayer.restoreFrom: the game mode again (onUpdateAbilities). + g.send(&C::PlayerAbilities(play::PlayerAbilities { + flags: g.ability_flags(), + flying_speed: 0.05, + walking_speed: 0.1, + })); + // The new player faces the level's respawn direction (snapTo). + g.yaw = 0.0; + g.pitch = 0.0; g.position = at; g.previous_position = at; g.send(&C::Respawn(play::Respawn { @@ -1679,6 +1711,34 @@ impl Hub { g.chunk_queue.clear(); g.tracker.clear(); self.teleport(i, None); + let spawn = self.default_spawn(ctx.spawn); + let g = &mut self.guests[i]; + g.send(&spawn); + g.send(&C::ChangeDifficulty(play::ChangeDifficulty { + difficulty: ctx.difficulty, + locked: ctx.difficulty_locked, + })); + let xp = (g.xp_progress, g.xp_level, g.xp_total); + g.send(&C::SetExperience(play::SetExperience { + progress: xp.0, + level: xp.1, + total: xp.2, + })); + g.sent_xp = Some(xp); + // ServerPlayer.sendPostEffects. + g.send(&raw(ids::POST_EFFECTS, vec![0])); + self.send_level_info(i, ctx); + self.send_permission_level(i); + // ServerLevel.addRespawnedPlayer: the chunk tracking starts again at the player. + let g = &mut self.guests[i]; + let (cx, cz) = g.chunk(); + g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { + x: cx, + z: cz, + })); + g.center = None; + g.center_sent = Some((cx, cz)); + // ServerPlayer.initInventoryMenu. self.send_inventory(i); } } diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs index a2e40bf3d..d37874bc8 100644 --- a/crates/horizon-client/src/lan/menu.rs +++ b/crates/horizon-client/src/lan/menu.rs @@ -28,6 +28,8 @@ pub struct Menu { pub sent: Vec>, /// An unfinished drag: (mode, slots). pub drag: Option<(u8, Vec)>, + /// The data slots the client was last sent (ContainerSetData), a furnace's progress. + pub sent_data: Vec, } /// Where the slots of a container menu live. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index 109f33b66..bb438b735 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -125,7 +125,10 @@ public final class VanillaProtocolClient { client.status(host, port); client.join(host, port, name); } catch (Exception e) { - client.lines.add("error " + client.state + " " + e); + // With its causes: a decoder error names the field it could not read there. + StringBuilder line = new StringBuilder("error " + client.state + " " + e); + for (Throwable c = e.getCause(); c != null; c = c.getCause()) line.append(" / caused by ").append(c); + client.lines.add(line.toString()); } finally { if (client.socket != null) client.socket.close(); } @@ -427,9 +430,23 @@ public final class VanillaProtocolClient { boolean loaded = false; PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0); long lastChunk = 0; - long deadline = System.currentTimeMillis() + 90_000; + long deadline = System.currentTimeMillis() + 150_000; int step = 0; long stepAt = 0; + // The death the console deals and the respawn after it (PlayerList.respawn): from the + // client's PERFORM_RESPAWN until its level is loaded again (LevelLoadTracker: the level + // info's "level chunks load start" event, then the chunk under the player). + boolean respawning = false; + boolean respawned = false; + boolean loadStart = false; + boolean respawnChunk = false; + String runType = null; + int run = 0; + PositionMoveRotation respawnAt = null; + // The furnace set beside the respawn point: its window and the menu's state id. + net.minecraft.core.BlockPos furnace = null; + int furnaceWindow = -1; + int furnaceState = 0; // The villager the server's console summoned beside the spawn. int villager = -1; net.minecraft.world.phys.Vec3 villagerAt = null; @@ -445,6 +462,22 @@ public final class VanillaProtocolClient { Packet packet = r.packet; counts.merge(r.type, 1, Integer::sum); if (r.type.equals("minecraft:chunk_batch_start")) ordered = false; + if (respawning && !respawned) { + String line = respawnLine(r); + // PlayerList.respawn ends with initInventoryMenu: what follows is the + // next ticks' (health, entity data, chunks), in each server's own order. + respawned = r.type.equals("minecraft:container_set_content") && respawnAt != null; + if (line != null && !line.equals(runType)) { + if (runType != null) record("play-respawn", runLine(runType, run)); + runType = line; + run = 0; + } + if (line != null) run++; + if (packet instanceof net.minecraft.network.protocol.game.ClientboundGameEventPacket p + && p.getEvent() == net.minecraft.network.protocol.game.ClientboundGameEventPacket.LEVEL_CHUNKS_LOAD_START) { + loadStart = true; + } + } if (packet instanceof ClientboundKeepAlivePacket p) { send(new ServerboundKeepAlivePacket(p.getId())); } else if (packet instanceof ClientboundPingPacket p) { @@ -452,9 +485,14 @@ public final class VanillaProtocolClient { } else if (packet instanceof ClientboundPlayerPositionPacket p) { position = PositionMoveRotation.calculateAbsolute(position, p.change(), p.relatives()); record("play-move", text(position.position()) + " " + position.yRot() + " " + position.xRot()); + if (respawning) respawnAt = position; send(new ServerboundAcceptTeleportationPacket(p.id(), position.position().x, position.position().y, position.position().z, position.yRot(), position.xRot())); - send(new ServerboundMovePlayerPacket.PosRot(position.position(), position.yRot(), position.xRot(), false, false)); + // The 26.3 client answers with the acceptance alone; a second position in the + // same tick is an invalid move to vanilla's server once the player is loaded. + if (!respawning) { + send(new ServerboundMovePlayerPacket.PosRot(position.position(), position.yRot(), position.xRot(), false, false)); + } if (!loaded) { send(new ServerboundPlayerLoadedPacket()); loaded = true; @@ -467,20 +505,48 @@ public final class VanillaProtocolClient { lastChunk = now; int px = (int) Math.floor(position.position().x) >> 4; int pz = (int) Math.floor(position.position().z) >> 4; - if (p.x() == px && p.z() == pz) chunkParts(p); - } else if (packet instanceof ClientboundSystemChatPacket p && step > 0) { + if (p.x() == px && p.z() == pz && !respawning) chunkParts(p); + if (p.x() == px && p.z() == pz && respawnAt != null) respawnChunk = true; + } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundContainerSetContentPacket p + && furnaceWindow > 0 && p.containerId() == furnaceWindow) { + furnaceState = p.stateId(); + record("play-furnace", "content " + p.items() + " carried " + p.carriedItem()); + } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket p + && furnaceWindow > 0 && p.getContainerId() == furnaceWindow) { + furnaceState = p.getStateId(); + record("play-furnace", "slot " + p.getSlot() + " " + p.getItem()); + } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundContainerSetDataPacket p + && furnaceWindow > 0 && p.getContainerId() == furnaceWindow && (p.getId() == 1 || p.getId() == 3)) { + // Lit total and cooking total; the time left and the cooking timer follow the ticks. + record("play-furnace", "data " + p.getId() + " " + p.getValue()); + } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundEntityEventPacket p + && step == 5 + REPLIES.length && (int) (byte) field(p, "eventId") == 28) { + // Operator (level 4, as the console made it): it may run /kill on itself. + send(new ServerboundChatCommandPacket("kill")); + step++; + } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundPlayerCombatKillPacket p && step > 0) { + // The death message is left out: guests' death messages aren't Horizon's yet. + record("play-death", "death screen"); + send(new net.minecraft.network.protocol.game.ServerboundClientCommandPacket( + net.minecraft.network.protocol.game.ServerboundClientCommandPacket.Action.PERFORM_RESPAWN)); + respawning = true; + } else if (packet instanceof ClientboundSystemChatPacket p && step > 0 && step < 5 + REPLIES.length) { record("play-chat", "system " + p.overlay() + " " + json(p.content())); - } else if (packet instanceof ClientboundPlayerChatPacket p && step > 0) { + } else if (packet instanceof ClientboundPlayerChatPacket p && step > 0 && step < 5 + REPLIES.length) { record("play-chat", "player " + p.sender() + " " + p.index() + " " + p.body().content() + " " + p.signature().isPresent() + " " + p.unsignedContent().map(VanillaProtocolClient::json) + " " + text(p.filterMask()) + " " + p.chatType().chatType().getRegisteredName() + " " + json(p.chatType().name()) + " " + p.chatType().targetName().map(VanillaProtocolClient::json)); - } else if (packet instanceof ClientboundDisguisedChatPacket p && step > 0) { + } else if (packet instanceof ClientboundDisguisedChatPacket p && step > 0 && step < 5 + REPLIES.length) { record("play-chat", "disguised " + json(p.message()) + " " + p.chatType().chatType().getRegisteredName()); } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket p && p.getType() == net.minecraft.world.entity.EntityTypes.VILLAGER) { villager = p.getId(); villagerAt = new net.minecraft.world.phys.Vec3(p.getX(), p.getY(), p.getZ()); + } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundOpenScreenPacket p && step > 6 + REPLIES.length) { + furnaceWindow = p.getContainerId(); + record("play-furnace", "open " + net.minecraft.core.registries.BuiltInRegistries.MENU.getKey(p.getType()) + " " + + json(p.getTitle())); } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundOpenScreenPacket p && step > 0) { record("play-trade", "open " + p.getContainerId() + " " + net.minecraft.core.registries.BuiltInRegistries.MENU.getKey(p.getType()) + " " @@ -561,12 +627,101 @@ public final class VanillaProtocolClient { } else if (step == 4 + REPLIES.length && now - stepAt > 1500) { send(new net.minecraft.network.protocol.game.ServerboundContainerClosePacket(1)); record("play-counts", "chunks " + counts.getOrDefault("minecraft:level_chunk_with_light", 0)); + // The harness's console makes the player an operator once it reads this line. + send(new ServerboundChatPacket("ready to respawn", Instant.now(), 0L, Optional.empty(), + new LastSeenMessages.Update(0, new BitSet(), (byte) 0))); + step++; + stepAt = now; + } else if (step == 6 + REPLIES.length && loadStart && respawnChunk) { + // LevelLoadTracker is done: the vanilla client leaves the loading screen. + if (runType != null) record("play-respawn", runLine(runType, run)); + record("play-respawn", "level loaded at " + text(respawnAt.position())); + send(new ServerboundPlayerLoadedPacket()); + // A furnace two blocks south, an ore and its fuel. + furnace = net.minecraft.core.BlockPos.containing(respawnAt.position()).south(2); + send(new ServerboundChatCommandPacket("setblock " + furnace.getX() + " " + furnace.getY() + " " + furnace.getZ() + + " minecraft:furnace")); + send(new ServerboundChatCommandPacket("give @s minecraft:raw_iron")); + send(new ServerboundChatCommandPacket("give @s minecraft:coal")); + step++; + stepAt = now; + } else if (step == 7 + REPLIES.length && now - stepAt > 1500) { + // Right-click it with an empty hand (AbstractFurnaceBlock.useWithoutItem). + send(new net.minecraft.network.protocol.game.ServerboundUseItemOnPacket(net.minecraft.world.InteractionHand.MAIN_HAND, + new net.minecraft.world.phys.BlockHitResult(net.minecraft.world.phys.Vec3.atCenterOf(furnace), + net.minecraft.core.Direction.NORTH, furnace, false), 1)); + step++; + stepAt = now; + } else if (step >= 8 + REPLIES.length && step <= 10 + REPLIES.length && furnaceWindow > 0 + && now - stepAt > (step == 10 + REPLIES.length ? 12_000 : 1500)) { + // Shift-click the ore (hotbar 0) into the input, the coal (hotbar 1) into the + // fuel slot, and the smelted ingot out of the result; nothing claimed, so the + // server sends every slot the click changed. + int slot = step == 8 + REPLIES.length ? 30 : step == 9 + REPLIES.length ? 31 : 2; + record("play-furnace", "quick move " + slot); + send(new net.minecraft.network.protocol.game.ServerboundContainerClickPacket(furnaceWindow, furnaceState, (short) slot, + (byte) 0, net.minecraft.world.inventory.ContainerInput.QUICK_MOVE, + new it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<>(), net.minecraft.network.HashedStack.EMPTY)); + step++; + stepAt = now; + } else if (step == 11 + REPLIES.length && now - stepAt > 1500) { + send(new net.minecraft.network.protocol.game.ServerboundContainerClosePacket(furnaceWindow)); + record("play-furnace", "closed"); return; } } + if (respawning) { + if (runType != null) record("play-respawn", runLine(runType, run)); + record("play-respawn", "level never loaded: load start " + loadStart + ", chunk under the player " + respawnChunk); + } record("error", "timed out in play, step " + step + ", chunks " + chunks.size()); } + /** + * A run of the same packet: counted, but for the entities removed with the dead player + * (which mobs are tracked near the spawn at that moment varies). + */ + private static String runLine(String type, int run) { + return type + (run > 1 && !type.equals("minecraft:remove_entities") ? " x" + run : ""); + } + + /** + * A packet after the respawn request, as compared: entity ids and periodic or streamed + * packets (time, keep-alive, chunk data and light, whose batching follows each server's + * timing) left out; null to skip it. + */ + private String respawnLine(Received r) { + String t = r.type; + // Entities moving and the dead player's health land in the window between the death + // and the respawn as each server's ticks fall: left out. + if (t.startsWith("minecraft:move_entity") || t.equals("minecraft:rotate_head") || t.equals("minecraft:set_entity_motion") + || t.equals("minecraft:set_entity_data") || t.equals("minecraft:entity_position_sync") || t.equals("minecraft:set_health")) { + return null; + } + if (t.equals("minecraft:keep_alive") || t.equals("minecraft:ping") || t.equals("minecraft:level_chunk_with_light") + || t.equals("minecraft:chunk_batch_start") || t.equals("minecraft:chunk_batch_finished") + || t.equals("minecraft:light_update") || t.equals("minecraft:bundle_delimiter") + // Chat (the death message and /kill's feedback) is compared before the death. + || t.equals("minecraft:system_chat") || t.equals("minecraft:player_chat") || t.equals("minecraft:disguised_chat")) { + return null; + } + if (r.packet instanceof net.minecraft.network.protocol.game.ClientboundSetTimePacket p && p.clockUpdates().isEmpty()) { + return null; + } + if (r.packet instanceof net.minecraft.network.protocol.game.ClientboundEntityEventPacket p) { + return t + " " + field(p, "eventId"); + } + if (r.packet instanceof net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket p) { + return t; + } + if (t.equals("minecraft:respawn") || t.equals("minecraft:game_event") || t.equals("minecraft:set_default_spawn_position") + || t.equals("minecraft:change_difficulty") || t.equals("minecraft:set_experience") || t.equals("minecraft:set_health") + || t.equals("minecraft:set_chunk_cache_center") || t.equals("minecraft:initialize_border")) { + return t + " " + text(r.packet); + } + return t; + } + /** * A chunk's blocks, biomes, heightmaps and block entities (its * ClientboundLevelChunkPacketData bytes). The light is left out: both servers relight around chunks diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 7861b1157..c30abe4b0 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -10,8 +10,13 @@ read is an error), pings each server, joins it in offline mode through login, configuration and play, accepts the spawn teleport, receives the chunks around the spawn (their bytes are compared: the world is loaded from the same files), chats, runs /list and commands that fail (`/random value -7..7`, `/random value x`, `/trigger nope`) and leaves. The console then -runs `list` and `say` and `stop`. Compared, all of them exactly: +7..7`, `/random value x`, `/trigger nope`), trades, is made an operator by +the console, runs /kill, respawns (as vanilla's LevelLoadTracker waits: until the "level +chunks load start" event and the chunk under the player), sets a furnace +beside itself, gives itself raw iron and coal, opens the furnace, shift-clicks +the ore and the coal in and the ingot out, and leaves. The +console then runs `list` and `say` and `stop`. Compared, all of them +exactly: - the status response (MOTD, players, version, favicon) and the ping; - the legacy (pre-1.7, 0xFE) ping reply; @@ -22,6 +27,12 @@ runs `list` and `say` and `stop`. Compared, all of them exactly: advancements, which vanilla keeps in hash maps, sorted); the command tree node by node; the chunks sent and their bytes; the replies to the chat message, /list and the failing commands, as text components; +- after /kill, the packets from the death screen to the respawned + inventory (PlayerList.respawn; chat, chunk data, light and keep-alives + left out, runs of a packet counted), then that the level loads where the + player respawned (guests' death messages aren't Horizon's yet: left out); +- the furnace menu: its type and title, its contents, the slots each + shift-click changes and its lit and cooking totals; - the console lines about the player, the chat, `list`, `say` and `stop`; - the files the servers leave: server.properties (but the date line), eula.txt, ops.json, whitelist.json, banned-players.json, banned-ips.json. @@ -197,12 +208,18 @@ CONSOLE_LINE = re.compile(r'^\[\d\d:\d\d:\d\d\] \[([^\]]+)\]: (.*)$') KEPT = re.compile(r'Tester|\[Server\]|\[Not Secure\]|There are|Stopping|Saving|ThreadedAnvilChunkStorage|All dimensions|Unknown or incomplete') +# Guests' death messages, the op's command feedback broadcast to the console and guests' +# advancement announcements aren't Horizon's yet (the client's own transcript leaves the +# death message out as well). +NOT_YET = re.compile(r'Tester was killed|Killed Tester|System chat: \[Tester: |Tester has made the advancement') + + def console_lines(lines): """The console lines the comparison covers, timestamps and ports aside.""" out = [] for line in lines: m = CONSOLE_LINE.match(line) - if not m or not KEPT.search(m.group(2)): + if not m or not KEPT.search(m.group(2)) or NOT_YET.search(m.group(2)): continue text = re.sub(r'/127\.0\.0\.1:\d+', '/127.0.0.1:_', m.group(2)) text = re.sub(r'entity id \d+', 'entity id _', text) @@ -246,7 +263,27 @@ def run_side(label, command, directory, client): '{profession:"minecraft:librarian",level:2,type:"minecraft:plains"}}') port = int(PROPERTIES_PORTS[label]) legacy = legacy_ping(port) - client(port, directory.parent / f'{label}-client.txt') + # The client asks to be made an operator once it has traded, runs /kill and respawns. + failure = [] + + def join(): + try: + client(port, directory.parent / f'{label}-client.txt') + except BaseException as error: # noqa: BLE001 - reported on the main thread + failure.append(error) + + joined = threading.Thread(target=join) + joined.start() + deadline = time.time() + 300 + while joined.is_alive() and not any(' ready to respawn' in l for l in server.lines): + if time.time() > deadline: + break + time.sleep(0.2) + if joined.is_alive(): + server.console(f'op {PLAYER}') + joined.join() + if failure: + raise failure[0] time.sleep(1) server.console('list') server.console('say console says hi')