Merge remote-tracking branch 'origin/wip/parity-net' into t3/minecraft-parity

# Conflicts:
#	crates/horizon-client/src/game.rs
This commit is contained in:
Ludovic Marie
2026-10-08 23:19:58 +02:00
32 changed files with 7802 additions and 6 deletions
Generated
+10
View File
@@ -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"
+1 -1
View File
@@ -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]
+1
View File
@@ -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"
+47 -2
View File
@@ -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<PathBuf>,
/// Multiplayer: `--server HOST[:PORT]` joins at start; `--name` is the offline player name.
server: Option<String>,
player_name: String,
}
impl Options {
fn read() -> Result<Option<Self>> {
@@ -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<std::sync::mpsc::Sender<String>>,
pending_bench: Option<(Instant, std::sync::mpsc::Sender<String>)>,
persist: persist::EntityMemory,
/// Connected to a server: the world comes from the network (game/remote.rs).
remote: Option<remote::Remote>,
}
#[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<ItemStack> = 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)?;
+35
View File
@@ -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(),
})
}
}
File diff suppressed because it is too large Load Diff
+2
View File
@@ -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;
+276
View File
@@ -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<Mutex<HashMap<String, Ping>>>;
#[derive(Clone, Debug)]
pub enum Screen {
List { servers: Vec<ServerEntry>, selected: Option<usize>, pings: Pings },
/// Add (index None) or edit a server entry.
Edit { index: Option<usize>, 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<ButtonSpec> {
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<u8>, 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<String> {
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
}
+295
View File
@@ -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<Dynamic>, uuid: u128, name: String },
Packet(Box<play::Clientbound>),
/// 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<Dynamic>),
Disconnected(String),
}
pub struct Session {
events: Receiver<Event>,
writer: Arc<Mutex<Option<ConnWriter>>>,
thread: Option<JoinHandle<()>>,
pub address: String,
pub name: String,
pub counters: Arc<Mutex<Option<Arc<Counters>>>>,
/// 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<Language>) -> 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<Event> {
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<Event>, 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<Event>,
shared_writer: &Mutex<Option<ConnWriter>>,
shared_counters: &Mutex<Option<Arc<Counters>>>,
) -> Result<String, String> {
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::<serde_json::Value>(&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<Option<ConnWriter>>, lang: &Language) -> Result<Dynamic, String> {
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<u8> {
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<String> = 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()))
}
+28 -2
View File
@@ -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<crate::assets::Assets>,
@@ -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<Arc<Chunk>> {
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 {
+31 -1
View File
@@ -18,6 +18,7 @@ pub enum Mode {
Main,
Select { worlds: Vec<WorldEntry>, selected: Option<usize> },
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<i64>, 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,
+12
View File
@@ -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"
+209
View File
@@ -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<dyn std::error::Error>> {
let args: Vec<String> = 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(())
}
+686
View File
@@ -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<const N: usize>(&mut self) -> Result<[u8; N]> {
Ok(self.bytes(N)?.try_into().expect("length checked"))
}
pub fn u8(&mut self) -> Result<u8> {
Ok(self.array::<1>()?[0])
}
pub fn i8(&mut self) -> Result<i8> {
Ok(self.u8()? as i8)
}
pub fn bool(&mut self) -> Result<bool> {
Ok(self.u8()? != 0)
}
pub fn i16(&mut self) -> Result<i16> {
Ok(i16::from_be_bytes(self.array()?))
}
pub fn u16(&mut self) -> Result<u16> {
Ok(u16::from_be_bytes(self.array()?))
}
pub fn i32(&mut self) -> Result<i32> {
Ok(i32::from_be_bytes(self.array()?))
}
pub fn u32(&mut self) -> Result<u32> {
Ok(u32::from_be_bytes(self.array()?))
}
pub fn i64(&mut self) -> Result<i64> {
Ok(i64::from_be_bytes(self.array()?))
}
pub fn f32(&mut self) -> Result<f32> {
Ok(f32::from_be_bytes(self.array()?))
}
pub fn f64(&mut self) -> Result<f64> {
Ok(f64::from_be_bytes(self.array()?))
}
/// VarInt.read: at most five 7-bit groups, least significant first.
pub fn varint(&mut self) -> Result<i32> {
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<i64> {
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<usize> {
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<String> {
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<Vec<u8>> {
let len = self.count(max)?;
Ok(self.bytes(len)?.to_vec())
}
pub fn uuid(&mut self) -> Result<u128> {
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<Tag> {
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<Vec<i64>> {
let n = self.count(self.remaining() / 8)?;
(0..n).map(|_| self.i64()).collect()
}
pub fn fixed_longs(&mut self, n: usize) -> Result<Vec<i64>> {
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<u8>,
}
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<u8>, 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<T> {
fn read(r: &mut Reader) -> Result<T>;
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<String> for Str {
fn read(r: &mut Reader) -> Result<String> {
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<const N: usize>;
impl<const N: usize> Codec<String> for StrN<N> {
fn read(r: &mut Reader) -> Result<String> {
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<Vec<u8>> for Bytes {
fn read(r: &mut Reader) -> Result<Vec<u8>> {
r.byte_array(r.remaining())
}
fn write(v: &Vec<u8>, w: &mut Writer) {
w.byte_array(v)
}
}
/// Everything left in the packet (custom payloads).
pub struct Rest;
impl Codec<Vec<u8>> for Rest {
fn read(r: &mut Reader) -> Result<Vec<u8>> {
Ok(r.rest().to_vec())
}
fn write(v: &Vec<u8>, w: &mut Writer) {
w.bytes(v)
}
}
/// Any network NBT tag (`Tag::End` when absent).
pub struct Nbt;
impl Codec<Tag> for Nbt {
fn read(r: &mut Reader) -> Result<Tag> {
r.nbt()
}
fn write(v: &Tag, w: &mut Writer) {
w.nbt(v)
}
}
/// ByteBufCodecs.LONG_ARRAY.
pub struct Longs;
impl Codec<Vec<i64>> for Longs {
fn read(r: &mut Reader) -> Result<Vec<i64>> {
r.long_array()
}
fn write(v: &Vec<i64>, w: &mut Writer) {
w.long_array(v)
}
}
/// ByteBufCodecs.list(): VarInt count then elements.
pub struct List<C>(PhantomData<C>);
impl<T, C: Codec<T>> Codec<Vec<T>> for List<C> {
fn read(r: &mut Reader) -> Result<Vec<T>> {
let n = r.count(r.remaining())?;
(0..n).map(|_| C::read(r)).collect()
}
fn write(v: &Vec<T>, 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<C>(PhantomData<C>);
impl<T, C: Codec<T>> Codec<Option<T>> for Opt<C> {
fn read(r: &mut Reader) -> Result<Option<T>> {
if r.bool()? {
Ok(Some(C::read(r)?))
} else {
Ok(None)
}
}
fn write(v: &Option<T>, 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<Option<i32>> for OptVarInt {
fn read(r: &mut Reader) -> Result<Option<i32>> {
let v = r.varint()?;
Ok(if v == 0 { None } else { Some(v - 1) })
}
fn write(v: &Option<i32>, 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<Vec<u8>> for BitSet {
fn read(r: &mut Reader) -> Result<Vec<u8>> {
r.byte_array(r.remaining())
}
fn write(v: &Vec<u8>, 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<u8>, 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<T: PartialEq + std::fmt::Debug, C: Codec<T>>(v: T) -> Vec<u8> {
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::<i32, VarInt>(0), [0x00]);
assert_eq!(round::<i32, VarInt>(1), [0x01]);
assert_eq!(round::<i32, VarInt>(127), [0x7f]);
assert_eq!(round::<i32, VarInt>(128), [0x80, 0x01]);
assert_eq!(round::<i32, VarInt>(255), [0xff, 0x01]);
assert_eq!(round::<i32, VarInt>(25565), [0xdd, 0xc7, 0x01]);
assert_eq!(round::<i32, VarInt>(2097151), [0xff, 0xff, 0x7f]);
assert_eq!(
round::<i32, VarInt>(i32::MAX),
[0xff, 0xff, 0xff, 0xff, 0x07]
);
assert_eq!(round::<i32, VarInt>(-1), [0xff, 0xff, 0xff, 0xff, 0x0f]);
assert_eq!(
round::<i32, VarInt>(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::<i32, VarInt>(v).len());
}
assert!(Reader::new(&[0xff; 6]).varint().is_err());
}
#[test]
fn varlong_matches_vanilla_examples() {
assert_eq!(round::<i64, VarLong>(0), [0x00]);
assert_eq!(
round::<i64, VarLong>(2147483647),
[0xff, 0xff, 0xff, 0xff, 0x07]
);
assert_eq!(
round::<i64, VarLong>(i64::MAX),
[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f]
);
assert_eq!(
round::<i64, VarLong>(-1),
[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]
);
assert_eq!(
round::<i64, VarLong>(i64::MIN),
[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01]
);
}
#[test]
fn strings_positions_and_options() {
assert_eq!(round::<String, Str>("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::<Option<String>, Opt<Str>>(Some("x".into()));
round::<Option<String>, Opt<Str>>(None);
round::<Option<i32>, OptVarInt>(Some(0));
round::<Vec<i32>, List<VarInt>>(vec![1, 300, -1]);
round::<u128, Uuid>(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);
}
}
+393
View File
@@ -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<i32>,
pub data: Vec<i64>,
}
impl Paletted {
pub fn read(r: &mut Reader, strategy: Strategy, global_bits: u8) -> Result<Self> {
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::<Result<_>>()?
};
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<i32> = 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<Self> {
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<Vec<(i32, Vec<i64>)>> for Heightmaps {
fn read(r: &mut Reader) -> Result<Vec<(i32, Vec<i64>)>> {
let n = r.count(16)?;
(0..n).map(|_| Ok((r.varint()?, r.long_array()?))).collect()
}
fn write(v: &Vec<(i32, Vec<i64>)>, 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<i64>)> => Heightmaps,
buffer: Vec<u8> => Bytes,
block_entities: Vec<BlockEntityInfo> => crate::buf::List<BlockEntityInfo>,
}
);
impl ChunkData {
/// Decode `count` sections from the buffer.
pub fn sections(&self, count: usize, block_bits: u8, biome_bits: u8) -> Result<Vec<Section>> {
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<u8> {
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<Vec<Vec<u8>>> for Layers {
fn read(r: &mut Reader) -> Result<Vec<Vec<u8>>> {
let n = r.count(r.remaining())?;
(0..n).map(|_| r.byte_array(2048)).collect()
}
fn write(v: &Vec<Vec<u8>>, 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<u8> => BitSet,
block_mask: Vec<u8> => BitSet,
empty_sky_mask: Vec<u8> => BitSet,
empty_block_mask: Vec<u8> => BitSet,
sky: Vec<Vec<u8>> => Layers,
block: Vec<Vec<u8>> => 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<SectionLight> {
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<Vec<u8>>, Option<Vec<u8>>);
/// 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<i32> = (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<i32> = (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<i32> = (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());
}
}
+183
View File
@@ -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<u8>,
decrypt: Option<Cfb8>,
pub threshold: Option<usize>,
pub counters: Arc<Counters>,
}
pub struct ConnWriter {
stream: TcpStream,
encrypt: Option<Cfb8>,
pub threshold: Option<usize>,
counters: Arc<Counters>,
}
/// 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<Self> {
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<Self> {
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<u8>)> {
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<u8>)> {
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<Duration>) -> 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();
}
}
+275
View File
@@ -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<u32> = (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<u32> = 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<u8> {
(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"
);
}
}
+189
View File
@@ -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<Tag>),
Item(Option<Stack>),
Bool(bool),
Floats(Vec<f32>),
Pos([i32; 3]),
OptPos(Option<[i32; 3]>),
OptUuid(Option<u128>),
/// 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<Option<Value>> {
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<Vec<(u8, i32, Value)>> for EntityData {
fn read(r: &mut Reader) -> Result<Vec<(u8, i32, Value)>> {
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))]);
}
}
+155
View File
@@ -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<usize>) -> Result<Vec<u8>> {
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<u8>) -> Result<Option<Vec<u8>>> {
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<u8>, threshold: Option<usize>) -> Result<Vec<u8>> {
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<u8> = (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());
}
}
+590
View File
@@ -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()
}
+337
View File
@@ -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<Tag>),
Enchantments(Vec<(i32, i32)>),
CustomModelData {
floats: Vec<f32>,
flags: Vec<bool>,
strings: Vec<String>,
colors: Vec<i32>,
},
TooltipDisplay {
hide: bool,
hidden: Vec<i32>,
},
}
impl Component {
fn read(kind: i32, r: &mut Reader) -> Result<Self> {
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::<Result<_>>()?)
}
ENCHANTMENTS | STORED_ENCHANTMENTS => {
let n = r.count(r.remaining())?;
Self::Enchantments(
(0..n)
.map(|_| Ok((r.varint()?, r.varint()?)))
.collect::<Result<_>>()?,
)
}
CUSTOM_MODEL_DATA => {
let n = r.count(r.remaining())?;
let floats = (0..n).map(|_| r.f32()).collect::<Result<_>>()?;
let n = r.count(r.remaining())?;
let flags = (0..n).map(|_| r.bool()).collect::<Result<_>>()?;
let n = r.count(r.remaining())?;
let strings = (0..n).map(|_| r.string(32767)).collect::<Result<_>>()?;
let n = r.count(r.remaining())?;
let colors = (0..n).map(|_| r.i32()).collect::<Result<_>>()?;
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::<Result<_>>()?,
}
}
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<i32>,
}
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<Option<Stack>> for Slot {
fn read(r: &mut Reader) -> Result<Option<Stack>> {
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::<Result<_>>()?;
Ok(Some(Stack {
item,
count,
added,
removed,
}))
}
fn write(v: &Option<Stack>, 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<i32>,
}
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<Option<Hashed>> for HashedSlot {
fn read(r: &mut Reader) -> Result<Option<Hashed>> {
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::<Result<_>>()?;
let n = r.count(256)?;
let removed = (0..n).map(|_| r.varint()).collect::<Result<_>>()?;
Ok(Some(Hashed {
item,
count,
added,
removed,
}))
}
fn write(v: &Option<Hashed>, 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<T: PartialEq + std::fmt::Debug, C: Codec<T>>(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::<Option<Stack>, Slot>(None);
round::<Option<Stack>, 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::<Option<Stack>, Slot>(Some(sword.clone()));
round::<Option<Hashed>, HashedSlot>(Some(Hashed::of(&sword)));
round::<Option<Hashed>, 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());
}
}
+58
View File
@@ -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<String>) -> 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<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Self(e.to_string())
}
}
pub type Result<T> = std::result::Result<T, Error>;
@@ -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<u8> => 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<Tag> => Opt<Nbt> }
);
packet!(RegistryData { registry: String => Ident, entries: Vec<RegistryEntry> => List<RegistryEntry> });
packet!(ResourcePackPop { id: Option<u128> => Opt<Uuid> });
packet!(ResourcePackPush {
id: u128 => Uuid,
url: String => Str,
hash: String => StrN<40>,
required: bool => Bool,
prompt: Option<Tag> => Opt<Nbt>,
});
packet!(StoreCookie { key: String => Ident, payload: Vec<u8> => crate::buf::Bytes });
packet!(Transfer { host: String => Str, port: i32 => VarInt });
packet!(UpdateEnabledFeatures { features: Vec<String> => List<Ident> });
packet!(TagEntry { name: String => Ident, ids: Vec<i32> => List<VarInt> });
packet!(RegistryTags { registry: String => Ident, tags: Vec<TagEntry> => List<TagEntry> });
packet!(
/// ClientboundUpdateTagsPacket: tags per registry.
UpdateTags { registries: Vec<RegistryTags> => List<RegistryTags> }
);
packet!(KnownPack { namespace: String => Str, id: String => Str, version: String => Str });
packet!(SelectKnownPacks { packs: Vec<KnownPack> => List<KnownPack> });
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<ClientInformation> for ClientInformation {
fn read(r: &mut Reader) -> Result<Self> {
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<Vec<u8>> => Opt<crate::buf::Bytes> });
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);
}
}
}
@@ -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);
}
}
@@ -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<String> => Opt<StrN<1024>>,
}
);
packet!(
/// ByteBufCodecs.GAME_PROFILE.
GameProfile {
uuid: u128 => Uuid,
name: String => StrN<16>,
properties: Vec<Property> => crate::buf::List<Property>,
}
);
packet!(Disconnect { reason_json: String => StrN<262144> });
packet!(Hello {
server_id: String => StrN<20>,
public_key: Vec<u8> => Bytes,
challenge: Vec<u8> => 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<u8> => 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<u8> => Bytes, challenge: Vec<u8> => Bytes });
packet!(CustomQueryAnswer { transaction: i32 => VarInt, payload: Option<Vec<u8>> => Opt<Rest> });
packet!(CookieResponse { key: String => Ident, payload: Option<Vec<u8>> => Opt<Bytes> });
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());
}
}
@@ -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<u8>),
}
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<Self> {
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<u8> {
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<Empty> for Empty {
fn read(_: &mut Reader) -> crate::Result<Empty> {
Ok(Empty)
}
fn write(_: &Empty, _: &mut Writer) {}
}
#[cfg(test)]
pub(crate) fn round_trip<T: Clone + PartialEq + std::fmt::Debug>(
packet: T,
encode: impl Fn(&T) -> Vec<u8>,
decode: impl Fn(i32, &[u8]) -> crate::Result<T>,
) {
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);
}
File diff suppressed because it is too large Load Diff
@@ -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,
);
}
}
+221
View File
@@ -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<String>,
pub ids: HashMap<String, i32>,
}
impl Ids {
pub fn from_names(names: Vec<String>) -> 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<i32> {
self.ids.get(name).copied()
}
}
/// The built-in registries from `registries.json` (`--reports`).
#[derive(Clone, Debug, Default)]
pub struct Builtin {
pub registries: HashMap<String, Ids>,
}
impl Builtin {
pub fn load(path: &Path) -> Result<Self> {
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<Self> {
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<std::path::PathBuf> {
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<String, Vec<(String, Option<Tag>)>>,
}
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);
}
}
+149
View File
@@ -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<String>,
/// ServerPackStatus: None = prompt, Some(true) enabled, Some(false) disabled.
pub accept_textures: Option<bool>,
}
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<Self> {
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<ServerEntry> {
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);
}
}
+190
View File
@@ -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<String, String>;
fn string(tag: &Tag) -> Option<String> {
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<String> = 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::<usize>().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), "<Steve> 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");
}
}
+70
View File
@@ -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()