diff --git a/Cargo.lock b/Cargo.lock index 8eadbf02a..a9c516955 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -685,6 +685,7 @@ dependencies = [ "glam", "horizon-assets", "horizon-core", + "horizon-protocol", "horizon-world", "png", "pollster", @@ -698,6 +699,15 @@ dependencies = [ name = "horizon-core" version = "0.1.0" +[[package]] +name = "horizon-protocol" +version = "0.1.0" +dependencies = [ + "flate2", + "horizon-world", + "serde_json", +] + [[package]] name = "horizon-world" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index aca7bb21d..e58b4f001 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets"] +members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol"] resolver = "2" [workspace.package] diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 4da5f8513..edd4db819 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -11,6 +11,7 @@ description = "Horizon native development client" horizon-assets = { path = "../horizon-assets" } horizon-core = { path = "../horizon-core" } horizon-world = { path = "../horizon-world" } +horizon-protocol = { path = "../horizon-protocol" } wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] } winit = "0.30.13" pollster = "0.4" diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 3352b1205..38e50dcb2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -14,6 +14,7 @@ mod explosion; mod growth; mod machines; mod tnt; +mod remote; use horizon_client::{ Result, assets::Assets, @@ -90,6 +91,9 @@ struct Options { no_pause: bool, /// Control socket path (`--control`), for `horizon-ctl`. control: Option, + /// Multiplayer: `--server HOST[:PORT]` joins at start; `--name` is the offline player name. + server: Option, + player_name: String, } impl Options { fn read() -> Result> { @@ -119,13 +123,15 @@ impl Options { dimension: None, no_pause: false, control: None, + server: None, + player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()), }; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (tools/prepare_native_client.py)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." + "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (tools/prepare_native_client.py)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." ); return Ok(None); } @@ -158,6 +164,8 @@ impl Options { "--smoke-report" => o.report = Some(value.into()), "--screenshot-after" => o.screenshot_after = Some(value.parse()?), "--world" => o.world = Some(value), + "--server" => o.server = Some(value), + "--name" => o.player_name = value, "--control-socket" => o.control = Some(value.into()), "--time" => o.time = Some(value.parse()?), "--weather" => o.weather = Some(value), @@ -441,6 +449,8 @@ struct Game<'a> { pending_screenshot: Option>, pending_bench: Option<(Instant, std::sync::mpsc::Sender)>, persist: persist::EntityMemory, + /// Connected to a server: the world comes from the network (game/remote.rs). + remote: Option, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Dim { @@ -1299,7 +1309,7 @@ impl Game<'_> { None } fn spawn_player(&mut self) -> Result<()> { - if self.player.is_some() { + if self.player.is_some() || self.remote.is_some() { return Ok(()); } if let Some((_, target)) = &self.travelling { @@ -1376,6 +1386,9 @@ impl Game<'_> { Ok(()) } fn tick(&mut self) -> Result<()> { + if self.remote.is_some() { + return self.tick_remote(); + } self.ticks += 1; self.world.game_time += 1; self.world.weather.tick(&mut self.world.random); @@ -1674,6 +1687,9 @@ impl Game<'_> { } let atlas_ptr: *const HudAtlas = &self.res.atlas; let _ = atlas_ptr; + if self.remote_overlay(&mut batch) { + return batch; + } if self.player.is_none() { let text = if self.spawn_search > 0 { "Finding a place to spawn..." } else { "Loading terrain..." }; let atlas = &self.res.atlas; @@ -1824,6 +1840,7 @@ impl Game<'_> { } Screen::Playing | Screen::Options => {} } + self.remote_hud(&mut batch); batch } fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) { @@ -1999,6 +2016,9 @@ impl Game<'_> { } fn close_container(&mut self) { self.close_station(); + if self.remote.is_some() { + return self.remote_close_container(); + } let mut returned: Vec = self.carried.take().into_iter().collect(); returned.extend(self.craft_grid.iter_mut().filter_map(Option::take)); for stack in returned { @@ -2021,6 +2041,8 @@ impl Game<'_> { fn click_inventory(&mut self, right: bool) { if self.station_click(right) { return; + if self.remote.is_some() { + return self.remote_click(right); } let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return }; let batch = HudBatch::new(size); @@ -3267,6 +3289,9 @@ impl Game<'_> { Ok(()) } fn close_world(&mut self) -> Result<()> { + if self.remote.is_some() { + return self.leave_server(None); + } self.save_game()?; self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); @@ -4165,6 +4190,9 @@ impl Game<'_> { } } fn save_game(&mut self) -> Result<()> { + if self.remote.is_some() { + return Ok(()); + } let keys: Vec<_> = self.world.modified.drain().collect(); let chunks: Vec<_> = keys .iter() @@ -4317,6 +4345,9 @@ impl Game<'_> { } /// A key press while a world is open (keyboard or control socket). fn key_pressed(&mut self, key: KeyCode) -> Result<()> { + if self.remote.is_some() && self.remote_key(key)? { + return Ok(()); + } match key { KeyCode::Escape => match self.screen { Screen::Options => { @@ -4383,6 +4414,9 @@ impl Game<'_> { } /// A mouse button while playing (window or control socket). fn play_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { + if self.remote.is_some() { + return self.remote_mouse(button, pressed); + } match button { MouseButton::Left => { if pressed && self.attack() { @@ -4414,6 +4448,9 @@ impl Game<'_> { Ok(()) } fn update_world(&mut self) { + if let Err(e) = self.poll_remote() { + eprintln!("Horizon: {e}"); + } if let Some(p) = &self.player { self.streaming.center = ((p.position.x.floor() as i32) >> 4, (p.position.z.floor() as i32) >> 4); } @@ -4563,6 +4600,7 @@ impl ApplicationHandler for Game<'_> { } Action::Play { folder } => self.open_world(&folder, None, None, false)?, Action::Create { folder, name, seed, creative } => self.open_world(&folder, Some(&name), seed, creative)?, + Action::Connect { address } => self.connect_server(&address, &self.options.player_name.clone())?, Action::None => {} } } @@ -4604,6 +4642,7 @@ impl ApplicationHandler for Game<'_> { } } } + Screen::Dead if pressed && self.remote.is_some() => self.remote_respawn(), Screen::Dead if pressed => { self.respawn_out_of_end()?; self.player = None; @@ -4638,6 +4677,7 @@ impl ApplicationHandler for Game<'_> { let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace); self.station_text(event.text.as_deref(), backspace); } + WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => self.remote_chat_key(&event), WindowEvent::KeyboardInput { event, .. } if self.title.is_some() => { if event.state == ElementState::Pressed && let Some(title) = self.title.as_mut() @@ -4936,6 +4976,7 @@ pub fn run() -> Result<()> { pending_screenshot: None, pending_bench: None, persist: Default::default(), + remote: None, }; if let Some(path) = &game.options.control { let server = horizon_client::control::Server::start(path) @@ -4944,6 +4985,10 @@ pub fn run() -> Result<()> { game.control = Some(server); } match game.options.world.clone() { + _ if game.options.server.is_some() => { + let (address, name) = (game.options.server.clone().unwrap_or_default(), game.options.player_name.clone()); + game.connect_server(&address, &name)?; + } Some(folder) => { let (seed, creative) = (game.options.seed, game.options.creative); game.open_world(&folder, None, Some(seed), creative)?; diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 563ba0cb5..e0993e691 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -27,6 +27,10 @@ const HELP: &[&str] = &[ "bench SECONDS reset stats, wait, then reply with the summary", "open WORLD [SEED] [creative] open or create a world from the title screen", "save save the world", + "connect HOST[:PORT] [NAME] join a multiplayer server (offline mode) from the title screen", + "chat MESSAGE send chat or a /command to the server", + "disconnect leave the server for the server list", + "respawn respawn after death on a server", "quit save and exit", ]; @@ -245,6 +249,36 @@ impl Game<'_> { self.open_world(folder, Some(folder), seed, creative)?; ok() } + "connect" => { + if self.title.is_none() { + return Err("leave the current world first".into()); + } + let name = words.get(2).map_or_else(|| self.options.player_name.clone(), |n| (*n).to_owned()); + self.connect_server(arg(1)?, &name)?; + ok() + } + "chat" => { + if self.remote.is_none() { + return Err("not connected to a server".into()); + } + let message = line.trim_start().strip_prefix("chat").unwrap_or("").trim(); + self.send_chat(message); + ok() + } + "respawn" => { + if self.remote.is_none() || self.screen != Screen::Dead { + return Err("respawn needs the death screen on a server".into()); + } + self.remote_respawn(); + ok() + } + "disconnect" => { + if self.remote.is_none() { + return Err("not connected to a server".into()); + } + self.leave_server(None)?; + ok() + } "save" => { self.require_world()?; self.save_game()?; @@ -338,6 +372,7 @@ impl Game<'_> { "meshed_sections": self.streaming.meshed_total, "renderer": renderer, "uptime_seconds": self.started.elapsed().as_secs_f64(), + "server": self.remote_status(), }) } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs new file mode 100644 index 000000000..53f18b075 --- /dev/null +++ b/crates/horizon-client/src/game/remote.rs @@ -0,0 +1,1688 @@ +//! Multiplayer: the game driven by a server connection instead of the local +//! simulation. Mirrors vanilla's ClientPacketListener (chunks, entities, +//! inventory, health, time, weather, chat, respawn and dimension changes), +//! LocalPlayer.sendPosition (movement packets) and MultiPlayerGameMode +//! (block breaking with sequence numbers, use-item, attacks, container +//! clicks). The player still moves with the local physics, as the vanilla +//! client predicts its own movement; the server stays authoritative for +//! everything else. +use super::{Dim, Game, Mining, Screen}; +use horizon_client::{ + Result, + chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS, Section}, + containers::{BlockEntity, Furnace, FurnaceKind}, + entities::{Experience, ItemEntity}, + hud::{HudBatch, rgba}, + items::ItemStack, + mobs::{Anim, Brain, Mob, MobType}, + motion::{MotionWorld, PlayerMotion}, + net::{Event, Session}, + save::SaveDir, + sprint::Keys, + streaming::{ChunkGenerator, Proto, Streaming}, + world::World, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_protocol::{ + entity_data::{ITEM_ENTITY_ITEM, Value}, + item::{Hashed, Stack}, + packets::{ + Empty, + play::{self, Clientbound as C, Serverbound as S}, + }, + registry::{Builtin, DimensionType, Dynamic, ceil_log2}, + text::{Language, format_java, plain}, +}; +use horizon_world::{nbt::Tag, registry::BlockStateId}; +use std::{ + collections::HashMap, + sync::Arc, + time::{Duration, Instant}, +}; +use winit::{event::MouseButton, keyboard::KeyCode}; + +/// Streaming needs a generator; a server world never generates. +struct NoTerrain; +impl ChunkGenerator for NoTerrain { + type Worker = (); + fn worker(&self) {} + fn proto(&self, _: &mut (), _: i32, _: i32) -> Proto { + Box::new(()) + } + fn finish(&self, _: Proto) -> Chunk { + Chunk::empty(0, 0) + } +} + +/// A server entity the client tracks (position as last sent). +struct Tracked { + kind: String, + position: [f64; 3], +} +/// Smooth an entity toward a new position over three ticks (InterpolationHandler). +#[derive(Clone, Copy)] +struct Lerp { + target: [f64; 3], + steps: u32, +} + +pub(super) struct Remote { + pub session: Session, + builtin: Arc, + lang: Arc, + registries: Arc, + joined: bool, + status: String, + entity_id: i32, + dimension: DimensionType, + biome_map: Vec, + biome_bits: u8, + view_distance: i32, + sequence: i32, + last_pos: [f64; 3], + last_rot: (f32, f32), + last_on_ground: bool, + last_collision: bool, + reminder: u32, + last_input: u8, + was_sprinting: bool, + carried: Option, + loaded_sent: bool, + /// Open container: (window id, menu name). + menu: Option<(i32, String)>, + state_id: i32, + use_target: Option<[i32; 3]>, + entities: HashMap, + lerps: HashMap, + /// Item entities waiting for their item data. + pending_items: HashMap, + health: (f32, i32, f32), + game_mode: i32, + pub chat: Vec<(String, Instant)>, + pub chat_input: Option, + action_bar: Option<(String, Instant)>, + players: HashMap, + destroying: Option<([i32; 3], u8, f32)>, + destroy_delay: u32, + placing: Option<([i32; 3], u64)>, + death_message: Option, + player_type: Option>, + /// Inventory as last synchronised, for creative-mode slot updates. + synced: Vec>, + decode_errors: u32, + clock: Option, + clock_rate: f32, +} + +fn face_direction(face: [i32; 3]) -> u8 { + match face { + [0, -1, 0] => 0, + [0, 1, 0] => 1, + [0, 0, -1] => 2, + [0, 0, 1] => 3, + [-1, 0, 0] => 4, + [1, 0, 0] => 5, + _ => 1, + } +} + +impl Game<'_> { + /// Leave the title for a server (ConnectScreen): an empty world fed by the connection. + pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> { + let root = self.options.resources.clone(); + let builtin = Builtin::find(&root) + .and_then(|p| Builtin::load(&p).ok()) + .ok_or("registries.json not found next to the resources; run the data generator reports (tools/prepare_native_client.py)")?; + let lang = Arc::new(horizon_client::net::load_language(&root)); + let view = self.settings.render_distance.clamp(2, 32) as i8; + let session = Session::connect(address, name, view, lang.clone()); + let player_type = horizon_client::mobs::load_model(&root, "minecraft:player#main").map(|model| { + Arc::new(MobType { + id: "minecraft:player".into(), + width: 0.6, + height: 1.8, + eye_height: 1.62, + category: "misc".into(), + max_health: 20.0, + speed: 0.1, + attack_damage: 1.0, + follow_range: 0.0, + step_height: 0.6, + model: Arc::new(model), + texture: "entity/player/wide/steve".into(), + brain: Brain::Passive, + anim: Anim::Humanoid { zombie_arms: false }, + sounds: ["entity.player.hurt", "entity.player.hurt", "entity.player.death"], + }) + }); + let mut streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), self.res.threads); + streaming.remote = true; + streaming.radius = self.settings.render_distance; + self.streaming = streaming; + self.world = World::new(self.res.facts.air, 0); + self.save = Arc::new(SaveDir::new(std::env::temp_dir().join("horizon-remote-unused"))); + self.inventory = vec![None; 36]; + self.armor = [None, None, None, None]; + self.craft_grid = vec![None; 9]; + self.craft_size = 2; + self.player = None; + self.spawn = None; + self.mobs.clear(); + self.arrows.clear(); + self.dropped.clear(); + self.particles.clear(); + self.orbs.clear(); + self.falling.clear(); + self.travelling = None; + self.mining = None; + self.container = None; + self.carried = None; + self.using = None; + self.creative = false; + self.experience = Experience { level: 0, progress: 0.0, total: 0 }; + self.screen = Screen::Playing; + self.title = None; + self.dim = Dim::Overworld; + if let Some(r) = self.renderer.as_mut() { + r.clear_sections(); + } + self.apply_settings(); + self.remote = Some(Remote { + session, + builtin: Arc::new(builtin), + lang, + registries: Arc::new(Dynamic::default()), + joined: false, + status: "Connecting to the server...".into(), + entity_id: 0, + dimension: DimensionType::vanilla("minecraft:overworld"), + biome_map: Vec::new(), + biome_bits: 7, + view_distance: self.settings.render_distance, + sequence: 0, + last_pos: [0.0; 3], + last_rot: (0.0, 0.0), + last_on_ground: false, + last_collision: false, + reminder: 0, + last_input: 0, + was_sprinting: false, + carried: None, + loaded_sent: false, + menu: None, + state_id: 0, + use_target: None, + entities: HashMap::new(), + lerps: HashMap::new(), + pending_items: HashMap::new(), + health: (20.0, 20, 5.0), + game_mode: 0, + chat: Vec::new(), + chat_input: None, + action_bar: None, + players: HashMap::new(), + destroying: None, + destroy_delay: 0, + placing: None, + death_message: None, + player_type, + synced: vec![None; 36], + decode_errors: 0, + clock: None, + clock_rate: 1.0, + }); + Ok(()) + } + + /// Disconnect and return to the multiplayer screen (DisconnectedScreen). + pub(super) fn leave_server(&mut self, reason: Option) -> Result<()> { + if let Some(mut r) = self.remote.take() { + r.session.disconnect(); + } + self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1); + self.streaming.paused = true; + self.world = World::new(self.res.facts.air, 0); + self.player = None; + self.mobs.clear(); + self.dropped.clear(); + self.particles.clear(); + self.screen = Screen::Playing; + self.container = None; + if let Some(r) = self.renderer.as_mut() { + r.clear_sections(); + } + let saves = std::env::current_dir()?.join("saves"); + let mut title = horizon_client::title::Title::new(saves.clone()); + title.mode = horizon_client::title::Mode::Multiplayer(match reason { + Some(reason) => horizon_client::multiplayer::Screen::Disconnected { reason }, + None => horizon_client::multiplayer::Screen::list(&saves), + }); + self.title = Some(title); + self.capture(false); + Ok(()) + } + + fn send(&self, packet: S) { + if let Some(r) = &self.remote { + r.session.send(packet); + } + } + fn next_sequence(&mut self) -> i32 { + let r = self.remote.as_mut().expect("remote"); + r.sequence += 1; + r.sequence + } + fn item_name(&self, id: i32) -> Arc { + let r = self.remote.as_ref().expect("remote"); + Arc::from(r.builtin.get("minecraft:item").and_then(|i| i.name(id)).unwrap_or("minecraft:air")) + } + fn item_id(&self, name: &str) -> i32 { + let r = self.remote.as_ref().expect("remote"); + r.builtin.get("minecraft:item").and_then(|i| i.id(name)).unwrap_or(0) + } + fn to_stack(&self, s: &Option) -> Option { + let s = s.as_ref()?; + Some(ItemStack { item: self.item_name(s.item), count: s.count.max(0) as u32, damage: s.damage().max(0) as u32 }) + } + fn to_network(&self, s: &Option) -> Option { + let s = s.as_ref()?; + let mut stack = Stack::new(self.item_id(&s.item), s.count as i32); + if s.damage > 0 { + stack.added.push((horizon_protocol::item::component::DAMAGE, horizon_protocol::item::Component::Int(s.damage as i32))); + } + Some(stack) + } + fn chat_line(&mut self, text: String) { + eprintln!("[chat] {text}"); + if let Some(r) = self.remote.as_mut() { + r.chat.push((text, Instant::now())); + if r.chat.len() > 100 { + r.chat.remove(0); + } + } + } + + /// Process everything the network thread received (once per frame, like + /// the client's packet processor). + pub(super) fn poll_remote(&mut self) -> Result<()> { + let Some(r) = &self.remote else { return Ok(()) }; + let events = r.session.poll(); + for event in events { + match event { + Event::Status(s) => { + if let Some(r) = self.remote.as_mut() { + r.status = s; + } + } + Event::Joined { registries, name, .. } => { + self.set_registries(registries); + if let Some(r) = self.remote.as_mut() { + r.joined = true; + r.status = format!("Joined as {name}; loading terrain..."); + } + } + Event::Reconfigured(registries) => self.set_registries(registries), + Event::DecodeError(e) => { + if let Some(r) = self.remote.as_mut() { + r.decode_errors += 1; + if r.decode_errors <= 20 { + eprintln!("Horizon: skipped undecodable packet {e}"); + } + } + } + Event::Disconnected(reason) => { + eprintln!("Horizon: disconnected: {reason}"); + return self.leave_server(Some(reason)); + } + Event::Packet(packet) => self.handle_packet(*packet)?, + } + if self.remote.is_none() { + break; + } + } + Ok(()) + } + fn set_registries(&mut self, registries: Arc) { + let biomes: Vec = registries + .registries + .get("minecraft:worldgen/biome") + .map(|list| list.iter().map(|(name, _)| self.res.biomes.id(name)).collect()) + .unwrap_or_default(); + if let Some(r) = self.remote.as_mut() { + r.biome_bits = ceil_log2(biomes.len()); + r.biome_map = biomes; + r.registries = registries; + } + } + /// Switch to a (possibly new) dimension: a fresh client level. + fn enter_remote_dimension(&mut self, spawn: &play::SpawnInfo, keep_world: bool) { + let Some(r) = self.remote.as_mut() else { return }; + let dimension = r.registries.dimension(spawn.dimension_type); + let same = r.dimension.name == dimension.name && keep_world; + r.dimension = dimension; + r.game_mode = spawn.game_type; + r.loaded_sent = false; + self.creative = spawn.game_type == 1; + self.dim = if spawn.dimension == "minecraft:the_nether" { Dim::Nether } else { Dim::Overworld }; + if !same { + let mut streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), self.res.threads); + streaming.remote = true; + streaming.radius = self.streaming.radius; + self.streaming = streaming; + let (time, day, weather) = (self.world.game_time, self.world.day_time, self.world.weather); + self.world = World::new(self.res.facts.air, spawn.seed); + self.world.game_time = time; + self.world.day_time = day; + self.world.weather = weather; + self.mobs.clear(); + self.dropped.clear(); + self.particles.clear(); + if let Some(r) = self.remote.as_mut() { + r.entities.clear(); + r.lerps.clear(); + r.pending_items.clear(); + } + if let Some(renderer) = self.renderer.as_mut() { + renderer.clear_sections(); + } + } + let has_sky = self.remote.as_ref().is_none_or(|r| r.dimension.has_skylight); + self.streaming.sky_light = has_sky; + self.streaming.nether_shading = self.dim == Dim::Nether; + self.player = None; + self.apply_settings(); + } + + /// LevelChunkSection data into the client's fixed -64..320 column. + fn remote_chunk(&self, p: &play::LevelChunkWithLight) -> std::result::Result { + let r = self.remote.as_ref().ok_or("no connection")?; + let sections = p.chunk.sections(r.dimension.sections(), 16, r.biome_bits).map_err(|e| e.to_string())?; + let mut chunk = Chunk::empty(p.x, p.z); + let mut biomes = vec![0u16; chunk.biomes.len()]; + let offset = (r.dimension.min_y - MIN_Y).div_euclid(16); + for (i, s) in sections.iter().enumerate() { + let target = offset + i as i32; + if !(0..SECTIONS as i32).contains(&target) { + continue; + } + let blocks = if s.states.bits == 0 { + Blocks::Uniform(s.states.get(0) as u16) + } else { + let mut a = Box::new([0u16; 4096]); + for (j, v) in a.iter_mut().enumerate() { + *v = s.states.get(j) as u16; + } + Blocks::Full(a) + }; + let mut section = Section { blocks, light: Light::Uniform(0xF0) }; + section.compact(); + chunk.sections[target as usize] = Arc::new(section); + for j in 0..64 { + let biome = r.biome_map.get(s.biomes.get(j) as usize).copied().unwrap_or(0); + if let Some(cell) = biomes.get_mut(target as usize * 64 + j) { + *cell = biome; + } + } + } + // Columns outside the dimension's range take its nearest biome. + let (lo, hi) = (offset.max(0) as usize * 64, ((offset + sections.len() as i32).min(SECTIONS as i32)) as usize * 64); + if lo < hi { + for j in 0..biomes.len() { + if j < lo { + biomes[j] = biomes[lo + j % 16]; + } else if j >= hi { + biomes[j] = biomes[hi - 16 + j % 16]; + } + } + } + chunk.biomes = Arc::new(biomes); + Ok(chunk) + } + /// Keep the renderable block entities (chests, furnaces) in step with blocks. + fn sync_block_entity(&mut self, pos: (i32, i32, i32), state: BlockStateId) { + let name = self.res.facts.get(state).name.clone(); + match BlockEntity::for_block(&name) { + Some(entity) => { + let same = self.world.block_entities.get(&pos).is_some_and(|e| e.id() == entity.id()); + if !same { + self.world.block_entities.insert(pos, entity); + } + } + None => { + self.world.block_entities.remove(&pos); + } + } + } + fn set_block(&mut self, pos: [i32; 3], state: i32) { + let state = BlockStateId(state.max(0) as u32); + if self.world.loaded(pos[0], pos[2]) && self.world.set(pos[0], pos[1], pos[2], state).is_ok() { + self.sync_block_entity((pos[0], pos[1], pos[2]), state); + } + // A block we just placed: play its place sound (the server skips the placer). + if let Some((target, _)) = self.remote.as_ref().and_then(|r| r.placing) + && target == pos + && !self.res.facts.is_air(state) + { + let s = self.res.facts.get(state).sounds.clone(); + let at = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; + self.audio.play(&s.place, Some(at), (s.volume + 1.0) / 2.0, s.pitch * 0.8); + if let Some(r) = self.remote.as_mut() { + r.placing = None; + } + } + } + fn spawn_entity(&mut self, id: i32, kind: &str, position: [f64; 3], yaw: f32, head: f32) { + let at = Vec3::new(position[0], position[1], position[2]); + let mob_type = if kind == "minecraft:player" { + self.remote.as_ref().and_then(|r| r.player_type.clone()) + } else { + self.res.mob_types.get(kind).cloned() + }; + if let Some(t) = mob_type { + let mut mob = Mob::new(id as u32, t, at, head); + mob.body_yaw = yaw; + mob.previous_body_yaw = yaw; + mob.persistent = true; + self.mobs.retain(|m| m.id != id as u32); + self.mobs.push(mob); + } + if let Some(r) = self.remote.as_mut() { + if kind == "minecraft:item" { + r.pending_items.insert(id, position); + } + r.entities.insert(id, Tracked { kind: kind.to_owned(), position }); + } + } + fn move_entity(&mut self, id: i32, position: [f64; 3], rotation: Option<(f32, f32)>, on_ground: bool) { + if let Some(r) = self.remote.as_mut() { + if let Some(t) = r.entities.get_mut(&id) { + t.position = position; + } + r.lerps.insert(id, Lerp { target: position, steps: 3 }); + if let Some(p) = r.pending_items.get_mut(&id) { + *p = position; + } + } + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { + m.on_ground = on_ground; + if let Some((yaw, pitch)) = rotation { + m.body_yaw = yaw; + m.head_pitch = pitch; + } + } + } + fn remove_entity(&mut self, id: i32) { + self.mobs.retain(|m| m.id != id as u32); + self.dropped.retain(|d| d.id != id as u32); + if let Some(r) = self.remote.as_mut() { + r.entities.remove(&id); + r.lerps.remove(&id); + r.pending_items.remove(&id); + } + } + /// Map a menu slot to Horizon's inventory screen slot ids. + fn menu_slot(menu: &str, slot: i32) -> Option { + let s = usize::try_from(slot).ok()?; + let rows = |n: usize| -> Option { + match s { + _ if s < n * 9 => Some(300 + s), + _ if s < n * 9 + 27 => Some(9 + s - n * 9), + _ if s < n * 9 + 36 => Some(s - n * 9 - 27), + _ => None, + } + }; + match menu { + "inventory" => match s { + 0 => Some(200), + 1..=4 => Some(100 + s - 1), + 5..=8 => Some(500 + s - 5), + 9..=35 => Some(s), + 36..=44 => Some(s - 36), + _ => None, + }, + "minecraft:crafting" => match s { + 0 => Some(200), + 1..=9 => Some(100 + s - 1), + 10..=36 => Some(9 + s - 10), + 37..=45 => Some(s - 37), + _ => None, + }, + "minecraft:furnace" | "minecraft:blast_furnace" | "minecraft:smoker" => match s { + 0..=2 => Some(300 + s), + 3..=29 => Some(9 + s - 3), + 30..=38 => Some(s - 30), + _ => None, + }, + "minecraft:generic_9x1" => rows(1), + "minecraft:generic_9x2" => rows(2), + "minecraft:generic_9x3" | "minecraft:shulker_box" => rows(3), + "minecraft:generic_9x4" => rows(4), + "minecraft:generic_9x5" => rows(5), + "minecraft:generic_9x6" => rows(6), + _ => None, + } + } + fn open_menu_name(&self, container: i32) -> String { + match self.remote.as_ref().and_then(|r| r.menu.as_ref()) { + Some((id, name)) if *id == container && container != 0 => name.clone(), + _ => "inventory".into(), + } + } + fn set_menu_slot(&mut self, container: i32, slot: i32, item: Option) { + let menu = self.open_menu_name(container); + if container != 0 && menu == "inventory" { + return; + } + let Some(internal) = Self::menu_slot(&menu, slot) else { return }; + if internal == 200 { + return; // the result slot is recomputed from the grid + } + *self.slot_mut(internal) = item; + } + + fn handle_packet(&mut self, packet: C) -> Result<()> { + match packet { + C::Login(p) => { + if let Some(r) = self.remote.as_mut() { + r.entity_id = p.player_id; + r.view_distance = p.chunk_radius; + } + self.streaming.radius = self.settings.render_distance.min(p.chunk_radius + 1).max(2); + self.enter_remote_dimension(&p.spawn, false); + self.send(S::ClientInformation(horizon_protocol::packets::configuration::ClientInformation::new(self.settings.render_distance.clamp(2, 32) as i8))); + } + C::Respawn(p) => { + self.enter_remote_dimension(&p.spawn, true); + self.screen = Screen::Playing; + if let Some(r) = self.remote.as_mut() { + r.death_message = None; + r.health = (20.0, 20, 5.0); + } + self.capture(true); + } + C::PlayerPosition(p) => self.remote_teleport(&p)?, + C::PlayerRotation(p) => { + self.yaw = if p.relative_yaw { self.yaw + p.yaw } else { p.yaw }; + self.pitch = (if p.relative_pitch { self.pitch + p.pitch } else { p.pitch }).clamp(-90.0, 90.0); + } + C::LevelChunkWithLight(p) => match self.remote_chunk(&p) { + Ok(chunk) => { + let (x, z) = (p.x, p.z); + self.streaming.insert_remote(&mut self.world, chunk); + self.world.block_entities.retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); + for info in &p.chunk.block_entities { + let pos = (x * 16 + i32::from(info.packed_xz as u8 >> 4), i32::from(info.y), z * 16 + i32::from(info.packed_xz as u8 & 15)); + let state = self.world.block(pos.0, pos.1, pos.2); + self.sync_block_entity(pos, state); + } + } + Err(e) => eprintln!("Horizon: chunk {} {}: {e}", p.x, p.z), + }, + C::ForgetLevelChunk(p) => { + let [x, z] = p.pos; + self.streaming.forget(&mut self.world, x, z); + self.world.block_entities.retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); + if let Some(renderer) = self.renderer.as_mut() { + for sy in 0..SECTIONS as i32 { + renderer.remove((x, sy, z)); + } + } + } + C::ChunkBatchFinished(_) => { + // ChunkBatchSizeCalculator's ceiling; meshing runs on workers. + self.send(S::ChunkBatchReceived(play::ChunkBatchReceived { chunks_per_tick: 64.0 })); + } + C::BlockUpdate(p) => self.set_block(p.pos, p.state), + C::SectionBlocksUpdate(p) => { + let [sx, sy, sz] = p.section; + for change in p.changes { + let local = (change & 0xFFF) as i32; + let pos = [sx * 16 + (local >> 8 & 15), sy * 16 + (local & 15), sz * 16 + (local >> 4 & 15)]; + self.set_block(pos, (change >> 12) as i32); + } + } + C::BlockChangedAck(_) => {} + C::LevelEvent(p) if p.kind == 2001 => { + // LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block. + let state = BlockStateId(p.data.max(0) as u32); + let s = self.res.facts.get(state).sounds.clone(); + let at = [f64::from(p.pos[0]) + 0.5, f64::from(p.pos[1]) + 0.5, f64::from(p.pos[2]) + 0.5]; + self.audio.play(&s.break_sound, Some(at), (s.volume + 1.0) / 2.0, s.pitch * 0.8); + self.destroy_particles(p.pos, state); + } + C::Sound(p) => { + let name = match &p.sound.1 { + Some((location, _)) => Some(location.clone()), + None => self.remote.as_ref().and_then(|r| r.builtin.get("minecraft:sound_event")?.name(p.sound.0).map(str::to_owned)), + }; + if let Some(name) = name { + let at = [f64::from(p.x) / 8.0, f64::from(p.y) / 8.0, f64::from(p.z) / 8.0]; + self.audio.play(&name, Some(at), p.volume, p.pitch); + } + } + C::AddEntity(p) => { + let kind = self.remote.as_ref().and_then(|r| r.builtin.get("minecraft:entity_type")?.name(p.kind).map(str::to_owned)).unwrap_or_default(); + let yaw = horizon_protocol::buf::unpack_degrees(p.yaw); + let head = horizon_protocol::buf::unpack_degrees(p.head_yaw); + self.spawn_entity(p.id, &kind, p.position, yaw, head); + } + C::RemoveEntities(p) => { + for id in p.ids { + self.remove_entity(id); + } + } + C::MoveEntityPos(play::MoveEntityPos(m)) | C::MoveEntityPosRot(play::MoveEntityPosRot(m)) | C::MoveEntityRot(play::MoveEntityRot(m)) => { + let base = self.remote.as_ref().and_then(|r| r.entities.get(&m.id)).map(|t| t.position); + let Some(base) = base else { return Ok(()) }; + let position = m.delta.as_ref().map_or(base, |d| d.end(base)); + let rotation = m.rotation.map(|(y, x)| (horizon_protocol::buf::unpack_degrees(y), horizon_protocol::buf::unpack_degrees(x))); + self.move_entity(m.id, position, rotation, m.on_ground); + } + C::EntityPositionSync(p) => self.move_entity(p.id, p.path.end(), Some((p.yaw, p.pitch)), p.on_ground), + C::TeleportEntity(p) => { + let base = self.remote.as_ref().and_then(|r| r.entities.get(&p.id)).map_or([0.0; 3], |t| t.position); + let rel = |bit: i32, i: usize| if p.relatives & bit != 0 { base[i] + p.position[i] } else { p.position[i] }; + let position = [rel(play::relative::X, 0), rel(play::relative::Y, 1), rel(play::relative::Z, 2)]; + self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground); + } + C::RotateHead(p) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.yaw = horizon_protocol::buf::unpack_degrees(p.head_yaw); + } + } + C::SetEntityData(p) => { + for (index, _, value) in &p.values { + if *index == ITEM_ENTITY_ITEM + && let Value::Item(stack) = value + { + self.remote_item_data(p.id, stack); + } + } + } + C::TakeItemEntity(p) => { + if self.remote.as_ref().is_some_and(|r| r.entity_id == p.player) + && let Some(eye) = self.eye_position() + { + let pitch = ((self.world.random.next_float() - self.world.random.next_float()) * 0.7 + 1.0) * 2.0; + self.audio.play("minecraft:entity.item.pickup", Some(eye), 0.2, pitch); + } + self.remove_entity(p.item); + } + C::HurtAnimation(p) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.hurt_time = 10; + } + } + C::EntityEvent(p) => { + // EntityEvent.DEATH: start the death animation. + if p.event == 3 + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) + { + m.health = 0.0; + } + } + C::Animate(p) if p.action == 0 => {} + C::SetHealth(p) => { + if let Some(r) = self.remote.as_mut() { + r.health = (p.health, p.food, p.saturation); + } + self.apply_remote_health(); + if p.health <= 0.0 && self.screen != Screen::Dead && self.player.is_some() { + self.screen = Screen::Dead; + self.capture(false); + } + } + C::PlayerCombatKill(p) => { + let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); + let message = plain(&p.message, &lang); + if let Some(r) = self.remote.as_mut() { + r.death_message = Some(message); + } + } + C::SetExperience(p) => self.experience = Experience { level: p.level, progress: p.progress, total: p.total }, + C::SetTime(p) => { + self.world.game_time = p.game_time; + let clock = { + let r = self.remote.as_ref(); + let names = r.and_then(|r| r.registries.registries.get("minecraft:world_clock")); + let wanted = r.map(|r| r.dimension.name.clone()).unwrap_or_default(); + p.clocks + .iter() + .find(|c| names.and_then(|n| n.get(c.clock as usize)).is_some_and(|(n, _)| *n == wanted)) + .or_else(|| p.clocks.first()) + .cloned() + }; + if let Some(c) = clock { + self.world.day_time = c.total_ticks; + if let Some(r) = self.remote.as_mut() { + r.clock = Some(c.clock); + r.clock_rate = c.rate; + } + } + } + C::GameEvent(p) => match p.event { + 1 => { + self.world.weather.raining = true; + self.world.weather.rain_level = (0.0, 0.0); + } + 2 => { + self.world.weather.raining = false; + self.world.weather.rain_level = (1.0, 1.0); + } + 3 => { + let mode = p.param as i32; + self.creative = mode == 1; + if let Some(r) = self.remote.as_mut() { + r.game_mode = mode; + } + } + 7 => { + self.world.weather.rain_level = (p.param, p.param); + self.world.weather.raining = p.param > 0.0; + } + 8 => { + self.world.weather.thunder_level = (p.param, p.param); + self.world.weather.thundering = p.param > 0.0; + } + _ => {} + }, + C::PlayerAbilities(p) => self.creative = p.flags & 8 != 0, + C::SetHeldSlot(p) => { + self.selected = p.slot.clamp(0, 8) as usize; + if let Some(r) = self.remote.as_mut() { + r.carried = Some(self.selected); + } + } + C::ContainerSetContent(p) => { + if let Some(r) = self.remote.as_mut() { + r.state_id = p.state; + } + for (slot, item) in p.items.iter().enumerate() { + let stack = self.to_stack(item); + self.set_menu_slot(p.container, slot as i32, stack); + } + self.carried = self.to_stack(&p.carried); + self.remote_synced(); + } + C::ContainerSetSlot(p) => { + if let Some(r) = self.remote.as_mut() { + r.state_id = p.state; + } + let stack = self.to_stack(&p.item); + self.set_menu_slot(p.container, i32::from(p.slot), stack); + self.remote_synced(); + } + C::SetCursorItem(p) => self.carried = self.to_stack(&p.item), + C::SetPlayerInventory(p) => { + let stack = self.to_stack(&p.item); + match p.slot { + 0..=35 => self.inventory[p.slot as usize] = stack, + 36..=39 => self.armor[3 - (p.slot - 36) as usize] = stack, + _ => {} + } + self.remote_synced(); + } + C::ContainerSetData(p) => { + if let Some(key) = self.container + && let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&key) + { + let v = i32::from(p.value); + match p.id { + 0 => f.lit_remaining = v, + 1 => f.lit_total = v, + 2 => f.cooking_timer = v, + 3 => f.cooking_total = v, + _ => {} + } + } + } + C::OpenScreen(p) => self.remote_open_screen(p), + C::ContainerClose(_) => { + if self.screen == Screen::Inventory { + self.remote_close_local(); + self.screen = Screen::Playing; + self.capture(true); + } + } + C::SystemChat(p) => { + let text = plain(&p.content, &self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default()); + if p.overlay { + if let Some(r) = self.remote.as_mut() { + r.action_bar = Some((text, Instant::now())); + } + } else { + self.chat_line(text); + } + } + C::PlayerChat(p) => { + let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); + let content = p.unsigned_content.as_ref().map_or_else(|| p.content.clone(), |t| plain(t, &lang)); + let line = self.format_chat(&p.chat_type, &content); + self.chat_line(line); + } + C::DisguisedChat(p) => { + let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); + let content = plain(&p.message, &lang); + let line = self.format_chat(&p.chat_type, &content); + self.chat_line(line); + } + C::PlayerInfoUpdate(p) => { + if let Some(r) = self.remote.as_mut() { + for e in p.entries { + if let Some(name) = e.name { + r.players.insert(e.uuid, name); + } + } + } + } + C::PlayerInfoRemove(p) => { + if let Some(r) = self.remote.as_mut() { + for u in p.uuids { + r.players.remove(&u); + } + } + } + C::SetChunkCacheRadius(p) => { + self.streaming.radius = self.settings.render_distance.min(p.distance + 1).max(2); + if let Some(r) = self.remote.as_mut() { + r.view_distance = p.distance; + } + } + C::SetActionBarText(p) | C::SetTitleText(p) => { + let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); + let text = plain(&p.text, &lang); + if let Some(r) = self.remote.as_mut() { + r.action_bar = Some((text, Instant::now())); + } + } + _ => {} + } + Ok(()) + } + /// ChatType decoration: `chat.translation_key` with sender/content parameters. + fn format_chat(&self, bound: &play::ChatTypeBound, content: &str) -> String { + let Some(r) = self.remote.as_ref() else { return content.to_owned() }; + let sender = plain(&bound.name, &r.lang); + let decoration = r.registries.data("minecraft:chat_type", bound.chat_type).and_then(|t| t.get("chat")); + let key = match decoration.and_then(|d| d.get("translation_key")) { + Some(Tag::String(s)) => s.to_string_lossy(), + _ => "chat.type.text".into(), + }; + let params: Vec = match decoration.and_then(|d| d.get("parameters")) { + Some(Tag::List(list)) => list + .iter() + .map(|p| match p { + Tag::String(s) => match s.to_string_lossy().as_str() { + "sender" => sender.clone(), + "target" => bound.target.as_ref().map(|t| plain(t, &r.lang)).unwrap_or_default(), + _ => content.to_owned(), + }, + _ => String::new(), + }) + .collect(), + _ => vec![sender, content.to_owned()], + }; + let pattern = r.lang.get(&key).cloned().unwrap_or_else(|| "<%s> %s".into()); + format_java(&pattern, ¶ms) + } + fn remote_item_data(&mut self, id: i32, stack: &Option) { + let Some(stack) = self.to_stack(stack) else { return }; + let position = self.remote.as_mut().and_then(|r| r.pending_items.remove(&id)); + if let Some(item) = self.dropped.iter_mut().find(|d| d.id == id as u32) { + item.stack = stack; + return; + } + let Some(p) = position else { return }; + let at = Vec3::new(p[0], p[1], p[2]); + let bob_offset = self.world.random.next_float() * std::f32::consts::PI * 2.0; + self.dropped.push(ItemEntity { + id: id as u32, + stack, + position: at, + previous: at, + velocity: Vec3::ZERO, + on_ground: false, + age: 0, + pickup_delay: 0, + bob_offset, + }); + } + fn apply_remote_health(&mut self) { + let Some((health, food, saturation)) = self.remote.as_ref().map(|r| r.health) else { return }; + if let Some(p) = self.player.as_mut() { + if (p.health.health() - health).abs() > f32::EPSILON { + let _ = p.set_health(health.max(0.0), false); + } + p.health.food.food = food; + p.health.food.saturation = saturation; + } + } + /// ClientPacketListener.handleMovePlayer. + fn remote_teleport(&mut self, p: &play::PlayerPosition) -> Result<()> { + use play::relative as rel; + let current = self.player.as_ref().map(|pl| pl.position).unwrap_or(Vec3::ZERO); + let velocity = self.player.as_ref().map(|pl| pl.velocity).unwrap_or(Vec3::ZERO); + let pick = |bit: i32, base: f64, v: f64| if p.relatives & bit != 0 { base + v } else { v }; + let position = Vec3::new(pick(rel::X, current.x, p.position[0]), pick(rel::Y, current.y, p.position[1]), pick(rel::Z, current.z, p.position[2])); + let yaw = if p.relatives & rel::Y_ROT != 0 { self.yaw + p.yaw } else { p.yaw }; + let pitch = (if p.relatives & rel::X_ROT != 0 { self.pitch + p.pitch } else { p.pitch }).clamp(-90.0, 90.0); + let delta = Vec3::new( + pick(rel::DELTA_X, velocity.x, p.delta[0]), + pick(rel::DELTA_Y, velocity.y, p.delta[1]), + pick(rel::DELTA_Z, velocity.z, p.delta[2]), + ); + match self.player.as_mut() { + Some(player) => { + player.position = position; + player.velocity = delta; + } + None => { + let mut player = PlayerMotion::new(self.motion, position)?; + player.velocity = delta; + self.player = Some(player); + self.eye = 1.62; + self.previous_eye = 1.62; + self.clock.reset(); + self.apply_remote_health(); + } + } + self.previous_position = position; + self.yaw = yaw; + self.pitch = pitch; + if let Some(r) = self.remote.as_mut() { + r.last_pos = [position.x, position.y, position.z]; + r.last_rot = (yaw, pitch); + r.destroying = None; + } + self.mining = None; + self.send(S::AcceptTeleportation(play::AcceptTeleportation { id: p.teleport, x: position.x, y: position.y, z: position.z, yaw, pitch })); + Ok(()) + } + + /// One client tick while connected (Minecraft.tick with a ClientLevel). + pub(super) fn tick_remote(&mut self) -> Result<()> { + self.ticks += 1; + self.world.game_time += 1; + let rate = self.remote.as_ref().map_or(1.0, |r| r.clock_rate); + if rate > 0.0 { + self.world.day_time += rate.round() as i64; + } + // Weather levels drift toward their targets between server updates. + let w = &mut self.world.weather; + w.rain_level.0 = w.rain_level.1; + w.thunder_level.0 = w.thunder_level.1; + if self.use_delay > 0 { + self.use_delay -= 1; + } + self.tick_remote_entities(); + self.tick_hand(); + let facts = &self.res.facts; + let world = &self.world; + self.particles.retain_mut(|p| p.tick(world, |id| facts.states[id as usize].full_collision)); + let Some(player) = self.player.as_mut() else { return Ok(()) }; + let (cx, cz) = ((player.position.x.floor() as i32) >> 4, (player.position.z.floor() as i32) >> 4); + if !self.streaming.is_lit(cx, cz) { + return Ok(()); + } + if self.remote.as_ref().is_some_and(|r| !r.loaded_sent) { + // ClientPacketListener: the level around the player is ready. + self.send(S::PlayerLoaded(Empty)); + if let Some(r) = self.remote.as_mut() { + r.loaded_sent = true; + } + } + let Some(player) = self.player.as_mut() else { return Ok(()) }; + let chatting = self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()); + let playing = self.screen == Screen::Playing && !chatting; + let held = |k| playing && self.keys.contains(&k); + let keys = Keys { + forward: held(KeyCode::KeyW), + backward: held(KeyCode::KeyS), + left: held(KeyCode::KeyA), + right: held(KeyCode::KeyD), + jump: held(KeyCode::Space), + shift: held(KeyCode::ShiftLeft), + sprint: held(KeyCode::ControlLeft), + }; + let input = u8::from(keys.forward) + | u8::from(keys.backward) << 1 + | u8::from(keys.left) << 2 + | u8::from(keys.right) << 3 + | u8::from(keys.jump) << 4 + | u8::from(keys.shift) << 5 + | u8::from(keys.sprint) << 6; + self.previous_position = player.position; + player.yaw = self.yaw; + let dead = self.screen == Screen::Dead; + if !dead { + MotionWorld { player, scene: &mut self.world, assets: &self.res.assets, collision_binding: self.collision, resources: self.motion } + .controlled_simulation_tick(keys)?; + } + let events = std::mem::take(&mut player.events); + self.previous_eye = self.eye; + self.eye += (player.dimensions.eye_height - self.eye) * 0.5; + let crouching = player.pose == horizon_client::pose::Pose::Crouching; + let feet = [player.position.x, player.position.y, player.position.z]; + for event in events { + if let horizon_client::motion::MotionEvent::Emission { state, .. } = event + && !crouching + { + let sounds = self.res.facts.get(state).sounds.clone(); + self.audio.play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch); + } + } + // The server owns health and hunger: undo local food/fall changes. + self.apply_remote_health(); + if let Some(p) = &self.player { + let (dx, dz) = (p.position.x - self.previous_position.x, p.position.z - self.previous_position.z); + let speed = ((dx * dx + dz * dz).sqrt() as f32).min(0.1); + self.walk.0 = self.walk.1; + self.walk.1 += (dx * dx + dz * dz).sqrt() as f32 * 0.6; + self.bob.0 = self.bob.1; + let target = if p.ground.on_ground { speed } else { 0.0 }; + self.bob.1 += (target - self.bob.1) * 0.4; + } + if !dead { + self.remote_mining(); + if self.right && self.use_delay == 0 && playing { + self.remote_use(); + self.use_delay = 4; + } + } + self.remote_send_state(input); + self.send(S::ClientTickEnd(Empty)); + Ok(()) + } + fn tick_remote_entities(&mut self) { + let Some(r) = self.remote.as_mut() else { return }; + let mut lerps = std::mem::take(&mut r.lerps); + for m in &mut self.mobs { + m.previous = m.position; + m.previous_yaw = m.yaw; + m.previous_body_yaw = m.body_yaw; + m.previous_limb_speed = m.limb_speed; + m.age += 1; + if m.hurt_time > 0 { + m.hurt_time -= 1; + } + if !m.alive() { + m.death_time += 1; + } + if let Some(l) = lerps.get_mut(&(m.id as i32)) + && l.steps > 0 + { + let n = f64::from(l.steps); + m.position = Vec3::new( + m.position.x + (l.target[0] - m.position.x) / n, + m.position.y + (l.target[1] - m.position.y) / n, + m.position.z + (l.target[2] - m.position.z) / n, + ); + l.steps -= 1; + } + // WalkAnimationState.update from the horizontal distance moved. + let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z); + let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0); + m.limb_speed += (target - m.limb_speed) * 0.4; + m.limb_position += m.limb_speed; + } + for d in &mut self.dropped { + d.previous = d.position; + d.age += 1; + if let Some(l) = lerps.get_mut(&(d.id as i32)) + && l.steps > 0 + { + let n = f64::from(l.steps); + d.position = Vec3::new( + d.position.x + (l.target[0] - d.position.x) / n, + d.position.y + (l.target[1] - d.position.y) / n, + d.position.z + (l.target[2] - d.position.z) / n, + ); + l.steps -= 1; + } + } + lerps.retain(|_, l| l.steps > 0); + if let Some(r) = self.remote.as_mut() { + for (id, l) in lerps { + r.lerps.entry(id).or_insert(l); + } + } + } + /// LocalPlayer.sendPosition plus input, sprint and held-slot updates. + fn remote_send_state(&mut self, input: u8) { + let Some(p) = self.player.as_ref() else { return }; + let (pos, on_ground, collision, sprinting) = ([p.position.x, p.position.y, p.position.z], p.ground.on_ground, p.collision.horizontal, p.sprinting); + let (yaw, pitch, selected) = (self.yaw, self.pitch, self.selected); + let Some(r) = self.remote.as_mut() else { return }; + let mut out = Vec::new(); + if r.carried != Some(selected) { + r.carried = Some(selected); + out.push(S::SetCarriedItem(play::SetCarriedItem { slot: selected as i16 })); + } + if input != r.last_input { + r.last_input = input; + out.push(S::PlayerInput(play::PlayerInput { flags: input })); + } + if sprinting != r.was_sprinting { + r.was_sprinting = sprinting; + out.push(S::PlayerCommand(play::PlayerCommand { id: r.entity_id, action: if sprinting { 1 } else { 2 }, data: 0 })); + } + r.reminder += 1; + let d = [pos[0] - r.last_pos[0], pos[1] - r.last_pos[1], pos[2] - r.last_pos[2]]; + let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 2.0e-4 * 2.0e-4 || r.reminder >= 20; + let rotated = yaw != r.last_rot.0 || pitch != r.last_rot.1; + let flags = u8::from(on_ground) | u8::from(collision) << 1; + let [x, y, z] = pos; + if moved && rotated { + out.push(S::MovePlayerPosRot(play::MovePlayerPosRot { x, y, z, yaw, pitch, flags })); + } else if moved { + out.push(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags })); + } else if rotated { + out.push(S::MovePlayerRot(play::MovePlayerRot { yaw, pitch, flags })); + } else if r.last_on_ground != on_ground || r.last_collision != collision { + out.push(S::MovePlayerStatus(play::MovePlayerStatus { flags })); + } + if moved { + r.last_pos = pos; + r.reminder = 0; + } + if rotated { + r.last_rot = (yaw, pitch); + } + r.last_on_ground = on_ground; + r.last_collision = collision; + // Creative inventory edits are sent slot by slot (SetCreativeModeSlot). + let mut creative_slots = Vec::new(); + if self.creative { + for i in 0..36 { + if self.inventory[i] != r.synced[i] { + r.synced[i] = self.inventory[i].clone(); + creative_slots.push(i); + } + } + } + for packet in out { + self.send(packet); + } + for i in creative_slots { + let slot = if i < 9 { 36 + i } else { i } as i16; + let item = self.to_network(&self.inventory[i]); + self.send(S::SetCreativeModeSlot(play::SetCreativeModeSlot { slot, item })); + } + } + /// Inventory as the server last described it. + fn remote_synced(&mut self) { + let inventory = self.inventory.clone(); + if let Some(r) = self.remote.as_mut() { + r.synced = inventory; + } + } + + /// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock. + fn remote_mining(&mut self) { + let Some(r) = self.remote.as_mut() else { return }; + if r.destroy_delay > 0 { + r.destroy_delay -= 1; + } + let chatting = r.chat_input.is_some(); + if !self.left || self.screen != Screen::Playing || chatting { + if let Some((pos, _, _)) = r.destroying.take() { + self.send(S::PlayerAction(play::PlayerAction { action: 2, pos, direction: 0, sequence: 0 })); + } + self.mining = None; + return; + } + let Some(hit) = self.pick() else { + self.mining = None; + return; + }; + let face = face_direction(hit.face); + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + if self.res.facts.is_air(state) { + return; + } + if self.remote.as_ref().is_some_and(|r| r.destroy_delay > 0) { + return; + } + self.swing_arm(); + self.send(S::Punch(Empty)); + if self.creative { + let seq = self.next_sequence(); + self.predict_break(hit.pos, state); + self.send(S::PlayerAction(play::PlayerAction { action: 0, pos: hit.pos, direction: face, sequence: seq })); + if let Some(r) = self.remote.as_mut() { + r.destroy_delay = 5; + } + return; + } + let facts = self.res.facts.get(state).clone(); + let held = self.held().cloned(); + let mut speed = self.res.items.mining_speed(held.as_ref(), &facts.name); + if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) { + speed /= 5.0; + } + let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held.as_ref(), &facts.name); + let progress = if facts.hardness < 0.0 { + 0.0 + } else if facts.hardness == 0.0 { + 1.0 + } else { + speed / facts.hardness / if harvest { 30.0 } else { 100.0 } + }; + let same = self.remote.as_ref().and_then(|r| r.destroying).is_some_and(|(p, _, _)| p == hit.pos); + if !same { + if let Some((old, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) { + self.send(S::PlayerAction(play::PlayerAction { action: 2, pos: old, direction: face, sequence: 0 })); + } + let seq = self.next_sequence(); + self.send(S::PlayerAction(play::PlayerAction { action: 0, pos: hit.pos, direction: face, sequence: seq })); + if progress >= 1.0 { + self.predict_break(hit.pos, state); + if let Some(r) = self.remote.as_mut() { + r.destroy_delay = 5; + } + return; + } + if let Some(r) = self.remote.as_mut() { + r.destroying = Some((hit.pos, face, 0.0)); + } + self.mining = Some(Mining { pos: hit.pos, progress: 0.0, ticks: 0 }); + return; + } + let Some((pos, last_face, done)) = self.remote.as_ref().and_then(|r| r.destroying) else { return }; + let done = done + progress; + let ticks = self.mining.as_ref().map_or(0, |m| m.ticks) + 1; + if ticks % 4 == 1 { + let c = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; + self.audio.play(&facts.sounds.hit, Some(c), (facts.sounds.volume + 1.0) / 8.0, facts.sounds.pitch * 0.5); + } + self.crack_particle(pos, hit.face, state); + if done >= 1.0 { + let seq = self.next_sequence(); + self.predict_break(pos, state); + self.send(S::PlayerAction(play::PlayerAction { action: 3, pos, direction: face, sequence: seq })); + if let Some(r) = self.remote.as_mut() { + r.destroying = None; + r.destroy_delay = 5; + } + self.mining = None; + } else { + if last_face != face { + self.send(S::PlayerAction(play::PlayerAction { action: 1, pos, direction: face, sequence: 0 })); + } + if let Some(r) = self.remote.as_mut() { + r.destroying = Some((pos, face, done)); + } + self.mining = Some(Mining { pos, progress: done, ticks }); + } + } + /// MultiPlayerGameMode.destroyBlock: the predicted break. + fn predict_break(&mut self, pos: [i32; 3], state: BlockStateId) { + let s = self.res.facts.get(state).sounds.clone(); + let at = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; + self.audio.play(&s.break_sound, Some(at), (s.volume + 1.0) / 2.0, s.pitch * 0.8); + self.destroy_particles(pos, state); + // The server's block update follows (waterlogged blocks leave water). + let air = self.world.air; + if self.world.set(pos[0], pos[1], pos[2], air).is_ok() { + self.world.block_entities.remove(&(pos[0], pos[1], pos[2])); + } + self.mining = None; + } + /// Minecraft.startUseItem: use on the targeted block, then the item itself. + fn remote_use(&mut self) { + let held_block = self.held().and_then(|h| self.res.items.get(&h.item)).is_some_and(|i| i.block.is_some()); + let sneaking = self.keys.contains(&KeyCode::ShiftLeft); + // Entities first (interact), like the hit result order. + if let Some((i, _)) = self.mob_hit() { + let id = self.mobs[i].id as i32; + self.send(S::Interact(play::Interact { id, hand: 0, location: [0.0, 1.0, 0.0], secondary: sneaking })); + self.swing_arm(); + return; + } + if let Some(hit) = self.pick() { + let seq = self.next_sequence(); + let cursor = [ + (hit.point[0] - f64::from(hit.pos[0])) as f32, + (hit.point[1] - f64::from(hit.pos[1])) as f32, + (hit.point[2] - f64::from(hit.pos[2])) as f32, + ]; + self.send(S::UseItemOn(play::UseItemOn { + hand: 0, + pos: hit.pos, + face: i32::from(face_direction(hit.face)), + cursor, + inside: hit.face == [0; 3], + world_border: false, + sequence: seq, + })); + let target = [hit.pos[0] + hit.face[0], hit.pos[1] + hit.face[1], hit.pos[2] + hit.face[2]]; + let ticks = self.ticks; + if let Some(r) = self.remote.as_mut() { + r.use_target = Some(hit.pos); + r.placing = Some((target, ticks)); + } + if held_block { + self.swing_arm(); + return; + } + } + if self.held().is_some() { + let seq = self.next_sequence(); + self.send(S::UseItem(play::UseItem { hand: 0, sequence: seq, yaw: self.yaw, pitch: self.pitch })); + } + } + /// Left click: attack the targeted entity (MultiPlayerGameMode.attack). + pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { + if self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) { + return Ok(()); + } + match button { + MouseButton::Left => { + if pressed && let Some((i, _)) = self.mob_hit() { + let id = self.mobs[i].id as i32; + self.send(S::Attack(play::Attack { id })); + self.send(S::Punch(Empty)); + self.swing_arm(); + return Ok(()); + } + if pressed && self.pick().is_none() { + self.send(S::Punch(Empty)); + self.swing_arm(); + } + self.left = pressed; + } + MouseButton::Right => { + self.right = pressed; + if pressed { + self.remote_use(); + self.use_delay = 4; + } else { + self.send(S::PlayerAction(play::PlayerAction { action: 6, pos: [0; 3], direction: 0, sequence: 0 })); + } + } + MouseButton::Middle if pressed => { + if let Some(hit) = self.pick() { + self.send(S::PickItemFromBlock(play::PickItemFromBlock { pos: hit.pos, include_data: false })); + } + } + _ => {} + } + Ok(()) + } + /// Keys with a multiplayer meaning; returns true when consumed. + pub(super) fn remote_key(&mut self, key: KeyCode) -> Result { + if self.screen != Screen::Playing { + if key == KeyCode::KeyE && self.screen == Screen::Inventory || key == KeyCode::Escape && self.screen == Screen::Inventory { + self.remote_close_container(); + self.screen = Screen::Playing; + self.capture(true); + return Ok(true); + } + return Ok(false); + } + match key { + KeyCode::KeyT | KeyCode::Slash | KeyCode::Enter => { + let text = if key == KeyCode::Slash { "/" } else { "" }; + if let Some(r) = self.remote.as_mut() { + r.chat_input = Some(text.to_owned()); + } + self.keys.clear(); + self.left = false; + self.right = false; + self.capture(false); + Ok(true) + } + KeyCode::KeyQ => { + let all = self.keys.contains(&KeyCode::ControlLeft); + self.send(S::PlayerAction(play::PlayerAction { action: if all { 4 } else { 5 }, pos: [0; 3], direction: 0, sequence: 0 })); + // Inventory.removeFromSelected (prediction). + let slot = &mut self.inventory[self.selected]; + if let Some(s) = slot { + if all || s.count <= 1 { + *slot = None; + } else { + s.count -= 1; + } + } + self.swing_arm(); + Ok(true) + } + KeyCode::KeyE => { + // The inventory opens without telling the server. + self.screen = if self.creative { Screen::Creative } else { Screen::Inventory }; + self.craft_size = 2; + self.capture(false); + Ok(true) + } + _ => Ok(false), + } + } + pub(super) fn remote_chat_open(&self) -> bool { + self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) + } + /// ChatScreen: typing, Enter to send, Escape to cancel. + pub(super) fn remote_chat_key(&mut self, event: &winit::event::KeyEvent) { + use winit::keyboard::{Key, NamedKey}; + if event.state != winit::event::ElementState::Pressed { + return; + } + let Some(r) = self.remote.as_mut() else { return }; + let Some(input) = r.chat_input.as_mut() else { return }; + // Logical keys: the text, not the scancode, decides (layouts, virtual keyboards). + match &event.logical_key { + Key::Named(NamedKey::Escape) => { + r.chat_input = None; + self.capture(true); + } + Key::Named(NamedKey::Backspace) => { + input.pop(); + } + Key::Named(NamedKey::Enter) => { + let message = r.chat_input.take().unwrap_or_default(); + self.send_chat(&message); + self.capture(true); + } + _ => { + if let Some(text) = &event.text { + for c in text.chars().filter(|c| !c.is_control()) { + if input.chars().count() < 256 { + input.push(c); + } + } + } + } + } + } + /// ClientPacketListener.sendChat / sendCommand (unsigned). + pub(super) fn send_chat(&mut self, message: &str) { + let message = message.trim(); + if message.is_empty() { + return; + } + if let Some(command) = message.strip_prefix('/') { + self.send(S::ChatCommand(play::ChatCommand { command: command.to_owned() })); + } else { + let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64); + self.send(S::Chat(play::Chat { + message: message.chars().take(256).collect(), + timestamp, + salt: 0, + signature: None, + last_seen: play::LastSeenUpdate { offset: 0, acknowledged: [0; 3], checksum: 0 }, + })); + } + } + /// A container click: the server answers with the authoritative slots. + pub(super) fn remote_click(&mut self, right: bool) { + let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return }; + let batch = HudBatch::new(size); + let Some(internal) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return }; + let (container, menu) = match self.remote.as_ref().and_then(|r| r.menu.clone()) { + Some((id, name)) => (id, name), + None => (0, "inventory".to_owned()), + }; + let slot = (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal)); + let Some(slot) = slot else { return }; + let shift = self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); + let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s)); + let state = self.remote.as_ref().map_or(0, |r| r.state_id); + self.send(S::ContainerClick(play::ContainerClick { + container, + state, + slot: slot as i16, + button: i8::from(right), + input: if shift { 1 } else { 0 }, + changed: Vec::new(), + carried, + })); + } + pub(super) fn remote_close_container(&mut self) { + let id = self.remote.as_ref().and_then(|r| r.menu.as_ref().map(|m| m.0)).unwrap_or(0); + self.send(S::ContainerClose(play::ContainerClose { container: id })); + self.remote_close_local(); + } + fn remote_close_local(&mut self) { + if let Some(r) = self.remote.as_mut() { + r.menu = None; + } + self.craft_size = 2; + if let Some(key) = self.container.take() { + // Server containers stay renderable but lose their copied slots. + if let Some(entity) = self.world.block_entities.get_mut(&key) { + for s in entity.slots_mut() { + *s = None; + } + } + } + } + /// ClientboundOpenScreenPacket for the menus Horizon draws. + fn remote_open_screen(&mut self, p: play::OpenScreen) { + let menu = self.remote.as_ref().and_then(|r| r.builtin.get("minecraft:menu")?.name(p.menu).map(str::to_owned)).unwrap_or_default(); + let target = self.remote.as_ref().and_then(|r| r.use_target).map(|t| (t[0], t[1], t[2])); + let entity = match menu.as_str() { + "minecraft:crafting" => None, + "minecraft:furnace" | "minecraft:blast_furnace" | "minecraft:smoker" => { + let kind = match menu.as_str() { + "minecraft:blast_furnace" => FurnaceKind::BlastFurnace, + "minecraft:smoker" => FurnaceKind::Smoker, + _ => FurnaceKind::Furnace, + }; + Some(BlockEntity::Furnace(Furnace { + kind, + items: [None, None, None], + lit_remaining: 0, + lit_total: 0, + cooking_timer: 0, + cooking_total: 0, + speed: 1.0, + })) + } + m if m.starts_with("minecraft:generic_9x") || m == "minecraft:shulker_box" => { + let rows = m.strip_prefix("minecraft:generic_9x").and_then(|r| r.parse::().ok()).unwrap_or(3); + Some(BlockEntity::Chest(vec![None; rows * 9])) + } + _ => { + // Unsupported menu: tell the server we closed it. + self.send(S::ContainerClose(play::ContainerClose { container: p.container })); + self.chat_line(format!("(Horizon cannot show {menu} screens yet)")); + return; + } + }; + if let Some(r) = self.remote.as_mut() { + r.menu = Some((p.container, menu.clone())); + } + self.craft_size = if menu == "minecraft:crafting" { 3 } else { 2 }; + self.container = None; + if let Some(entity) = entity { + let key = target.unwrap_or((i32::MIN, 0, 0)); + self.world.block_entities.insert(key, entity); + self.container = Some(key); + } + self.screen = Screen::Inventory; + self.capture(false); + } + pub(super) fn remote_respawn(&mut self) { + self.send(S::ClientCommand(play::ClientCommand { action: 0 })); + } + + /// Connecting / loading screens; true when it covered the frame. + pub(super) fn remote_overlay(&self, batch: &mut HudBatch) -> bool { + let Some(r) = &self.remote else { return false }; + if self.player.is_some() { + return false; + } + let atlas = &self.res.atlas; + let (w, h) = (batch.width, batch.height); + batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255)); + for (i, line) in [r.status.as_str(), r.session.address.as_str()].iter().enumerate() { + let tw = HudBatch::text_width(atlas, line); + batch.text(atlas, line, (w - tw) / 2.0, h / 2.0 - 12.0 + i as f32 * 12.0, if i == 0 { u32::MAX } else { rgba(160, 160, 160, 255) }, true); + } + let _ = r.joined; + true + } + /// Chat (ChatComponent), the chat input line and the action bar. + pub(super) fn remote_hud(&self, batch: &mut HudBatch) { + let Some(r) = &self.remote else { return }; + let atlas = &self.res.atlas; + let (w, h) = (batch.width, batch.height); + let open = r.chat_input.is_some(); + let now = Instant::now(); + let mut y = h - 48.0; + // Container screens cover the chat (vanilla draws them over the HUD). + let shown = if matches!(self.screen, Screen::Playing | Screen::Dead) { if open { 20 } else { 10 } } else { 0 }; + for (text, at) in r.chat.iter().rev().take(shown) { + let age = now.duration_since(*at); + // Lines fade out after ten seconds unless the chat is open. + let alpha = if open { 1.0 } else { (1.0 - (age.as_secs_f32() - 9.0).max(0.0)).clamp(0.0, 1.0) }; + if alpha <= 0.0 { + break; + } + let a = (alpha * 255.0) as u8; + batch.fill(atlas, 2.0, y - 1.0, 320.0, 9.0, rgba(0, 0, 0, (alpha * 128.0) as u8)); + batch.text(atlas, text, 4.0, y, rgba(255, 255, 255, a), true); + y -= 9.0; + } + if let Some(input) = &r.chat_input { + batch.fill(atlas, 2.0, h - 14.0, w - 4.0, 12.0, rgba(0, 0, 0, 128)); + let blink = (self.started.elapsed().as_millis() / 300).is_multiple_of(2); + let shown = if blink { format!("{input}_") } else { input.clone() }; + batch.text(atlas, &shown, 4.0, h - 12.0, rgba(224, 224, 224, 255), true); + } + if let Some((text, at)) = &r.action_bar + && now.duration_since(*at) < Duration::from_secs(3) + { + let tw = HudBatch::text_width(atlas, text); + batch.text(atlas, text, (w - tw) / 2.0, h - 68.0, u32::MAX, true); + } + if self.screen == Screen::Dead + && let Some(message) = &r.death_message + { + let tw = HudBatch::text_width(atlas, message); + batch.text(atlas, message, (w - tw) / 2.0, 85.0, u32::MAX, true); + } + } + /// Status for `horizon-ctl status`. + pub(super) fn remote_status(&self) -> Option { + let r = self.remote.as_ref()?; + Some(serde_json::json!({ + "address": r.session.address, + "name": r.session.name, + "joined": r.joined, + "status": r.status, + "entity_id": r.entity_id, + "dimension": r.dimension.name, + "game_mode": r.game_mode, + "chunks": self.world.chunks.len(), + "entities": r.entities.values().fold(std::collections::BTreeMap::<&str, u32>::new(), |mut m, t| { + *m.entry(t.kind.as_str()).or_default() += 1; + m + }), + "players": r.players.values().collect::>(), + "health": r.health.0, + "food": r.health.1, + "decode_errors": r.decode_errors, + "chat": r.chat.iter().rev().take(10).rev().map(|(t, _)| t.clone()).collect::>(), + })) + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 7eb279a31..fe60db2e6 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -33,6 +33,8 @@ pub mod mesher; pub mod mobs; pub mod models; pub mod motion; +pub mod multiplayer; +pub mod net; pub mod particles; pub mod pose; pub mod save; diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs new file mode 100644 index 000000000..5072f616f --- /dev/null +++ b/crates/horizon-client/src/multiplayer.rs @@ -0,0 +1,276 @@ +//! Multiplayer screens on the title: the server list (JoinMultiplayerScreen, +//! stored in servers.dat), Add/Edit Server, Direct Connection, and the +//! Disconnected screen. Entries are pinged in the background like +//! ServerStatusPinger to show the MOTD, player count and latency. +use crate::hud::{HudAtlas, HudBatch, rgba}; +use horizon_protocol::servers::{self, ServerEntry}; +use std::{ + collections::HashMap, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, + time::Duration, +}; + +/// The result of pinging one address. +#[derive(Clone, Debug)] +pub enum Ping { + Pinging, + Ok { motd: String, players: String, ms: u128, version: String }, + Failed(String), +} +type Pings = Arc>>; + +#[derive(Clone, Debug)] +pub enum Screen { + List { servers: Vec, selected: Option, pings: Pings }, + /// Add (index None) or edit a server entry. + Edit { index: Option, name: String, address: String, focus: u8 }, + Direct { address: String }, + Disconnected { reason: String }, +} +/// What a click asks the title screen to do. +pub enum Outcome { + None, + Back, + Connect(String), +} +/// A button: x, y, width, label, enabled, id. +pub type ButtonSpec = (f32, f32, f32, String, bool, u8); + +pub fn servers_file(saves: &Path) -> PathBuf { + saves.parent().map_or_else(|| PathBuf::from("servers.dat"), |p| p.join("servers.dat")) +} +fn ping_all(servers: &[ServerEntry], pings: &Pings) { + for s in servers { + let address = s.ip.clone(); + pings.lock().unwrap().insert(address.clone(), Ping::Pinging); + let pings = pings.clone(); + let _ = std::thread::Builder::new().name("horizon-ping".into()).spawn(move || { + let result = match crate::net::ping(&address, Duration::from_secs(5)) { + Ok((json, ms)) => { + let lang = Default::default(); + let motd = crate::net::json_text(&json["description"], &lang); + let players = format!("{}/{}", json["players"]["online"].as_i64().unwrap_or(0), json["players"]["max"].as_i64().unwrap_or(0)); + let version = json["version"]["name"].as_str().unwrap_or("?").to_owned(); + Ping::Ok { motd, players, ms, version } + } + Err(e) => Ping::Failed(e), + }; + pings.lock().unwrap().insert(address, result); + }); + } +} + +impl Screen { + pub fn list(saves: &Path) -> Self { + let servers = servers::load(&servers_file(saves)); + let pings: Pings = Arc::default(); + ping_all(&servers, &pings); + Self::List { servers, selected: None, pings } + } + pub fn buttons(&self, w: f32, h: f32) -> Vec { + let b = |x: f32, y: f32, bw: f32, label: &str, enabled: bool, id: u8| (x, y, bw, label.to_owned(), enabled, id); + match self { + // JoinMultiplayerScreen's two button rows. + Self::List { selected, .. } => vec![ + b(w / 2.0 - 154.0, h - 52.0, 100.0, "Join Server", selected.is_some(), 40), + b(w / 2.0 - 50.0, h - 52.0, 100.0, "Direct Connection", true, 41), + b(w / 2.0 + 54.0, h - 52.0, 100.0, "Add Server", true, 42), + b(w / 2.0 - 154.0, h - 28.0, 74.0, "Edit", selected.is_some(), 43), + b(w / 2.0 - 76.0, h - 28.0, 74.0, "Delete", selected.is_some(), 44), + b(w / 2.0 + 2.0, h - 28.0, 74.0, "Refresh", true, 45), + b(w / 2.0 + 80.0, h - 28.0, 74.0, "Back", true, 46), + ], + Self::Edit { address, .. } => vec![ + b(w / 2.0 - 100.0, h / 4.0 + 96.0 + 18.0, 200.0, "Done", servers::parse_address(address).is_some(), 50), + b(w / 2.0 - 100.0, h / 4.0 + 120.0 + 18.0, 200.0, "Cancel", true, 51), + ], + Self::Direct { address } => vec![ + b(w / 2.0 - 100.0, h / 4.0 + 96.0 + 12.0, 200.0, "Join Server", servers::parse_address(address).is_some(), 52), + b(w / 2.0 - 100.0, h / 4.0 + 120.0 + 12.0, 200.0, "Cancel", true, 53), + ], + Self::Disconnected { .. } => vec![b(w / 2.0 - 100.0, h / 2.0 + 30.0, 200.0, "Back to Server List", true, 54)], + } + } + fn field(atlas: &HudAtlas, batch: &mut HudBatch, label: &str, value: &str, y: f32, focused: bool, blink: bool) { + let w = batch.width; + batch.text(atlas, label, w / 2.0 - 100.0, y, rgba(160, 160, 160, 255), true); + batch.fill(atlas, w / 2.0 - 100.0, y + 11.0, 200.0, 20.0, if focused { u32::MAX } else { rgba(160, 160, 160, 255) }); + batch.fill(atlas, w / 2.0 - 99.0, y + 12.0, 198.0, 18.0, rgba(0, 0, 0, 255)); + let shown = if focused && blink { format!("{value}_") } else { value.to_owned() }; + batch.text(atlas, &shown, w / 2.0 - 96.0, y + 17.0, rgba(224, 224, 224, 255), true); + } + pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool) { + let (w, h) = (batch.width, batch.height); + batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120)); + let centered = |batch: &mut HudBatch, text: &str, y: f32, color: u32| { + let tw = HudBatch::text_width(atlas, text); + batch.text(atlas, text, (w - tw) / 2.0, y, color, true); + }; + match self { + Self::List { servers, selected, pings } => { + centered(batch, "Play Multiplayer", 8.0, u32::MAX); + batch.fill(atlas, 0.0, 32.0, w, h - 32.0 - 64.0, rgba(0, 0, 0, 100)); + let pings = pings.lock().unwrap(); + for (i, server) in servers.iter().enumerate() { + let y = 36.0 + i as f32 * 36.0; + if y + 36.0 > h - 64.0 { + break; + } + let x = w / 2.0 - 152.0; + if *selected == Some(i) { + batch.fill(atlas, x - 2.0, y - 2.0, 306.0, 36.0, rgba(128, 128, 128, 255)); + batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255)); + } + batch.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX); + batch.text(atlas, &server.name, x + 35.0, y + 1.0, u32::MAX, false); + let (line, right, color) = match pings.get(&server.ip) { + Some(Ping::Ok { motd, players, ms, .. }) => (motd.lines().next().unwrap_or("").to_owned(), format!("{players} {ms} ms"), rgba(128, 128, 128, 255)), + Some(Ping::Failed(_)) => ("Can't connect to server".to_owned(), String::new(), rgba(170, 0, 0, 255)), + _ => ("Pinging...".to_owned(), String::new(), rgba(128, 128, 128, 255)), + }; + batch.text(atlas, &line, x + 35.0, y + 12.0, color, false); + batch.text(atlas, &server.ip, x + 35.0, y + 22.0, rgba(96, 96, 96, 255), false); + if !right.is_empty() { + let tw = HudBatch::text_width(atlas, &right); + batch.text(atlas, &right, x + 300.0 - tw, y + 1.0, rgba(128, 128, 128, 255), false); + } + } + if servers.is_empty() { + centered(batch, "No servers yet: add one or use Direct Connection", h / 2.0 - 20.0, rgba(160, 160, 160, 255)); + } + } + Self::Edit { index, name, address, focus } => { + centered(batch, if index.is_some() { "Edit Server Info" } else { "Add Server" }, 17.0, u32::MAX); + Self::field(atlas, batch, "Server Name", name, 53.0, *focus == 0, blink); + Self::field(atlas, batch, "Server Address", address, 94.0, *focus == 1, blink); + } + Self::Direct { address } => { + centered(batch, "Direct Connection", 20.0, u32::MAX); + Self::field(atlas, batch, "Server Address", address, 100.0 - 11.0, true, blink); + } + Self::Disconnected { reason } => { + centered(batch, "Connection Lost", h / 2.0 - 40.0, rgba(170, 170, 170, 255)); + for (i, line) in wrap(reason, 300.0, atlas).iter().enumerate() { + centered(batch, line, h / 2.0 - 16.0 + i as f32 * 9.0, u32::MAX); + } + } + } + } + pub fn click(&mut self, id: Option, x: f32, y: f32, size: (f32, f32), saves: &Path) -> Outcome { + let (w, h) = size; + match (&mut *self, id) { + (Self::List { servers, selected, .. }, Some(40)) => { + if let Some(s) = selected.and_then(|i| servers.get(i)) { + return Outcome::Connect(s.ip.clone()); + } + } + (Self::List { .. }, Some(41)) => *self = Self::Direct { address: String::new() }, + (Self::List { .. }, Some(42)) => *self = Self::Edit { index: None, name: "Minecraft Server".into(), address: String::new(), focus: 1 }, + (Self::List { servers, selected, .. }, Some(43)) => { + if let Some((i, s)) = selected.and_then(|i| servers.get(i).map(|s| (i, s.clone()))) { + *self = Self::Edit { index: Some(i), name: s.name, address: s.ip, focus: 0 }; + } + } + (Self::List { servers, selected, .. }, Some(44)) => { + if let Some(i) = selected.take() + && i < servers.len() + { + servers.remove(i); + let _ = servers::save(&servers_file(saves), servers); + } + } + (Self::List { .. }, Some(45)) => *self = Self::list(saves), + (Self::List { .. }, Some(46)) => return Outcome::Back, + (Self::List { servers, selected, .. }, None) => { + let index = ((y - 36.0) / 36.0).floor(); + if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 && (index as usize) < servers.len() { + let index = index as usize; + if *selected == Some(index) { + return Outcome::Connect(servers[index].ip.clone()); + } + *selected = Some(index); + } + } + (Self::Edit { index, name, address, .. }, Some(50)) => { + let mut list = servers::load(&servers_file(saves)); + let entry = ServerEntry::new(name.trim(), address.trim()); + match index.and_then(|i| list.get_mut(i)) { + Some(e) => { + e.name = entry.name; + e.ip = entry.ip; + } + None => list.push(entry), + } + let _ = servers::save(&servers_file(saves), &list); + *self = Self::list(saves); + } + (Self::Edit { .. } | Self::Direct { .. } | Self::Disconnected { .. }, Some(51 | 53 | 54)) => *self = Self::list(saves), + (Self::Direct { address }, Some(52)) => return Outcome::Connect(address.trim().to_owned()), + (Self::Edit { focus, .. }, None) => { + for (i, fy) in [(0u8, 53.0 + 11.0), (1, 94.0 + 11.0)] { + if y >= fy && y < fy + 20.0 && (x - w / 2.0).abs() < 100.0 { + *focus = i; + } + } + } + _ => {} + } + Outcome::None + } + fn focused_field(&mut self) -> Option<&mut String> { + match self { + Self::Edit { name, address, focus, .. } => Some(if *focus == 0 { name } else { address }), + Self::Direct { address } => Some(address), + _ => None, + } + } + pub fn type_text(&mut self, text: &str) { + if let Some(field) = self.focused_field() { + for c in text.chars().filter(|c| !c.is_control()) { + if field.chars().count() < 128 { + field.push(c); + } + } + } + } + pub fn backspace(&mut self) { + if let Some(field) = self.focused_field() { + field.pop(); + } + } + pub fn tab(&mut self) { + if let Self::Edit { focus, .. } = self { + *focus = (*focus + 1) % 2; + } + } + /// Escape: back to the list, or out of it (true). + pub fn escape(&mut self, saves: &Path) -> bool { + match self { + Self::List { .. } => true, + _ => { + *self = Self::list(saves); + false + } + } + } +} + +/// Greedy word wrap to a pixel width. +pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec { + let mut lines = Vec::new(); + for paragraph in text.lines() { + let mut line = String::new(); + for word in paragraph.split(' ') { + let candidate = if line.is_empty() { word.to_owned() } else { format!("{line} {word}") }; + if HudBatch::text_width(atlas, &candidate) > width && !line.is_empty() { + lines.push(std::mem::take(&mut line)); + line = word.to_owned(); + } else { + line = candidate; + } + } + lines.push(line); + } + lines +} diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs new file mode 100644 index 000000000..551fdac41 --- /dev/null +++ b/crates/horizon-client/src/net.rs @@ -0,0 +1,295 @@ +//! Multiplayer session: a network thread that connects to a server, logs in +//! (offline mode only), runs the configuration phase and then forwards decoded +//! play packets to the game thread. Keep-alives and pings are answered on the +//! network thread like vanilla's connection handlers so a busy frame never +//! times the client out. Online-mode (authenticated) servers are refused: +//! Horizon never handles Microsoft credentials. +use horizon_protocol::{ + PROTOCOL_VERSION, + connection::{ConnReader, ConnWriter, Connection, Counters}, + crypto::offline_uuid, + packets::{Empty, configuration as cfg, handshake, login, play}, + registry::Dynamic, + servers::parse_address, + text::{Language, plain}, +}; +use std::{ + sync::{ + Arc, Mutex, + mpsc::{Receiver, Sender, channel}, + }, + thread::JoinHandle, + time::Duration, +}; + +/// What the network thread reports to the game. +pub enum Event { + /// Progress text for the connecting screen. + Status(String), + /// Configuration finished: the play state begins with these registries. + Joined { registries: Arc, uuid: u128, name: String }, + Packet(Box), + /// A packet that failed to decode (skipped, like vanilla's skippable packets). + DecodeError(String), + /// The server sent us back to configuration and finished it again. + Reconfigured(Arc), + Disconnected(String), +} + +pub struct Session { + events: Receiver, + writer: Arc>>, + thread: Option>, + pub address: String, + pub name: String, + pub counters: Arc>>>, + /// HORIZON_NET_DEBUG=1 logs every packet sent from the game thread. + debug: bool, +} +impl Session { + /// Start connecting in the background. + pub fn connect(address: &str, name: &str, view_distance: i8, lang: Arc) -> Self { + let (send, events) = channel(); + let writer = Arc::new(Mutex::new(None)); + let counters = Arc::new(Mutex::new(None)); + let (thread_writer, thread_counters) = (writer.clone(), counters.clone()); + let (address_owned, name_owned) = (address.to_owned(), name.to_owned()); + let thread = std::thread::Builder::new() + .name("horizon-net".into()) + .spawn(move || { + let reason = match run(&address_owned, &name_owned, view_distance, &lang, &send, &thread_writer, &thread_counters) { + Ok(reason) => reason, + Err(e) => e, + }; + if let Some(w) = thread_writer.lock().unwrap().take() { + w.shutdown(); + } + let _ = send.send(Event::Disconnected(reason)); + }) + .ok(); + let debug = std::env::var_os("HORIZON_NET_DEBUG").is_some(); + Self { events, writer, thread, address: address.to_owned(), name: name.to_owned(), counters, debug } + } + /// Everything received since the last poll. + pub fn poll(&self) -> Vec { + self.events.try_iter().collect() + } + /// Send a play packet; silently dropped once the connection is gone. + pub fn send(&self, packet: play::Serverbound) { + if self.debug && !matches!(packet, play::Serverbound::ClientTickEnd(_) | play::Serverbound::MovePlayerPos(_) | play::Serverbound::MovePlayerPosRot(_)) { + eprintln!("[net] -> {packet:?}"); + } + if let Some(w) = self.writer.lock().unwrap().as_mut() + && w.send(&packet.encode()).is_err() + { + w.shutdown(); + } + } + pub fn disconnect(&mut self) { + if let Some(w) = self.writer.lock().unwrap().take() { + w.shutdown(); + } + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } +} +impl Drop for Session { + fn drop(&mut self) { + self.disconnect(); + } +} + +fn status(send: &Sender, text: &str) { + let _ = send.send(Event::Status(text.to_owned())); +} + +/// The whole connection; returns the disconnect reason. +fn run( + address: &str, + name: &str, + view_distance: i8, + lang: &Language, + send: &Sender, + shared_writer: &Mutex>, + shared_counters: &Mutex>>, +) -> Result { + let (host, port) = parse_address(address).ok_or_else(|| format!("Invalid server address: {address}"))?; + status(send, "Connecting to the server..."); + let mut c = Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?; + *shared_counters.lock().unwrap() = Some(c.reader.counters.clone()); + let e = |e: horizon_protocol::Error| e.to_string(); + c.send( + &handshake::Serverbound::Intention(handshake::Intention { protocol: PROTOCOL_VERSION, host: host.clone(), port, intent: handshake::LOGIN }) + .encode(), + ) + .map_err(e)?; + status(send, "Logging in..."); + let uuid = offline_uuid(name); + c.send(&login::Serverbound::Hello(login::ServerHello { name: name.to_owned(), uuid }).encode()).map_err(e)?; + let profile = loop { + let (id, payload) = c.recv().map_err(e)?; + match login::Clientbound::decode(id, &payload).map_err(e)? { + login::Clientbound::Compression(p) => c.set_compression(p.threshold), + login::Clientbound::LoginFinished(p) => { + c.send(&login::Serverbound::LoginAcknowledged(Empty).encode()).map_err(e)?; + break p.profile; + } + login::Clientbound::Disconnect(p) => { + let reason = serde_json::from_str::(&p.reason_json).map(|v| json_text(&v, lang)).unwrap_or(p.reason_json); + return Err(reason); + } + login::Clientbound::Hello(_) => { + return Err("This server is in online mode. Horizon only joins offline-mode servers (online-mode=false).".into()); + } + login::Clientbound::CustomQuery(q) => { + c.send(&login::Serverbound::CustomQueryAnswer(login::CustomQueryAnswer { transaction: q.transaction, payload: None }).encode()) + .map_err(e)?; + } + login::Clientbound::CookieRequest(q) => { + c.send(&login::Serverbound::CookieResponse(login::CookieResponse { key: q.key, payload: None }).encode()).map_err(e)?; + } + login::Clientbound::Unknown(..) => {} + } + }; + status(send, "Joining world..."); + c.send(&cfg::Serverbound::ClientInformation(cfg::ClientInformation::new(view_distance)).encode()).map_err(e)?; + c.send(&cfg::Serverbound::CustomPayload(cfg::CustomPayload { channel: "minecraft:brand".into(), data: brand() }).encode()).map_err(e)?; + let (mut reader, writer) = c.split(); + *shared_writer.lock().unwrap() = Some(writer); + let registries = configure(&mut reader, shared_writer, lang)?; + let _ = send.send(Event::Joined { registries: Arc::new(registries), uuid: profile.uuid, name: profile.name }); + loop { + let (id, payload) = reader.recv().map_err(e)?; + let packet = match play::Clientbound::decode(id, &payload) { + Ok(p) => p, + Err(err) => { + let name = horizon_protocol::ids::name(horizon_protocol::State::Play, horizon_protocol::Direction::Clientbound, id).unwrap_or("?"); + let _ = send.send(Event::DecodeError(format!("{name}: {err}"))); + continue; + } + }; + let reply = |p: play::Serverbound| { + if let Some(w) = shared_writer.lock().unwrap().as_mut() { + let _ = w.send(&p.encode()); + } + }; + match packet { + play::Clientbound::KeepAlive(k) => reply(play::Serverbound::KeepAlive(k)), + play::Clientbound::Ping(p) => reply(play::Serverbound::Pong(p)), + play::Clientbound::BundleDelimiter(_) => {} + play::Clientbound::ResourcePackPush(p) => { + // Declined: Horizon has no server resource packs. + reply(play::Serverbound::ResourcePack(cfg::ResourcePackResponse { id: p.id, action: 1 })); + } + play::Clientbound::StartConfiguration(_) => { + reply(play::Serverbound::ConfigurationAcknowledged(Empty)); + let registries = configure(&mut reader, shared_writer, lang)?; + let _ = send.send(Event::Reconfigured(Arc::new(registries))); + } + play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)), + other => { + if send.send(Event::Packet(Box::new(other))).is_err() { + return Ok("Disconnected".into()); + } + } + } + } +} + +/// The configuration phase: registries, tags and known packs until the +/// server finishes it (ClientConfigurationPacketListenerImpl). +fn configure(reader: &mut ConnReader, writer: &Mutex>, lang: &Language) -> Result { + let mut registries = Dynamic::default(); + let reply = |p: cfg::Serverbound| -> Result<(), String> { + match writer.lock().unwrap().as_mut() { + Some(w) => w.send(&p.encode()).map_err(|e| e.to_string()), + None => Err("Disconnected".into()), + } + }; + loop { + let (id, payload) = reader.recv().map_err(|e| e.to_string())?; + match cfg::Clientbound::decode(id, &payload).map_err(|e| e.to_string())? { + cfg::Clientbound::KeepAlive(k) => reply(cfg::Serverbound::KeepAlive(k))?, + cfg::Clientbound::Ping(p) => reply(cfg::Serverbound::Pong(p))?, + // Know no packs: the server then sends every registry entry in full. + cfg::Clientbound::SelectKnownPacks(_) => reply(cfg::Serverbound::SelectKnownPacks(cfg::SelectKnownPacks { packs: vec![] }))?, + cfg::Clientbound::RegistryData(r) => registries.add(r), + cfg::Clientbound::CodeOfConduct(_) => reply(cfg::Serverbound::AcceptCodeOfConduct(Empty))?, + cfg::Clientbound::ResourcePackPush(p) => reply(cfg::Serverbound::ResourcePack(cfg::ResourcePackResponse { id: p.id, action: 1 }))?, + cfg::Clientbound::CookieRequest(q) => reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse { key: q.key, payload: None }))?, + cfg::Clientbound::Disconnect(d) => return Err(plain(&d.reason, lang)), + cfg::Clientbound::FinishConfiguration(_) => { + reply(cfg::Serverbound::FinishConfiguration(Empty))?; + return Ok(registries); + } + _ => {} + } + } +} + +/// The minecraft:brand payload: a string naming the client. +fn brand() -> Vec { + let mut w = horizon_protocol::buf::Writer::new(); + w.string("horizon"); + w.data +} + +/// Flatten a JSON chat component (login disconnects are JSON). +pub fn json_text(v: &serde_json::Value, lang: &Language) -> String { + match v { + serde_json::Value::String(s) => s.clone(), + serde_json::Value::Array(a) => a.iter().map(|e| json_text(e, lang)).collect(), + serde_json::Value::Object(o) => { + let mut out = if let Some(t) = o.get("text").and_then(|t| t.as_str()) { + t.to_owned() + } else if let Some(key) = o.get("translate").and_then(|t| t.as_str()) { + let args: Vec = o.get("with").and_then(|w| w.as_array()).map(|a| a.iter().map(|e| json_text(e, lang)).collect()).unwrap_or_default(); + let pattern = lang.get(key).cloned().or_else(|| o.get("fallback").and_then(|f| f.as_str()).map(str::to_owned)).unwrap_or_else(|| key.to_owned()); + horizon_protocol::text::format_java(&pattern, &args) + } else { + String::new() + }; + if let Some(extra) = o.get("extra").and_then(|e| e.as_array()) { + for e in extra { + out.push_str(&json_text(e, lang)); + } + } + out + } + other => other.to_string(), + } +} + +/// en_us.json from the prepared resources. +pub fn load_language(resources: &std::path::Path) -> Language { + std::fs::read(resources.join("assets/minecraft/lang/en_us.json")) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() +} + +/// Ask a server for its status (ServerStatusPinger): MOTD, players and the +/// round trip time in milliseconds. +pub fn ping(address: &str, timeout: Duration) -> Result<(serde_json::Value, u128), String> { + use horizon_protocol::packets::status; + let (host, port) = parse_address(address).ok_or("Invalid address")?; + let mut c = Connection::connect(&host, port, timeout).map_err(|e| e.to_string())?; + c.reader.set_read_timeout(Some(timeout)).map_err(|e| e.to_string())?; + let e = |e: horizon_protocol::Error| e.to_string(); + c.send( + &handshake::Serverbound::Intention(handshake::Intention { protocol: PROTOCOL_VERSION, host: host.clone(), port, intent: handshake::STATUS }) + .encode(), + ) + .map_err(e)?; + c.send(&status::Serverbound::StatusRequest(Empty).encode()).map_err(e)?; + let (id, payload) = c.recv().map_err(e)?; + let json = match status::Clientbound::decode(id, &payload).map_err(e)? { + status::Clientbound::StatusResponse(s) => serde_json::from_str(&s.json).map_err(|e| e.to_string())?, + _ => return Err("unexpected status reply".into()), + }; + let start = std::time::Instant::now(); + c.send(&status::Serverbound::PingRequest(status::Ping { time: 1 }).encode()).map_err(e)?; + let _ = c.recv().map_err(e)?; + Ok((json, start.elapsed().as_millis())) +} diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index c69ae2046..1daff0ab0 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -118,6 +118,9 @@ pub struct Streaming { light_snapshots: HashMap<(i32, i32), u64>, pub generated_total: u64, pub meshed_total: u64, + /// Chunks come from a server (`insert_remote`/`forget`): nothing is + /// generated and columns are only unloaded when the server says so. + pub remote: bool, } pub struct WorkerContext { pub assets: Arc, @@ -217,8 +220,31 @@ impl Streaming { light_snapshots: HashMap::new(), generated_total: 0, meshed_total: 0, + remote: false, } } + /// A column received from a server: store it and relight it and its neighbours. + pub fn insert_remote(&mut self, world: &mut World, chunk: Chunk) { + let key = (chunk.x, chunk.z); + self.lit.remove(&key); + self.lighting.remove(&key); + world.chunks.insert(key, Arc::new(chunk)); + self.generated_total += 1; + for dz in -1..=1 { + for dx in -1..=1 { + world.dirty_light.insert((key.0 + dx, key.1 + dz)); + } + } + } + /// A column the server unloaded (ClientboundForgetLevelChunkPacket). + pub fn forget(&mut self, world: &mut World, x: i32, z: i32) -> Option> { + self.lit.remove(&(x, z)); + self.meshed.remove(&(x, z)); + self.lighting.remove(&(x, z)); + self.meshing.retain(|k, _| (k.0, k.2) != (x, z)); + world.dirty_sections.retain(|k| (k.0, k.2) != (x, z)); + world.chunks.remove(&(x, z)) + } fn submit(&mut self, priority: i64, job: Job) { self.order += 1; self.shared.queue.lock().unwrap().push(Queued { @@ -335,7 +361,7 @@ impl Streaming { .chunks .keys() .copied() - .filter(|&(x, z)| !self.in_range(x, z, 3)) + .filter(|&(x, z)| !self.remote && !self.in_range(x, z, 3)) .collect(); for key in &far { self.decorated.remove(key); @@ -409,7 +435,7 @@ impl Streaming { } // Generation (load or proto), closest first, bounded in flight. let margin = if self.decorates { 3 } else { 1 }; - if self.generating.len() < workers * 3 { + if !self.remote && self.generating.len() < workers * 3 { let r = self.radius + margin; let mut wanted = Vec::new(); for dz in -r..=r { diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index ba53902ea..c720d6183 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -18,6 +18,7 @@ pub enum Mode { Main, Select { worlds: Vec, selected: Option }, Create { name: String, seed: String, creative: bool, focus: u8 }, + Multiplayer(crate::multiplayer::Screen), } #[derive(Clone, Debug, PartialEq)] pub enum Action { @@ -26,6 +27,7 @@ pub enum Action { Options, Play { folder: String }, Create { folder: String, name: String, seed: Option, creative: bool }, + Connect { address: String }, } pub struct Title { pub mode: Mode, @@ -79,7 +81,7 @@ impl Title { let y = h / 4.0 + 48.0; vec![ b(w / 2.0 - 100.0, y, 200.0, "Singleplayer", true, 1), - b(w / 2.0 - 100.0, y + 24.0, 200.0, "Multiplayer", false, 0), + b(w / 2.0 - 100.0, y + 24.0, 200.0, "Multiplayer", true, 4), b(w / 2.0 - 100.0, y + 48.0, 200.0, "Minecraft Realms", false, 0), b(w / 2.0 - 100.0, y + 84.0, 98.0, "Options...", true, 3), b(w / 2.0 + 2.0, y + 84.0, 98.0, "Quit Game", true, 2), @@ -95,6 +97,7 @@ impl Title { b(w / 2.0 - 155.0, h - 28.0, 150.0, "Create New World", true, 21), b(w / 2.0 + 5.0, h - 28.0, 150.0, "Cancel", true, 22), ], + Mode::Multiplayer(screen) => screen.buttons(w, h).into_iter().map(|(x, y, bw, label, enabled, id)| b(x, y, bw, &label, enabled, id)).collect(), } } pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, cursor: (f32, f32)) { @@ -155,6 +158,7 @@ impl Title { batch.text(atlas, &shown, w / 2.0 - 96.0, y + 17.0, rgba(224, 224, 224, 255), true); } } + Mode::Multiplayer(screen) => screen.draw(atlas, batch, (self.started.elapsed().as_millis() / 300).is_multiple_of(2)), } for b in self.buttons(w, h) { let hover = b.enabled && cursor.0 >= b.x && cursor.0 < b.x + b.w && cursor.1 >= b.y && cursor.1 < b.y + 20.0; @@ -193,6 +197,18 @@ impl Title { Action::None } (Mode::Main, Some(2)) => Action::Quit, + (Mode::Main, Some(4)) => { + self.mode = Mode::Multiplayer(crate::multiplayer::Screen::list(&self.saves)); + Action::None + } + (Mode::Multiplayer(screen), hit) => match screen.click(hit, x, y, (w, h), &self.saves) { + crate::multiplayer::Outcome::Back => { + self.mode = Mode::Main; + Action::None + } + crate::multiplayer::Outcome::Connect(address) => Action::Connect { address }, + crate::multiplayer::Outcome::None => Action::None, + }, (Mode::Main, Some(3)) => Action::Options, (Mode::Select { worlds, selected }, Some(10)) => match selected.and_then(|i| worlds.get(i)) { Some(world) => Action::Play { folder: world.folder.clone() }, @@ -254,6 +270,9 @@ impl Title { } } pub fn type_text(&mut self, text: &str) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.type_text(text); + } if let Mode::Create { name, seed, focus, .. } = &mut self.mode { let field = if *focus == 0 { name } else { seed }; for c in text.chars().filter(|c| !c.is_control()) { @@ -264,17 +283,28 @@ impl Title { } } pub fn backspace(&mut self) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.backspace(); + } if let Mode::Create { name, seed, focus, .. } = &mut self.mode { let field = if *focus == 0 { name } else { seed }; field.pop(); } } pub fn tab(&mut self) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.tab(); + } if let Mode::Create { focus, .. } = &mut self.mode { *focus = (*focus + 1) % 2; } } pub fn escape(&mut self) { + if let Mode::Multiplayer(screen) = &mut self.mode + && !screen.escape(&self.saves) + { + return; + } self.mode = match &self.mode { Mode::Create { .. } => Mode::Select { worlds: list_worlds(&self.saves), selected: None }, _ => Mode::Main, diff --git a/crates/horizon-protocol/Cargo.toml b/crates/horizon-protocol/Cargo.toml new file mode 100644 index 000000000..0875a7bc4 --- /dev/null +++ b/crates/horizon-protocol/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "horizon-protocol" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version.workspace = true +description = "Horizon's Minecraft Java Edition 26.3 network protocol (version 777)" + +[dependencies] +horizon-world = { path = "../horizon-world" } +flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } +serde_json = "1.0.151" diff --git a/crates/horizon-protocol/examples/probe.rs b/crates/horizon-protocol/examples/probe.rs new file mode 100644 index 000000000..005be919f --- /dev/null +++ b/crates/horizon-protocol/examples/probe.rs @@ -0,0 +1,209 @@ +//! Log into a server in offline mode and decode everything it sends for a few +//! seconds, reporting packet counts and any decode failures. A differential +//! check of the codecs against a real vanilla server: +//! +//! cargo run -p horizon-protocol --example probe -- 127.0.0.1:25565 [seconds] [registries.json] +use horizon_protocol::{ + PROTOCOL_VERSION, State, + connection::Connection, + ids, + packets::{Empty, configuration as cfg, handshake, login, play}, + registry::{Builtin, Dynamic, ceil_log2}, + servers::parse_address, +}; +use std::{ + collections::BTreeMap, + time::{Duration, Instant}, +}; + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + let (host, port) = + parse_address(args.get(1).map_or("127.0.0.1", String::as_str)).ok_or("bad address")?; + let seconds: u64 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(10); + let builtin = args + .get(3) + .map(|p| Builtin::load(std::path::Path::new(p))) + .transpose()?; + let mut c = Connection::connect(&host, port, Duration::from_secs(5))?; + c.send( + &handshake::Serverbound::Intention(handshake::Intention { + protocol: PROTOCOL_VERSION, + host: host.clone(), + port, + intent: handshake::LOGIN, + }) + .encode(), + )?; + let name = "HorizonProbe"; + c.send( + &login::Serverbound::Hello(login::ServerHello { + name: name.into(), + uuid: horizon_protocol::crypto::offline_uuid(name), + }) + .encode(), + )?; + loop { + let (id, payload) = c.recv()?; + match login::Clientbound::decode(id, &payload)? { + login::Clientbound::Compression(p) => c.set_compression(p.threshold), + login::Clientbound::LoginFinished(p) => { + println!( + "logged in as {} {}", + p.profile.name, + horizon_protocol::crypto::uuid_string(p.profile.uuid) + ); + c.send(&login::Serverbound::LoginAcknowledged(Empty).encode())?; + break; + } + login::Clientbound::Disconnect(p) => return Err(p.reason_json.into()), + other => println!("login: {other:?}"), + } + } + c.send(&cfg::Serverbound::ClientInformation(cfg::ClientInformation::new(8)).encode())?; + let mut registries = Dynamic::default(); + loop { + let (id, payload) = c.recv()?; + match cfg::Clientbound::decode(id, &payload) { + Ok(cfg::Clientbound::SelectKnownPacks(p)) => { + println!("known packs offered: {:?}", p.packs); + c.send( + &cfg::Serverbound::SelectKnownPacks(cfg::SelectKnownPacks { packs: vec![] }) + .encode(), + )?; + } + Ok(cfg::Clientbound::RegistryData(p)) => { + println!("registry {} ({} entries)", p.registry, p.entries.len()); + registries.add(p); + } + Ok(cfg::Clientbound::KeepAlive(p)) => { + c.send(&cfg::Serverbound::KeepAlive(p).encode())? + } + Ok(cfg::Clientbound::Ping(p)) => c.send(&cfg::Serverbound::Pong(p).encode())?, + Ok(cfg::Clientbound::CodeOfConduct(_)) => { + c.send(&cfg::Serverbound::AcceptCodeOfConduct(Empty).encode())? + } + Ok(cfg::Clientbound::FinishConfiguration(_)) => { + c.send(&cfg::Serverbound::FinishConfiguration(Empty).encode())?; + break; + } + Ok(cfg::Clientbound::Disconnect(p)) => return Err(format!("{:?}", p.reason).into()), + Ok(cfg::Clientbound::UpdateTags(p)) => { + println!("tags for {} registries", p.registries.len()) + } + Ok(other) => println!( + "configuration: {}", + ids::name( + State::Configuration, + horizon_protocol::Direction::Clientbound, + other.id() + ) + .unwrap_or("?") + ), + Err(e) => println!("configuration decode error in {id}: {e}"), + } + } + let biome_bits = ceil_log2(registries.len("minecraft:worldgen/biome")); + let mut counts: BTreeMap<&str, (u32, u32)> = BTreeMap::new(); + let mut dimension = registries.dimension(0); + let start = Instant::now(); + c.reader + .set_read_timeout(Some(Duration::from_millis(500)))?; + let mut ticks = 0; + while start.elapsed() < Duration::from_secs(seconds) { + let (id, payload) = match c.recv() { + Ok(p) => p, + Err(e) if e.0.contains("timed out") || e.0.contains("temporarily unavailable") => { + continue; + } + Err(e) => return Err(e.into()), + }; + let name = + ids::name(State::Play, horizon_protocol::Direction::Clientbound, id).unwrap_or("?"); + let entry = counts.entry(name).or_default(); + entry.0 += 1; + match play::Clientbound::decode(id, &payload) { + Ok(packet) => match packet { + play::Clientbound::Login(p) => { + dimension = registries.dimension(p.spawn.dimension_type); + println!( + "login: entity {} in {} ({:?})", + p.player_id, p.spawn.dimension, dimension + ); + c.send(&play::Serverbound::PlayerLoaded(Empty).encode())?; + } + play::Clientbound::KeepAlive(p) => { + c.send(&play::Serverbound::KeepAlive(p).encode())? + } + play::Clientbound::Ping(p) => c.send(&play::Serverbound::Pong(p).encode())?, + play::Clientbound::PlayerPosition(p) => { + println!("position {:?} teleport {}", p.position, p.teleport); + let [x, y, z] = p.position; + c.send( + &play::Serverbound::AcceptTeleportation(play::AcceptTeleportation { + id: p.teleport, + x, + y, + z, + yaw: p.yaw, + pitch: p.pitch, + }) + .encode(), + )?; + // One position per client tick: end the tick like the client. + c.send(&play::Serverbound::ClientTickEnd(Empty).encode())?; + } + play::Clientbound::ChunkBatchFinished(_) => { + c.send( + &play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived { + chunks_per_tick: 50.0, + }) + .encode(), + )?; + ticks += 1; + } + play::Clientbound::LevelChunkWithLight(p) => { + if let Err(e) = p.chunk.sections(dimension.sections(), 16, biome_bits) { + println!("chunk {} {} sections: {e}", p.x, p.z); + entry.1 += 1; + } + } + play::Clientbound::AddEntity(p) => { + let kind = builtin + .as_ref() + .and_then(|b| b.get("minecraft:entity_type")?.name(p.kind)) + .unwrap_or("?"); + if counts.get("add_entity").is_some_and(|c| c.0 < 4) { + println!("entity {} {kind} at {:?}", p.id, p.position); + } + } + play::Clientbound::SystemChat(p) => println!( + "chat: {}", + horizon_protocol::text::plain(&p.content, &Default::default()) + ), + play::Clientbound::Disconnect(p) => { + return Err(format!("disconnected: {:?}", p.reason).into()); + } + _ => {} + }, + Err(e) => { + entry.1 += 1; + if entry.1 <= 2 { + println!("decode error in {name} ({} bytes): {e}", payload.len()); + } + } + } + } + println!("{ticks} chunk batches"); + for (name, (n, errors)) in counts { + println!( + "{name:32} {n:6} {}", + if errors > 0 { + format!("{errors} ERRORS") + } else { + String::new() + } + ); + } + Ok(()) +} diff --git a/crates/horizon-protocol/src/buf.rs b/crates/horizon-protocol/src/buf.rs new file mode 100644 index 000000000..d937ff8b9 --- /dev/null +++ b/crates/horizon-protocol/src/buf.rs @@ -0,0 +1,686 @@ +//! Byte buffers with vanilla's primitive encodings (FriendlyByteBuf, VarInt, +//! VarLong, ByteBufCodecs) and the `Codec` building blocks packets are +//! composed from, mirroring `StreamCodec.composite`. +use crate::{Error, Result}; +use horizon_world::nbt::{self, Tag}; +use std::marker::PhantomData; + +/// Vanilla's default NBT quota for network tags (NbtAccounter.defaultQuota). +pub const NBT_QUOTA: usize = 2_097_152; + +/// A cursor over a received packet body. +pub struct Reader<'a> { + data: &'a [u8], + pos: usize, +} +impl<'a> Reader<'a> { + pub fn new(data: &'a [u8]) -> Self { + Self { data, pos: 0 } + } + pub fn remaining(&self) -> usize { + self.data.len() - self.pos + } + pub fn position(&self) -> usize { + self.pos + } + pub fn rest(&mut self) -> &'a [u8] { + let rest = &self.data[self.pos..]; + self.pos = self.data.len(); + rest + } + pub fn bytes(&mut self, n: usize) -> Result<&'a [u8]> { + if self.remaining() < n { + return Err(Error::new(format!( + "needed {n} bytes, {} left", + self.remaining() + ))); + } + let out = &self.data[self.pos..self.pos + n]; + self.pos += n; + Ok(out) + } + fn array(&mut self) -> Result<[u8; N]> { + Ok(self.bytes(N)?.try_into().expect("length checked")) + } + pub fn u8(&mut self) -> Result { + Ok(self.array::<1>()?[0]) + } + pub fn i8(&mut self) -> Result { + Ok(self.u8()? as i8) + } + pub fn bool(&mut self) -> Result { + Ok(self.u8()? != 0) + } + pub fn i16(&mut self) -> Result { + Ok(i16::from_be_bytes(self.array()?)) + } + pub fn u16(&mut self) -> Result { + Ok(u16::from_be_bytes(self.array()?)) + } + pub fn i32(&mut self) -> Result { + Ok(i32::from_be_bytes(self.array()?)) + } + pub fn u32(&mut self) -> Result { + Ok(u32::from_be_bytes(self.array()?)) + } + pub fn i64(&mut self) -> Result { + Ok(i64::from_be_bytes(self.array()?)) + } + pub fn f32(&mut self) -> Result { + Ok(f32::from_be_bytes(self.array()?)) + } + pub fn f64(&mut self) -> Result { + Ok(f64::from_be_bytes(self.array()?)) + } + /// VarInt.read: at most five 7-bit groups, least significant first. + pub fn varint(&mut self) -> Result { + let mut value = 0u32; + for i in 0..5 { + let b = self.u8()?; + value |= u32::from(b & 0x7F) << (7 * i); + if b & 0x80 == 0 { + return Ok(value as i32); + } + } + Err(Error::new("VarInt too big")) + } + /// VarLong.read: at most ten 7-bit groups. + pub fn varlong(&mut self) -> Result { + let mut value = 0u64; + for i in 0..10 { + let b = self.u8()?; + value |= u64::from(b & 0x7F) << (7 * i); + if b & 0x80 == 0 { + return Ok(value as i64); + } + } + Err(Error::new("VarLong too big")) + } + /// A VarInt count that must fit in what is left (ByteBufCodecs.readCount). + pub fn count(&mut self, max: usize) -> Result { + let n = self.varint()?; + let n = usize::try_from(n).map_err(|_| Error::new(format!("negative count {n}")))?; + if n > max { + return Err(Error::new(format!( + "{n} elements is more than allowed {max}" + ))); + } + Ok(n) + } + /// Utf8String.read: VarInt byte length, UTF-8, at most `max` chars. + pub fn string(&mut self, max: usize) -> Result { + let len = self.count(max.saturating_mul(3))?; + let s = std::str::from_utf8(self.bytes(len)?) + .map_err(|e| Error::new(format!("bad UTF-8: {e}")))?; + if s.chars().count() > max { + return Err(Error::new(format!("string longer than {max} chars"))); + } + Ok(s.to_owned()) + } + pub fn byte_array(&mut self, max: usize) -> Result> { + let len = self.count(max)?; + Ok(self.bytes(len)?.to_vec()) + } + pub fn uuid(&mut self) -> Result { + Ok(u128::from_be_bytes(self.array()?)) + } + /// A network NBT tag (NbtIo.readAnyTag without a root name); `End` means none. + pub fn nbt(&mut self) -> Result { + let limits = nbt::Limits { + max_bytes: NBT_QUOTA, + ..nbt::Limits::default() + }; + let (tag, used) = nbt::read_network(&self.data[self.pos..], limits) + .map_err(|e| Error::new(format!("NBT: {e}")))?; + self.pos += used; + Ok(tag) + } + pub fn long_array(&mut self) -> Result> { + let n = self.count(self.remaining() / 8)?; + (0..n).map(|_| self.i64()).collect() + } + pub fn fixed_longs(&mut self, n: usize) -> Result> { + if self.remaining() < n * 8 { + return Err(Error::new("fixed long array past the end")); + } + (0..n).map(|_| self.i64()).collect() + } +} + +/// An outgoing packet body. +#[derive(Default)] +pub struct Writer { + pub data: Vec, +} +impl Writer { + pub fn new() -> Self { + Self::default() + } + pub fn u8(&mut self, v: u8) { + self.data.push(v); + } + pub fn i8(&mut self, v: i8) { + self.data.push(v as u8); + } + pub fn bool(&mut self, v: bool) { + self.data.push(u8::from(v)); + } + pub fn i16(&mut self, v: i16) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn u16(&mut self, v: u16) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn i32(&mut self, v: i32) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn u32(&mut self, v: u32) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn i64(&mut self, v: i64) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn f32(&mut self, v: f32) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn f64(&mut self, v: f64) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn varint(&mut self, v: i32) { + write_varint(&mut self.data, v); + } + pub fn varlong(&mut self, v: i64) { + let mut v = v as u64; + loop { + if v & !0x7F == 0 { + self.data.push(v as u8); + return; + } + self.data.push((v as u8 & 0x7F) | 0x80); + v >>= 7; + } + } + pub fn string(&mut self, s: &str) { + self.varint(s.len() as i32); + self.data.extend_from_slice(s.as_bytes()); + } + pub fn byte_array(&mut self, b: &[u8]) { + self.varint(b.len() as i32); + self.data.extend_from_slice(b); + } + pub fn bytes(&mut self, b: &[u8]) { + self.data.extend_from_slice(b); + } + pub fn uuid(&mut self, v: u128) { + self.data.extend_from_slice(&v.to_be_bytes()); + } + pub fn nbt(&mut self, tag: &Tag) { + match nbt::write_network(tag, nbt::Limits::default()) { + Ok(bytes) => self.data.extend_from_slice(&bytes), + // Unencodable tags (too deep) are sent as "no tag". + Err(_) => self.data.push(0), + } + } + pub fn long_array(&mut self, v: &[i64]) { + self.varint(v.len() as i32); + for &l in v { + self.i64(l); + } + } +} +pub fn write_varint(out: &mut Vec, v: i32) { + let mut v = v as u32; + loop { + if v & !0x7F == 0 { + out.push(v as u8); + return; + } + out.push((v as u8 & 0x7F) | 0x80); + v >>= 7; + } +} +pub fn varint_size(v: i32) -> usize { + let v = v as u32; + (1..5).find(|i| v >> (7 * i) == 0).unwrap_or(5) +} + +/// A wire encoding for values of type `T` (vanilla's StreamCodec). +pub trait Codec { + fn read(r: &mut Reader) -> Result; + fn write(v: &T, w: &mut Writer); +} +macro_rules! primitive { + ($name:ident, $ty:ty, $read:ident, $write:ident) => { + pub struct $name; + impl Codec<$ty> for $name { + fn read(r: &mut Reader) -> Result<$ty> { + r.$read() + } + fn write(v: &$ty, w: &mut Writer) { + w.$write(*v) + } + } + }; +} +primitive!(Bool, bool, bool, bool); +primitive!(Byte, i8, i8, i8); +primitive!(UByte, u8, u8, u8); +primitive!(Short, i16, i16, i16); +primitive!(UShort, u16, u16, u16); +primitive!(Int, i32, i32, i32); +primitive!(Long, i64, i64, i64); +primitive!(Float, f32, f32, f32); +primitive!(Double, f64, f64, f64); +primitive!(VarInt, i32, varint, varint); +primitive!(VarLong, i64, varlong, varlong); +primitive!(Uuid, u128, uuid, uuid); + +/// ByteBufCodecs.STRING_UTF8 (32767 chars). +pub struct Str; +impl Codec for Str { + fn read(r: &mut Reader) -> Result { + r.string(32767) + } + fn write(v: &String, w: &mut Writer) { + w.string(v) + } +} +/// A string with a smaller vanilla limit, e.g. player names (16). +pub struct StrN; +impl Codec for StrN { + fn read(r: &mut Reader) -> Result { + r.string(N) + } + fn write(v: &String, w: &mut Writer) { + w.string(v) + } +} +/// Identifier.STREAM_CODEC: a resource location string. +pub type Ident = StrN<32767>; +/// VarInt-prefixed bytes. +pub struct Bytes; +impl Codec> for Bytes { + fn read(r: &mut Reader) -> Result> { + r.byte_array(r.remaining()) + } + fn write(v: &Vec, w: &mut Writer) { + w.byte_array(v) + } +} +/// Everything left in the packet (custom payloads). +pub struct Rest; +impl Codec> for Rest { + fn read(r: &mut Reader) -> Result> { + Ok(r.rest().to_vec()) + } + fn write(v: &Vec, w: &mut Writer) { + w.bytes(v) + } +} +/// Any network NBT tag (`Tag::End` when absent). +pub struct Nbt; +impl Codec for Nbt { + fn read(r: &mut Reader) -> Result { + r.nbt() + } + fn write(v: &Tag, w: &mut Writer) { + w.nbt(v) + } +} +/// ByteBufCodecs.LONG_ARRAY. +pub struct Longs; +impl Codec> for Longs { + fn read(r: &mut Reader) -> Result> { + r.long_array() + } + fn write(v: &Vec, w: &mut Writer) { + w.long_array(v) + } +} +/// ByteBufCodecs.list(): VarInt count then elements. +pub struct List(PhantomData); +impl> Codec> for List { + fn read(r: &mut Reader) -> Result> { + let n = r.count(r.remaining())?; + (0..n).map(|_| C::read(r)).collect() + } + fn write(v: &Vec, w: &mut Writer) { + w.varint(v.len() as i32); + for e in v { + C::write(e, w); + } + } +} +/// ByteBufCodecs.optional(): a boolean presence flag. +pub struct Opt(PhantomData); +impl> Codec> for Opt { + fn read(r: &mut Reader) -> Result> { + if r.bool()? { + Ok(Some(C::read(r)?)) + } else { + Ok(None) + } + } + fn write(v: &Option, w: &mut Writer) { + w.bool(v.is_some()); + if let Some(v) = v { + C::write(v, w); + } + } +} +/// ByteBufCodecs.OPTIONAL_VAR_INT: 0 = empty, otherwise value + 1. +pub struct OptVarInt; +impl Codec> for OptVarInt { + fn read(r: &mut Reader) -> Result> { + let v = r.varint()?; + Ok(if v == 0 { None } else { Some(v - 1) }) + } + fn write(v: &Option, w: &mut Writer) { + w.varint(v.map_or(0, |v| v + 1)) + } +} +/// Vec3.STREAM_CODEC: three doubles. +pub struct Vec3d; +impl Codec<[f64; 3]> for Vec3d { + fn read(r: &mut Reader) -> Result<[f64; 3]> { + Ok([r.f64()?, r.f64()?, r.f64()?]) + } + fn write(v: &[f64; 3], w: &mut Writer) { + for c in v { + w.f64(*c); + } + } +} +/// BlockPos.STREAM_CODEC: x (26 bits), z (26 bits), y (12 bits) in one long. +pub struct Pos; +impl Codec<[i32; 3]> for Pos { + fn read(r: &mut Reader) -> Result<[i32; 3]> { + Ok(unpack_block_pos(r.i64()?)) + } + fn write(v: &[i32; 3], w: &mut Writer) { + w.i64(pack_block_pos(*v)) + } +} +pub fn pack_block_pos(p: [i32; 3]) -> i64 { + ((i64::from(p[0]) & 0x3FF_FFFF) << 38) + | ((i64::from(p[2]) & 0x3FF_FFFF) << 12) + | (i64::from(p[1]) & 0xFFF) +} +pub fn unpack_block_pos(v: i64) -> [i32; 3] { + [ + (v >> 38) as i32, + (v << 52 >> 52) as i32, + (v << 26 >> 38) as i32, + ] +} +/// ChunkPos packed as x in the low and z in the high 32 bits. +pub struct ChunkPos; +impl Codec<[i32; 2]> for ChunkPos { + fn read(r: &mut Reader) -> Result<[i32; 2]> { + let v = r.i64()?; + Ok([v as i32, (v >> 32) as i32]) + } + fn write(v: &[i32; 2], w: &mut Writer) { + w.i64((i64::from(v[0]) & 0xFFFF_FFFF) | (i64::from(v[1]) << 32)) + } +} +/// SectionPos: x (22 bits), z (22 bits), y (20 bits). +pub struct SectionPos; +impl Codec<[i32; 3]> for SectionPos { + fn read(r: &mut Reader) -> Result<[i32; 3]> { + let v = r.i64()?; + Ok([ + (v >> 42) as i32, + (v << 44 >> 44) as i32, + (v << 22 >> 42) as i32, + ]) + } + fn write(v: &[i32; 3], w: &mut Writer) { + w.i64( + ((i64::from(v[0]) & 0x3F_FFFF) << 42) + | ((i64::from(v[2]) & 0x3F_FFFF) << 20) + | (i64::from(v[1]) & 0xF_FFFF), + ) + } +} +/// ByteBufCodecs.BIT_SET: java.util.BitSet as a VarInt-prefixed byte array. +pub struct BitSet; +impl Codec> for BitSet { + fn read(r: &mut Reader) -> Result> { + r.byte_array(r.remaining()) + } + fn write(v: &Vec, w: &mut Writer) { + // BitSet.toByteArray drops trailing zero bytes. + let len = v.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1); + w.byte_array(&v[..len]) + } +} +pub fn bit(set: &[u8], i: usize) -> bool { + set.get(i / 8).is_some_and(|b| b >> (i % 8) & 1 != 0) +} +pub fn set_bit(set: &mut Vec, i: usize) { + if set.len() <= i / 8 { + set.resize(i / 8 + 1, 0); + } + set[i / 8] |= 1 << (i % 8); +} +/// LpVec3: a low-precision velocity (Vec3.LP_STREAM_CODEC). +pub struct LpVec3; +impl LpVec3 { + fn unpack(v: u64) -> f64 { + ((v & 32767) as f64).min(32766.0) * 2.0 / 32766.0 - 1.0 + } + fn pack(v: f64) -> u64 { + ((v * 0.5 + 0.5) * 32766.0).round() as u64 + } + fn sanitize(v: f64) -> f64 { + if v.is_nan() { + 0.0 + } else { + v.clamp(-1.717_986_918_3e10, 1.717_986_918_3e10) + } + } +} +impl Codec<[f64; 3]> for LpVec3 { + fn read(r: &mut Reader) -> Result<[f64; 3]> { + let lowest = u64::from(r.u8()?); + if lowest == 0 { + return Ok([0.0; 3]); + } + let middle = u64::from(r.u8()?); + let highest = u64::from(r.u32()?); + let buffer = highest << 16 | middle << 8 | lowest; + let mut scale = lowest & 3; + if lowest & 4 == 4 { + scale |= (u64::from(r.varint()? as u32)) << 2; + } + let s = scale as f64; + Ok([ + Self::unpack(buffer >> 3) * s, + Self::unpack(buffer >> 18) * s, + Self::unpack(buffer >> 33) * s, + ]) + } + fn write(v: &[f64; 3], w: &mut Writer) { + let [x, y, z] = v.map(Self::sanitize); + let length = x.abs().max(y.abs()).max(z.abs()); + if length < 3.051_944_088_384_301e-5 { + w.u8(0); + return; + } + let scale = length.ceil() as u64; + let partial = scale & 3 != scale; + let markers = if partial { scale & 3 | 4 } else { scale }; + let s = scale as f64; + let buffer = + markers | Self::pack(x / s) << 3 | Self::pack(y / s) << 18 | Self::pack(z / s) << 33; + w.u8(buffer as u8); + w.u8((buffer >> 8) as u8); + w.i32((buffer >> 16) as i32); + if partial { + w.varint((scale >> 2) as i32); + } + } +} +/// A degree angle sent as a byte (Mth.packDegrees / unpackDegrees). +pub fn pack_degrees(deg: f32) -> i8 { + (deg * 256.0 / 360.0).floor() as i32 as i8 +} +pub fn unpack_degrees(b: i8) -> f32 { + f32::from(b) * 360.0 / 256.0 +} + +/// Define a packet struct and its codec from (field: type => codec) triples, +/// like vanilla's `StreamCodec.composite`. +#[macro_export] +macro_rules! packet { + ($(#[$meta:meta])* $name:ident { $($field:ident : $ty:ty => $codec:ty),* $(,)? }) => { + $(#[$meta])* + #[derive(Clone, Debug, PartialEq)] + pub struct $name { + $(pub $field: $ty),* + } + impl $crate::buf::Codec<$name> for $name { + #[allow(unused_variables)] + fn read(r: &mut $crate::buf::Reader) -> $crate::Result<$name> { + Ok($name { $($field: <$codec as $crate::buf::Codec<$ty>>::read(r)?),* }) + } + #[allow(unused_variables)] + fn write(v: &$name, w: &mut $crate::buf::Writer) { + $(<$codec as $crate::buf::Codec<$ty>>::write(&v.$field, w);)* + } + } + }; +} + +#[cfg(test)] +mod tests { + use super::*; + + fn round>(v: T) -> Vec { + let mut w = Writer::new(); + C::write(&v, &mut w); + let mut r = Reader::new(&w.data); + assert_eq!(C::read(&mut r).unwrap(), v); + assert_eq!(r.remaining(), 0); + w.data + } + + #[test] + fn varint_matches_vanilla_examples() { + // wiki.vg / VarInt.java examples. + assert_eq!(round::(0), [0x00]); + assert_eq!(round::(1), [0x01]); + assert_eq!(round::(127), [0x7f]); + assert_eq!(round::(128), [0x80, 0x01]); + assert_eq!(round::(255), [0xff, 0x01]); + assert_eq!(round::(25565), [0xdd, 0xc7, 0x01]); + assert_eq!(round::(2097151), [0xff, 0xff, 0x7f]); + assert_eq!( + round::(i32::MAX), + [0xff, 0xff, 0xff, 0xff, 0x07] + ); + assert_eq!(round::(-1), [0xff, 0xff, 0xff, 0xff, 0x0f]); + assert_eq!( + round::(i32::MIN), + [0x80, 0x80, 0x80, 0x80, 0x08] + ); + for v in [0, 1, 127, 128, 16383, 16384, 2097151, 2097152, i32::MAX, -1] { + assert_eq!(varint_size(v), round::(v).len()); + } + assert!(Reader::new(&[0xff; 6]).varint().is_err()); + } + + #[test] + fn varlong_matches_vanilla_examples() { + assert_eq!(round::(0), [0x00]); + assert_eq!( + round::(2147483647), + [0xff, 0xff, 0xff, 0xff, 0x07] + ); + assert_eq!( + round::(i64::MAX), + [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f] + ); + assert_eq!( + round::(-1), + [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01] + ); + assert_eq!( + round::(i64::MIN), + [0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01] + ); + } + + #[test] + fn strings_positions_and_options() { + assert_eq!(round::("héllo".into()), b"\x06h\xc3\xa9llo"); + let mut w = Writer::new(); + w.string("seventeen chars!!"); + assert!(Reader::new(&w.data).string(16).is_err()); + for p in [ + [0, 0, 0], + [-1, -64, -1], + [33_554_431, 2047, -33_554_432], + [123, -2048, -456], + ] { + round::<[i32; 3], Pos>(p); + assert_eq!(unpack_block_pos(pack_block_pos(p)), p); + } + // BlockPos.asLong(1, 2, 3) + assert_eq!(pack_block_pos([1, 2, 3]), (1 << 38) | (3 << 12) | 2); + round::<[i32; 3], SectionPos>([-5, -4, 1_000]); + round::<[i32; 2], ChunkPos>([-7, 12]); + round::, Opt>(Some("x".into())); + round::, Opt>(None); + round::, OptVarInt>(Some(0)); + round::, List>(vec![1, 300, -1]); + round::(0x0123_4567_89ab_cdef_0011_2233_4455_6677); + } + + #[test] + fn bitset_drops_trailing_zero_bytes() { + let mut set = vec![0u8; 4]; + set_bit(&mut set, 3); + set_bit(&mut set, 9); + let mut w = Writer::new(); + BitSet::write(&set, &mut w); + assert_eq!(w.data, [2, 0b1000, 0b10]); + let read = BitSet::read(&mut Reader::new(&w.data)).unwrap(); + assert!(bit(&read, 3) && bit(&read, 9) && !bit(&read, 4) && !bit(&read, 100)); + } + + #[test] + fn lp_vec3_round_trips_within_precision() { + for v in [ + [0.0, 0.0, 0.0], + [0.1, -0.2, 0.3], + [1.5, -3.25, 0.0], + [12.0, 0.0, -40.5], + [0.0, -3.92, 0.0], + ] { + let mut w = Writer::new(); + LpVec3::write(&v, &mut w); + let back = LpVec3::read(&mut Reader::new(&w.data)).unwrap(); + let scale = v.iter().fold(0.0f64, |m, c| m.max(c.abs())).ceil().max(1.0); + for i in 0..3 { + assert!( + (back[i] - v[i]).abs() <= scale / 32766.0 * 1.01, + "{v:?} -> {back:?}" + ); + } + } + // Zero is a single byte. + let mut w = Writer::new(); + LpVec3::write(&[0.0, 1e-9, 0.0], &mut w); + assert_eq!(w.data, [0]); + } + + #[test] + fn angles_pack_like_mth() { + assert_eq!(pack_degrees(90.0), 64); + assert_eq!(pack_degrees(-90.0), -64); + assert_eq!(pack_degrees(180.0), -128); + assert_eq!(unpack_degrees(64), 90.0); + } +} diff --git a/crates/horizon-protocol/src/chunk.rs b/crates/horizon-protocol/src/chunk.rs new file mode 100644 index 000000000..3343eacf5 --- /dev/null +++ b/crates/horizon-protocol/src/chunk.rs @@ -0,0 +1,393 @@ +//! Chunk column payloads: ClientboundLevelChunkPacketData (heightmaps, the +//! serialized LevelChunkSections with their PalettedContainers, block +//! entities) and ClientboundLightUpdatePacketData (sky/block DataLayers). +use crate::{ + Result, + buf::{BitSet, Bytes, Codec, Longs, Reader, VarInt, Writer}, + packet, +}; +use horizon_world::nbt::Tag; + +/// Blocks: 16^3 entries; biomes: 4^3 entries per section. +pub const BLOCKS: usize = 4096; +pub const BIOMES: usize = 64; + +/// Which palette Strategy a container uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Strategy { + /// Strategy.createForBlockStates. + Blocks, + /// Strategy.createForBiomes. + Biomes, +} +impl Strategy { + fn entries(self) -> usize { + match self { + Self::Blocks => BLOCKS, + Self::Biomes => BIOMES, + } + } + /// getConfigurationForBitCount: (uses a palette, bits in storage). + fn configuration(self, bits: u8, global_bits: u8) -> (bool, u8) { + match (self, bits) { + (_, 0) => (true, 0), + (Self::Blocks, 1..=4) => (true, 4), + (Self::Blocks, 5..=8) => (true, bits), + (Self::Biomes, 1..=3) => (true, bits), + _ => (false, global_bits.max(bits)), + } + } +} + +/// SimpleBitStorage: `64 / bits` values per long, never spanning longs. +pub fn storage_get(data: &[i64], bits: u8, i: usize) -> u32 { + if bits == 0 { + return 0; + } + let per = 64 / bits as usize; + let (cell, offset) = (i / per, (i % per) * bits as usize); + data.get(cell) + .map_or(0, |&l| ((l as u64 >> offset) & ((1u64 << bits) - 1)) as u32) +} +pub fn storage_len(bits: u8, entries: usize) -> usize { + if bits == 0 { + 0 + } else { + entries.div_ceil(64 / bits as usize) + } +} + +/// One PalettedContainer as sent. +#[derive(Clone, Debug, PartialEq)] +pub struct Paletted { + /// Bits per entry as written (Data.storage.getBits()). + pub bits: u8, + /// Palette entries (registry ids); empty for the global palette. + pub palette: Vec, + pub data: Vec, +} +impl Paletted { + pub fn read(r: &mut Reader, strategy: Strategy, global_bits: u8) -> Result { + let wire = r.u8()?; + let (has_palette, bits) = strategy.configuration(wire, global_bits); + let palette = if !has_palette { + Vec::new() + } else if bits == 0 { + vec![r.varint()?] + } else { + let n = r.count(1 << bits)?; + (0..n).map(|_| r.varint()).collect::>()? + }; + let data = r.fixed_longs(storage_len(bits, strategy.entries()))?; + Ok(Self { + bits, + palette, + data, + }) + } + pub fn write(&self, w: &mut Writer) { + w.u8(self.bits); + if !self.palette.is_empty() { + if self.bits != 0 { + w.varint(self.palette.len() as i32); + } + for &p in &self.palette { + w.varint(p); + } + } + for &l in &self.data { + w.i64(l); + } + } + /// The registry id at entry `i` ((y * 16 + z) * 16 + x for blocks). + pub fn get(&self, i: usize) -> i32 { + if self.bits == 0 { + return self.palette.first().copied().unwrap_or(0); + } + let v = storage_get(&self.data, self.bits, i); + if self.palette.is_empty() { + v as i32 + } else { + self.palette.get(v as usize).copied().unwrap_or(0) + } + } + /// Pack values the way the server's container would have grown: + /// the smallest configuration for the number of distinct values. + pub fn from_values(values: &[i32], strategy: Strategy, global_bits: u8) -> Self { + let mut palette: Vec = Vec::new(); + for &v in values { + if !palette.contains(&v) { + palette.push(v); + } + } + let needed = if palette.len() <= 1 { + 0 + } else { + (usize::BITS - (palette.len() - 1).leading_zeros()) as u8 + }; + let (has_palette, bits) = strategy.configuration(needed, global_bits); + if bits == 0 { + return Self { + bits: 0, + palette: vec![palette.first().copied().unwrap_or(0)], + data: Vec::new(), + }; + } + let mut data = vec![0i64; storage_len(bits, values.len())]; + let per = 64 / bits as usize; + for (i, &v) in values.iter().enumerate() { + let id = if has_palette { + palette.iter().position(|&p| p == v).unwrap_or(0) as u64 + } else { + v as u64 + }; + data[i / per] |= (id << ((i % per) * bits as usize)) as i64; + } + Self { + bits, + palette: if has_palette { palette } else { Vec::new() }, + data, + } + } +} + +/// LevelChunkSection.write. +#[derive(Clone, Debug, PartialEq)] +pub struct Section { + pub non_empty: i16, + pub fluids: i16, + pub states: Paletted, + pub biomes: Paletted, +} +impl Section { + pub fn read(r: &mut Reader, block_bits: u8, biome_bits: u8) -> Result { + Ok(Self { + non_empty: r.i16()?, + fluids: r.i16()?, + states: Paletted::read(r, Strategy::Blocks, block_bits)?, + biomes: Paletted::read(r, Strategy::Biomes, biome_bits)?, + }) + } + pub fn write(&self, w: &mut Writer) { + w.i16(self.non_empty); + w.i16(self.fluids); + self.states.write(w); + self.biomes.write(w); + } +} + +packet!( + /// ClientboundLevelChunkPacketData.BlockEntityInfo. + BlockEntityInfo { + packed_xz: i8 => crate::buf::Byte, + y: i16 => crate::buf::Short, + kind: i32 => VarInt, + tag: Tag => crate::buf::Nbt, + } +); +/// Heightmap type id with its packed long array. +pub struct Heightmaps; +impl Codec)>> for Heightmaps { + fn read(r: &mut Reader) -> Result)>> { + let n = r.count(16)?; + (0..n).map(|_| Ok((r.varint()?, r.long_array()?))).collect() + } + fn write(v: &Vec<(i32, Vec)>, w: &mut Writer) { + w.varint(v.len() as i32); + for (kind, data) in v { + w.varint(*kind); + Longs::write(data, w); + } + } +} +packet!( + /// ClientboundLevelChunkPacketData. + ChunkData { + heightmaps: Vec<(i32, Vec)> => Heightmaps, + buffer: Vec => Bytes, + block_entities: Vec => crate::buf::List, + } +); +impl ChunkData { + /// Decode `count` sections from the buffer. + pub fn sections(&self, count: usize, block_bits: u8, biome_bits: u8) -> Result> { + let mut r = Reader::new(&self.buffer); + (0..count) + .map(|_| Section::read(&mut r, block_bits, biome_bits)) + .collect() + } + pub fn from_sections(sections: &[Section]) -> Vec { + let mut w = Writer::new(); + for s in sections { + s.write(&mut w); + } + w.data + } +} +/// ByteBufCodecs.byteArray(2048) per DataLayer. +pub struct Layers; +impl Codec>> for Layers { + fn read(r: &mut Reader) -> Result>> { + let n = r.count(r.remaining())?; + (0..n).map(|_| r.byte_array(2048)).collect() + } + fn write(v: &Vec>, w: &mut Writer) { + w.varint(v.len() as i32); + for l in v { + w.byte_array(l); + } + } +} +packet!( + /// ClientboundLightUpdatePacketData. Bit `i` of a mask is light section + /// `minLightSection + i` (one below the lowest block section). + LightData { + sky_mask: Vec => BitSet, + block_mask: Vec => BitSet, + empty_sky_mask: Vec => BitSet, + empty_block_mask: Vec => BitSet, + sky: Vec> => Layers, + block: Vec> => Layers, + } +); +impl LightData { + /// Per light section: the sky and block DataLayers (None = absent/unchanged, + /// Some(zeroed) when marked empty). + pub fn layers(&self, light_sections: usize) -> Vec { + use crate::buf::bit; + let (mut sky, mut block) = (self.sky.iter(), self.block.iter()); + (0..light_sections) + .map(|i| { + let s = if bit(&self.sky_mask, i) { + sky.next().cloned() + } else if bit(&self.empty_sky_mask, i) { + Some(vec![0; 2048]) + } else { + None + }; + let b = if bit(&self.block_mask, i) { + block.next().cloned() + } else if bit(&self.empty_block_mask, i) { + Some(vec![0; 2048]) + } else { + None + }; + (s, b) + }) + .collect() + } +} +/// A light section's (sky, block) DataLayers. +pub type SectionLight = (Option>, Option>); +/// DataLayer.get: the nibble at (y << 8 | z << 4 | x), low nibble first. +pub fn nibble(layer: &[u8], i: usize) -> u8 { + layer + .get(i >> 1) + .map_or(0, |b| if i & 1 == 0 { b & 15 } else { b >> 4 }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bit_storage_matches_simple_bit_storage() { + // 5 bits: 12 values per long, the top 4 bits of each long unused. + let values: Vec = (0..BLOCKS as i32).map(|i| i % 20).collect(); + let p = Paletted::from_values(&values, Strategy::Blocks, 16); + assert_eq!(p.bits, 5); + assert_eq!(p.data.len(), 4096usize.div_ceil(12)); + for i in [0, 11, 12, 13, 4095] { + assert_eq!(p.get(i), values[i]); + } + } + + #[test] + fn palettes_follow_the_strategies() { + let single = Paletted::from_values(&[7; BLOCKS], Strategy::Blocks, 16); + assert_eq!( + (single.bits, single.palette.clone(), single.data.len()), + (0, vec![7], 0) + ); + // Two distinct block states still use the four-bit linear palette. + let mut two = vec![0; BLOCKS]; + two[100] = 9; + let p = Paletted::from_values(&two, Strategy::Blocks, 16); + assert_eq!((p.bits, p.data.len()), (4, 256)); + // Biomes with two values use one bit; more than eight use the global palette. + let mut biomes = vec![3; BIOMES]; + biomes[5] = 4; + assert_eq!(Paletted::from_values(&biomes, Strategy::Biomes, 7).bits, 1); + let many: Vec = (0..BIOMES as i32).map(|i| i % 9).collect(); + let g = Paletted::from_values(&many, Strategy::Biomes, 7); + assert!(g.palette.is_empty() && g.bits == 7); + assert_eq!(g.get(10), 1); + // Over 256 block states: global palette with the registry's bit width. + let wide: Vec = (0..BLOCKS as i32).map(|i| i * 7).collect(); + let g = Paletted::from_values(&wide, Strategy::Blocks, 16); + assert!(g.palette.is_empty() && g.bits == 16); + assert_eq!(g.get(4095), 4095 * 7); + } + + #[test] + fn chunk_data_round_trips() { + let mut states = vec![0; BLOCKS]; + for (i, s) in states.iter_mut().enumerate().take(256) { + *s = (i % 3) as i32 + 1; + } + let section = Section { + non_empty: 256, + fluids: 0, + states: Paletted::from_values(&states, Strategy::Blocks, 16), + biomes: Paletted::from_values(&[2; BIOMES], Strategy::Biomes, 7), + }; + let empty = Section { + non_empty: 0, + fluids: 0, + states: Paletted::from_values(&[0; BLOCKS], Strategy::Blocks, 16), + biomes: Paletted::from_values(&[2; BIOMES], Strategy::Biomes, 7), + }; + let data = ChunkData { + heightmaps: vec![(1, vec![1, 2, 3]), (4, vec![5])], + buffer: ChunkData::from_sections(&[section.clone(), empty.clone()]), + block_entities: vec![BlockEntityInfo { + packed_xz: 0x3f, + y: -60, + kind: 2, + tag: Tag::End, + }], + }; + let mut w = Writer::new(); + ChunkData::write(&data, &mut w); + let back = ChunkData::read(&mut Reader::new(&w.data)).unwrap(); + assert_eq!(back, data); + let sections = back.sections(2, 16, 7).unwrap(); + assert_eq!(sections, vec![section, empty]); + assert_eq!(sections[0].states.get(4), 2); + assert_eq!(sections[1].states.get(4), 0); + } + + #[test] + fn light_layers_follow_masks() { + let mut light = LightData { + sky_mask: vec![], + block_mask: vec![], + empty_sky_mask: vec![], + empty_block_mask: vec![], + sky: vec![vec![0xF0; 2048]], + block: vec![], + }; + crate::buf::set_bit(&mut light.sky_mask, 3); + crate::buf::set_bit(&mut light.empty_block_mask, 1); + let mut w = Writer::new(); + LightData::write(&light, &mut w); + let back = LightData::read(&mut Reader::new(&w.data)).unwrap(); + assert_eq!(back, light); + let layers = back.layers(26); + assert_eq!(layers.len(), 26); + assert_eq!(nibble(layers[3].0.as_ref().unwrap(), 1), 15); + assert_eq!(nibble(layers[3].0.as_ref().unwrap(), 0), 0); + assert_eq!(layers[1].1.as_deref(), Some(&[0u8; 2048][..])); + assert!(layers[0].0.is_none() && layers[0].1.is_none()); + } +} diff --git a/crates/horizon-protocol/src/connection.rs b/crates/horizon-protocol/src/connection.rs new file mode 100644 index 000000000..5c0bba188 --- /dev/null +++ b/crates/horizon-protocol/src/connection.rs @@ -0,0 +1,183 @@ +//! A blocking TCP connection with vanilla's pipeline: optional AES/CFB8 +//! encryption, VarInt21 framing and threshold compression. After login it +//! splits into a reader (for a receive thread) and a shareable writer. +use crate::{Error, Result, buf::Reader, crypto::Cfb8, frame}; +use std::{ + io::{Read, Write}, + net::{Shutdown, TcpStream, ToSocketAddrs}, + sync::{ + Arc, + atomic::{AtomicI64, Ordering}, + }, + time::Duration, +}; + +/// Packets received/sent and bytes in/out, for the debug screen. +#[derive(Debug, Default)] +pub struct Counters { + pub received: AtomicI64, + pub sent: AtomicI64, + pub bytes_in: AtomicI64, + pub bytes_out: AtomicI64, +} + +pub struct ConnReader { + stream: TcpStream, + buffer: Vec, + decrypt: Option, + pub threshold: Option, + pub counters: Arc, +} +pub struct ConnWriter { + stream: TcpStream, + encrypt: Option, + pub threshold: Option, + counters: Arc, +} +/// Both halves before the split. +pub struct Connection { + pub reader: ConnReader, + pub writer: ConnWriter, +} +impl Connection { + pub fn connect(host: &str, port: u16, timeout: Duration) -> Result { + let addrs: Vec<_> = (host, port) + .to_socket_addrs() + .map_err(|e| Error::new(format!("Unknown host {host}: {e}")))? + .collect(); + let mut last = Error::new(format!("Unknown host {host}")); + for addr in addrs { + match TcpStream::connect_timeout(&addr, timeout) { + Ok(stream) => return Self::from_stream(stream), + Err(e) => last = Error::new(format!("Connection refused: {e}")), + } + } + Err(last) + } + pub fn from_stream(stream: TcpStream) -> Result { + stream.set_nodelay(true)?; + let counters = Arc::new(Counters::default()); + let write = stream.try_clone()?; + Ok(Self { + reader: ConnReader { + stream, + buffer: Vec::new(), + decrypt: None, + threshold: None, + counters: counters.clone(), + }, + writer: ConnWriter { + stream: write, + encrypt: None, + threshold: None, + counters, + }, + }) + } + /// ClientboundLoginCompressionPacket: negative thresholds disable compression. + pub fn set_compression(&mut self, threshold: i32) { + let t = usize::try_from(threshold).ok(); + self.reader.threshold = t; + self.writer.threshold = t; + } + /// Connection.setEncryptionKey: both directions keyed with the shared secret. + pub fn enable_encryption(&mut self, secret: &[u8; 16]) { + self.reader.decrypt = Some(Cfb8::new(secret, secret)); + self.writer.encrypt = Some(Cfb8::new(secret, secret)); + } + pub fn send(&mut self, body: &[u8]) -> Result<()> { + self.writer.send(body) + } + pub fn recv(&mut self) -> Result<(i32, Vec)> { + self.reader.recv() + } + pub fn split(self) -> (ConnReader, ConnWriter) { + (self.reader, self.writer) + } +} +impl ConnReader { + /// Block until a whole packet arrives: (id, payload). + pub fn recv(&mut self) -> Result<(i32, Vec)> { + loop { + if let Some(frame) = frame::split(&mut self.buffer)? { + let body = frame::decompress(frame, self.threshold)?; + let mut r = Reader::new(&body); + let id = r.varint()?; + let start = r.position(); + self.counters.received.fetch_add(1, Ordering::Relaxed); + return Ok((id, body[start..].to_vec())); + } + let mut chunk = [0u8; 16384]; + let n = self.stream.read(&mut chunk)?; + if n == 0 { + return Err(Error::new("Connection closed by the server")); + } + self.counters + .bytes_in + .fetch_add(n as i64, Ordering::Relaxed); + let data = &mut chunk[..n]; + if let Some(c) = &mut self.decrypt { + c.decrypt(data); + } + self.buffer.extend_from_slice(data); + } + } + pub fn set_read_timeout(&self, timeout: Option) -> Result<()> { + Ok(self.stream.set_read_timeout(timeout)?) + } +} +impl ConnWriter { + /// Send one packet body (VarInt id + payload). + pub fn send(&mut self, body: &[u8]) -> Result<()> { + let mut framed = frame::encode(body, self.threshold)?; + if let Some(c) = &mut self.encrypt { + c.encrypt(&mut framed); + } + self.stream.write_all(&framed)?; + self.counters.sent.fetch_add(1, Ordering::Relaxed); + self.counters + .bytes_out + .fetch_add(framed.len() as i64, Ordering::Relaxed); + Ok(()) + } + pub fn shutdown(&self) { + let _ = self.stream.shutdown(Shutdown::Both); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::net::TcpListener; + + #[test] + fn loopback_with_compression_and_encryption() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut c = Connection::from_stream(stream).unwrap(); + let (id, payload) = c.recv().unwrap(); + assert_eq!((id, payload.as_slice()), (0, &b"plain"[..])); + c.enable_encryption(&[7; 16]); + c.set_compression(64); + let (id, payload) = c.recv().unwrap(); + assert_eq!((id, payload.len()), (5, 1000)); + let mut body = vec![9]; + body.extend_from_slice(b"reply"); + c.send(&body).unwrap(); + }); + let mut c = Connection::connect("127.0.0.1", port, Duration::from_secs(5)).unwrap(); + let mut body = vec![0]; + body.extend_from_slice(b"plain"); + c.send(&body).unwrap(); + c.enable_encryption(&[7; 16]); + c.set_compression(64); + let mut big = vec![5]; + big.extend(std::iter::repeat_n(3u8, 1000)); + c.send(&big).unwrap(); + let (id, payload) = c.recv().unwrap(); + assert_eq!((id, payload.as_slice()), (9, &b"reply"[..])); + server.join().unwrap(); + } +} diff --git a/crates/horizon-protocol/src/crypto.rs b/crates/horizon-protocol/src/crypto.rs new file mode 100644 index 000000000..c55b003b5 --- /dev/null +++ b/crates/horizon-protocol/src/crypto.rs @@ -0,0 +1,275 @@ +//! Connection encryption (Crypt.getCipher: AES/CFB8/NoPadding with the shared +//! secret as key and IV) and MD5 name-based UUIDs for offline-mode profiles +//! (UUIDUtil.createOfflinePlayerUUID). Only the AES forward cipher is needed: +//! CFB8 encrypts the shift register in both directions. + +const SBOX: [u8; 256] = { + // Generated from the AES field inverse and affine transform at compile time. + let mut sbox = [0u8; 256]; + let mut p: u8 = 1; + let mut q: u8 = 1; + loop { + // p *= 3 + p = p ^ (p << 1) ^ if p & 0x80 != 0 { 0x1B } else { 0 }; + // q /= 3 + q ^= q << 1; + q ^= q << 2; + q ^= q << 4; + if q & 0x80 != 0 { + q ^= 0x09; + } + let x = q ^ q.rotate_left(1) ^ q.rotate_left(2) ^ q.rotate_left(3) ^ q.rotate_left(4); + sbox[p as usize] = x ^ 0x63; + if p == 1 { + break; + } + } + sbox[0] = 0x63; + sbox +}; + +fn xtime(b: u8) -> u8 { + (b << 1) ^ if b & 0x80 != 0 { 0x1B } else { 0 } +} + +/// AES-128 block encryption (FIPS-197). +#[derive(Clone)] +pub struct Aes128 { + round_keys: [[u8; 16]; 11], +} +impl Aes128 { + pub fn new(key: &[u8; 16]) -> Self { + let mut w = [[0u8; 4]; 44]; + for i in 0..4 { + w[i].copy_from_slice(&key[i * 4..i * 4 + 4]); + } + let mut rcon = 1u8; + for i in 4..44 { + let mut t = w[i - 1]; + if i % 4 == 0 { + t = [ + SBOX[t[1] as usize] ^ rcon, + SBOX[t[2] as usize], + SBOX[t[3] as usize], + SBOX[t[0] as usize], + ]; + rcon = xtime(rcon); + } + for j in 0..4 { + w[i][j] = w[i - 4][j] ^ t[j]; + } + } + let mut round_keys = [[0u8; 16]; 11]; + for (r, key) in round_keys.iter_mut().enumerate() { + for c in 0..4 { + key[c * 4..c * 4 + 4].copy_from_slice(&w[r * 4 + c]); + } + } + Self { round_keys } + } + pub fn encrypt_block(&self, block: &mut [u8; 16]) { + let add = |s: &mut [u8; 16], k: &[u8; 16]| s.iter_mut().zip(k).for_each(|(a, b)| *a ^= b); + add(block, &self.round_keys[0]); + for round in 1..=10 { + for b in block.iter_mut() { + *b = SBOX[*b as usize]; + } + // ShiftRows (column-major state: byte r + 4c). + let s = *block; + for c in 0..4 { + for r in 0..4 { + block[r + 4 * c] = s[r + 4 * ((c + r) % 4)]; + } + } + if round != 10 { + for c in 0..4 { + let col = [ + block[4 * c], + block[4 * c + 1], + block[4 * c + 2], + block[4 * c + 3], + ]; + let all = col[0] ^ col[1] ^ col[2] ^ col[3]; + for r in 0..4 { + block[4 * c + r] = col[r] ^ all ^ xtime(col[r] ^ col[(r + 1) % 4]); + } + } + } + add(block, &self.round_keys[round]); + } + } +} + +/// AES/CFB8 stream state for one direction of a connection. +#[derive(Clone)] +pub struct Cfb8 { + aes: Aes128, + register: [u8; 16], +} +impl Cfb8 { + /// Minecraft uses the 16-byte shared secret as both key and IV. + pub fn new(key: &[u8; 16], iv: &[u8; 16]) -> Self { + Self { + aes: Aes128::new(key), + register: *iv, + } + } + fn keystream(&self) -> u8 { + let mut block = self.register; + self.aes.encrypt_block(&mut block); + block[0] + } + fn shift(&mut self, cipher_byte: u8) { + self.register.copy_within(1.., 0); + self.register[15] = cipher_byte; + } + pub fn encrypt(&mut self, data: &mut [u8]) { + for b in data { + *b ^= self.keystream(); + self.shift(*b); + } + } + pub fn decrypt(&mut self, data: &mut [u8]) { + for b in data { + let c = *b; + *b ^= self.keystream(); + self.shift(c); + } + } +} + +/// MD5 (RFC 1321). +pub fn md5(input: &[u8]) -> [u8; 16] { + const S: [u32; 64] = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, + 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, + 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, + ]; + let k: Vec = (0..64) + .map(|i| ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32) + .collect(); + let (mut a0, mut b0, mut c0, mut d0) = ( + 0x6745_2301u32, + 0xefcd_ab89u32, + 0x98ba_dcfeu32, + 0x1032_5476u32, + ); + let mut msg = input.to_vec(); + msg.push(0x80); + while msg.len() % 64 != 56 { + msg.push(0); + } + msg.extend_from_slice(&((input.len() as u64).wrapping_mul(8)).to_le_bytes()); + for chunk in msg.chunks(64) { + let m: Vec = chunk + .chunks(4) + .map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])) + .collect(); + let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0); + for i in 0..64 { + let (f, g) = match i / 16 { + 0 => ((b & c) | (!b & d), i), + 1 => ((d & b) | (!d & c), (5 * i + 1) % 16), + 2 => (b ^ c ^ d, (3 * i + 5) % 16), + _ => (c ^ (b | !d), (7 * i) % 16), + }; + let f = f.wrapping_add(a).wrapping_add(k[i]).wrapping_add(m[g]); + a = d; + d = c; + c = b; + b = b.wrapping_add(f.rotate_left(S[i])); + } + a0 = a0.wrapping_add(a); + b0 = b0.wrapping_add(b); + c0 = c0.wrapping_add(c); + d0 = d0.wrapping_add(d); + } + let mut out = [0u8; 16]; + for (i, v) in [a0, b0, c0, d0].iter().enumerate() { + out[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes()); + } + out +} + +/// UUID.nameUUIDFromBytes("OfflinePlayer:" + name): MD5, version 3, IETF variant. +pub fn offline_uuid(name: &str) -> u128 { + let mut h = md5(format!("OfflinePlayer:{name}").as_bytes()); + h[6] = (h[6] & 0x0f) | 0x30; + h[8] = (h[8] & 0x3f) | 0x80; + u128::from_be_bytes(h) +} +/// The canonical 8-4-4-4-12 form. +pub fn uuid_string(u: u128) -> String { + let h = format!("{u:032x}"); + format!( + "{}-{}-{}-{}-{}", + &h[..8], + &h[8..12], + &h[12..16], + &h[16..20], + &h[20..] + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hex(s: &str) -> Vec { + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) + .collect() + } + + #[test] + fn sbox_spot_checks() { + assert_eq!(SBOX[0x00], 0x63); + assert_eq!(SBOX[0x01], 0x7c); + assert_eq!(SBOX[0x53], 0xed); + assert_eq!(SBOX[0xff], 0x16); + } + + #[test] + fn aes128_fips197_vector() { + let key: [u8; 16] = hex("000102030405060708090a0b0c0d0e0f").try_into().unwrap(); + let mut block: [u8; 16] = hex("00112233445566778899aabbccddeeff").try_into().unwrap(); + Aes128::new(&key).encrypt_block(&mut block); + assert_eq!(block.to_vec(), hex("69c4e0d86a7b0430d8cdb78070b4c55a")); + } + + #[test] + fn cfb8_nist_sp800_38a_vector() { + let key: [u8; 16] = hex("2b7e151628aed2a6abf7158809cf4f3c").try_into().unwrap(); + let iv: [u8; 16] = hex("000102030405060708090a0b0c0d0e0f").try_into().unwrap(); + let plain = hex("6bc1bee22e409f96e93d7e117393172aae2d"); + let expected = hex("3b79424c9c0dd436bace9e0ed4586a4f32b9"); + let mut data = plain.clone(); + // Split across calls: the stream state carries over. + let mut enc = Cfb8::new(&key, &iv); + let (a, b) = data.split_at_mut(5); + enc.encrypt(a); + enc.encrypt(b); + assert_eq!(data, expected); + let mut dec = Cfb8::new(&key, &iv); + dec.decrypt(&mut data); + assert_eq!(data, plain); + } + + #[test] + fn md5_and_offline_uuids() { + assert_eq!(md5(b"").to_vec(), hex("d41d8cd98f00b204e9800998ecf8427e")); + assert_eq!( + md5(b"abc").to_vec(), + hex("900150983cd24fb0d6963f7d28e17f72") + ); + assert_eq!( + md5(&[b'a'; 100]).to_vec(), + hex("36a92cc94a9e0fa21f625f8bfb007adf") + ); + assert_eq!( + uuid_string(offline_uuid("Notch")), + "b50ad385-829d-3141-a216-7e7d7539ba7f" + ); + } +} diff --git a/crates/horizon-protocol/src/entity_data.rs b/crates/horizon-protocol/src/entity_data.rs new file mode 100644 index 000000000..08872ed43 --- /dev/null +++ b/crates/horizon-protocol/src/entity_data.rs @@ -0,0 +1,189 @@ +//! SynchedEntityData values (ClientboundSetEntityDataPacket): an entry index, +//! the EntityDataSerializers id, and the serializer's value, ending with 0xFF. +//! Serializers Horizon cannot decode end the list early; the entries before +//! them are kept. +use crate::{ + Result, + buf::{Codec, Reader, Writer}, + item::{Slot, Stack}, +}; +use horizon_world::nbt::Tag; + +#[derive(Clone, Debug, PartialEq)] +pub enum Value { + Byte(i8), + Int(i32), + Long(i64), + Float(f32), + String(String), + Text(Tag), + OptText(Option), + Item(Option), + Bool(bool), + Floats(Vec), + Pos([i32; 3]), + OptPos(Option<[i32; 3]>), + OptUuid(Option), + /// Any VarInt-valued serializer (direction, block state, pose, variants ...). + Id(i32), +} +/// Serializer ids in EntityDataSerializers registration order. +pub mod serializer { + pub const BYTE: i32 = 0; + pub const INT: i32 = 1; + pub const LONG: i32 = 2; + pub const FLOAT: i32 = 3; + pub const STRING: i32 = 4; + pub const COMPONENT: i32 = 5; + pub const OPTIONAL_COMPONENT: i32 = 6; + pub const ITEM_STACK: i32 = 7; + pub const BOOLEAN: i32 = 8; + pub const ROTATIONS: i32 = 9; + pub const BLOCK_POS: i32 = 10; + pub const OPTIONAL_BLOCK_POS: i32 = 11; + pub const DIRECTION: i32 = 12; + pub const OPTIONAL_LIVING_ENTITY_REFERENCE: i32 = 13; + pub const BLOCK_STATE: i32 = 14; + pub const OPTIONAL_BLOCK_STATE: i32 = 15; + pub const OPTIONAL_UNSIGNED_INT: i32 = 19; + pub const POSE: i32 = 20; + pub const VECTOR3: i32 = 40; + pub const QUATERNION: i32 = 41; + pub const HUMANOID_ARM: i32 = 43; + pub const DYE_COLOR: i32 = 44; +} +fn read_value(kind: i32, r: &mut Reader) -> Result> { + use serializer::*; + Ok(Some(match kind { + BYTE => Value::Byte(r.i8()?), + INT => Value::Int(r.varint()?), + LONG => Value::Long(r.varlong()?), + FLOAT => Value::Float(r.f32()?), + STRING => Value::String(r.string(32767)?), + COMPONENT => Value::Text(r.nbt()?), + OPTIONAL_COMPONENT => Value::OptText(if r.bool()? { Some(r.nbt()?) } else { None }), + ITEM_STACK => Value::Item(Slot::read(r)?), + BOOLEAN => Value::Bool(r.bool()?), + ROTATIONS | VECTOR3 => Value::Floats(vec![r.f32()?, r.f32()?, r.f32()?]), + QUATERNION => Value::Floats(vec![r.f32()?, r.f32()?, r.f32()?, r.f32()?]), + BLOCK_POS => Value::Pos(crate::buf::Pos::read(r)?), + OPTIONAL_BLOCK_POS => Value::OptPos(if r.bool()? { + Some(crate::buf::Pos::read(r)?) + } else { + None + }), + OPTIONAL_LIVING_ENTITY_REFERENCE => { + Value::OptUuid(if r.bool()? { Some(r.uuid()?) } else { None }) + } + // VarInt-encoded: direction, block states, optional ints, pose, the + // holder-registry variants (21..=33) and enum states (36..=39), arm, dye. + DIRECTION + | BLOCK_STATE + | OPTIONAL_BLOCK_STATE + | OPTIONAL_UNSIGNED_INT + | POSE + | 21..=33 + | 36..=39 + | HUMANOID_ARM + | DYE_COLOR => Value::Id(r.varint()?), + _ => return Ok(None), + })) +} +fn write_value(kind: i32, v: &Value, w: &mut Writer) { + match v { + Value::Byte(b) => w.i8(*b), + Value::Int(i) | Value::Id(i) => w.varint(*i), + Value::Long(l) => w.varlong(*l), + Value::Float(f) => w.f32(*f), + Value::String(s) => w.string(s), + Value::Text(t) => w.nbt(t), + Value::OptText(t) => { + w.bool(t.is_some()); + if let Some(t) = t { + w.nbt(t); + } + } + Value::Item(s) => Slot::write(s, w), + Value::Bool(b) => w.bool(*b), + Value::Floats(f) => f.iter().for_each(|f| w.f32(*f)), + Value::Pos(p) => crate::buf::Pos::write(p, w), + Value::OptPos(p) => { + w.bool(p.is_some()); + if let Some(p) = p { + crate::buf::Pos::write(p, w); + } + } + Value::OptUuid(u) => { + w.bool(u.is_some()); + if let Some(u) = u { + w.uuid(*u); + } + } + } + let _ = kind; +} + +/// (index, serializer id, value) entries. +pub struct EntityData; +impl Codec> for EntityData { + fn read(r: &mut Reader) -> Result> { + let mut out = Vec::new(); + loop { + let index = r.u8()?; + if index == 0xFF { + return Ok(out); + } + let kind = r.varint()?; + match read_value(kind, r)? { + Some(v) => out.push((index, kind, v)), + None => { + r.rest(); + return Ok(out); + } + } + } + } + fn write(v: &Vec<(u8, i32, Value)>, w: &mut Writer) { + for (index, kind, value) in v { + w.u8(*index); + w.varint(*kind); + write_value(*kind, value, w); + } + w.u8(0xFF); + } +} + +/// ItemEntity.DATA_ITEM (after the eight Entity data entries). +pub const ITEM_ENTITY_ITEM: u8 = 8; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips_and_stops_at_unknown_serializers() { + let entries = vec![ + (0u8, serializer::BYTE, Value::Byte(0x02)), + (1, serializer::INT, Value::Int(300)), + (2, serializer::OPTIONAL_COMPONENT, Value::OptText(None)), + (6, serializer::POSE, Value::Id(5)), + ( + 8, + serializer::ITEM_STACK, + Value::Item(Some(Stack::new(3, 12))), + ), + ]; + let mut w = Writer::new(); + EntityData::write(&entries, &mut w); + assert_eq!(*w.data.last().unwrap(), 0xFF); + assert_eq!( + EntityData::read(&mut Reader::new(&w.data)).unwrap(), + entries + ); + // A particle (16) cannot be skipped: keep what came before. + let mut bytes = vec![0, 0, 7, 9, 16, 1, 2, 3]; + bytes.push(0xFF); + let read = EntityData::read(&mut Reader::new(&bytes)).unwrap(); + assert_eq!(read, vec![(0, 0, Value::Byte(7))]); + } +} diff --git a/crates/horizon-protocol/src/frame.rs b/crates/horizon-protocol/src/frame.rs new file mode 100644 index 000000000..9a1402e0b --- /dev/null +++ b/crates/horizon-protocol/src/frame.rs @@ -0,0 +1,155 @@ +//! Packet framing (Varint21FrameDecoder / Varint21LengthFieldPrepender) and +//! zlib compression above a threshold (CompressionEncoder / CompressionDecoder). +use crate::{ + Error, Result, + buf::{Reader, varint_size, write_varint}, +}; +use flate2::{Compression, read::ZlibDecoder, write::ZlibEncoder}; +use std::io::{Read, Write}; + +/// Frames are at most three VarInt bytes long (21 bits). +pub const MAX_FRAME: usize = (1 << 21) - 1; +/// CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH. +pub const MAX_UNCOMPRESSED: usize = 8_388_608; + +/// Build the frame for one packet body (`id` + payload already concatenated): +/// length prefix, and with compression enabled the uncompressed-length +/// field (0 when below the threshold). +pub fn encode(body: &[u8], threshold: Option) -> Result> { + let inner = match threshold { + None => body.to_vec(), + Some(t) if body.len() < t => { + let mut v = Vec::with_capacity(body.len() + 1); + v.push(0); + v.extend_from_slice(body); + v + } + Some(_) => { + let mut v = Vec::with_capacity(body.len() / 2 + 8); + write_varint(&mut v, body.len() as i32); + let mut z = ZlibEncoder::new(v, Compression::default()); + z.write_all(body)?; + z.finish()? + } + }; + if inner.len() > MAX_FRAME { + return Err(Error::new(format!( + "packet too large: {} bytes", + inner.len() + ))); + } + let mut out = Vec::with_capacity(inner.len() + 3); + write_varint(&mut out, inner.len() as i32); + out.extend_from_slice(&inner); + Ok(out) +} + +/// Split one complete frame off the front of `buffer`, if available. +/// Returns the frame contents (without the length prefix). +pub fn split(buffer: &mut Vec) -> Result>> { + let mut len = 0usize; + for i in 0..3 { + let Some(&b) = buffer.get(i) else { + return Ok(None); + }; + len |= usize::from(b & 0x7F) << (7 * i); + if b & 0x80 == 0 { + let start = i + 1; + if buffer.len() < start + len { + return Ok(None); + } + let frame = buffer[start..start + len].to_vec(); + buffer.drain(..start + len); + return Ok(Some(frame)); + } + } + Err(Error::new("length wider than 21 bits")) +} + +/// Undo compression on a frame, giving the packet body (id + payload). +pub fn decompress(frame: Vec, threshold: Option) -> Result> { + let Some(threshold) = threshold else { + return Ok(frame); + }; + let mut r = Reader::new(&frame); + let size = r.varint()?; + if size == 0 { + return Ok(frame[1..].to_vec()); + } + let size = usize::try_from(size).map_err(|_| Error::new("negative uncompressed length"))?; + if size < threshold { + return Err(Error::new(format!( + "Badly compressed packet - size of {size} is below server threshold of {threshold}" + ))); + } + if size > MAX_UNCOMPRESSED { + return Err(Error::new(format!( + "Badly compressed packet - size of {size} is larger than protocol maximum" + ))); + } + let start = varint_size(size as i32); + let mut out = Vec::with_capacity(size); + ZlibDecoder::new(&frame[start..]) + .take(size as u64 + 1) + .read_to_end(&mut out)?; + if out.len() != size { + return Err(Error::new(format!( + "Badly compressed packet - actual length {} does not match declared size {size}", + out.len() + ))); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn uncompressed_frames_round_trip() { + let body = vec![0x00, 1, 2, 3]; + let framed = encode(&body, None).unwrap(); + assert_eq!(framed, [4, 0, 1, 2, 3]); + let mut buffer = framed.clone(); + buffer.extend_from_slice(&framed[..2]); + assert_eq!(split(&mut buffer).unwrap(), Some(body)); + assert_eq!(split(&mut buffer).unwrap(), None); + assert_eq!(buffer, [4, 0]); + } + + #[test] + fn compression_threshold_like_vanilla() { + // Below the threshold: a zero data length, then the raw body. + let small = vec![7u8; 10]; + let framed = encode(&small, Some(256)).unwrap(); + assert_eq!(&framed[..2], &[11, 0]); + let mut buffer = framed; + let frame = split(&mut buffer).unwrap().unwrap(); + assert_eq!(decompress(frame, Some(256)).unwrap(), small); + // At or above: the uncompressed size and a zlib stream. + let big: Vec = (0..5000u32).map(|i| (i % 7) as u8).collect(); + let framed = encode(&big, Some(256)).unwrap(); + assert!(framed.len() < big.len()); + let mut buffer = framed; + let frame = split(&mut buffer).unwrap().unwrap(); + assert_eq!(Reader::new(&frame).varint().unwrap(), 5000); + assert_eq!(decompress(frame, Some(256)).unwrap(), big); + } + + #[test] + fn rejects_bad_compressed_lengths() { + // Declared size below the threshold is a protocol error. + let mut frame = vec![10]; + let mut z = ZlibEncoder::new(Vec::new(), Compression::default()); + z.write_all(&[1; 10]).unwrap(); + frame.extend(z.finish().unwrap()); + assert!(decompress(frame, Some(256)).is_err()); + // Declared size that does not match the stream. + let mut frame = Vec::new(); + write_varint(&mut frame, 300); + let mut z = ZlibEncoder::new(Vec::new(), Compression::default()); + z.write_all(&[1; 299]).unwrap(); + frame.extend(z.finish().unwrap()); + assert!(decompress(frame, Some(256)).is_err()); + } +} diff --git a/crates/horizon-protocol/src/ids.rs b/crates/horizon-protocol/src/ids.rs new file mode 100644 index 000000000..892b6af9a --- /dev/null +++ b/crates/horizon-protocol/src/ids.rs @@ -0,0 +1,590 @@ +//! Packet ids per connection state and direction for protocol 777 (26.3). +//! Generated by tools/generate_packet_ids.py from the data generator's +//! packets report; do not edit by hand. +#![allow(missing_docs)] +use crate::{Direction, State}; + +pub mod handshake { + pub mod serverbound { + pub const INTENTION: i32 = 0; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &["intention"]; + } +} +pub mod status { + pub mod clientbound { + pub const STATUS_RESPONSE: i32 = 0; + pub const PONG_RESPONSE: i32 = 1; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &["status_response", "pong_response"]; + } + pub mod serverbound { + pub const STATUS_REQUEST: i32 = 0; + pub const PING_REQUEST: i32 = 1; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &["status_request", "ping_request"]; + } +} +pub mod login { + pub mod clientbound { + pub const LOGIN_DISCONNECT: i32 = 0; + pub const HELLO: i32 = 1; + pub const LOGIN_FINISHED: i32 = 2; + pub const LOGIN_COMPRESSION: i32 = 3; + pub const CUSTOM_QUERY: i32 = 4; + pub const COOKIE_REQUEST: i32 = 5; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "login_disconnect", + "hello", + "login_finished", + "login_compression", + "custom_query", + "cookie_request", + ]; + } + pub mod serverbound { + pub const HELLO: i32 = 0; + pub const KEY: i32 = 1; + pub const CUSTOM_QUERY_ANSWER: i32 = 2; + pub const LOGIN_ACKNOWLEDGED: i32 = 3; + pub const COOKIE_RESPONSE: i32 = 4; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "hello", + "key", + "custom_query_answer", + "login_acknowledged", + "cookie_response", + ]; + } +} +pub mod configuration { + pub mod clientbound { + pub const COOKIE_REQUEST: i32 = 0; + pub const CUSTOM_PAYLOAD: i32 = 1; + pub const DISCONNECT: i32 = 2; + pub const FINISH_CONFIGURATION: i32 = 3; + pub const KEEP_ALIVE: i32 = 4; + pub const PING: i32 = 5; + pub const RESET_CHAT: i32 = 6; + pub const REGISTRY_DATA: i32 = 7; + pub const RESOURCE_PACK_POP: i32 = 8; + pub const RESOURCE_PACK_PUSH: i32 = 9; + pub const POST_EFFECTS: i32 = 10; + pub const STORE_COOKIE: i32 = 11; + pub const TRANSFER: i32 = 12; + pub const UPDATE_ENABLED_FEATURES: i32 = 13; + pub const UPDATE_TAGS: i32 = 14; + pub const SELECT_KNOWN_PACKS: i32 = 15; + pub const CUSTOM_REPORT_DETAILS: i32 = 16; + pub const SERVER_LINKS: i32 = 17; + pub const CLEAR_DIALOG: i32 = 18; + pub const SHOW_DIALOG: i32 = 19; + pub const CODE_OF_CONDUCT: i32 = 20; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "cookie_request", + "custom_payload", + "disconnect", + "finish_configuration", + "keep_alive", + "ping", + "reset_chat", + "registry_data", + "resource_pack_pop", + "resource_pack_push", + "post_effects", + "store_cookie", + "transfer", + "update_enabled_features", + "update_tags", + "select_known_packs", + "custom_report_details", + "server_links", + "clear_dialog", + "show_dialog", + "code_of_conduct", + ]; + } + pub mod serverbound { + pub const CLIENT_INFORMATION: i32 = 0; + pub const COOKIE_RESPONSE: i32 = 1; + pub const CUSTOM_PAYLOAD: i32 = 2; + pub const FINISH_CONFIGURATION: i32 = 3; + pub const KEEP_ALIVE: i32 = 4; + pub const PONG: i32 = 5; + pub const RESOURCE_PACK: i32 = 6; + pub const SELECT_KNOWN_PACKS: i32 = 7; + pub const CUSTOM_CLICK_ACTION: i32 = 8; + pub const ACCEPT_CODE_OF_CONDUCT: i32 = 9; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "client_information", + "cookie_response", + "custom_payload", + "finish_configuration", + "keep_alive", + "pong", + "resource_pack", + "select_known_packs", + "custom_click_action", + "accept_code_of_conduct", + ]; + } +} +pub mod play { + pub mod clientbound { + pub const BUNDLE_DELIMITER: i32 = 0; + pub const ADD_ENTITY: i32 = 1; + pub const ANIMATE: i32 = 2; + pub const AWARD_STATS: i32 = 3; + pub const BLOCK_CHANGED_ACK: i32 = 4; + pub const BLOCK_DESTRUCTION: i32 = 5; + pub const BLOCK_ENTITY_DATA: i32 = 6; + pub const BLOCK_EVENT: i32 = 7; + pub const BLOCK_UPDATE: i32 = 8; + pub const BOSS_EVENT: i32 = 9; + pub const CHANGE_DIFFICULTY: i32 = 10; + pub const CHUNK_BATCH_FINISHED: i32 = 11; + pub const CHUNK_BATCH_START: i32 = 12; + pub const CHUNKS_BIOMES: i32 = 13; + pub const CLEAR_TITLES: i32 = 14; + pub const COMMAND_SUGGESTIONS: i32 = 15; + pub const COMMANDS: i32 = 16; + pub const CONTAINER_CLOSE: i32 = 17; + pub const CONTAINER_SET_CONTENT: i32 = 18; + pub const CONTAINER_SET_DATA: i32 = 19; + pub const CONTAINER_SET_SLOT: i32 = 20; + pub const COOKIE_REQUEST: i32 = 21; + pub const COOLDOWN: i32 = 22; + pub const CUSTOM_CHAT_COMPLETIONS: i32 = 23; + pub const CUSTOM_PAYLOAD: i32 = 24; + pub const DAMAGE_EVENT: i32 = 25; + pub const DEBUG_BLOCK_VALUE: i32 = 26; + pub const DEBUG_CHUNK_VALUE: i32 = 27; + pub const DEBUG_ENTITY_VALUE: i32 = 28; + pub const DEBUG_EVENT: i32 = 29; + pub const DEBUG_SAMPLE: i32 = 30; + pub const DELETE_CHAT: i32 = 31; + pub const DISCONNECT: i32 = 32; + pub const DISGUISED_CHAT: i32 = 33; + pub const ENTITY_EVENT: i32 = 34; + pub const ENTITY_POSITION_SYNC: i32 = 35; + pub const EXPLODE: i32 = 36; + pub const ADD_TRANSIENT_BLOCK: i32 = 37; + pub const FORGET_LEVEL_CHUNK: i32 = 38; + pub const GAME_EVENT: i32 = 39; + pub const GAME_RULE_VALUES: i32 = 40; + pub const GAME_TEST_HIGHLIGHT_POS: i32 = 41; + pub const MOUNT_SCREEN_OPEN: i32 = 42; + pub const HURT_ANIMATION: i32 = 43; + pub const INITIALIZE_BORDER: i32 = 44; + pub const KEEP_ALIVE: i32 = 45; + pub const LEVEL_CHUNK_WITH_LIGHT: i32 = 46; + pub const LEVEL_EVENT: i32 = 47; + pub const LEVEL_PARTICLES: i32 = 48; + pub const LIGHT_UPDATE: i32 = 49; + pub const LOGIN: i32 = 50; + pub const LOW_DISK_SPACE_WARNING: i32 = 51; + pub const MAP_ITEM_DATA: i32 = 52; + pub const MERCHANT_OFFERS: i32 = 53; + pub const MOVE_ENTITY_POS: i32 = 54; + pub const MOVE_ENTITY_POS_ROT: i32 = 55; + pub const MOVE_MINECART_ALONG_TRACK: i32 = 56; + pub const MOVE_ENTITY_ROT: i32 = 57; + pub const MOVE_VEHICLE: i32 = 58; + pub const OPEN_BOOK: i32 = 59; + pub const OPEN_SCREEN: i32 = 60; + pub const OPEN_SIGN_EDITOR: i32 = 61; + pub const PING: i32 = 62; + pub const PONG_RESPONSE: i32 = 63; + pub const PLACE_GHOST_RECIPE: i32 = 64; + pub const PLAYER_ABILITIES: i32 = 65; + pub const PLAYER_CHAT: i32 = 66; + pub const PLAYER_COMBAT_END: i32 = 67; + pub const PLAYER_COMBAT_ENTER: i32 = 68; + pub const PLAYER_COMBAT_KILL: i32 = 69; + pub const PLAYER_INFO_REMOVE: i32 = 70; + pub const PLAYER_INFO_UPDATE: i32 = 71; + pub const PLAYER_LOOK_AT: i32 = 72; + pub const PLAYER_POSITION: i32 = 73; + pub const PLAYER_ROTATION: i32 = 74; + pub const RECIPE_BOOK_ADD: i32 = 75; + pub const RECIPE_BOOK_REMOVE: i32 = 76; + pub const RECIPE_BOOK_SETTINGS: i32 = 77; + pub const REMOVE_ENTITIES: i32 = 78; + pub const REMOVE_MOB_EFFECT: i32 = 79; + pub const RESET_SCORE: i32 = 80; + pub const RESOURCE_PACK_POP: i32 = 81; + pub const RESOURCE_PACK_PUSH: i32 = 82; + pub const POST_EFFECTS: i32 = 83; + pub const RESPAWN: i32 = 84; + pub const ROTATE_HEAD: i32 = 85; + pub const SECTION_BLOCKS_UPDATE: i32 = 86; + pub const SELECT_ADVANCEMENTS_TAB: i32 = 87; + pub const SERVER_DATA: i32 = 88; + pub const SET_ACTION_BAR_TEXT: i32 = 89; + pub const SET_BORDER_CENTER: i32 = 90; + pub const SET_BORDER_LERP_SIZE: i32 = 91; + pub const SET_BORDER_SIZE: i32 = 92; + pub const SET_BORDER_WARNING_DELAY: i32 = 93; + pub const SET_BORDER_WARNING_DISTANCE: i32 = 94; + pub const SET_CAMERA: i32 = 95; + pub const SET_CHUNK_CACHE_CENTER: i32 = 96; + pub const SET_CHUNK_CACHE_RADIUS: i32 = 97; + pub const SET_CURSOR_ITEM: i32 = 98; + pub const SET_DEFAULT_SPAWN_POSITION: i32 = 99; + pub const SET_DISPLAY_OBJECTIVE: i32 = 100; + pub const SET_ENTITY_DATA: i32 = 101; + pub const SET_ENTITY_LINK: i32 = 102; + pub const SET_ENTITY_MOTION: i32 = 103; + pub const SET_EQUIPMENT: i32 = 104; + pub const SET_EXPERIENCE: i32 = 105; + pub const SET_HEALTH: i32 = 106; + pub const SET_HELD_SLOT: i32 = 107; + pub const SET_OBJECTIVE: i32 = 108; + pub const SET_PASSENGERS: i32 = 109; + pub const SET_PLAYER_INVENTORY: i32 = 110; + pub const SET_PLAYER_TEAM: i32 = 111; + pub const SET_SCORE: i32 = 112; + pub const SET_SIMULATION_DISTANCE: i32 = 113; + pub const SET_SUBTITLE_TEXT: i32 = 114; + pub const SET_TIME: i32 = 115; + pub const SET_TITLE_TEXT: i32 = 116; + pub const SET_TITLES_ANIMATION: i32 = 117; + pub const SOUND_ENTITY: i32 = 118; + pub const SOUND: i32 = 119; + pub const START_CONFIGURATION: i32 = 120; + pub const STOP_SOUND: i32 = 121; + pub const STORE_COOKIE: i32 = 122; + pub const SWING_ANIMATION: i32 = 123; + pub const SYSTEM_CHAT: i32 = 124; + pub const TAB_LIST: i32 = 125; + pub const TAG_QUERY: i32 = 126; + pub const TAKE_ITEM_ENTITY: i32 = 127; + pub const TELEPORT_ENTITY: i32 = 128; + pub const TEST_INSTANCE_BLOCK_STATUS: i32 = 129; + pub const TICKING_STATE: i32 = 130; + pub const TICKING_STEP: i32 = 131; + pub const TRANSFER: i32 = 132; + pub const UPDATE_ADVANCEMENTS: i32 = 133; + pub const UPDATE_ATTRIBUTES: i32 = 134; + pub const UPDATE_MOB_EFFECT: i32 = 135; + pub const UPDATE_RECIPES: i32 = 136; + pub const UPDATE_TAGS: i32 = 137; + pub const PROJECTILE_POWER: i32 = 138; + pub const CUSTOM_REPORT_DETAILS: i32 = 139; + pub const SERVER_LINKS: i32 = 140; + pub const WAYPOINT: i32 = 141; + pub const CLEAR_DIALOG: i32 = 142; + pub const SHOW_DIALOG: i32 = 143; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "bundle_delimiter", + "add_entity", + "animate", + "award_stats", + "block_changed_ack", + "block_destruction", + "block_entity_data", + "block_event", + "block_update", + "boss_event", + "change_difficulty", + "chunk_batch_finished", + "chunk_batch_start", + "chunks_biomes", + "clear_titles", + "command_suggestions", + "commands", + "container_close", + "container_set_content", + "container_set_data", + "container_set_slot", + "cookie_request", + "cooldown", + "custom_chat_completions", + "custom_payload", + "damage_event", + "debug/block_value", + "debug/chunk_value", + "debug/entity_value", + "debug/event", + "debug_sample", + "delete_chat", + "disconnect", + "disguised_chat", + "entity_event", + "entity_position_sync", + "explode", + "add_transient_block", + "forget_level_chunk", + "game_event", + "game_rule_values", + "game_test_highlight_pos", + "mount_screen_open", + "hurt_animation", + "initialize_border", + "keep_alive", + "level_chunk_with_light", + "level_event", + "level_particles", + "light_update", + "login", + "low_disk_space_warning", + "map_item_data", + "merchant_offers", + "move_entity_pos", + "move_entity_pos_rot", + "move_minecart_along_track", + "move_entity_rot", + "move_vehicle", + "open_book", + "open_screen", + "open_sign_editor", + "ping", + "pong_response", + "place_ghost_recipe", + "player_abilities", + "player_chat", + "player_combat_end", + "player_combat_enter", + "player_combat_kill", + "player_info_remove", + "player_info_update", + "player_look_at", + "player_position", + "player_rotation", + "recipe_book_add", + "recipe_book_remove", + "recipe_book_settings", + "remove_entities", + "remove_mob_effect", + "reset_score", + "resource_pack_pop", + "resource_pack_push", + "post_effects", + "respawn", + "rotate_head", + "section_blocks_update", + "select_advancements_tab", + "server_data", + "set_action_bar_text", + "set_border_center", + "set_border_lerp_size", + "set_border_size", + "set_border_warning_delay", + "set_border_warning_distance", + "set_camera", + "set_chunk_cache_center", + "set_chunk_cache_radius", + "set_cursor_item", + "set_default_spawn_position", + "set_display_objective", + "set_entity_data", + "set_entity_link", + "set_entity_motion", + "set_equipment", + "set_experience", + "set_health", + "set_held_slot", + "set_objective", + "set_passengers", + "set_player_inventory", + "set_player_team", + "set_score", + "set_simulation_distance", + "set_subtitle_text", + "set_time", + "set_title_text", + "set_titles_animation", + "sound_entity", + "sound", + "start_configuration", + "stop_sound", + "store_cookie", + "swing_animation", + "system_chat", + "tab_list", + "tag_query", + "take_item_entity", + "teleport_entity", + "test_instance_block_status", + "ticking_state", + "ticking_step", + "transfer", + "update_advancements", + "update_attributes", + "update_mob_effect", + "update_recipes", + "update_tags", + "projectile_power", + "custom_report_details", + "server_links", + "waypoint", + "clear_dialog", + "show_dialog", + ]; + } + pub mod serverbound { + pub const ACCEPT_TELEPORTATION: i32 = 0; + pub const ATTACK: i32 = 1; + pub const BLOCK_ENTITY_TAG_QUERY: i32 = 2; + pub const BUNDLE_ITEM_SELECTED: i32 = 3; + pub const CHANGE_DIFFICULTY: i32 = 4; + pub const CHANGE_GAME_MODE: i32 = 5; + pub const CHAT_ACK: i32 = 6; + pub const CHAT_COMMAND: i32 = 7; + pub const CHAT_COMMAND_SIGNED: i32 = 8; + pub const CHAT: i32 = 9; + pub const CHAT_SESSION_UPDATE: i32 = 10; + pub const CHUNK_BATCH_RECEIVED: i32 = 11; + pub const CLIENT_COMMAND: i32 = 12; + pub const CLIENT_TICK_END: i32 = 13; + pub const CLIENT_INFORMATION: i32 = 14; + pub const COMMAND_SUGGESTION: i32 = 15; + pub const CONFIGURATION_ACKNOWLEDGED: i32 = 16; + pub const CONTAINER_BUTTON_CLICK: i32 = 17; + pub const CONTAINER_CLICK: i32 = 18; + pub const CONTAINER_CLOSE: i32 = 19; + pub const CONTAINER_SLOT_STATE_CHANGED: i32 = 20; + pub const COOKIE_RESPONSE: i32 = 21; + pub const CUSTOM_PAYLOAD: i32 = 22; + pub const DEBUG_SUBSCRIPTION_REQUEST: i32 = 23; + pub const EDIT_BOOK: i32 = 24; + pub const ENTITY_TAG_QUERY: i32 = 25; + pub const INTERACT: i32 = 26; + pub const JIGSAW_GENERATE: i32 = 27; + pub const KEEP_ALIVE: i32 = 28; + pub const LOCK_DIFFICULTY: i32 = 29; + pub const MOVE_PLAYER_POS: i32 = 30; + pub const MOVE_PLAYER_POS_ROT: i32 = 31; + pub const MOVE_PLAYER_ROT: i32 = 32; + pub const MOVE_PLAYER_STATUS_ONLY: i32 = 33; + pub const MOVE_VEHICLE: i32 = 34; + pub const PADDLE_BOAT: i32 = 35; + pub const PICK_ITEM_FROM_BLOCK: i32 = 36; + pub const PICK_ITEM_FROM_ENTITY: i32 = 37; + pub const PING_REQUEST: i32 = 38; + pub const PLACE_RECIPE: i32 = 39; + pub const PLAYER_ABILITIES: i32 = 40; + pub const PLAYER_ACTION: i32 = 41; + pub const PLAYER_COMMAND: i32 = 42; + pub const PLAYER_INPUT: i32 = 43; + pub const PLAYER_LOADED: i32 = 44; + pub const PONG: i32 = 45; + pub const PUNCH: i32 = 46; + pub const RECIPE_BOOK_CHANGE_SETTINGS: i32 = 47; + pub const RECIPE_BOOK_SEEN_RECIPE: i32 = 48; + pub const RENAME_ITEM: i32 = 49; + pub const RESOURCE_PACK: i32 = 50; + pub const SEEN_ADVANCEMENTS: i32 = 51; + pub const SELECT_TRADE: i32 = 52; + pub const SET_BEACON: i32 = 53; + pub const SET_CARRIED_ITEM: i32 = 54; + pub const SET_COMMAND_BLOCK: i32 = 55; + pub const SET_COMMAND_MINECART: i32 = 56; + pub const SET_CREATIVE_MODE_SLOT: i32 = 57; + pub const SET_GAME_RULE: i32 = 58; + pub const SET_JIGSAW_BLOCK: i32 = 59; + pub const SET_STRUCTURE_BLOCK: i32 = 60; + pub const SET_TEST_BLOCK: i32 = 61; + pub const SIGN_UPDATE: i32 = 62; + pub const SPECTATOR_ACTION: i32 = 63; + pub const TELEPORT_TO_ENTITY: i32 = 64; + pub const TEST_INSTANCE_BLOCK_ACTION: i32 = 65; + pub const USE_ITEM_ON: i32 = 66; + pub const USE_ITEM: i32 = 67; + pub const CUSTOM_CLICK_ACTION: i32 = 68; + /// Packet names indexed by id. + pub const NAMES: &[&str] = &[ + "accept_teleportation", + "attack", + "block_entity_tag_query", + "bundle_item_selected", + "change_difficulty", + "change_game_mode", + "chat_ack", + "chat_command", + "chat_command_signed", + "chat", + "chat_session_update", + "chunk_batch_received", + "client_command", + "client_tick_end", + "client_information", + "command_suggestion", + "configuration_acknowledged", + "container_button_click", + "container_click", + "container_close", + "container_slot_state_changed", + "cookie_response", + "custom_payload", + "debug_subscription_request", + "edit_book", + "entity_tag_query", + "interact", + "jigsaw_generate", + "keep_alive", + "lock_difficulty", + "move_player_pos", + "move_player_pos_rot", + "move_player_rot", + "move_player_status_only", + "move_vehicle", + "paddle_boat", + "pick_item_from_block", + "pick_item_from_entity", + "ping_request", + "place_recipe", + "player_abilities", + "player_action", + "player_command", + "player_input", + "player_loaded", + "pong", + "punch", + "recipe_book_change_settings", + "recipe_book_seen_recipe", + "rename_item", + "resource_pack", + "seen_advancements", + "select_trade", + "set_beacon", + "set_carried_item", + "set_command_block", + "set_command_minecart", + "set_creative_mode_slot", + "set_game_rule", + "set_jigsaw_block", + "set_structure_block", + "set_test_block", + "sign_update", + "spectator_action", + "teleport_to_entity", + "test_instance_block_action", + "use_item_on", + "use_item", + "custom_click_action", + ]; + } +} + +/// The packet name for an id, if the state and direction define it. +pub fn name(state: State, direction: Direction, id: i32) -> Option<&'static str> { + let names: &[&str] = match (state, direction) { + (State::Handshake, Direction::Serverbound) => handshake::serverbound::NAMES, + (State::Status, Direction::Clientbound) => status::clientbound::NAMES, + (State::Status, Direction::Serverbound) => status::serverbound::NAMES, + (State::Login, Direction::Clientbound) => login::clientbound::NAMES, + (State::Login, Direction::Serverbound) => login::serverbound::NAMES, + (State::Configuration, Direction::Clientbound) => configuration::clientbound::NAMES, + (State::Configuration, Direction::Serverbound) => configuration::serverbound::NAMES, + (State::Play, Direction::Clientbound) => play::clientbound::NAMES, + (State::Play, Direction::Serverbound) => play::serverbound::NAMES, + _ => &[], + }; + usize::try_from(id).ok().and_then(|i| names.get(i)).copied() +} diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs new file mode 100644 index 000000000..81d429865 --- /dev/null +++ b/crates/horizon-protocol/src/item.rs @@ -0,0 +1,337 @@ +//! Item stacks on the wire (ItemStack.OPTIONAL_STREAM_CODEC): a count, the +//! item's registry id and a data component patch, plus the hashed form the +//! client sends back in container clicks (HashedStack). +use crate::{ + Error, Result, + buf::{Codec, Reader, Writer}, +}; +use horizon_world::nbt::Tag; + +/// minecraft:data_component_type registry ids (26.3). +pub mod component { + pub const CUSTOM_DATA: i32 = 0; + pub const MAX_STACK_SIZE: i32 = 1; + pub const MAX_DAMAGE: i32 = 2; + pub const DAMAGE: i32 = 3; + pub const UNBREAKABLE: i32 = 4; + pub const CUSTOM_NAME: i32 = 6; + pub const ITEM_NAME: i32 = 9; + pub const ITEM_MODEL: i32 = 10; + pub const LORE: i32 = 11; + pub const RARITY: i32 = 12; + pub const ENCHANTMENTS: i32 = 13; + pub const CUSTOM_MODEL_DATA: i32 = 17; + pub const TOOLTIP_DISPLAY: i32 = 18; + pub const REPAIR_COST: i32 = 19; + pub const CREATIVE_SLOT_LOCK: i32 = 20; + pub const ENCHANTMENT_GLINT_OVERRIDE: i32 = 21; + pub const STORED_ENCHANTMENTS: i32 = 45; + pub const DYED_COLOR: i32 = 47; + pub const MAP_ID: i32 = 48; +} + +/// The value of one patched data component. Components whose stream codec +/// Horizon does not implement make the whole stack (and packet) undecodable. +#[derive(Clone, Debug, PartialEq)] +pub enum Component { + Int(i32), + Unit, + Bool(bool), + Text(Tag), + Nbt(Tag), + Ident(String), + Lore(Vec), + Enchantments(Vec<(i32, i32)>), + CustomModelData { + floats: Vec, + flags: Vec, + strings: Vec, + colors: Vec, + }, + TooltipDisplay { + hide: bool, + hidden: Vec, + }, +} +impl Component { + fn read(kind: i32, r: &mut Reader) -> Result { + use component::*; + Ok(match kind { + MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID => { + Self::Int(r.varint()?) + } + DYED_COLOR => Self::Int(r.i32()?), + UNBREAKABLE | CREATIVE_SLOT_LOCK => Self::Unit, + ENCHANTMENT_GLINT_OVERRIDE => Self::Bool(r.bool()?), + CUSTOM_NAME | ITEM_NAME => Self::Text(r.nbt()?), + CUSTOM_DATA => Self::Nbt(r.nbt()?), + ITEM_MODEL => Self::Ident(r.string(32767)?), + LORE => { + let n = r.count(256)?; + Self::Lore((0..n).map(|_| r.nbt()).collect::>()?) + } + ENCHANTMENTS | STORED_ENCHANTMENTS => { + let n = r.count(r.remaining())?; + Self::Enchantments( + (0..n) + .map(|_| Ok((r.varint()?, r.varint()?))) + .collect::>()?, + ) + } + CUSTOM_MODEL_DATA => { + let n = r.count(r.remaining())?; + let floats = (0..n).map(|_| r.f32()).collect::>()?; + let n = r.count(r.remaining())?; + let flags = (0..n).map(|_| r.bool()).collect::>()?; + let n = r.count(r.remaining())?; + let strings = (0..n).map(|_| r.string(32767)).collect::>()?; + let n = r.count(r.remaining())?; + let colors = (0..n).map(|_| r.i32()).collect::>()?; + Self::CustomModelData { + floats, + flags, + strings, + colors, + } + } + TOOLTIP_DISPLAY => { + let hide = r.bool()?; + let n = r.count(r.remaining())?; + Self::TooltipDisplay { + hide, + hidden: (0..n).map(|_| r.varint()).collect::>()?, + } + } + other => return Err(Error::new(format!("unsupported item component {other}"))), + }) + } + fn write(&self, kind: i32, w: &mut Writer) { + match self { + Self::Int(v) if kind == component::DYED_COLOR => w.i32(*v), + Self::Int(v) => w.varint(*v), + Self::Unit => {} + Self::Bool(v) => w.bool(*v), + Self::Text(t) | Self::Nbt(t) => w.nbt(t), + Self::Ident(s) => w.string(s), + Self::Lore(lines) => { + w.varint(lines.len() as i32); + lines.iter().for_each(|l| w.nbt(l)); + } + Self::Enchantments(list) => { + w.varint(list.len() as i32); + for (e, level) in list { + w.varint(*e); + w.varint(*level); + } + } + Self::CustomModelData { + floats, + flags, + strings, + colors, + } => { + w.varint(floats.len() as i32); + floats.iter().for_each(|f| w.f32(*f)); + w.varint(flags.len() as i32); + flags.iter().for_each(|f| w.bool(*f)); + w.varint(strings.len() as i32); + strings.iter().for_each(|s| w.string(s)); + w.varint(colors.len() as i32); + colors.iter().for_each(|c| w.i32(*c)); + } + Self::TooltipDisplay { hide, hidden } => { + w.bool(*hide); + w.varint(hidden.len() as i32); + hidden.iter().for_each(|h| w.varint(*h)); + } + } + } +} + +/// A non-empty item stack. +#[derive(Clone, Debug, PartialEq)] +pub struct Stack { + pub item: i32, + pub count: i32, + pub added: Vec<(i32, Component)>, + pub removed: Vec, +} +impl Stack { + pub fn new(item: i32, count: i32) -> Self { + Self { + item, + count, + added: Vec::new(), + removed: Vec::new(), + } + } + pub fn component(&self, kind: i32) -> Option<&Component> { + self.added.iter().find(|(k, _)| *k == kind).map(|(_, c)| c) + } + pub fn damage(&self) -> i32 { + match self.component(component::DAMAGE) { + Some(Component::Int(d)) => *d, + _ => 0, + } + } +} +/// ItemStack.OPTIONAL_STREAM_CODEC: `None` is the empty stack (count 0). +pub struct Slot; +impl Codec> for Slot { + fn read(r: &mut Reader) -> Result> { + let count = r.varint()?; + if count <= 0 { + return Ok(None); + } + let item = r.varint()?; + let positive = r.count(65536)?; + let negative = r.count(65536)?; + let mut added = Vec::with_capacity(positive.min(64)); + for _ in 0..positive { + let kind = r.varint()?; + added.push((kind, Component::read(kind, r)?)); + } + let removed = (0..negative).map(|_| r.varint()).collect::>()?; + Ok(Some(Stack { + item, + count, + added, + removed, + })) + } + fn write(v: &Option, w: &mut Writer) { + let Some(s) = v else { + w.varint(0); + return; + }; + w.varint(s.count); + w.varint(s.item); + w.varint(s.added.len() as i32); + w.varint(s.removed.len() as i32); + for (kind, c) in &s.added { + w.varint(*kind); + c.write(*kind, w); + } + for kind in &s.removed { + w.varint(*kind); + } + } +} + +/// HashedStack: what the client believes a slot holds. Component values are +/// sent as hashes; Horizon sends patches without hashes, so a server whose +/// stack carries components resynchronises that slot (as it does for any +/// mismatched prediction). +#[derive(Clone, Debug, PartialEq)] +pub struct Hashed { + pub item: i32, + pub count: i32, + pub added: Vec<(i32, i32)>, + pub removed: Vec, +} +impl Hashed { + pub fn of(stack: &Stack) -> Self { + Self { + item: stack.item, + count: stack.count, + added: Vec::new(), + removed: stack.removed.clone(), + } + } +} +pub struct HashedSlot; +impl Codec> for HashedSlot { + fn read(r: &mut Reader) -> Result> { + if !r.bool()? { + return Ok(None); + } + let item = r.varint()?; + let count = r.varint()?; + let n = r.count(256)?; + let added = (0..n) + .map(|_| Ok((r.varint()?, r.i32()?))) + .collect::>()?; + let n = r.count(256)?; + let removed = (0..n).map(|_| r.varint()).collect::>()?; + Ok(Some(Hashed { + item, + count, + added, + removed, + })) + } + fn write(v: &Option, w: &mut Writer) { + w.bool(v.is_some()); + if let Some(h) = v { + w.varint(h.item); + w.varint(h.count); + w.varint(h.added.len() as i32); + for (k, hash) in &h.added { + w.varint(*k); + w.i32(*hash); + } + w.varint(h.removed.len() as i32); + for k in &h.removed { + w.varint(*k); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::text::literal; + + fn round>(v: T) { + let mut w = Writer::new(); + C::write(&v, &mut w); + let mut r = Reader::new(&w.data); + assert_eq!(C::read(&mut r).unwrap(), v); + assert_eq!(r.remaining(), 0); + } + + #[test] + fn stacks_round_trip() { + round::, Slot>(None); + round::, Slot>(Some(Stack::new(42, 64))); + let mut sword = Stack::new(900, 1); + sword.added.push((component::DAMAGE, Component::Int(17))); + sword.added.push(( + component::CUSTOM_NAME, + Component::Text(literal("Excalibur")), + )); + sword.added.push(( + component::ENCHANTMENTS, + Component::Enchantments(vec![(5, 3), (12, 1)]), + )); + sword + .added + .push((component::DYED_COLOR, Component::Int(-6265536))); + sword.added.push(( + component::LORE, + Component::Lore(vec![literal("a"), literal("b")]), + )); + sword.removed.push(component::REPAIR_COST); + assert_eq!(sword.damage(), 17); + round::, Slot>(Some(sword.clone())); + round::, HashedSlot>(Some(Hashed::of(&sword))); + round::, HashedSlot>(None); + } + + #[test] + fn empty_stack_is_a_zero_count() { + let mut w = Writer::new(); + Slot::write(&None, &mut w); + assert_eq!(w.data, [0]); + let mut w = Writer::new(); + Slot::write(&Some(Stack::new(1, 2)), &mut w); + assert_eq!(w.data, [2, 1, 0, 0]); + } + + #[test] + fn unknown_components_are_errors() { + let bytes = [1, 5, 1, 0, 99]; + assert!(Slot::read(&mut Reader::new(&bytes)).is_err()); + } +} diff --git a/crates/horizon-protocol/src/lib.rs b/crates/horizon-protocol/src/lib.rs new file mode 100644 index 000000000..1f29637dd --- /dev/null +++ b/crates/horizon-protocol/src/lib.rs @@ -0,0 +1,58 @@ +//! The Minecraft Java Edition 26.3 network protocol (protocol version 777): +//! primitive codecs, framing, compression, encryption, and typed packets for +//! every connection state, shared by the Horizon client and (later) server. +#![forbid(unsafe_code)] +pub mod buf; +pub mod chunk; +pub mod connection; +pub mod crypto; +pub mod entity_data; +pub mod frame; +pub mod ids; +pub mod item; +pub mod packets; +pub mod registry; +pub mod servers; +pub mod text; + +/// SharedConstants.getProtocolVersion() for 26.3. +pub const PROTOCOL_VERSION: i32 = 777; +/// The game version servers report in their status. +pub const GAME_VERSION: &str = "26.3"; + +/// Connection protocol states (ConnectionProtocol). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum State { + Handshake, + Status, + Login, + Configuration, + Play, +} +/// PacketFlow. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Direction { + Clientbound, + Serverbound, +} + +/// A malformed or unsupported packet. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Error(pub String); +impl Error { + pub fn new(message: impl Into) -> Self { + Self(message.into()) + } +} +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} +impl std::error::Error for Error {} +impl From for Error { + fn from(e: std::io::Error) -> Self { + Self(e.to_string()) + } +} +pub type Result = std::result::Result; diff --git a/crates/horizon-protocol/src/packets/configuration.rs b/crates/horizon-protocol/src/packets/configuration.rs new file mode 100644 index 000000000..a767110eb --- /dev/null +++ b/crates/horizon-protocol/src/packets/configuration.rs @@ -0,0 +1,226 @@ +//! Configuration state: registries, tags, known packs, feature flags and the +//! common packets (keep-alive, ping, custom payloads, resource packs). +use crate::{ + Result, + buf::{ + Bool, Byte, Codec, Ident, Int, List, Long, Nbt, Opt, Reader, Rest, Str, StrN, UByte, Uuid, + VarInt, Writer, + }, + packet, packet_enum, + packets::Empty, +}; +use horizon_world::nbt::Tag; + +packet!(CookieRequest { key: String => Ident }); +packet!(CustomPayload { channel: String => Ident, data: Vec => Rest }); +packet!( + /// Common disconnect: a chat component (NBT). + Disconnect { reason: Tag => Nbt } +); +packet!(KeepAlive { id: i64 => Long }); +packet!(Ping { id: i32 => Int }); +packet!( + /// RegistrySynchronization.PackedRegistryEntry: data is absent when the + /// client already has the entry from a known pack. + RegistryEntry { id: String => Ident, data: Option => Opt } +); +packet!(RegistryData { registry: String => Ident, entries: Vec => List }); +packet!(ResourcePackPop { id: Option => Opt }); +packet!(ResourcePackPush { + id: u128 => Uuid, + url: String => Str, + hash: String => StrN<40>, + required: bool => Bool, + prompt: Option => Opt, +}); +packet!(StoreCookie { key: String => Ident, payload: Vec => crate::buf::Bytes }); +packet!(Transfer { host: String => Str, port: i32 => VarInt }); +packet!(UpdateEnabledFeatures { features: Vec => List }); +packet!(TagEntry { name: String => Ident, ids: Vec => List }); +packet!(RegistryTags { registry: String => Ident, tags: Vec => List }); +packet!( + /// ClientboundUpdateTagsPacket: tags per registry. + UpdateTags { registries: Vec => List } +); +packet!(KnownPack { namespace: String => Str, id: String => Str, version: String => Str }); +packet!(SelectKnownPacks { packs: Vec => List }); +packet!(CodeOfConduct { text: String => Str }); + +packet_enum!(Clientbound, crate::ids::configuration::clientbound { + CookieRequest(CookieRequest) = COOKIE_REQUEST, + CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, + Disconnect(Disconnect) = DISCONNECT, + FinishConfiguration(Empty) = FINISH_CONFIGURATION, + KeepAlive(KeepAlive) = KEEP_ALIVE, + Ping(Ping) = PING, + ResetChat(Empty) = RESET_CHAT, + RegistryData(RegistryData) = REGISTRY_DATA, + ResourcePackPop(ResourcePackPop) = RESOURCE_PACK_POP, + ResourcePackPush(ResourcePackPush) = RESOURCE_PACK_PUSH, + StoreCookie(StoreCookie) = STORE_COOKIE, + Transfer(Transfer) = TRANSFER, + UpdateEnabledFeatures(UpdateEnabledFeatures) = UPDATE_ENABLED_FEATURES, + UpdateTags(UpdateTags) = UPDATE_TAGS, + SelectKnownPacks(SelectKnownPacks) = SELECT_KNOWN_PACKS, + ClearDialog(Empty) = CLEAR_DIALOG, + CodeOfConduct(CodeOfConduct) = CODE_OF_CONDUCT, +}); + +/// ClientInformation. +#[derive(Clone, Debug, PartialEq)] +pub struct ClientInformation { + pub language: String, + pub view_distance: i8, + /// ChatVisiblity: 0 full, 1 system, 2 hidden. + pub chat_visibility: i32, + pub chat_colors: bool, + /// Skin layer bits (PlayerModelPart). + pub model_customisation: u8, + /// HumanoidArm: 0 left, 1 right. + pub main_hand: i32, + pub text_filtering: bool, + pub allows_listing: bool, + /// ParticleStatus: 0 all, 1 decreased, 2 minimal. + pub particle_status: i32, +} +impl ClientInformation { + /// ClientInformation.createDefault with a view distance. + pub fn new(view_distance: i8) -> Self { + Self { + language: "en_us".into(), + view_distance, + chat_visibility: 0, + chat_colors: true, + model_customisation: 0x7F, + main_hand: 1, + text_filtering: false, + allows_listing: true, + particle_status: 0, + } + } +} +impl Codec for ClientInformation { + fn read(r: &mut Reader) -> Result { + Ok(Self { + language: StrN::<16>::read(r)?, + view_distance: Byte::read(r)?, + chat_visibility: VarInt::read(r)?, + chat_colors: Bool::read(r)?, + model_customisation: UByte::read(r)?, + main_hand: VarInt::read(r)?, + text_filtering: Bool::read(r)?, + allows_listing: Bool::read(r)?, + particle_status: VarInt::read(r)?, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.string(&v.language); + w.i8(v.view_distance); + w.varint(v.chat_visibility); + w.bool(v.chat_colors); + w.u8(v.model_customisation); + w.varint(v.main_hand); + w.bool(v.text_filtering); + w.bool(v.allows_listing); + w.varint(v.particle_status); + } +} +packet!(CookieResponse { key: String => Ident, payload: Option> => Opt }); +packet!( + /// ServerboundResourcePackPacket.Action: 0 loaded, 1 declined, 2 failed + /// download, 3 accepted, 4 downloaded, 5 invalid url, 6 failed reload, 7 discarded. + ResourcePackResponse { id: u128 => Uuid, action: i32 => VarInt } +); + +packet_enum!(Serverbound, crate::ids::configuration::serverbound { + ClientInformation(ClientInformation) = CLIENT_INFORMATION, + CookieResponse(CookieResponse) = COOKIE_RESPONSE, + CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, + FinishConfiguration(Empty) = FINISH_CONFIGURATION, + KeepAlive(KeepAlive) = KEEP_ALIVE, + Pong(Ping) = PONG, + ResourcePack(ResourcePackResponse) = RESOURCE_PACK, + SelectKnownPacks(SelectKnownPacks) = SELECT_KNOWN_PACKS, + AcceptCodeOfConduct(Empty) = ACCEPT_CODE_OF_CONDUCT, +}); + +#[cfg(test)] +mod tests { + use super::*; + use crate::packets::round_trip; + + #[test] + fn configuration_round_trips() { + let biome = Tag::compound([ + ("has_precipitation", Tag::Byte(1)), + ("temperature", Tag::Float(0.8f32.to_bits())), + ]); + for p in [ + Clientbound::CustomPayload(CustomPayload { + channel: "minecraft:brand".into(), + data: vec![7, b'v', b'a', b'n', b'i', b'l', b'l', b'a'], + }), + Clientbound::Disconnect(Disconnect { + reason: crate::text::literal("bye"), + }), + Clientbound::FinishConfiguration(Empty), + Clientbound::KeepAlive(KeepAlive { id: 99 }), + Clientbound::Ping(Ping { id: -3 }), + Clientbound::RegistryData(RegistryData { + registry: "minecraft:worldgen/biome".into(), + entries: vec![ + RegistryEntry { + id: "minecraft:plains".into(), + data: Some(biome), + }, + RegistryEntry { + id: "minecraft:desert".into(), + data: None, + }, + ], + }), + Clientbound::ResourcePackPush(ResourcePackPush { + id: 5, + url: "http://x".into(), + hash: String::new(), + required: false, + prompt: None, + }), + Clientbound::UpdateEnabledFeatures(UpdateEnabledFeatures { + features: vec!["minecraft:vanilla".into()], + }), + Clientbound::UpdateTags(UpdateTags { + registries: vec![RegistryTags { + registry: "minecraft:block".into(), + tags: vec![TagEntry { + name: "minecraft:logs".into(), + ids: vec![1, 2, 300], + }], + }], + }), + Clientbound::SelectKnownPacks(SelectKnownPacks { + packs: vec![KnownPack { + namespace: "minecraft".into(), + id: "core".into(), + version: "26.3".into(), + }], + }), + Clientbound::CodeOfConduct(CodeOfConduct { + text: "Be nice".into(), + }), + ] { + round_trip(p, Clientbound::encode, Clientbound::decode); + } + for p in [ + Serverbound::ClientInformation(ClientInformation::new(12)), + Serverbound::FinishConfiguration(Empty), + Serverbound::KeepAlive(KeepAlive { id: 99 }), + Serverbound::Pong(Ping { id: -3 }), + Serverbound::ResourcePack(ResourcePackResponse { id: 5, action: 1 }), + Serverbound::SelectKnownPacks(SelectKnownPacks { packs: vec![] }), + Serverbound::AcceptCodeOfConduct(Empty), + ] { + round_trip(p, Serverbound::encode, Serverbound::decode); + } + } +} diff --git a/crates/horizon-protocol/src/packets/handshake.rs b/crates/horizon-protocol/src/packets/handshake.rs new file mode 100644 index 000000000..1686adb23 --- /dev/null +++ b/crates/horizon-protocol/src/packets/handshake.rs @@ -0,0 +1,39 @@ +//! Handshake state: ClientIntentionPacket. +use crate::{ + buf::{StrN, UShort, VarInt}, + packet, packet_enum, +}; + +/// ClientIntent ids. +pub const STATUS: i32 = 1; +pub const LOGIN: i32 = 2; +pub const TRANSFER: i32 = 3; + +packet!(Intention { + protocol: i32 => VarInt, + host: String => StrN<255>, + port: u16 => UShort, + intent: i32 => VarInt, +}); + +packet_enum!(Serverbound, crate::ids::handshake::serverbound { Intention(Intention) = INTENTION }); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn intention_bytes() { + let p = Serverbound::Intention(Intention { + protocol: 777, + host: "localhost".into(), + port: 25565, + intent: LOGIN, + }); + let body = p.encode(); + assert_eq!(body[0], 0); + assert_eq!(&body[1..3], &[0x89, 0x06]); + assert_eq!(&body[body.len() - 3..], &[0x63, 0xdd, 2]); + crate::packets::round_trip(p, Serverbound::encode, Serverbound::decode); + } +} diff --git a/crates/horizon-protocol/src/packets/login.rs b/crates/horizon-protocol/src/packets/login.rs new file mode 100644 index 000000000..3e494a6a9 --- /dev/null +++ b/crates/horizon-protocol/src/packets/login.rs @@ -0,0 +1,134 @@ +//! Login state: offline/online hello, encryption request, compression, +//! login plugin queries and the finished game profile. +use crate::{ + buf::{Bool, Bytes, Ident, Opt, Rest, Str, StrN, Uuid, VarInt}, + packet, packet_enum, + packets::Empty, +}; + +packet!( + /// com.mojang.authlib.properties.Property. + Property { + name: String => StrN<64>, + value: String => Str, + signature: Option => Opt>, + } +); +packet!( + /// ByteBufCodecs.GAME_PROFILE. + GameProfile { + uuid: u128 => Uuid, + name: String => StrN<16>, + properties: Vec => crate::buf::List, + } +); +packet!(Disconnect { reason_json: String => StrN<262144> }); +packet!(Hello { + server_id: String => StrN<20>, + public_key: Vec => Bytes, + challenge: Vec => Bytes, + should_authenticate: bool => Bool, +}); +packet!(LoginFinished { profile: GameProfile => GameProfile, session: u128 => Uuid }); +packet!(Compression { threshold: i32 => VarInt }); +packet!(CustomQuery { transaction: i32 => VarInt, channel: String => Ident, data: Vec => Rest }); +packet!(CookieRequest { key: String => Ident }); + +packet_enum!(Clientbound, crate::ids::login::clientbound { + Disconnect(Disconnect) = LOGIN_DISCONNECT, + Hello(Hello) = HELLO, + LoginFinished(LoginFinished) = LOGIN_FINISHED, + Compression(Compression) = LOGIN_COMPRESSION, + CustomQuery(CustomQuery) = CUSTOM_QUERY, + CookieRequest(CookieRequest) = COOKIE_REQUEST, +}); + +packet!(ServerHello { name: String => StrN<16>, uuid: u128 => Uuid }); +packet!(Key { key: Vec => Bytes, challenge: Vec => Bytes }); +packet!(CustomQueryAnswer { transaction: i32 => VarInt, payload: Option> => Opt }); +packet!(CookieResponse { key: String => Ident, payload: Option> => Opt }); + +packet_enum!(Serverbound, crate::ids::login::serverbound { + Hello(ServerHello) = HELLO, + Key(Key) = KEY, + CustomQueryAnswer(CustomQueryAnswer) = CUSTOM_QUERY_ANSWER, + LoginAcknowledged(Empty) = LOGIN_ACKNOWLEDGED, + CookieResponse(CookieResponse) = COOKIE_RESPONSE, +}); + +#[cfg(test)] +mod tests { + use super::*; + use crate::packets::round_trip; + + #[test] + fn login_round_trips() { + let profile = GameProfile { + uuid: crate::crypto::offline_uuid("Horizon"), + name: "Horizon".into(), + properties: vec![Property { + name: "textures".into(), + value: "e30=".into(), + signature: None, + }], + }; + for p in [ + Clientbound::Disconnect(Disconnect { + reason_json: "{\"text\":\"bye\"}".into(), + }), + Clientbound::Hello(Hello { + server_id: String::new(), + public_key: vec![1, 2], + challenge: vec![3; 4], + should_authenticate: true, + }), + Clientbound::LoginFinished(LoginFinished { + profile, + session: 7, + }), + Clientbound::Compression(Compression { threshold: 256 }), + Clientbound::CustomQuery(CustomQuery { + transaction: 3, + channel: "velocity:player_info".into(), + data: vec![1], + }), + Clientbound::CookieRequest(CookieRequest { key: "a:b".into() }), + ] { + round_trip(p, Clientbound::encode, Clientbound::decode); + } + for p in [ + Serverbound::Hello(ServerHello { + name: "Horizon".into(), + uuid: 1, + }), + Serverbound::Key(Key { + key: vec![9; 128], + challenge: vec![8; 128], + }), + Serverbound::CustomQueryAnswer(CustomQueryAnswer { + transaction: 3, + payload: None, + }), + Serverbound::LoginAcknowledged(Empty), + Serverbound::CookieResponse(CookieResponse { + key: "a:b".into(), + payload: Some(vec![1]), + }), + ] { + round_trip(p, Serverbound::encode, Serverbound::decode); + } + } + + #[test] + fn rejects_trailing_bytes_and_long_names() { + let mut body = Serverbound::LoginAcknowledged(Empty).encode(); + body.push(0); + assert!(Serverbound::decode(3, &body[1..]).is_err()); + let long = Serverbound::Hello(ServerHello { + name: "x".repeat(17), + uuid: 0, + }) + .encode(); + assert!(Serverbound::decode(0, &long[1..]).is_err()); + } +} diff --git a/crates/horizon-protocol/src/packets/mod.rs b/crates/horizon-protocol/src/packets/mod.rs new file mode 100644 index 000000000..57c4f7f36 --- /dev/null +++ b/crates/horizon-protocol/src/packets/mod.rs @@ -0,0 +1,86 @@ +//! Typed packets per connection state and direction. Every state has a +//! `Clientbound` and a `Serverbound` enum whose `decode` checks that the +//! whole body was consumed (vanilla rejects oversized packets the same way) +//! and whose `encode` writes the id and payload. Packets Horizon does not +//! model decode as `Unknown` and keep their raw payload. +pub mod configuration; +pub mod handshake; +pub mod login; +pub mod play; +pub mod status; + +use crate::buf::{Codec, Reader, Writer}; + +/// Generate a state's packet enum from (Variant(Type) = ID) entries. +#[macro_export] +macro_rules! packet_enum { + ($(#[$meta:meta])* $name:ident, $ids:path { $($variant:ident($ty:ty) = $id:ident),* $(,)? }) => { + $(#[$meta])* + #[derive(Clone, Debug, PartialEq)] + pub enum $name { + $($variant($ty),)* + /// A packet Horizon does not model: id and raw payload. + Unknown(i32, Vec), + } + impl $name { + pub fn id(&self) -> i32 { + use $ids as ids; + match self { + $(Self::$variant(_) => ids::$id,)* + Self::Unknown(id, _) => *id, + } + } + /// Decode a packet body (after the id). + pub fn decode(id: i32, payload: &[u8]) -> $crate::Result { + use $ids as ids; + let mut r = $crate::buf::Reader::new(payload); + let packet = match id { + $(ids::$id => Self::$variant(<$ty as $crate::buf::Codec<$ty>>::read(&mut r)?),)* + _ => return Ok(Self::Unknown(id, payload.to_vec())), + }; + if r.remaining() != 0 { + return Err($crate::Error::new(format!( + "packet {} ({}) was larger than expected: {} extra bytes", + id, + stringify!($name), + r.remaining() + ))); + } + Ok(packet) + } + /// The packet body: VarInt id then payload. + pub fn encode(&self) -> Vec { + let mut w = $crate::buf::Writer::new(); + w.varint(self.id()); + match self { + $(Self::$variant(p) => <$ty as $crate::buf::Codec<$ty>>::write(p, &mut w),)* + Self::Unknown(_, payload) => w.bytes(payload), + } + w.data + } + } + }; +} + +/// A packet with no fields. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Empty; +impl Codec for Empty { + fn read(_: &mut Reader) -> crate::Result { + Ok(Empty) + } + fn write(_: &Empty, _: &mut Writer) {} +} + +#[cfg(test)] +pub(crate) fn round_trip( + packet: T, + encode: impl Fn(&T) -> Vec, + decode: impl Fn(i32, &[u8]) -> crate::Result, +) { + let body = encode(&packet); + let mut r = Reader::new(&body); + let id = r.varint().unwrap(); + let back = decode(id, r.rest()).unwrap(); + assert_eq!(back, packet); +} diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs new file mode 100644 index 000000000..f90370cf3 --- /dev/null +++ b/crates/horizon-protocol/src/packets/play.rs @@ -0,0 +1,1136 @@ +//! Play state packets: world, entities, player state, inventory and chat. +use crate::{ + Error, Result, + buf::{ + Bool, Byte, ChunkPos, Codec, Double, Float, Ident, Int, List, Long, LpVec3, Nbt, Opt, + OptVarInt, Pos, Reader, SectionPos, Short, Str, StrN, UByte, Uuid, VarInt, VarLong, Vec3d, + Writer, + }, + chunk::{ChunkData, LightData}, + entity_data::{EntityData, Value}, + item::{Hashed, HashedSlot, Slot, Stack}, + packet, packet_enum, + packets::{ + Empty, + configuration::{ + ClientInformation, CustomPayload, Disconnect, KeepAlive, Ping, ResourcePackPush, + ResourcePackResponse, UpdateTags, + }, + login::Property, + }, +}; +use horizon_world::nbt::Tag; + +// ---- shared structures ------------------------------------------------- + +packet!( + /// GlobalPos: a dimension and a block position. + GlobalPos { dimension: String => Ident, pos: [i32; 3] => Pos } +); +packet!( + /// CommonPlayerSpawnInfo. + SpawnInfo { + dimension_type: i32 => VarInt, + dimension: String => Ident, + seed: i64 => Long, + game_type: i32 => VarInt, + previous_game_type: Option => OptVarInt, + debug: bool => Bool, + flat: bool => Bool, + last_death: Option => Opt, + portal_cooldown: i32 => VarInt, + sea_level: i32 => VarInt, + } +); + +/// Relative flags (Relative.pack): X, Y, Z, Y_ROT, X_ROT, DELTA_X/Y/Z, ROTATE_DELTA. +pub mod relative { + pub const X: i32 = 1; + pub const Y: i32 = 2; + pub const Z: i32 = 4; + pub const Y_ROT: i32 = 8; + pub const X_ROT: i32 = 16; + pub const DELTA_X: i32 = 32; + pub const DELTA_Y: i32 = 64; + pub const DELTA_Z: i32 = 128; + pub const ROTATE_DELTA: i32 = 256; +} + +// ---- clientbound ------------------------------------------------------- + +packet!(AddEntity { + id: i32 => VarInt, + uuid: u128 => Uuid, + kind: i32 => VarInt, + position: [f64; 3] => Vec3d, + velocity: [f64; 3] => LpVec3, + pitch: i8 => Byte, + yaw: i8 => Byte, + head_yaw: i8 => Byte, + data: i32 => VarInt, +}); +packet!(Animate { id: i32 => VarInt, action: u8 => UByte }); +packet!(BlockChangedAck { sequence: i32 => VarInt }); +packet!(BlockDestruction { id: i32 => VarInt, pos: [i32; 3] => Pos, progress: u8 => UByte }); +packet!(BlockEntityData { pos: [i32; 3] => Pos, kind: i32 => VarInt, tag: Tag => Nbt }); +packet!(BlockUpdate { pos: [i32; 3] => Pos, state: i32 => VarInt }); +packet!(ChangeDifficulty { difficulty: i32 => VarInt, locked: bool => Bool }); +packet!(ChunkBatchFinished { size: i32 => VarInt }); +packet!(ContainerClose { container: i32 => VarInt }); +packet!(ContainerSetContent { + container: i32 => VarInt, + state: i32 => VarInt, + items: Vec> => List, + carried: Option => Slot, +}); +packet!(ContainerSetData { container: i32 => VarInt, id: i16 => Short, value: i16 => Short }); +packet!(ContainerSetSlot { container: i32 => VarInt, state: i32 => VarInt, slot: i16 => Short, item: Option => Slot }); +/// A holder reference: registry id + 1, or 0 for an inline value (unsupported). +pub struct HolderId; +impl Codec for HolderId { + fn read(r: &mut Reader) -> Result { + match r.varint()? { + 0 => Err(Error::new("inline registry values are not supported")), + id => Ok(id - 1), + } + } + fn write(v: &i32, w: &mut Writer) { + w.varint(v + 1) + } +} +packet!( + /// ChatType.Bound. + ChatTypeBound { chat_type: i32 => HolderId, name: Tag => Nbt, target: Option => Opt } +); +packet!(DisguisedChat { message: Tag => Nbt, chat_type: ChatTypeBound => ChatTypeBound }); +packet!(EntityEvent { id: i32 => Int, event: i8 => Byte }); +/// PositionPath: Linear(end position) or Stepped(list of (position, tick offset)). +#[derive(Clone, Debug, PartialEq)] +pub enum PositionPath { + Linear([f64; 3]), + Stepped(Vec<([f64; 3], i32)>), +} +impl PositionPath { + pub fn end(&self) -> [f64; 3] { + match self { + Self::Linear(p) => *p, + Self::Stepped(steps) => steps.last().map_or([0.0; 3], |s| s.0), + } + } +} +impl Codec for PositionPath { + fn read(r: &mut Reader) -> Result { + Ok(match r.varint()? { + 1 => { + let n = r.count(r.remaining() / 25)?; + Self::Stepped( + (0..n) + .map(|_| Ok((Vec3d::read(r)?, r.varint()?))) + .collect::>()?, + ) + } + _ => Self::Linear(Vec3d::read(r)?), + }) + } + fn write(v: &Self, w: &mut Writer) { + match v { + Self::Linear(p) => { + w.varint(0); + Vec3d::write(p, w); + } + Self::Stepped(steps) => { + w.varint(1); + w.varint(steps.len() as i32); + for (p, t) in steps { + Vec3d::write(p, w); + w.varint(*t); + } + } + } + } +} +packet!(EntityPositionSync { id: i32 => VarInt, path: PositionPath => PositionPath, yaw: f32 => Float, pitch: f32 => Float, on_ground: bool => Bool }); +packet!(ForgetLevelChunk { pos: [i32; 2] => ChunkPos }); +packet!(GameEvent { event: u8 => UByte, param: f32 => Float }); +packet!(HurtAnimation { id: i32 => VarInt, yaw: f32 => Float }); +packet!(LevelChunkWithLight { x: i32 => Int, z: i32 => Int, chunk: ChunkData => ChunkData, light: LightData => LightData }); +packet!(LevelEvent { kind: i32 => Int, pos: [i32; 3] => Pos, data: i32 => Int, global: bool => Bool }); +packet!(LightUpdate { x: i32 => VarInt, z: i32 => VarInt, light: LightData => LightData }); +packet!(Login { + player_id: i32 => Int, + hardcore: bool => Bool, + levels: Vec => List, + max_players: i32 => VarInt, + chunk_radius: i32 => VarInt, + simulation_distance: i32 => VarInt, + reduced_debug_info: bool => Bool, + show_death_screen: bool => Bool, + limited_crafting: bool => Bool, + spawn: SpawnInfo => SpawnInfo, + online_mode: bool => Bool, + enforces_secure_chat: bool => Bool, +}); +/// VecDelta: per-axis deltas in 1/4096 blocks, linear or in timed steps. +#[derive(Clone, Debug, PartialEq)] +pub enum VecDelta { + Linear([i16; 3]), + Stepped(Vec<([i16; 3], i32)>), +} +impl VecDelta { + /// VecDeltaCodec.decode against a base position: zero deltas keep the + /// base coordinate exactly, others add to its 1/4096 quantization. + pub fn apply(base: [f64; 3], delta: [i16; 3]) -> [f64; 3] { + let mut out = base; + for i in 0..3 { + if delta[i] != 0 { + out[i] = ((base[i] * 4096.0).round() as i64 + i64::from(delta[i])) as f64 / 4096.0; + } + } + out + } + /// The final position after all steps. + pub fn end(&self, base: [f64; 3]) -> [f64; 3] { + match self { + Self::Linear(d) => Self::apply(base, *d), + Self::Stepped(steps) => steps.iter().fold(base, |p, (d, _)| Self::apply(p, *d)), + } + } + fn read(r: &mut Reader, steps: usize) -> Result { + if steps == 0 { + return Ok(Self::Linear([r.i16()?, r.i16()?, r.i16()?])); + } + if steps > r.remaining() / 7 { + return Err(Error::new("VecDelta with too many steps")); + } + Ok(Self::Stepped( + (0..steps) + .map(|_| { + let ticks = r.varint()?; + Ok(([r.i16()?, r.i16()?, r.i16()?], ticks)) + }) + .collect::>()?, + )) + } + fn steps(&self) -> usize { + match self { + Self::Linear(_) => 0, + Self::Stepped(s) => s.len(), + } + } + fn write(&self, w: &mut Writer) { + match self { + Self::Linear(d) => d.iter().for_each(|v| w.i16(*v)), + Self::Stepped(steps) => { + for (d, ticks) in steps { + w.varint(*ticks); + d.iter().for_each(|v| w.i16(*v)); + } + } + } + } +} +/// ClientboundMoveEntityPacket.Pos / PosRot / Rot. +#[derive(Clone, Debug, PartialEq)] +pub struct MoveEntity { + pub id: i32, + pub delta: Option, + pub rotation: Option<(i8, i8)>, + pub on_ground: bool, +} +macro_rules! move_entity { + ($name:ident, pos: $pos:expr, rot: $rot:expr) => { + #[derive(Clone, Debug, PartialEq)] + pub struct $name(pub MoveEntity); + impl Codec<$name> for $name { + fn read(r: &mut Reader) -> Result<$name> { + Self::read_inner(r).map($name) + } + fn write(v: &$name, w: &mut Writer) { + Self::write_inner(&v.0, w) + } + } + impl $name { + fn read_inner(r: &mut Reader) -> Result { + let id = r.varint()?; + if !$pos { + let on_ground = r.bool()?; + let rotation = Some((r.i8()?, r.i8()?)); + return Ok(MoveEntity { + id, + delta: None, + rotation, + on_ground, + }); + } + let properties = r.varint()?; + let delta = Some(VecDelta::read(r, (properties as u32 >> 1) as usize)?); + let rotation = if $rot { Some((r.i8()?, r.i8()?)) } else { None }; + Ok(MoveEntity { + id, + delta, + rotation, + on_ground: properties & 1 != 0, + }) + } + fn write_inner(v: &MoveEntity, w: &mut Writer) { + w.varint(v.id); + if !$pos { + w.bool(v.on_ground); + } else { + let delta = v.delta.clone().unwrap_or(VecDelta::Linear([0; 3])); + w.varint(i32::from(v.on_ground) | (delta.steps() as i32) << 1); + delta.write(w); + } + if let Some((y, x)) = v.rotation.filter(|_| $rot) { + w.i8(y); + w.i8(x); + } + } + } + }; +} +move_entity!(MoveEntityPos, pos: true, rot: false); +move_entity!(MoveEntityPosRot, pos: true, rot: true); +move_entity!(MoveEntityRot, pos: false, rot: true); +packet!(OpenScreen { container: i32 => VarInt, menu: i32 => VarInt, title: Tag => Nbt }); +packet!(PlayerAbilities { flags: i8 => Byte, flying_speed: f32 => Float, walking_speed: f32 => Float }); +/// MessageSignature.Packed: an index into the last-seen cache or a full signature. +pub struct PackedSignature; +impl Codec<(i32, Option>)> for PackedSignature { + fn read(r: &mut Reader) -> Result<(i32, Option>)> { + let id = r.varint()? - 1; + Ok(if id == -1 { + (-1, Some(r.bytes(256)?.to_vec())) + } else { + (id, None) + }) + } + fn write(v: &(i32, Option>), w: &mut Writer) { + w.varint(v.0 + 1); + if let Some(sig) = &v.1 { + w.bytes(sig); + } + } +} +/// MessageSignature: 256 raw bytes. +pub struct Signature; +impl Codec> for Signature { + fn read(r: &mut Reader) -> Result> { + Ok(r.bytes(256)?.to_vec()) + } + fn write(v: &Vec, w: &mut Writer) { + w.bytes(v) + } +} +/// FilterMask: 0 pass-through, 1 fully filtered, 2 partially (with a BitSet). +pub struct FilterMask; +impl Codec<(i32, Vec)> for FilterMask { + fn read(r: &mut Reader) -> Result<(i32, Vec)> { + let kind = r.varint()?; + Ok(( + kind, + if kind == 2 { + r.long_array()? + } else { + Vec::new() + }, + )) + } + fn write(v: &(i32, Vec), w: &mut Writer) { + w.varint(v.0); + if v.0 == 2 { + w.long_array(&v.1); + } + } +} +packet!(PlayerChat { + global_index: i32 => VarInt, + sender: u128 => Uuid, + index: i32 => VarInt, + signature: Option> => Opt, + content: String => StrN<256>, + timestamp: i64 => Long, + salt: i64 => Long, + last_seen: Vec<(i32, Option>)> => List, + unsigned_content: Option => Opt, + filter: (i32, Vec) => FilterMask, + chat_type: ChatTypeBound => ChatTypeBound, +}); +packet!(PlayerCombatKill { id: i32 => VarInt, message: Tag => Nbt }); +packet!(PlayerInfoRemove { uuids: Vec => List }); +/// One ClientboundPlayerInfoUpdatePacket entry; fields are set for the +/// actions in the packet. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PlayerInfo { + pub uuid: u128, + pub name: Option, + pub properties: Vec, + /// RemoteChatSession.Data: session id, key expiry, key, key signature. + pub chat_session: Option<(u128, i64, Vec, Vec)>, + pub game_mode: Option, + pub listed: Option, + pub latency: Option, + pub display_name: Option>, + pub list_order: Option, + pub show_hat: Option, +} +/// Actions bits: ADD_PLAYER, INITIALIZE_CHAT, UPDATE_GAME_MODE, UPDATE_LISTED, +/// UPDATE_LATENCY, UPDATE_DISPLAY_NAME, UPDATE_LIST_ORDER, UPDATE_HAT. +#[derive(Clone, Debug, PartialEq)] +pub struct PlayerInfoUpdate { + pub actions: u8, + pub entries: Vec, +} +impl Codec for PlayerInfoUpdate { + fn read(r: &mut Reader) -> Result { + let actions = r.u8()?; + let n = r.count(r.remaining())?; + let mut entries = Vec::with_capacity(n.min(256)); + for _ in 0..n { + let mut e = PlayerInfo { + uuid: r.uuid()?, + ..PlayerInfo::default() + }; + if actions & 1 != 0 { + e.name = Some(r.string(16)?); + let count = r.count(16)?; + e.properties = (0..count) + .map(|_| Property::read(r)) + .collect::>()?; + } + if actions & 2 != 0 && r.bool()? { + e.chat_session = + Some((r.uuid()?, r.i64()?, r.byte_array(512)?, r.byte_array(4096)?)); + } + if actions & 4 != 0 { + e.game_mode = Some(r.varint()?); + } + if actions & 8 != 0 { + e.listed = Some(r.bool()?); + } + if actions & 16 != 0 { + e.latency = Some(r.varint()?); + } + if actions & 32 != 0 { + e.display_name = Some(if r.bool()? { Some(r.nbt()?) } else { None }); + } + if actions & 64 != 0 { + e.list_order = Some(r.varint()?); + } + if actions & 128 != 0 { + e.show_hat = Some(r.bool()?); + } + entries.push(e); + } + Ok(Self { actions, entries }) + } + fn write(v: &Self, w: &mut Writer) { + w.u8(v.actions); + w.varint(v.entries.len() as i32); + for e in &v.entries { + w.uuid(e.uuid); + if v.actions & 1 != 0 { + w.string(e.name.as_deref().unwrap_or("")); + w.varint(e.properties.len() as i32); + e.properties.iter().for_each(|p| Property::write(p, w)); + } + if v.actions & 2 != 0 { + w.bool(e.chat_session.is_some()); + if let Some((id, expires, key, sig)) = &e.chat_session { + w.uuid(*id); + w.i64(*expires); + w.byte_array(key); + w.byte_array(sig); + } + } + if v.actions & 4 != 0 { + w.varint(e.game_mode.unwrap_or(0)); + } + if v.actions & 8 != 0 { + w.bool(e.listed.unwrap_or(false)); + } + if v.actions & 16 != 0 { + w.varint(e.latency.unwrap_or(0)); + } + if v.actions & 32 != 0 { + let name = e.display_name.clone().flatten(); + w.bool(name.is_some()); + if let Some(t) = &name { + w.nbt(t); + } + } + if v.actions & 64 != 0 { + w.varint(e.list_order.unwrap_or(0)); + } + if v.actions & 128 != 0 { + w.bool(e.show_hat.unwrap_or(false)); + } + } + } +} +packet!(PlayerPosition { + teleport: i32 => VarInt, + position: [f64; 3] => Vec3d, + delta: [f64; 3] => Vec3d, + yaw: f32 => Float, + pitch: f32 => Float, + relatives: i32 => Int, +}); +packet!(PlayerRotation { yaw: f32 => Float, relative_yaw: bool => Bool, pitch: f32 => Float, relative_pitch: bool => Bool }); +packet!(RemoveEntities { ids: Vec => List }); +packet!(Respawn { spawn: SpawnInfo => SpawnInfo, keep: i8 => Byte }); +packet!(RotateHead { id: i32 => VarInt, head_yaw: i8 => Byte }); +packet!( + /// Each change is `state << 12 | x << 8 | z << 4 | y` within the section. + SectionBlocksUpdate { section: [i32; 3] => SectionPos, changes: Vec => List } +); +packet!(Text { text: Tag => Nbt }); +packet!(SetChunkCacheCenter { x: i32 => VarInt, z: i32 => VarInt }); +packet!(Distance { distance: i32 => VarInt }); +packet!(SetCursorItem { item: Option => Slot }); +packet!(SetDefaultSpawnPosition { pos: GlobalPos => GlobalPos, yaw: f32 => Float, pitch: f32 => Float }); +packet!(SetEntityData { id: i32 => VarInt, values: Vec<(u8, i32, Value)> => EntityData }); +packet!(SetEntityMotion { id: i32 => VarInt, velocity: [f64; 3] => LpVec3 }); +/// ClientboundSetEquipmentPacket: (EquipmentSlot ordinal, stack) pairs. +pub struct Equipment; +impl Codec)>> for Equipment { + fn read(r: &mut Reader) -> Result)>> { + let mut out = Vec::new(); + loop { + let slot = r.u8()?; + out.push((slot & 127, Slot::read(r)?)); + if slot & 128 == 0 { + return Ok(out); + } + } + } + fn write(v: &Vec<(u8, Option)>, w: &mut Writer) { + for (i, (slot, stack)) in v.iter().enumerate() { + w.u8(if i + 1 < v.len() { slot | 128 } else { *slot }); + Slot::write(stack, w); + } + } +} +packet!(SetEquipment { id: i32 => VarInt, slots: Vec<(u8, Option)> => Equipment }); +packet!(SetExperience { progress: f32 => Float, level: i32 => VarInt, total: i32 => VarInt }); +packet!(SetHealth { health: f32 => Float, food: i32 => VarInt, saturation: f32 => Float }); +packet!(SetHeldSlot { slot: i32 => VarInt }); +packet!(SetPlayerInventory { slot: i32 => VarInt, item: Option => Slot }); +packet!( + /// ClockNetworkState for one world clock (registry id). + ClockState { clock: i32 => VarInt, total_ticks: i64 => VarLong, partial_tick: f32 => Float, rate: f32 => Float } +); +packet!(SetTime { game_time: i64 => Long, clocks: Vec => List }); +packet!(TitlesAnimation { fade_in: i32 => Int, stay: i32 => Int, fade_out: i32 => Int }); +/// SoundEvent holder: a registry id, or an inline location with optional range. +pub struct SoundHolder; +impl Codec<(i32, Option<(String, Option)>)> for SoundHolder { + fn read(r: &mut Reader) -> Result<(i32, Option<(String, Option)>)> { + let id = r.varint()?; + if id != 0 { + return Ok((id - 1, None)); + } + let location = r.string(32767)?; + let range = if r.bool()? { Some(r.f32()?) } else { None }; + Ok((-1, Some((location, range)))) + } + fn write(v: &(i32, Option<(String, Option)>), w: &mut Writer) { + match &v.1 { + None => w.varint(v.0 + 1), + Some((location, range)) => { + w.varint(0); + w.string(location); + as Codec>>::write(range, w); + } + } + } +} +packet!(Sound { + sound: (i32, Option<(String, Option)>) => SoundHolder, + source: i32 => VarInt, + x: i32 => Int, + y: i32 => Int, + z: i32 => Int, + volume: f32 => Float, + pitch: f32 => Float, + seed: i64 => Long, +}); +packet!(SystemChat { content: Tag => Nbt, overlay: bool => Bool }); +packet!(TakeItemEntity { item: i32 => VarInt, player: i32 => VarInt, amount: i32 => VarInt }); +packet!(TeleportEntity { + id: i32 => VarInt, + position: [f64; 3] => Vec3d, + delta: [f64; 3] => Vec3d, + yaw: f32 => Float, + pitch: f32 => Float, + relatives: i32 => Int, + on_ground: bool => Bool, +}); + +packet_enum!(Clientbound, crate::ids::play::clientbound { + BundleDelimiter(Empty) = BUNDLE_DELIMITER, + AddEntity(AddEntity) = ADD_ENTITY, + Animate(Animate) = ANIMATE, + BlockChangedAck(BlockChangedAck) = BLOCK_CHANGED_ACK, + BlockDestruction(BlockDestruction) = BLOCK_DESTRUCTION, + BlockEntityData(BlockEntityData) = BLOCK_ENTITY_DATA, + BlockUpdate(BlockUpdate) = BLOCK_UPDATE, + ChangeDifficulty(ChangeDifficulty) = CHANGE_DIFFICULTY, + ChunkBatchFinished(ChunkBatchFinished) = CHUNK_BATCH_FINISHED, + ChunkBatchStart(Empty) = CHUNK_BATCH_START, + ClearTitles(Bool1) = CLEAR_TITLES, + ContainerClose(ContainerClose) = CONTAINER_CLOSE, + ContainerSetContent(ContainerSetContent) = CONTAINER_SET_CONTENT, + ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA, + ContainerSetSlot(ContainerSetSlot) = CONTAINER_SET_SLOT, + CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, + Disconnect(Disconnect) = DISCONNECT, + DisguisedChat(DisguisedChat) = DISGUISED_CHAT, + EntityEvent(EntityEvent) = ENTITY_EVENT, + EntityPositionSync(EntityPositionSync) = ENTITY_POSITION_SYNC, + ForgetLevelChunk(ForgetLevelChunk) = FORGET_LEVEL_CHUNK, + GameEvent(GameEvent) = GAME_EVENT, + HurtAnimation(HurtAnimation) = HURT_ANIMATION, + KeepAlive(KeepAlive) = KEEP_ALIVE, + LevelChunkWithLight(LevelChunkWithLight) = LEVEL_CHUNK_WITH_LIGHT, + LevelEvent(LevelEvent) = LEVEL_EVENT, + LightUpdate(LightUpdate) = LIGHT_UPDATE, + Login(Login) = LOGIN, + MoveEntityPos(MoveEntityPos) = MOVE_ENTITY_POS, + MoveEntityPosRot(MoveEntityPosRot) = MOVE_ENTITY_POS_ROT, + MoveEntityRot(MoveEntityRot) = MOVE_ENTITY_ROT, + OpenScreen(OpenScreen) = OPEN_SCREEN, + Ping(Ping) = PING, + PlayerAbilities(PlayerAbilities) = PLAYER_ABILITIES, + PlayerChat(PlayerChat) = PLAYER_CHAT, + PlayerCombatKill(PlayerCombatKill) = PLAYER_COMBAT_KILL, + PlayerInfoRemove(PlayerInfoRemove) = PLAYER_INFO_REMOVE, + PlayerInfoUpdate(PlayerInfoUpdate) = PLAYER_INFO_UPDATE, + PlayerPosition(PlayerPosition) = PLAYER_POSITION, + PlayerRotation(PlayerRotation) = PLAYER_ROTATION, + RemoveEntities(RemoveEntities) = REMOVE_ENTITIES, + ResourcePackPush(ResourcePackPush) = RESOURCE_PACK_PUSH, + Respawn(Respawn) = RESPAWN, + RotateHead(RotateHead) = ROTATE_HEAD, + SectionBlocksUpdate(SectionBlocksUpdate) = SECTION_BLOCKS_UPDATE, + SetActionBarText(Text) = SET_ACTION_BAR_TEXT, + SetChunkCacheCenter(SetChunkCacheCenter) = SET_CHUNK_CACHE_CENTER, + SetChunkCacheRadius(Distance) = SET_CHUNK_CACHE_RADIUS, + SetCursorItem(SetCursorItem) = SET_CURSOR_ITEM, + SetDefaultSpawnPosition(SetDefaultSpawnPosition) = SET_DEFAULT_SPAWN_POSITION, + SetEntityData(SetEntityData) = SET_ENTITY_DATA, + SetEntityMotion(SetEntityMotion) = SET_ENTITY_MOTION, + SetEquipment(SetEquipment) = SET_EQUIPMENT, + SetExperience(SetExperience) = SET_EXPERIENCE, + SetHealth(SetHealth) = SET_HEALTH, + SetHeldSlot(SetHeldSlot) = SET_HELD_SLOT, + SetPlayerInventory(SetPlayerInventory) = SET_PLAYER_INVENTORY, + SetSimulationDistance(Distance) = SET_SIMULATION_DISTANCE, + SetSubtitleText(Text) = SET_SUBTITLE_TEXT, + SetTime(SetTime) = SET_TIME, + SetTitleText(Text) = SET_TITLE_TEXT, + SetTitlesAnimation(TitlesAnimation) = SET_TITLES_ANIMATION, + Sound(Sound) = SOUND, + StartConfiguration(Empty) = START_CONFIGURATION, + SystemChat(SystemChat) = SYSTEM_CHAT, + TakeItemEntity(TakeItemEntity) = TAKE_ITEM_ENTITY, + TeleportEntity(TeleportEntity) = TELEPORT_ENTITY, + UpdateTags(UpdateTags) = UPDATE_TAGS, +}); +packet!( + /// ClientboundClearTitlesPacket: whether to also reset the timings. + Bool1 { value: bool => Bool } +); + +// ---- serverbound ------------------------------------------------------- + +packet!(AcceptTeleportation { id: i32 => VarInt, x: f64 => Double, y: f64 => Double, z: f64 => Double, yaw: f32 => Float, pitch: f32 => Float }); +packet!(Attack { id: i32 => VarInt }); +packet!(LastSeenUpdate { offset: i32 => VarInt, acknowledged: [u8; 3] => Fixed3, checksum: i8 => Byte }); +/// LastSeenMessages.Update's fixed 20-bit BitSet (3 bytes). +pub struct Fixed3; +impl Codec<[u8; 3]> for Fixed3 { + fn read(r: &mut Reader) -> Result<[u8; 3]> { + Ok(r.bytes(3)?.try_into().expect("3 bytes")) + } + fn write(v: &[u8; 3], w: &mut Writer) { + w.bytes(v) + } +} +packet!(Chat { + message: String => StrN<256>, + timestamp: i64 => Long, + salt: i64 => Long, + signature: Option> => Opt, + last_seen: LastSeenUpdate => LastSeenUpdate, +}); +packet!(ChatCommand { command: String => Str }); +packet!(ChunkBatchReceived { chunks_per_tick: f32 => Float }); +packet!( + /// ServerboundClientCommandPacket.Action: 0 respawn, 1 request stats, 2 request game rules. + ClientCommand { action: i32 => VarInt } +); +/// Changed slots: (slot, hashed stack) pairs. +pub struct ChangedSlots; +impl Codec)>> for ChangedSlots { + fn read(r: &mut Reader) -> Result)>> { + let n = r.count(128)?; + (0..n) + .map(|_| Ok((r.i16()?, HashedSlot::read(r)?))) + .collect() + } + fn write(v: &Vec<(i16, Option)>, w: &mut Writer) { + w.varint(v.len() as i32); + for (slot, h) in v { + w.i16(*slot); + HashedSlot::write(h, w); + } + } +} +packet!( + /// ContainerInput: 0 pickup, 1 quick move, 2 swap, 3 clone, 4 throw, 5 quick craft, 6 pickup all. + ContainerClick { + container: i32 => VarInt, + state: i32 => VarInt, + slot: i16 => Short, + button: i8 => Byte, + input: i32 => VarInt, + changed: Vec<(i16, Option)> => ChangedSlots, + carried: Option => HashedSlot, + } +); +packet!(Interact { id: i32 => VarInt, hand: i32 => VarInt, location: [f64; 3] => LpVec3, secondary: bool => Bool }); +packet!( + /// ServerboundMovePlayerPacket flags: 1 on ground, 2 horizontal collision. + MovePlayerPos { x: f64 => Double, y: f64 => Double, z: f64 => Double, flags: u8 => UByte } +); +packet!(MovePlayerPosRot { x: f64 => Double, y: f64 => Double, z: f64 => Double, yaw: f32 => Float, pitch: f32 => Float, flags: u8 => UByte }); +packet!(MovePlayerRot { yaw: f32 => Float, pitch: f32 => Float, flags: u8 => UByte }); +packet!(MovePlayerStatus { flags: u8 => UByte }); +packet!(PickItemFromBlock { pos: [i32; 3] => Pos, include_data: bool => Bool }); +packet!( + /// ServerboundPlayerActionPacket.Action: 0 start destroy, 1 change destroy + /// direction, 2 abort, 3 stop destroy, 4 drop all, 5 drop item, 6 release + /// use item, 7 swap offhand, 8 stab. Direction is the 3D data value. + PlayerAction { action: i32 => VarInt, pos: [i32; 3] => Pos, direction: u8 => UByte, sequence: i32 => VarInt } +); +packet!( + /// ServerboundPlayerCommandPacket.Action: 0 stop sleeping, 1 start sprinting, + /// 2 stop sprinting, 3/4 riding jump, 5 open inventory, 6 start fall flying. + PlayerCommand { id: i32 => VarInt, action: i32 => VarInt, data: i32 => VarInt } +); +packet!( + /// Input flags: forward 1, backward 2, left 4, right 8, jump 16, shift 32, sprint 64. + PlayerInput { flags: u8 => UByte } +); +packet!(SetCarriedItem { slot: i16 => Short }); +packet!(SetCreativeModeSlot { slot: i16 => Short, item: Option => Slot }); +packet!(UseItem { hand: i32 => VarInt, sequence: i32 => VarInt, yaw: f32 => Float, pitch: f32 => Float }); +packet!(UseItemOn { + hand: i32 => VarInt, + pos: [i32; 3] => Pos, + face: i32 => VarInt, + cursor: [f32; 3] => Cursor, + inside: bool => Bool, + world_border: bool => Bool, + sequence: i32 => VarInt, +}); +/// The click location relative to the block (three floats). +pub struct Cursor; +impl Codec<[f32; 3]> for Cursor { + fn read(r: &mut Reader) -> Result<[f32; 3]> { + Ok([r.f32()?, r.f32()?, r.f32()?]) + } + fn write(v: &[f32; 3], w: &mut Writer) { + v.iter().for_each(|f| w.f32(*f)); + } +} + +packet_enum!(Serverbound, crate::ids::play::serverbound { + AcceptTeleportation(AcceptTeleportation) = ACCEPT_TELEPORTATION, + Attack(Attack) = ATTACK, + Chat(Chat) = CHAT, + ChatCommand(ChatCommand) = CHAT_COMMAND, + ChunkBatchReceived(ChunkBatchReceived) = CHUNK_BATCH_RECEIVED, + ClientCommand(ClientCommand) = CLIENT_COMMAND, + ClientInformation(ClientInformation) = CLIENT_INFORMATION, + ClientTickEnd(Empty) = CLIENT_TICK_END, + ConfigurationAcknowledged(Empty) = CONFIGURATION_ACKNOWLEDGED, + ContainerClick(ContainerClick) = CONTAINER_CLICK, + ContainerClose(ContainerClose) = CONTAINER_CLOSE, + CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, + Interact(Interact) = INTERACT, + KeepAlive(KeepAlive) = KEEP_ALIVE, + MovePlayerPos(MovePlayerPos) = MOVE_PLAYER_POS, + MovePlayerPosRot(MovePlayerPosRot) = MOVE_PLAYER_POS_ROT, + MovePlayerRot(MovePlayerRot) = MOVE_PLAYER_ROT, + MovePlayerStatus(MovePlayerStatus) = MOVE_PLAYER_STATUS_ONLY, + PickItemFromBlock(PickItemFromBlock) = PICK_ITEM_FROM_BLOCK, + PlayerAction(PlayerAction) = PLAYER_ACTION, + PlayerCommand(PlayerCommand) = PLAYER_COMMAND, + PlayerInput(PlayerInput) = PLAYER_INPUT, + PlayerLoaded(Empty) = PLAYER_LOADED, + Pong(Ping) = PONG, + Punch(Empty) = PUNCH, + ResourcePack(ResourcePackResponse) = RESOURCE_PACK, + SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, + SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT, + UseItem(UseItem) = USE_ITEM, + UseItemOn(UseItemOn) = USE_ITEM_ON, +}); + +#[cfg(test)] +mod tests { + use super::*; + use crate::{chunk::BlockEntityInfo, packets::round_trip, text::literal}; + + fn spawn() -> SpawnInfo { + SpawnInfo { + dimension_type: 0, + dimension: "minecraft:overworld".into(), + seed: -123, + game_type: 0, + previous_game_type: None, + debug: false, + flat: false, + last_death: Some(GlobalPos { + dimension: "minecraft:the_nether".into(), + pos: [1, 2, 3], + }), + portal_cooldown: 0, + sea_level: 63, + } + } + + #[test] + fn clientbound_round_trips() { + let packets = vec![ + Clientbound::BundleDelimiter(Empty), + Clientbound::AddEntity(AddEntity { + id: 5, + uuid: 9, + kind: 100, + position: [1.5, 64.0, -3.25], + velocity: [0.0; 3], + pitch: 0, + yaw: 64, + head_yaw: 64, + data: 0, + }), + Clientbound::BlockUpdate(BlockUpdate { + pos: [-5, -60, 7], + state: 1, + }), + Clientbound::ContainerSetContent(ContainerSetContent { + container: 0, + state: 3, + items: vec![None, Some(Stack::new(1, 64))], + carried: None, + }), + Clientbound::ContainerSetSlot(ContainerSetSlot { + container: 0, + state: 4, + slot: 36, + item: Some(Stack::new(2, 1)), + }), + Clientbound::Disconnect(Disconnect { + reason: literal("kicked"), + }), + Clientbound::EntityPositionSync(EntityPositionSync { + id: 1, + path: PositionPath::Stepped(vec![([1.0, 2.0, 3.0], 0), ([1.5, 2.0, 3.0], 2)]), + yaw: 1.0, + pitch: 2.0, + on_ground: true, + }), + Clientbound::ForgetLevelChunk(ForgetLevelChunk { pos: [-1, 2] }), + Clientbound::GameEvent(GameEvent { + event: 13, + param: 0.0, + }), + Clientbound::LevelChunkWithLight(LevelChunkWithLight { + x: 3, + z: -4, + chunk: ChunkData { + heightmaps: vec![(4, vec![0; 37])], + buffer: vec![0, 0, 0, 0, 0, 0, 0, 0], + block_entities: vec![BlockEntityInfo { + packed_xz: 1, + y: 70, + kind: 3, + tag: Tag::End, + }], + }, + light: LightData { + sky_mask: vec![1], + block_mask: vec![], + empty_sky_mask: vec![], + empty_block_mask: vec![2], + sky: vec![vec![0xFF; 2048]], + block: vec![], + }, + }), + Clientbound::Login(Login { + player_id: 42, + hardcore: false, + levels: vec!["minecraft:overworld".into(), "minecraft:the_nether".into()], + max_players: 20, + chunk_radius: 10, + simulation_distance: 10, + reduced_debug_info: false, + show_death_screen: true, + limited_crafting: false, + spawn: spawn(), + online_mode: false, + enforces_secure_chat: false, + }), + Clientbound::MoveEntityPos(MoveEntityPos(MoveEntity { + id: 3, + delta: Some(VecDelta::Linear([4096, 0, -4096])), + rotation: None, + on_ground: true, + })), + Clientbound::MoveEntityPosRot(MoveEntityPosRot(MoveEntity { + id: 3, + delta: Some(VecDelta::Stepped(vec![([1, 2, 3], 1), ([0, 0, 1], 2)])), + rotation: Some((10, -10)), + on_ground: false, + })), + Clientbound::MoveEntityRot(MoveEntityRot(MoveEntity { + id: 3, + delta: None, + rotation: Some((1, 2)), + on_ground: true, + })), + Clientbound::OpenScreen(OpenScreen { + container: 1, + menu: 2, + title: literal("Chest"), + }), + Clientbound::PlayerChat(PlayerChat { + global_index: 0, + sender: 5, + index: 0, + signature: None, + content: "hello".into(), + timestamp: 1, + salt: 2, + last_seen: vec![(3, None), (-1, Some(vec![7; 256]))], + unsigned_content: None, + filter: (0, vec![]), + chat_type: ChatTypeBound { + chat_type: 0, + name: literal("Steve"), + target: None, + }, + }), + Clientbound::PlayerInfoUpdate(PlayerInfoUpdate { + actions: 0b0001_1101, + entries: vec![PlayerInfo { + uuid: 1, + name: Some("Steve".into()), + game_mode: Some(1), + listed: Some(true), + latency: Some(12), + ..PlayerInfo::default() + }], + }), + Clientbound::PlayerPosition(PlayerPosition { + teleport: 1, + position: [0.5, 70.0, 0.5], + delta: [0.0; 3], + yaw: 90.0, + pitch: 0.0, + relatives: relative::DELTA_X, + }), + Clientbound::Respawn(Respawn { + spawn: spawn(), + keep: 3, + }), + Clientbound::SectionBlocksUpdate(SectionBlocksUpdate { + section: [1, -4, 2], + changes: vec![(9 << 12) | 0x123], + }), + Clientbound::SetEntityData(SetEntityData { + id: 2, + values: vec![(8, 7, Value::Item(Some(Stack::new(5, 3))))], + }), + Clientbound::SetEntityMotion(SetEntityMotion { + id: 2, + velocity: [0.0; 3], + }), + Clientbound::SetEquipment(SetEquipment { + id: 2, + slots: vec![(0, None), (5, Some(Stack::new(1, 1)))], + }), + Clientbound::SetHealth(SetHealth { + health: 17.5, + food: 18, + saturation: 3.0, + }), + Clientbound::SetTime(SetTime { + game_time: 100, + clocks: vec![ClockState { + clock: 0, + total_ticks: 6000, + partial_tick: 0.0, + rate: 1.0, + }], + }), + Clientbound::Sound(Sound { + sound: (12, None), + source: 4, + x: 8, + y: 9, + z: 10, + volume: 1.0, + pitch: 1.0, + seed: 3, + }), + Clientbound::Sound(Sound { + sound: (-1, Some(("minecraft:x".into(), Some(16.0)))), + source: 0, + x: 0, + y: 0, + z: 0, + volume: 1.0, + pitch: 1.0, + seed: 0, + }), + Clientbound::SystemChat(SystemChat { + content: literal("hi"), + overlay: false, + }), + Clientbound::TeleportEntity(TeleportEntity { + id: 1, + position: [1.0; 3], + delta: [0.0; 3], + yaw: 0.0, + pitch: 0.0, + relatives: 0, + on_ground: true, + }), + ]; + for p in packets { + round_trip(p, Clientbound::encode, Clientbound::decode); + } + } + + #[test] + fn serverbound_round_trips() { + let packets = vec![ + Serverbound::AcceptTeleportation(AcceptTeleportation { + id: 1, + x: 0.5, + y: 64.0, + z: 0.5, + yaw: 0.0, + pitch: 0.0, + }), + Serverbound::Chat(Chat { + message: "hello".into(), + timestamp: 1, + salt: 0, + signature: None, + last_seen: LastSeenUpdate { + offset: 0, + acknowledged: [0; 3], + checksum: 0, + }, + }), + Serverbound::ChatCommand(ChatCommand { + command: "time set day".into(), + }), + Serverbound::ChunkBatchReceived(ChunkBatchReceived { + chunks_per_tick: 9.5, + }), + Serverbound::ClientCommand(ClientCommand { action: 0 }), + Serverbound::ClientTickEnd(Empty), + Serverbound::ContainerClick(ContainerClick { + container: 0, + state: 5, + slot: 36, + button: 0, + input: 0, + changed: vec![(36, None)], + carried: Some(Hashed::of(&Stack::new(1, 64))), + }), + Serverbound::MovePlayerPosRot(MovePlayerPosRot { + x: 1.0, + y: 2.0, + z: 3.0, + yaw: 4.0, + pitch: 5.0, + flags: 1, + }), + Serverbound::MovePlayerStatus(MovePlayerStatus { flags: 3 }), + Serverbound::PlayerAction(PlayerAction { + action: 0, + pos: [1, 2, 3], + direction: 1, + sequence: 7, + }), + Serverbound::PlayerInput(PlayerInput { flags: 0b0101_0001 }), + Serverbound::PlayerLoaded(Empty), + Serverbound::Punch(Empty), + Serverbound::SetCarriedItem(SetCarriedItem { slot: 4 }), + Serverbound::UseItemOn(UseItemOn { + hand: 0, + pos: [1, 64, 1], + face: 1, + cursor: [0.5, 1.0, 0.5], + inside: false, + world_border: false, + sequence: 8, + }), + Serverbound::Interact(Interact { + id: 9, + hand: 0, + location: [0.25, 1.0, 0.0], + secondary: false, + }), + ]; + for p in packets { + if let Serverbound::Interact(_) = &p { + // LpVec3 is lossy; check bytes instead. + let body = p.encode(); + let mut r = Reader::new(&body); + let id = r.varint().unwrap(); + assert!(matches!( + Serverbound::decode(id, r.rest()).unwrap(), + Serverbound::Interact(Interact { id: 9, .. }) + )); + continue; + } + round_trip(p, Serverbound::encode, Serverbound::decode); + } + } + + #[test] + fn move_entity_deltas_decode_like_vec_delta_codec() { + let base = [10.0, 64.0, -3.5]; + assert_eq!( + VecDelta::Linear([4096, 0, -2048]).end(base), + [11.0, 64.0, -4.0] + ); + // Zero deltas keep unquantized base coordinates exactly. + assert_eq!( + VecDelta::Linear([0, 0, 0]).end([0.123_456_789, 1.0, 2.0]), + [0.123_456_789, 1.0, 2.0] + ); + assert_eq!( + VecDelta::Stepped(vec![([4096, 0, 0], 1), ([4096, 0, 0], 2)]).end(base), + [12.0, 64.0, -3.5] + ); + } + + #[test] + fn unknown_packets_keep_their_payload() { + let p = Clientbound::decode(crate::ids::play::clientbound::BOSS_EVENT, &[1, 2, 3]).unwrap(); + assert_eq!( + p, + Clientbound::Unknown(crate::ids::play::clientbound::BOSS_EVENT, vec![1, 2, 3]) + ); + assert_eq!(p.encode()[1..], [1, 2, 3]); + } +} diff --git a/crates/horizon-protocol/src/packets/status.rs b/crates/horizon-protocol/src/packets/status.rs new file mode 100644 index 000000000..7df73880f --- /dev/null +++ b/crates/horizon-protocol/src/packets/status.rs @@ -0,0 +1,50 @@ +//! Status state: server list ping. +use crate::{ + buf::{Long, Str}, + packet, packet_enum, + packets::Empty, +}; + +packet!(StatusResponse { json: String => Str }); +packet!(Ping { time: i64 => Long }); + +packet_enum!(Clientbound, crate::ids::status::clientbound { + StatusResponse(StatusResponse) = STATUS_RESPONSE, + PongResponse(Ping) = PONG_RESPONSE, +}); +packet_enum!(Serverbound, crate::ids::status::serverbound { + StatusRequest(Empty) = STATUS_REQUEST, + PingRequest(Ping) = PING_REQUEST, +}); + +#[cfg(test)] +mod tests { + use super::*; + use crate::packets::round_trip; + + #[test] + fn status_round_trips() { + round_trip( + Clientbound::StatusResponse(StatusResponse { + json: "{\"version\":{}}".into(), + }), + Clientbound::encode, + Clientbound::decode, + ); + round_trip( + Clientbound::PongResponse(Ping { time: 123 }), + Clientbound::encode, + Clientbound::decode, + ); + round_trip( + Serverbound::StatusRequest(Empty), + Serverbound::encode, + Serverbound::decode, + ); + round_trip( + Serverbound::PingRequest(Ping { time: -5 }), + Serverbound::encode, + Serverbound::decode, + ); + } +} diff --git a/crates/horizon-protocol/src/registry.rs b/crates/horizon-protocol/src/registry.rs new file mode 100644 index 000000000..f97401670 --- /dev/null +++ b/crates/horizon-protocol/src/registry.rs @@ -0,0 +1,221 @@ +//! Registry id tables. Built-in registries (items, entity types, menus, sound +//! events ...) have fixed network ids, read from the data generator's +//! registries report. Data-driven registries (dimension types, biomes, chat +//! types, damage types ...) are numbered in the order the server sends them +//! during configuration. +use crate::{Error, Result, packets::configuration::RegistryData}; +use horizon_world::nbt::{JavaString, Tag}; +use std::{collections::HashMap, path::Path}; + +/// One registry: names by network id and the reverse lookup. +#[derive(Clone, Debug, Default)] +pub struct Ids { + pub names: Vec, + pub ids: HashMap, +} +impl Ids { + pub fn from_names(names: Vec) -> Self { + let ids = names + .iter() + .enumerate() + .map(|(i, n)| (n.clone(), i as i32)) + .collect(); + Self { names, ids } + } + pub fn name(&self, id: i32) -> Option<&str> { + usize::try_from(id) + .ok() + .and_then(|i| self.names.get(i)) + .map(String::as_str) + } + pub fn id(&self, name: &str) -> Option { + self.ids.get(name).copied() + } +} + +/// The built-in registries from `registries.json` (`--reports`). +#[derive(Clone, Debug, Default)] +pub struct Builtin { + pub registries: HashMap, +} +impl Builtin { + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path) + .map_err(|e| Error::new(format!("{}: {e}", path.display())))?; + Self::parse(&text) + } + pub fn parse(text: &str) -> Result { + let json: serde_json::Value = serde_json::from_str(text) + .map_err(|e| Error::new(format!("registries report: {e}")))?; + let mut registries = HashMap::new(); + for (name, registry) in json + .as_object() + .ok_or_else(|| Error::new("registries report is not an object"))? + { + let Some(entries) = registry["entries"].as_object() else { + continue; + }; + let mut names = vec![String::new(); entries.len()]; + for (entry, value) in entries { + let id = value["protocol_id"] + .as_u64() + .ok_or_else(|| Error::new(format!("{entry}: no protocol_id")))? + as usize; + if id >= names.len() { + names.resize(id + 1, String::new()); + } + names[id] = entry.clone(); + } + registries.insert(name.clone(), Ids::from_names(names)); + } + Ok(Self { registries }) + } + pub fn get(&self, registry: &str) -> Option<&Ids> { + self.registries.get(registry) + } + /// Look for the report next to prepared resources, then in the data + /// generator output of a development checkout. + pub fn find(resources: &Path) -> Option { + let candidates = [ + resources.join("registries.json"), + resources.join("../../datagen/out/reports/registries.json"), + resources.join("../datagen/out/reports/registries.json"), + ]; + candidates.into_iter().find(|p| p.is_file()) + } +} + +/// Registries synchronized during configuration, in arrival order. +#[derive(Clone, Debug, Default)] +pub struct Dynamic { + pub registries: HashMap)>>, +} +impl Dynamic { + pub fn add(&mut self, packet: RegistryData) { + let entries = packet.entries.into_iter().map(|e| (e.id, e.data)).collect(); + self.registries.insert(packet.registry, entries); + } + pub fn name(&self, registry: &str, id: i32) -> Option<&str> { + let i = usize::try_from(id).ok()?; + self.registries + .get(registry)? + .get(i) + .map(|(n, _)| n.as_str()) + } + pub fn data(&self, registry: &str, id: i32) -> Option<&Tag> { + let i = usize::try_from(id).ok()?; + self.registries.get(registry)?.get(i)?.1.as_ref() + } + pub fn len(&self, registry: &str) -> usize { + self.registries.get(registry).map_or(0, Vec::len) + } + pub fn is_empty(&self) -> bool { + self.registries.is_empty() + } + /// The dimension type's vertical range and sky light, from its + /// synchronized data or the vanilla defaults for known names. + pub fn dimension(&self, id: i32) -> DimensionType { + let name = self + .name("minecraft:dimension_type", id) + .unwrap_or("minecraft:overworld"); + let mut d = DimensionType::vanilla(name); + if let Some(Tag::Compound(map)) = self.data("minecraft:dimension_type", id) { + let int = |k: &str| match map.get(&JavaString::from(k)) { + Some(Tag::Int(v)) => Some(*v), + _ => None, + }; + if let Some(v) = int("min_y") { + d.min_y = v; + } + if let Some(v) = int("height") { + d.height = v; + } + if let Some(Tag::Byte(v)) = map.get(&JavaString::from("has_skylight")) { + d.has_skylight = *v != 0; + } + } + d + } +} +/// The parts of a DimensionType the client needs for chunk layout. +#[derive(Clone, Debug, PartialEq)] +pub struct DimensionType { + pub name: String, + pub min_y: i32, + pub height: i32, + pub has_skylight: bool, +} +impl DimensionType { + pub fn vanilla(name: &str) -> Self { + let (min_y, height, has_skylight) = match name { + "minecraft:the_nether" => (0, 256, false), + "minecraft:the_end" => (0, 256, false), + _ => (-64, 384, true), + }; + Self { + name: name.to_owned(), + min_y, + height, + has_skylight, + } + } + pub fn sections(&self) -> usize { + (self.height / 16) as usize + } +} + +/// Mth.ceillog2(n): bits for a global palette over `n` values. +pub fn ceil_log2(n: usize) -> u8 { + if n <= 1 { + 0 + } else { + (usize::BITS - (n - 1).leading_zeros()) as u8 + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::packets::configuration::RegistryEntry; + + #[test] + fn parses_registry_reports() { + let report = r#"{"minecraft:item":{"default":"minecraft:air","entries":{"minecraft:stone":{"protocol_id":1},"minecraft:air":{"protocol_id":0}},"protocol_id":5}}"#; + let b = Builtin::parse(report).unwrap(); + let items = b.get("minecraft:item").unwrap(); + assert_eq!(items.name(1), Some("minecraft:stone")); + assert_eq!(items.id("minecraft:air"), Some(0)); + assert_eq!(items.name(2), None); + } + + #[test] + fn dynamic_registries_follow_arrival_order() { + let mut d = Dynamic::default(); + d.add(RegistryData { + registry: "minecraft:dimension_type".into(), + entries: vec![ + RegistryEntry { + id: "minecraft:overworld".into(), + data: None, + }, + RegistryEntry { + id: "minecraft:the_nether".into(), + data: Some(Tag::compound([ + ("min_y", Tag::Int(0)), + ("height", Tag::Int(256)), + ("has_skylight", Tag::Byte(0)), + ])), + }, + ], + }); + assert_eq!( + d.dimension(0), + DimensionType::vanilla("minecraft:overworld") + ); + assert_eq!(d.dimension(1).sections(), 16); + assert!(!d.dimension(1).has_skylight); + assert_eq!(ceil_log2(35723), 16); + assert_eq!(ceil_log2(65), 7); + assert_eq!(ceil_log2(64), 6); + } +} diff --git a/crates/horizon-protocol/src/servers.rs b/crates/horizon-protocol/src/servers.rs new file mode 100644 index 000000000..1540df20a --- /dev/null +++ b/crates/horizon-protocol/src/servers.rs @@ -0,0 +1,149 @@ +//! The multiplayer server list, stored like vanilla's ServerList in an +//! uncompressed `servers.dat`: `{servers: [{name, ip, icon?, acceptTextures?}]}`. +use horizon_world::nbt::{self, JavaString, NamedTag, Tag}; +use std::path::Path; + +#[derive(Clone, Debug, PartialEq)] +pub struct ServerEntry { + pub name: String, + pub ip: String, + /// Base64 PNG favicon from the last status ping. + pub icon: Option, + /// ServerPackStatus: None = prompt, Some(true) enabled, Some(false) disabled. + pub accept_textures: Option, +} +impl ServerEntry { + pub fn new(name: &str, ip: &str) -> Self { + Self { + name: name.to_owned(), + ip: ip.to_owned(), + icon: None, + accept_textures: None, + } + } + fn to_tag(&self) -> Tag { + let mut entries = vec![ + ("name", Tag::String(JavaString::from(self.name.as_str()))), + ("ip", Tag::String(JavaString::from(self.ip.as_str()))), + ]; + if let Some(icon) = &self.icon { + entries.push(("icon", Tag::String(JavaString::from(icon.as_str())))); + } + if let Some(accept) = self.accept_textures { + entries.push(("acceptTextures", Tag::Byte(i8::from(accept)))); + } + Tag::compound(entries) + } + fn from_tag(tag: &Tag) -> Option { + let string = |k: &str| match tag.get(k) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + }; + Some(Self { + name: string("name").unwrap_or_default(), + ip: string("ip")?, + icon: string("icon"), + accept_textures: match tag.get("acceptTextures") { + Some(Tag::Byte(b)) => Some(*b != 0), + _ => None, + }, + }) + } +} + +/// ServerList.load: missing or unreadable files give an empty list. +pub fn load(path: &Path) -> Vec { + let Ok(bytes) = std::fs::read(path) else { + return Vec::new(); + }; + let Ok((root, _)) = nbt::read_named(&bytes, nbt::Limits::default()) else { + return Vec::new(); + }; + // ServerList skips entries flagged "hidden" (the LAN/quick-play ones). + match root.tag.get("servers") { + Some(Tag::List(list)) => list + .iter() + .filter(|t| !matches!(t.get("hidden"), Some(Tag::Byte(1)))) + .filter_map(ServerEntry::from_tag) + .collect(), + _ => Vec::new(), + } +} +/// ServerList.save: write to a temporary file, then replace. +pub fn save(path: &Path, servers: &[ServerEntry]) -> std::io::Result<()> { + let root = NamedTag { + name: JavaString::from(""), + tag: Tag::compound([( + "servers", + Tag::List(servers.iter().map(ServerEntry::to_tag).collect()), + )]), + }; + let bytes = nbt::write_named(&root, nbt::Limits::default()).map_err(std::io::Error::other)?; + let tmp = path.with_extension("dat_tmp"); + std::fs::write(&tmp, bytes)?; + std::fs::rename(tmp, path) +} + +/// ServerAddress.parseString: `host`, `host:port` or `[v6]:port`; default 25565. +pub fn parse_address(text: &str) -> Option<(String, u16)> { + let text = text.trim(); + if text.is_empty() { + return None; + } + if let Some(rest) = text.strip_prefix('[') { + let (host, tail) = rest.split_once(']')?; + let port = match tail.strip_prefix(':') { + Some(p) => p.parse().ok()?, + None if tail.is_empty() => 25565, + None => return None, + }; + return Some((host.to_owned(), port)); + } + match text.rsplit_once(':') { + Some((host, port)) if !host.contains(':') => Some((host.to_owned(), port.parse().ok()?)), + Some(_) => Some((text.to_owned(), 25565)), + None => Some((text.to_owned(), 25565)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn servers_dat_round_trips() { + let dir = std::env::temp_dir().join(format!("horizon-servers-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("servers.dat"); + let list = vec![ + ServerEntry::new("Minecraft Server", "localhost:25565"), + ServerEntry { + accept_textures: Some(false), + ..ServerEntry::new("Other", "example.org") + }, + ]; + save(&path, &list).unwrap(); + assert_eq!(load(&path), list); + // Vanilla layout: an unnamed root compound with a "servers" list. + let (root, _) = + nbt::read_named(&std::fs::read(&path).unwrap(), nbt::Limits::default()).unwrap(); + assert_eq!(root.name, JavaString::from("")); + assert!(matches!(root.tag.get("servers"), Some(Tag::List(l)) if l.len() == 2)); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn parses_addresses_like_server_address() { + assert_eq!( + parse_address("localhost"), + Some(("localhost".into(), 25565)) + ); + assert_eq!( + parse_address("127.0.0.1:25570"), + Some(("127.0.0.1".into(), 25570)) + ); + assert_eq!(parse_address("[::1]:1234"), Some(("::1".into(), 1234))); + assert_eq!(parse_address("host:notaport"), None); + assert_eq!(parse_address(""), None); + } +} diff --git a/crates/horizon-protocol/src/text.rs b/crates/horizon-protocol/src/text.rs new file mode 100644 index 000000000..7a23f16a8 --- /dev/null +++ b/crates/horizon-protocol/src/text.rs @@ -0,0 +1,190 @@ +//! Chat components as sent on the network (ComponentSerialization in NBT form) +//! flattened to display strings, with `translate` keys resolved through a +//! language table (en_us.json) and Java `String.format` style arguments. +use horizon_world::nbt::{JavaString, Tag}; +use std::collections::HashMap; + +/// A language table: translation key -> pattern. +pub type Language = HashMap; + +fn string(tag: &Tag) -> Option { + match tag { + Tag::String(s) => Some(s.to_string_lossy()), + _ => None, + } +} +fn get<'t>(tag: &'t Tag, key: &str) -> Option<&'t Tag> { + match tag { + Tag::Compound(map) => map.get(&JavaString::from(key)), + _ => None, + } +} + +/// Flatten a component to text. +pub fn plain(tag: &Tag, lang: &Language) -> String { + let mut out = String::new(); + append(tag, lang, &mut out, 0); + out +} +fn append(tag: &Tag, lang: &Language, out: &mut String, depth: usize) { + if depth > 32 { + return; + } + match tag { + Tag::String(s) => out.push_str(&s.to_string_lossy()), + Tag::Byte(v) => out.push_str(&v.to_string()), + Tag::Short(v) => out.push_str(&v.to_string()), + Tag::Int(v) => out.push_str(&v.to_string()), + Tag::Long(v) => out.push_str(&v.to_string()), + Tag::Float(v) => out.push_str(&f32::from_bits(*v).to_string()), + Tag::Double(v) => out.push_str(&f64::from_bits(*v).to_string()), + // A list is its first element with the rest appended as siblings. + Tag::List(items) => { + for item in items { + append(item, lang, out, depth + 1); + } + } + Tag::Compound(_) => { + if let Some(text) = get(tag, "text").and_then(string) { + out.push_str(&text); + } else if let Some(text) = get(tag, "").and_then(string) { + // Mixed-list wrapper for a bare string. + out.push_str(&text); + } else if let Some(key) = get(tag, "translate").and_then(string) { + let args: Vec = match get(tag, "with") { + Some(Tag::List(args)) => args + .iter() + .map(|a| { + let mut s = String::new(); + append(a, lang, &mut s, depth + 1); + s + }) + .collect(), + _ => Vec::new(), + }; + let pattern = lang + .get(&key) + .cloned() + .or_else(|| get(tag, "fallback").and_then(string)) + .unwrap_or_else(|| key.clone()); + out.push_str(&format_java(&pattern, &args)); + } else if let Some(key) = get(tag, "keybind").and_then(string) { + out.push_str(lang.get(&key).map_or(key.as_str(), String::as_str)); + } else if let Some(selector) = get(tag, "selector").and_then(string) { + out.push_str(&selector); + } else if let Some(score) = get(tag, "score") { + if let Some(name) = get(score, "name").and_then(string) { + out.push_str(&name); + } + } + if let Some(Tag::List(extra)) = get(tag, "extra") { + for e in extra { + append(e, lang, out, depth + 1); + } + } + } + _ => {} + } +} + +/// TranslatableContents.decomposeTemplate: `%s`, `%n$s` and `%%`. +pub fn format_java(pattern: &str, args: &[String]) -> String { + let mut out = String::new(); + let mut next = 0usize; + let mut chars = pattern.char_indices().peekable(); + while let Some((_, c)) = chars.next() { + if c != '%' { + out.push(c); + continue; + } + let mut digits = String::new(); + while let Some(&(_, d)) = chars.peek() { + if d.is_ascii_digit() { + digits.push(d); + chars.next(); + } else { + break; + } + } + match chars.next() { + Some((_, '%')) if digits.is_empty() => out.push('%'), + Some((_, '$')) if !digits.is_empty() => { + if chars.next().map(|(_, c)| c) == Some('s') { + let i = digits.parse::().unwrap_or(1).saturating_sub(1); + out.push_str(args.get(i).map_or("", String::as_str)); + } + } + Some((_, 's')) if digits.is_empty() => { + out.push_str(args.get(next).map_or("", String::as_str)); + next += 1; + } + Some((_, other)) => { + out.push('%'); + out.push_str(&digits); + out.push(other); + } + None => out.push('%'), + } + } + out +} + +/// A literal text component. +pub fn literal(text: &str) -> Tag { + Tag::String(JavaString::from(text)) +} +/// A translatable component with literal arguments. +pub fn translatable(key: &str, args: &[&str]) -> Tag { + let mut entries = vec![("translate", Tag::String(JavaString::from(key)))]; + if !args.is_empty() { + entries.push(("with", Tag::List(args.iter().map(|a| literal(a)).collect()))); + } + Tag::compound(entries) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn formats_like_translatable_contents() { + let args = vec!["Steve".to_owned(), "hi".to_owned()]; + assert_eq!(format_java("<%s> %s", &args), " hi"); + assert_eq!(format_java("%2$s by %1$s", &args), "hi by Steve"); + assert_eq!(format_java("100%% sure", &[]), "100% sure"); + } + + #[test] + fn flattens_components() { + let mut lang = Language::new(); + lang.insert( + "multiplayer.player.joined".into(), + "%s joined the game".into(), + ); + let joined = Tag::compound([ + ("translate", Tag::String("multiplayer.player.joined".into())), + ( + "with", + Tag::List(vec![Tag::compound([("text", Tag::String("Alex".into()))])]), + ), + ("color", Tag::String("yellow".into())), + ]); + assert_eq!(plain(&joined, &lang), "Alex joined the game"); + let extra = Tag::compound([ + ("text", Tag::String("a".into())), + ( + "extra", + Tag::List(vec![ + literal("b"), + Tag::compound([("text", Tag::String("c".into()))]), + ]), + ), + ]); + assert_eq!(plain(&extra, &lang), "abc"); + assert_eq!( + plain(&translatable("missing.key", &[]), &lang), + "missing.key" + ); + assert_eq!(plain(&literal("plain"), &lang), "plain"); + } +} diff --git a/tools/generate_packet_ids.py b/tools/generate_packet_ids.py new file mode 100644 index 000000000..c5c0b90f8 --- /dev/null +++ b/tools/generate_packet_ids.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Generate crates/horizon-protocol/src/ids.rs from the vanilla data generator's +packets report (`java -DbundlerMainClass=net.minecraft.data.Main -jar server.jar --reports`). + +Packet ids are protocol facts (the order packets are registered in each +connection state); the report is the authoritative source for them. +""" + +import argparse +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +STATES = ["handshake", "status", "login", "configuration", "play"] +DIRECTIONS = ["clientbound", "serverbound"] + + +def const_name(name): + return name.split(":", 1)[1].replace("/", "_").upper() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--report", type=Path, default=ROOT / ".local/datagen/out/reports/packets.json") + parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-protocol/src/ids.rs") + args = parser.parse_args() + report = json.loads(args.report.read_text()) + lines = [ + "//! Packet ids per connection state and direction for protocol 777 (26.3).", + "//! Generated by tools/generate_packet_ids.py from the data generator's", + "//! packets report; do not edit by hand.", + "#![allow(missing_docs)]", + "use crate::{Direction, State};", + "", + ] + tables = [] + for state in STATES: + lines.append(f"pub mod {state} {{") + for direction in DIRECTIONS: + packets = report.get(state, {}).get(direction, {}) + if not packets: + continue + ordered = sorted(packets.items(), key=lambda kv: kv[1]["protocol_id"]) + assert [e["protocol_id"] for _, e in ordered] == list(range(len(ordered))), (state, direction) + lines.append(f" pub mod {direction} {{") + for name, entry in ordered: + lines.append(f" pub const {const_name(name)}: i32 = {entry['protocol_id']};") + lines.append(" /// Packet names indexed by id.") + names = ", ".join(f'"{name.split(":", 1)[1]}"' for name, _ in ordered) + lines.append(f" pub const NAMES: &[&str] = &[{names}];") + lines.append(" }") + tables.append((state, direction)) + lines.append("}") + lines.append("") + lines.append("/// The packet name for an id, if the state and direction define it.") + lines.append("pub fn name(state: State, direction: Direction, id: i32) -> Option<&'static str> {") + lines.append(" let names: &[&str] = match (state, direction) {") + for state, direction in tables: + lines.append( + f" (State::{state.capitalize()}, Direction::{direction.capitalize()}) => {state}::{direction}::NAMES," + ) + lines.append(" _ => &[],") + lines.append(" };") + lines.append(" usize::try_from(id).ok().and_then(|i| names.get(i)).copied()") + lines.append("}") + args.out.write_text("\n".join(lines) + "\n") + + +if __name__ == "__main__": + main()