Open worlds to LAN

A world can now be opened to the local network from World Options in the pause menu (LAN on or off, port, command access, forcing the game mode, plus the default and personal game mode, cheats and difficulty), or with horizon-ctl lan open. The hosted world runs a server inside the game that speaks the vanilla 26.3 protocol: server list status, offline-mode login, the configuration phase with the synchronized registries and tags (sent as known-pack references to vanilla clients and in full to clients that know no packs), then the play state with chunks and light, time, weather, the player list, the host and other guests as visible players, mobs and dropped items, block changes, chat and keep-alives. Network I/O runs on its own threads and a world that is not open pays one check per tick. A vanilla 26.3 client and a second Horizon client were verified joining and seeing each other and the terrain.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 14:12:31 +02:00
parent e988862e92
commit b99de58761
22 changed files with 4980 additions and 23 deletions
+137
View File
@@ -0,0 +1,137 @@
//! Serve a small flat world on the LAN server without the game, for joining
//! with a real client while developing the protocol:
//! `cargo run --release --example lan_flat -- RESOURCES PORT`.
use horizon_client::{
assets::Assets,
blocks::BlockFacts,
chunk::{Chunk, MIN_Y},
lan::{
Lan,
chunks::ChunkEncoder,
data::SyncData,
hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
},
world::World,
};
use horizon_protocol::packets::play::Serverbound as S;
use std::{path::PathBuf, sync::Arc, time::Duration};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let root = PathBuf::from(args.next().ok_or("RESOURCES PORT")?);
let port: u16 = args.next().ok_or("port")?.parse()?;
let assets = Assets::load(&root)?;
let facts = BlockFacts::load(&root, assets.registry)?;
let state = |name: &str| {
assets
.registry
.default_state(name)
.map_or(0, |s| s.0 as u16)
};
let sync = Arc::new(SyncData::load(&root)?);
let biomes: Vec<String> = sync
.dynamic
.registries
.get("minecraft:worldgen/biome")
.map(|v| v.iter().map(|(n, _)| n.clone()).collect())
.unwrap_or_default();
let encoder = ChunkEncoder::new(
facts
.states
.iter()
.map(|s| (s.name.clone(), s.fluid_level > 0 || s.waterlogged)),
&sync.builtin,
&biomes,
&biomes,
);
let (stone, dirt, grass) = (
state("minecraft:stone"),
state("minecraft:dirt"),
state("minecraft:grass_block"),
);
let mut world = World::new(facts.air, 0);
for cz in -8..=8 {
for cx in -8..=8 {
let mut chunk = Chunk::empty(cx, cz);
for z in 0..16 {
for x in 0..16 {
for y in MIN_Y..60 {
let v = if y == 59 {
grass
} else if y > 55 {
dirt
} else {
stone
};
chunk.set(x, y, z, v);
}
}
}
chunk.lit = true;
world.chunks.insert((cx, cz), Arc::new(chunk));
}
}
let lan = Lan::start(sync.clone(), port, "Flat - Example".into(), 8)?;
println!("listening on {}", lan.port);
let mut hub = Hub::new(
lan,
sync,
encoder,
HubConfig {
default_game_mode: 1,
guest_commands: true,
force_game_mode: false,
hardcore: false,
view_distance: 8,
simulation_distance: 8,
dimension: "minecraft:overworld".into(),
seed: 0,
max_players: 8,
},
);
let mut next_entity = 100u32;
let host = HostState {
uuid: 42,
name: "Host".into(),
entity_id: 1,
position: [0.5, 60.0, 0.5],
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: true,
game_mode: 1,
sneaking: false,
sprinting: false,
equipment: Default::default(),
health: 20.0,
};
loop {
world.game_time += 1;
world.day_time += 1;
let mut ctx = TickCtx {
world: &mut world,
host: &host,
entities: &[],
next_entity: &mut next_entity,
spawn: [8.5, 60.0, 8.5],
difficulty: 2,
difficulty_locked: false,
clock_rate: 1.0,
};
for event in hub.tick(&mut ctx) {
match event {
HostEvent::Joined(conn) => hub.place_new_player(conn, &mut ctx),
HostEvent::Packet(_, packet) => {
if std::env::var_os("HORIZON_NET_DEBUG").is_some()
&& !matches!(*packet, S::ClientTickEnd(_))
{
eprintln!("[lan] {packet:?}");
}
}
HostEvent::Chat(line) => println!("{line}"),
HostEvent::Left(_) => {}
}
}
std::thread::sleep(Duration::from_millis(50));
}
}
+22
View File
@@ -27,6 +27,8 @@ mod frames;
mod game_mode;
mod growth;
mod jukebox;
mod lan;
mod lan_screen;
mod lightning;
mod machines;
mod maps;
@@ -250,6 +252,8 @@ enum Screen {
Stats,
/// The Advancements screen.
Advancements,
/// WorldOptionsScreen (game/lan_screen.rs).
WorldOptions,
}
#[derive(Clone)]
enum Icon {
@@ -623,6 +627,11 @@ struct Game<'a> {
persist: persist::EntityMemory,
/// Connected to a server: the world comes from the network (game/remote.rs).
remote: Option<remote::Remote>,
/// This world is open to the network (game/lan.rs).
lan: Option<lan::LanHost>,
world_options: Option<lan_screen::WorldOptions>,
/// Allow Cheats: whether guests may be given commands.
cheats: bool,
ui: chat::UiState,
combat: combat::CombatTracker,
mount: mounts::MountState,
@@ -2443,6 +2452,7 @@ impl Game<'_> {
self.tick_items();
self.spawn_loaded_entities();
self.tick_mobs()?;
self.tick_lan();
self.tick_experience();
self.tick_hand();
self.tick_sleep();
@@ -3000,6 +3010,7 @@ impl Game<'_> {
Screen::Dead => self.draw_death_screen(&mut batch),
Screen::Stats => self.draw_stats(&mut batch),
Screen::Advancements => self.draw_advancements(&mut batch),
Screen::WorldOptions => self.draw_world_options(&mut batch),
Screen::Inventory => {
self.draw_inventory(&mut batch);
}
@@ -3751,6 +3762,7 @@ impl Game<'_> {
// Mobs and their projectiles.
self.mob_geometry(camera, alpha, &mut out);
self.player_model_geometry(camera, alpha, &mut out);
self.guest_model_geometry(camera, alpha, &mut out);
self.fangs_geometry(camera, alpha, &mut out);
self.name_tag_geometry(camera, alpha, &mut out);
// Arrows: two crossed quads along the flight direction.
@@ -6793,6 +6805,7 @@ impl Game<'_> {
Screen::Dead => {}
Screen::Stats => self.screen = Screen::Paused,
Screen::Advancements => self.close_advancements(),
Screen::WorldOptions => self.close_world_options(),
Screen::Chat => self.close_chat(),
},
KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""),
@@ -7169,6 +7182,9 @@ impl ApplicationHandler for Game<'_> {
self.click_creative(button == MouseButton::Right);
}
Screen::Paused if pressed => self.pause_click()?,
Screen::WorldOptions if pressed && button == MouseButton::Left => {
self.world_options_click()
}
Screen::Dead if pressed => self.death_click()?,
Screen::Advancements if button == MouseButton::Left => {
let size = self
@@ -7237,6 +7253,9 @@ impl ApplicationHandler for Game<'_> {
WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => {
self.remote_chat_key(&event)
}
WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::WorldOptions => {
self.world_options_key(&event)
}
WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Options => {
if event.state == ElementState::Pressed
&& let PhysicalKey::Code(key) = event.physical_key
@@ -7678,6 +7697,9 @@ pub fn run() -> Result<()> {
pending_bench: None,
persist: Default::default(),
remote: None,
lan: None,
world_options: None,
cheats: true,
ui: Default::default(),
combat: Default::default(),
mount: Default::default(),
+1
View File
@@ -367,6 +367,7 @@ impl Game<'_> {
self.ui
.chat
.add(&self.res.atlas, line, None, self.ticks, focused);
self.lan_host_chat(message);
}
}
pub(super) fn chat_scroll(&mut self, amount: f32) {
@@ -406,6 +406,12 @@ impl Game<'_> {
let Some(Arg::GameMode(m)) = ctx.get("gamemode") else {
return Ok(0);
};
self.set_default_game_mode(match m {
horizon_client::command::args::GameMode::Survival => 0,
horizon_client::command::args::GameMode::Creative => 1,
horizon_client::command::args::GameMode::Adventure => 2,
horizon_client::command::args::GameMode::Spectator => 3,
});
self.feedback(Text::translate(
"commands.defaultgamemode.success",
&[Text::translate(&format!("gameMode.{}", m.name()), &[])],
@@ -78,11 +78,15 @@ impl Game<'_> {
if let Some(value) = self.block_command(&words)? {
return Ok(Some(value));
}
if let Some(value) = self.lan_control(&words)? {
return Ok(Some(value));
}
match words[0] {
"help" => Ok(Some(json!({ "commands": HELP
.iter()
.chain(super::station_control::HELP)
.chain(super::blockctl::HELP)
.chain(super::lan::HELP)
.chain(super::render_control::HELP)
.collect::<Vec<_>>() }))),
"setblock" | "fill" | "particle" | "signedit" => self.render_command(&words),
@@ -446,6 +450,7 @@ impl Game<'_> {
Screen::Chat => "chat",
Screen::Stats => "stats",
Screen::Advancements => "advancements",
Screen::WorldOptions => "world-options",
}
}
+570
View File
@@ -0,0 +1,570 @@
//! Hosting the open world on the local network ("Open to LAN"): starts the
//! server threads and the play-state hub, feeds it the world's entities each
//! tick and turns what the guests do into gameplay. A world that is not open
//! costs one `Option` check per tick.
use super::{Game, chat::PLAYER_NAME};
use horizon_client::{
Result,
items::ItemStack,
lan::{
self, Lan, MAX_PLAYERS,
chunks::ChunkEncoder,
data::SyncData,
entity::EntityState,
hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
playerdata,
},
mobs::Mob,
text::Text,
};
use horizon_core::geometry::Vec3;
use horizon_protocol::{
crypto::offline_uuid,
entity_data::{Value, serializer},
};
use std::{
collections::HashMap,
sync::{Arc, OnceLock},
};
/// The registries and tags are the same for every world: load them once.
static SYNC: OnceLock<std::result::Result<Arc<SyncData>, String>> = OnceLock::new();
/// The settings of the open world (WorldOptionsScreen's multiplayer section).
#[derive(Clone, Debug)]
pub struct LanSettings {
pub port: u16,
pub guest_commands: bool,
pub force_game_mode: bool,
}
pub(super) struct LanHost {
pub hub: Hub,
pub settings: LanSettings,
pub host_entity: i32,
pub host_uuid: u128,
/// The guests' models in the host's world.
pub models: HashMap<u32, Mob>,
host_mode: i32,
}
/// A stable UUID for an entity that has none.
fn entity_uuid(id: u32) -> u128 {
0x4856_5a4e_0000_0000_0000_0000_0000_0000u128 | u128::from(id)
}
/// Species that are AgeableMob (or have a baby flag at the same index).
fn ageable(kind: &str) -> bool {
matches!(
kind,
"minecraft:cow"
| "minecraft:mooshroom"
| "minecraft:pig"
| "minecraft:sheep"
| "minecraft:chicken"
| "minecraft:horse"
| "minecraft:donkey"
| "minecraft:mule"
| "minecraft:llama"
| "minecraft:cat"
| "minecraft:wolf"
| "minecraft:fox"
| "minecraft:rabbit"
| "minecraft:panda"
| "minecraft:villager"
| "minecraft:zombie"
| "minecraft:husk"
| "minecraft:drowned"
| "minecraft:zombie_villager"
| "minecraft:piglin"
| "minecraft:hoglin"
| "minecraft:goat"
| "minecraft:ocelot"
| "minecraft:turtle"
| "minecraft:strider"
| "minecraft:camel"
| "minecraft:axolotl"
)
}
pub const HELP: &[&str] = &[
"lan open [PORT] [commands] [force] open the world to the network (PORT 0 picks one)",
"lan close stop hosting",
"lan status the hosting state and the guests",
];
impl Game<'_> {
/// `horizon-ctl lan ...`.
pub(super) fn lan_control(&mut self, words: &[&str]) -> Result<Option<serde_json::Value>> {
use serde_json::json;
if words[0] != "lan" {
return Ok(None);
}
match words.get(1).copied() {
Some("open") => {
if self.title.is_some() {
return Err("open a world first".into());
}
let port = words.get(2).map_or(Ok(0), |p| p.parse::<u16>())?;
self.lan_open(LanSettings {
port: if port == 0 {
lan::available_port()
} else {
port
},
guest_commands: words.contains(&"commands"),
force_game_mode: words.contains(&"force"),
})?;
Ok(Some(json!({ "ok": true, "port": self.lan_port() })))
}
Some("close") => {
self.lan_close(true);
Ok(Some(json!({ "ok": true })))
}
Some("status") => Ok(Some(match &self.lan {
Some(h) => json!({
"open": true,
"port": h.settings.port,
"guests": h.hub.guests.iter().map(|g| json!({
"name": g.name,
"position": g.position,
"placed": g.placed,
"loaded": g.loaded,
"game_mode": g.game_mode,
"chunks": g.sent_chunks.len(),
"tracked": g.tracker.len(),
})).collect::<Vec<_>>(),
}),
None => json!({ "open": false }),
})),
_ => Err("lan open|close|status".into()),
}
}
pub(super) fn lan_open(&mut self, settings: LanSettings) -> Result<()> {
if self.lan.is_some() || self.remote.is_some() || self.title.is_some() {
return Err("already open".into());
}
let root = self.options.resources.clone();
let sync = SYNC
.get_or_init(|| SyncData::load(&root).map(Arc::new))
.clone()?;
let biome_names: Vec<String> = self
.res
.biomes
.list
.iter()
.map(|b| b.name.clone())
.collect();
let registry: Vec<String> = sync
.dynamic
.registries
.get("minecraft:worldgen/biome")
.map(|v| v.iter().map(|(n, _)| n.clone()).collect())
.unwrap_or_default();
let encoder = ChunkEncoder::new(
self.res
.facts
.states
.iter()
.map(|s| (s.name.clone(), s.fluid_level > 0 || s.waterlogged)),
&sync.builtin,
&biome_names,
&registry,
);
let motd = format!("{PLAYER_NAME} - {}", self.level.name);
let lan = Lan::start(sync.clone(), settings.port, motd, MAX_PLAYERS)?;
let host_uuid = self.level.player_uuid.map_or_else(
|| offline_uuid(PLAYER_NAME),
|u| {
u128::from(u[0] as u32) << 96
| u128::from(u[1] as u32) << 64
| u128::from(u[2] as u32) << 32
| u128::from(u[3] as u32)
},
);
lan.reserve(host_uuid);
self.next_entity += 1;
let host_entity = self.next_entity as i32;
let hub = Hub::new(
lan,
sync,
encoder,
HubConfig {
default_game_mode: self.level.mode(),
guest_commands: settings.guest_commands,
force_game_mode: settings.force_game_mode,
hardcore: self.level.hardcore,
view_distance: self.settings.render_distance.clamp(2, 32),
simulation_distance: self.settings.render_distance.clamp(2, 32),
dimension: self.dim.id().to_owned(),
seed: self.level.seed,
max_players: MAX_PLAYERS,
},
);
let port = hub.lan.port;
self.world.block_log = Some(Vec::new());
self.lan = Some(LanHost {
hub,
settings: LanSettings { port, ..settings },
host_entity,
host_uuid,
models: HashMap::new(),
host_mode: self.mode_id(),
});
self.system_message(Text::translate(
"menu.multiplayerOptions.publish.started.lan",
&[Text::literal(port.to_string())],
));
Ok(())
}
/// IntegratedServer.unpublishServer: the guests are sent away.
pub(super) fn lan_close(&mut self, announce: bool) {
let Some(mut host) = self.lan.take() else {
return;
};
for g in &host.hub.guests {
playerdata::save(g, &self.world_root);
}
host.hub.disconnect_all();
// Give the writer threads a moment to flush the disconnect packets.
std::thread::sleep(std::time::Duration::from_millis(100));
self.world.block_log = None;
self.streaming.extra.clear();
if announce {
self.system_message(Text::translate(
"menu.multiplayerOptions.publish.stopped",
&[],
));
}
}
/// The world's default game mode (`defaultgamemode`).
pub(super) fn set_default_game_mode(&mut self, mode: i32) {
self.level.game_mode = mode;
self.level.creative = mode == 1;
if let Some(host) = self.lan.as_mut() {
host.hub.config.default_game_mode = mode;
}
}
/// New command access and game mode forcing settings of the open world.
pub(super) fn lan_apply_settings(&mut self, guest_commands: bool, force: bool) {
if let Some(host) = self.lan.as_mut() {
host.settings.guest_commands = guest_commands;
host.settings.force_game_mode = force;
host.hub.config.guest_commands = guest_commands;
host.hub.config.force_game_mode = force;
host.hub.resend_commands();
}
}
pub(super) fn lan_port(&self) -> Option<u16> {
self.lan.as_ref().map(|h| h.settings.port)
}
/// The host as the guests see them.
fn lan_host_state(&self, host: &LanHost) -> Option<HostState> {
let p = self.player.as_ref()?;
let mut equipment: [Option<ItemStack>; 6] = Default::default();
equipment[0] = self.inventory.get(self.selected).cloned().flatten();
equipment[1] = self.offhand.clone();
// Feet, legs, chest, head are slots 2..=5; armor is stored head first.
equipment[2] = self.armor[3].clone();
equipment[3] = self.armor[2].clone();
equipment[4] = self.armor[1].clone();
equipment[5] = self.armor[0].clone();
Some(HostState {
uuid: host.host_uuid,
name: PLAYER_NAME.to_owned(),
entity_id: host.host_entity,
position: [p.position.x, p.position.y, p.position.z],
yaw: self.yaw,
pitch: self.pitch,
head_yaw: self.yaw,
on_ground: p.ground.on_ground,
game_mode: self.mode_id(),
sneaking: p.pose == horizon_client::pose::Pose::Crouching,
sprinting: p.sprinting,
equipment,
health: p.health.health(),
})
}
/// Mobs and items as the entities guests track.
fn lan_entities(&self, hub: &mut Hub) -> Vec<EntityState> {
let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len());
for m in self.mobs.iter().filter(|m| !m.removed) {
let mut meta = Vec::new();
if let Some(name) = &m.custom_name {
meta.push((
2,
serializer::OPTIONAL_COMPONENT,
Value::OptText(Some(horizon_protocol::text::literal(name))),
));
if m.name_visible {
meta.push((3, serializer::BOOLEAN, Value::Bool(true)));
}
}
if m.fire_ticks > 0 {
meta.push((0, serializer::BYTE, Value::Byte(1)));
}
if m.health < m.kind.max_health {
meta.push((9, serializer::FLOAT, Value::Float(m.health.max(0.0))));
}
let kind = m.kind.id.as_str();
if ageable(kind) && m.is_baby() {
meta.push((16, serializer::BOOLEAN, Value::Bool(true)));
}
if kind == "minecraft:sheep" {
let value = (m.extra.color & 15) | if m.extra.sheared { 16 } else { 0 };
meta.push((17, serializer::BYTE, Value::Byte(value as i8)));
}
let (yaw, pitch) = (m.yaw, m.head_pitch);
out.push(EntityState {
id: m.id as i32,
uuid: entity_uuid(m.id),
kind: kind.to_owned(),
position: [m.position.x, m.position.y, m.position.z],
yaw,
pitch,
head_yaw: m.head_yaw,
on_ground: m.on_ground,
velocity: [m.velocity.x, m.velocity.y, m.velocity.z],
data: 0,
meta,
equipment: Vec::new(),
send_velocity: false,
});
}
for d in &self.dropped {
let stack = hub.stack(&Some(d.stack.clone()));
out.push(EntityState {
id: d.id as i32,
uuid: entity_uuid(d.id),
kind: "minecraft:item".to_owned(),
position: [d.position.x, d.position.y, d.position.z],
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: d.on_ground,
velocity: [d.velocity.x, d.velocity.y, d.velocity.z],
data: 0,
meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))],
equipment: Vec::new(),
send_velocity: true,
});
}
out
}
/// Run the hub for this tick and apply what the guests did.
pub(super) fn tick_lan(&mut self) {
let Some(mut host) = self.lan.take() else {
return;
};
if let Some(state) = self.lan_host_state(&host) {
let has_guests = !host.hub.guests.is_empty();
let entities = if has_guests {
self.lan_entities(&mut host.hub)
} else {
Vec::new()
};
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let events = {
let mut ctx = TickCtx {
world: &mut self.world,
host: &state,
entities: &entities,
next_entity: &mut self.next_entity,
spawn,
difficulty: i32::from(self.ui.difficulty),
difficulty_locked: false,
clock_rate: if self.ui.rules.bool("advance_time") {
self.ui.clock.rate
} else {
0.0
},
};
host.hub.tick(&mut ctx)
};
if host.host_mode != state.game_mode {
host.host_mode = state.game_mode;
host.hub.set_host_game_mode(state.uuid, state.game_mode);
}
for event in events {
match event {
HostEvent::Joined(conn) => {
self.lan_guest_joined(&mut host, conn, &state, &entities, spawn)
}
HostEvent::Left(guest) => {
playerdata::save(&guest, &self.world_root);
host.models.remove(&guest.conn);
}
HostEvent::Chat(line) => self.system_message(Text::literal(line)),
HostEvent::Packet(conn, packet) => {
self.lan_guest_packet(&mut host, conn, *packet);
}
}
}
}
self.lan_update_streaming(&host);
self.lan_update_models(&mut host);
self.lan = Some(host);
}
fn lan_guest_joined(
&mut self,
host: &mut LanHost,
conn: u32,
state: &HostState,
entities: &[EntityState],
spawn: [f64; 3],
) {
let default_mode = host.hub.config.default_game_mode;
let force = host.hub.config.force_game_mode;
let root = self.world_root.clone();
let Some(g) = host.hub.guest_mut(conn) else {
return;
};
let known = playerdata::load(g, &root);
if !known || force {
g.game_mode = default_mode;
}
if !known {
g.position = spawn;
g.previous_position = spawn;
g.health = 20.0;
g.food = 20;
}
let mut ctx = TickCtx {
world: &mut self.world,
host: state,
entities,
next_entity: &mut self.next_entity,
spawn,
difficulty: i32::from(self.ui.difficulty),
difficulty_locked: false,
clock_rate: self.ui.clock.rate,
};
host.hub.place_new_player(conn, &mut ctx);
}
fn lan_guest_packet(
&mut self,
_host: &mut LanHost,
_conn: u32,
_packet: horizon_protocol::packets::play::Serverbound,
) {
}
/// Keep the chunks around every guest loaded.
fn lan_update_streaming(&mut self, host: &LanHost) {
self.streaming.extra = host
.hub
.guests
.iter()
.filter(|g| g.placed)
.map(|g| (g.chunk(), g.view_distance + 1))
.collect();
}
/// The guests' models, for the host to see them.
fn lan_update_models(&mut self, host: &mut LanHost) {
let Some(kind) = self.res.player_type.clone() else {
return;
};
host.models
.retain(|conn, _| host.hub.guest(*conn).is_some_and(|g| g.placed));
for g in host.hub.guests.iter().filter(|g| g.placed) {
let at = Vec3::new(
g.position[0],
g.position[1] - if g.sneaking { 0.125 } else { 0.0 },
g.position[2],
);
let m = host
.models
.entry(g.conn)
.or_insert_with(|| Mob::new(g.entity_id as u32, kind.clone(), at, g.yaw));
let (dx, dy, dz) = (
at.x - m.position.x,
at.y - m.position.y,
at.z - m.position.z,
);
m.previous = m.position;
m.position = at;
if dx * dx + dy * dy + dz * dz > 100.0 {
m.previous = at;
}
m.previous_yaw = m.yaw;
m.previous_body_yaw = m.body_yaw;
m.previous_head_yaw = m.head_yaw;
m.previous_head_pitch = m.head_pitch;
m.yaw = g.yaw;
m.head_yaw = g.head_yaw;
m.head_pitch = g.pitch;
let mut target = m.body_yaw;
if dx * dx + dz * dz > 0.002_500_000_2 {
target = (dz.atan2(dx) as f32).to_degrees() - 90.0;
}
let wrap = |a: f32| (a + 180.0).rem_euclid(360.0) - 180.0;
m.body_yaw += wrap(target - m.body_yaw) * 0.3;
let diff = wrap(g.yaw - m.body_yaw);
if diff.abs() > 50.0 {
m.body_yaw += diff - diff.signum() * 50.0;
}
let dist = (dx * dx + dz * dz).sqrt() as f32;
m.previous_limb_speed = m.limb_speed;
m.limb_speed += ((dist * 4.0).min(1.0) - m.limb_speed) * 0.4;
m.limb_position += m.limb_speed;
m.age = m.age.wrapping_add(1);
m.extra.main_hand = g
.inventory
.get(g.selected)
.and_then(|s| s.as_ref())
.map(|s| s.item.clone());
m.extra.off_hand = g.offhand.as_ref().map(|s| s.item.clone());
m.extra.crouching = g.sneaking;
}
}
/// The guests' models for the entity pass.
pub(super) fn guest_model_geometry(
&self,
camera: glam::DVec3,
alpha: f64,
out: &mut Vec<horizon_client::mesher::Vertex>,
) {
let Some(host) = &self.lan else {
return;
};
let atlas = &self.res.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
for m in host.models.values() {
let light = self.world.light(
m.position.x.floor() as i32,
(m.position.y + 1.62).floor() as i32,
m.position.z.floor() as i32,
);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
horizon_client::mobs::render::render_with(
m,
alpha as f32,
camera,
&lookup,
packed,
&self.res.mob_data,
&self.player_armor_layers(),
out,
);
}
}
/// A chat line the host typed, for the guests.
pub(super) fn lan_host_chat(&mut self, message: &str) {
if let Some(host) = &self.lan {
host.hub.chat(PLAYER_NAME, message);
}
}
}
@@ -0,0 +1,371 @@
//! WorldOptionsScreen: the in-world options with the multiplayer section
//! that opens the world to the local network (the 26.3 replacement of the
//! old "Open to LAN" screen): default and personal game mode, cheats,
//! difficulty, LAN on/off with its port, command access for guests and
//! forcing the game mode.
use super::{Game, Screen, lan::LanSettings};
use horizon_client::{
hud::{HudBatch, rgba},
text::Text,
ui::{self, EditBox},
};
use winit::{event::KeyEvent, keyboard::PhysicalKey};
pub(super) struct WorldOptions {
default_mode: i32,
personal_mode: i32,
cheats: bool,
difficulty: u8,
lan: bool,
port: EditBox,
/// The free port suggested while the box is empty.
hint: u16,
guest_commands: bool,
force: bool,
initial: Snapshot,
}
#[derive(Clone, PartialEq)]
struct Snapshot {
default_mode: i32,
personal_mode: i32,
cheats: bool,
difficulty: u8,
lan: bool,
port: u16,
guest_commands: bool,
force: bool,
}
const MODES: [&str; 4] = ["survival", "creative", "adventure", "spectator"];
const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"];
#[derive(Clone, Copy, PartialEq)]
enum Button {
DefaultMode,
PersonalMode,
Cheats,
Difficulty,
Lan,
CommandAccess,
Force,
Apply,
Cancel,
}
fn on_off(on: bool) -> Text {
Text::translate(if on { "options.on" } else { "options.off" }, &[])
}
fn labelled(key: &str, value: Text) -> Text {
Text::translate("options.generic_value", &[Text::translate(key, &[]), value])
}
impl WorldOptions {
fn parsed_port(&self) -> Option<u16> {
if self.port.value.is_empty() {
return Some(self.hint);
}
self.port.value.parse::<u16>().ok().filter(|p| *p >= 1024)
}
fn snapshot(&self) -> Snapshot {
Snapshot {
default_mode: self.default_mode,
personal_mode: self.personal_mode,
cheats: self.cheats,
difficulty: self.difficulty,
lan: self.lan,
port: if self.lan {
self.parsed_port().unwrap_or(0)
} else {
0
},
guest_commands: self.guest_commands && self.lan && self.cheats,
force: self.force,
}
}
fn changed(&self) -> bool {
let valid = !self.lan || self.parsed_port().is_some();
valid && self.snapshot() != self.initial
}
fn buttons(w: f32) -> Vec<(Button, f32, f32, f32)> {
let x = (w / 2.0 - 154.0).floor();
let right = x + 158.0;
vec![
(Button::DefaultMode, x, 38.0, 308.0),
(Button::PersonalMode, x, 62.0, 308.0),
(Button::Cheats, x, 86.0, 150.0),
(Button::Difficulty, right, 86.0, 150.0),
(Button::Lan, x, 126.0, 150.0),
(Button::CommandAccess, x, 150.0, 150.0),
(Button::Force, right, 150.0, 150.0),
]
}
fn footer(w: f32, h: f32) -> [(Button, f32, f32, f32); 2] {
let x = (w / 2.0 - 154.0).floor();
[
(Button::Apply, x, h - 28.0, 150.0),
(Button::Cancel, x + 158.0, h - 28.0, 150.0),
]
}
fn label(&self, b: Button) -> Text {
let mode = |m: i32| {
Text::translate(
&format!("selectWorld.gameMode.{}", MODES[m as usize & 3]),
&[],
)
};
match b {
Button::DefaultMode => {
labelled("options.worldOptions.game_mode", mode(self.default_mode))
}
Button::PersonalMode => labelled(
"options.worldOptions.personal_game_mode",
mode(self.personal_mode),
),
Button::Cheats => labelled("selectWorld.allowCommands", on_off(self.cheats)),
Button::Difficulty => labelled(
"options.difficulty",
Text::translate(
&format!(
"options.difficulty.{}",
DIFFICULTIES[usize::from(self.difficulty) & 3]
),
&[],
),
),
Button::Lan => labelled("menu.multiplayerOptions.lan", on_off(self.lan)),
Button::CommandAccess => labelled(
"options.worldOptions.guest.command_access",
on_off(self.guest_commands && self.lan && self.cheats),
),
Button::Force => labelled(
"options.worldOptions.guest.force_game_mode",
on_off(self.force || !self.lan),
),
Button::Apply => Text::translate("menu.multiplayerOptions.applyChanges", &[]),
Button::Cancel => Text::translate("gui.cancel", &[]),
}
}
fn active(&self, b: Button) -> bool {
match b {
Button::CommandAccess => self.lan && self.cheats,
Button::Force => self.lan && !(self.guest_commands && self.cheats),
Button::Apply => self.changed(),
_ => true,
}
}
}
impl Game<'_> {
pub(super) fn open_world_options(&mut self) {
let hint = horizon_client::lan::available_port();
let lan = self.lan.is_some();
let mut port = EditBox::new(0.0, 0.0, 150.0, 20.0);
port.max_length = 5;
let (guest_commands, force) = self.lan.as_ref().map_or((false, true), |h| {
(h.settings.guest_commands, h.settings.force_game_mode)
});
if let Some(p) = self.lan_port() {
port.set_value(&p.to_string());
}
let mut options = WorldOptions {
default_mode: self.level.mode(),
personal_mode: self.mode_id(),
cheats: self.cheats,
difficulty: self.ui.difficulty,
lan,
port,
hint,
guest_commands,
force,
initial: Snapshot {
default_mode: 0,
personal_mode: 0,
cheats: false,
difficulty: 0,
lan: false,
port: 0,
guest_commands: false,
force: false,
},
};
options.initial = options.snapshot();
self.world_options = Some(options);
self.screen = Screen::WorldOptions;
}
pub(super) fn close_world_options(&mut self) {
self.world_options = None;
self.screen = Screen::Paused;
}
pub(super) fn draw_world_options(&mut self, batch: &mut HudBatch) {
let Some(mut o) = self.world_options.take() else {
return;
};
let atlas = &self.res.atlas;
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
let centered = |batch: &mut HudBatch, key: &str, y: f32| {
let t = Text::translate(key, &[]);
let tw = atlas.font.width_text(&t);
batch.text_styled(atlas, &t, ((w - tw) / 2.0).floor(), y, u32::MAX, true);
};
centered(batch, "options.worldOptions.title", 12.0);
centered(batch, "options.worldOptions.general.title", 26.0);
centered(batch, "options.worldOptions.multiplayer.title", 114.0);
for (b, x, y, bw) in WorldOptions::buttons(w)
.into_iter()
.chain(WorldOptions::footer(w, h))
{
let active = o.active(b);
let hover = active && ui::hovered(self.cursor, x, y, bw, 20.0);
ui::button(batch, atlas, x, y, bw, 20.0, &o.label(b), active, hover);
}
// The port box sits beside the LAN button.
let x = (w / 2.0 - 154.0).floor() + 158.0;
o.port.x = x;
o.port.y = 126.0;
o.port.focused = o.lan && o.port.focused;
if o.lan {
o.port.draw(batch, atlas, None);
if o.port.value.is_empty() {
let hint = Text::literal(o.hint.to_string());
batch.text_styled(
atlas,
&hint,
x + 4.0,
132.0,
rgba(160, 160, 160, 255),
false,
);
}
if o.parsed_port().is_none() {
let t = Text::translate(
"lanServer.port.invalid.new",
&[Text::literal("1024"), Text::literal("65535")],
);
let first = t.clone();
batch.text_styled(atlas, &first, x, 148.0, rgba(255, 85, 85, 255), true);
}
} else {
ui::button(
batch,
atlas,
x,
126.0,
150.0,
20.0,
&Text::translate("lanServer.port", &[]),
false,
false,
);
}
self.world_options = Some(o);
}
pub(super) fn world_options_click(&mut self) {
let Some(mut o) = self.world_options.take() else {
return;
};
let size = self
.renderer
.as_ref()
.map_or([1, 1], |r| [r.config.width, r.config.height]);
let b = HudBatch::new(size);
let (w, h) = (b.width, b.height);
let port_x = (w / 2.0 - 154.0).floor() + 158.0;
o.port.focused = o.lan && ui::hovered(self.cursor, port_x, 126.0, 150.0, 20.0);
let hit = WorldOptions::buttons(w)
.into_iter()
.chain(WorldOptions::footer(w, h))
.find(|(button, x, y, bw)| {
o.active(*button) && ui::hovered(self.cursor, *x, *y, *bw, 20.0)
})
.map(|b| b.0);
match hit {
Some(Button::DefaultMode) => o.default_mode = (o.default_mode + 1) % 4,
Some(Button::PersonalMode) => o.personal_mode = (o.personal_mode + 1) % 4,
Some(Button::Cheats) => o.cheats = !o.cheats,
Some(Button::Difficulty) => o.difficulty = (o.difficulty + 1) % 4,
Some(Button::Lan) => {
o.lan = !o.lan;
o.port.focused = false;
}
Some(Button::CommandAccess) => o.guest_commands = !o.guest_commands,
Some(Button::Force) => o.force = !o.force,
Some(Button::Cancel) => {
self.world_options = Some(o);
self.close_world_options();
return;
}
Some(Button::Apply) => {
let wanted = o.snapshot();
let before = o.initial.clone();
self.world_options = Some(o);
self.apply_world_options(&before, &wanted);
self.close_world_options();
self.screen = Screen::Playing;
self.capture(true);
return;
}
None => {}
}
self.world_options = Some(o);
}
pub(super) fn world_options_key(&mut self, event: &KeyEvent) {
if event.state != winit::event::ElementState::Pressed {
return;
}
let PhysicalKey::Code(key) = event.physical_key else {
return;
};
let ctrl = self.keys.contains(&winit::keyboard::KeyCode::ControlLeft);
let Some(o) = self.world_options.as_mut() else {
return;
};
if !o.port.focused {
return;
}
if !o.port.key(key, ctrl, false)
&& !ctrl
&& let Some(text) = &event.text
{
let digits: String = text.chars().filter(char::is_ascii_digit).collect();
if !digits.is_empty() {
o.port.insert_text(&digits);
}
}
}
fn apply_world_options(&mut self, before: &Snapshot, wanted: &Snapshot) {
if wanted.difficulty != before.difficulty {
let name = DIFFICULTIES[usize::from(wanted.difficulty) & 3];
self.run_command(&format!("difficulty {name}"));
}
if wanted.default_mode != before.default_mode {
self.set_default_game_mode(wanted.default_mode);
}
if wanted.personal_mode != before.personal_mode {
self.set_mode_id(wanted.personal_mode);
}
self.cheats = wanted.cheats;
let settings_changed =
wanted.guest_commands != before.guest_commands || wanted.force != before.force;
if wanted.lan != before.lan || (wanted.lan && wanted.port != before.port) {
self.lan_close(before.lan);
if wanted.lan {
let opened = self.lan_open(LanSettings {
port: wanted.port,
guest_commands: wanted.guest_commands,
force_game_mode: wanted.force,
});
if opened.is_err() {
self.system_message(Text::translate("commands.publish.failed", &[]));
}
}
} else if settings_changed {
self.lan_apply_settings(wanted.guest_commands, wanted.force);
}
}
}
+2 -1
View File
@@ -24,7 +24,7 @@ fn pause_buttons(w: f32, h: f32) -> Vec<(f32, f32, f32, &'static str, u8, bool)>
98.0,
"options.worldOptions.button",
9,
false,
true,
),
(x0 + 4.0, y0 + 146.0, 204.0, "menu.returnToMenu", 2, true),
]
@@ -114,6 +114,7 @@ impl Game<'_> {
Some(1) => self.open_options(false),
Some(3) => self.open_stats(),
Some(4) => self.open_advancements(true),
Some(9) => self.open_world_options(),
Some(2) => self.close_world()?,
_ => {}
}
+356
View File
@@ -0,0 +1,356 @@
//! Encoding resident chunks for the wire: ClientboundLevelChunkWithLightPacket
//! (sections with their paletted containers, block entities and the sky and
//! block DataLayers) and the section block-change batches.
use crate::{
chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS, Section},
containers::BlockEntity,
};
use horizon_protocol::{
buf::set_bit,
chunk::{BIOMES, BLOCKS, BlockEntityInfo, ChunkData, LightData, Paletted, Strategy},
packets::play::LevelChunkWithLight,
registry::{Builtin, ceil_log2},
};
use horizon_world::nbt::Tag;
use std::{collections::HashMap, sync::Arc};
const NON_AIR: u8 = 1;
const FLUID: u8 = 2;
const ENTITY: u8 = 4;
/// The vanilla block entity type of a block (BlockEntityType.validBlocks).
pub fn block_entity_type(name: &str) -> Option<&'static str> {
let n = name.strip_prefix("minecraft:")?;
Some(match n {
"chest" => "minecraft:chest",
"trapped_chest" => "minecraft:trapped_chest",
"ender_chest" => "minecraft:ender_chest",
"barrel" => "minecraft:barrel",
"furnace" => "minecraft:furnace",
"blast_furnace" => "minecraft:blast_furnace",
"smoker" => "minecraft:smoker",
"hopper" => "minecraft:hopper",
"dispenser" => "minecraft:dispenser",
"dropper" => "minecraft:dropper",
"brewing_stand" => "minecraft:brewing_stand",
"beacon" => "minecraft:beacon",
"bell" => "minecraft:bell",
"campfire" | "soul_campfire" => "minecraft:campfire",
"enchanting_table" => "minecraft:enchanting_table",
"jukebox" => "minecraft:jukebox",
"lectern" => "minecraft:lectern",
"spawner" => "minecraft:mob_spawner",
"comparator" => "minecraft:comparator",
"daylight_detector" => "minecraft:daylight_detector",
"conduit" => "minecraft:conduit",
"decorated_pot" => "minecraft:decorated_pot",
"moving_piston" => "minecraft:piston",
"structure_block" => "minecraft:structure_block",
"jigsaw" => "minecraft:jigsaw",
"command_block" | "chain_command_block" | "repeating_command_block" => {
"minecraft:command_block"
}
"end_portal" => "minecraft:end_portal",
"end_gateway" => "minecraft:end_gateway",
"sculk_sensor" => "minecraft:sculk_sensor",
"calibrated_sculk_sensor" => "minecraft:calibrated_sculk_sensor",
"sculk_catalyst" => "minecraft:sculk_catalyst",
"sculk_shrieker" => "minecraft:sculk_shrieker",
"crafter" => "minecraft:crafter",
"chiseled_bookshelf" => "minecraft:chiseled_bookshelf",
"trial_spawner" => "minecraft:trial_spawner",
"vault" => "minecraft:vault",
"beehive" | "bee_nest" => "minecraft:beehive",
"suspicious_sand" | "suspicious_gravel" => "minecraft:brushable_block",
"creaking_heart" => "minecraft:creaking_heart",
"test_block" => "minecraft:test_block",
"test_instance_block" => "minecraft:test_instance_block",
n if n.ends_with("shulker_box") => "minecraft:shulker_box",
n if n.ends_with("_wall_hanging_sign") || n.ends_with("_hanging_sign") => {
"minecraft:hanging_sign"
}
n if n.ends_with("_sign") => "minecraft:sign",
n if n.ends_with("_banner") => "minecraft:banner",
n if n.ends_with("_head") || n.ends_with("_skull") => "minecraft:skull",
n if n.ends_with("_shelf") => "minecraft:shelf",
n if n.ends_with("copper_golem_statue") => "minecraft:copper_golem_statue",
_ => return None,
})
}
/// Per-state facts and registry ids for encoding chunks.
pub struct ChunkEncoder {
flags: Vec<u8>,
/// Block entity type id per state (-1 for none).
entity_types: Vec<i16>,
/// Network biome id per internal biome index.
pub biome_ids: Vec<i32>,
biome_bits: u8,
/// The block registry id of each state's block, for BlockEvent.
pub block_ids: Vec<i32>,
}
impl ChunkEncoder {
/// `biome_names`: the internal biome list in order; `biome_registry`:
/// the synchronized biome entries in network order.
pub fn new(
states: impl IntoIterator<Item = (Arc<str>, bool)>,
builtin: &Builtin,
biome_names: &[String],
biome_registry: &[String],
) -> Self {
let types = builtin.get("minecraft:block_entity_type");
let blocks = builtin.get("minecraft:block");
let mut flags = Vec::new();
let mut entity_types = Vec::new();
let mut block_ids = Vec::new();
for (name, has_fluid) in states {
let air = matches!(
&*name,
"minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
);
let mut f = 0u8;
if !air {
f |= NON_AIR;
if has_fluid {
f |= FLUID;
}
}
let t = block_entity_type(&name)
.and_then(|t| types.and_then(|ids| ids.id(t)))
.map_or(-1, |v| v as i16);
if t >= 0 {
f |= ENTITY;
}
flags.push(f);
entity_types.push(t);
block_ids.push(blocks.and_then(|b| b.id(&name)).unwrap_or(0));
}
let biome_ids = biome_names
.iter()
.map(|n| {
biome_registry
.iter()
.position(|b| b == n)
.map_or(0, |i| i as i32)
})
.collect();
Self {
flags,
entity_types,
biome_ids,
biome_bits: ceil_log2(biome_registry.len()),
block_ids,
}
}
pub fn entity_type(&self, state: u16) -> Option<i32> {
self.entity_types
.get(usize::from(state))
.filter(|t| **t >= 0)
.map(|t| i32::from(*t))
}
pub fn is_air(&self, state: u16) -> bool {
self.flags
.get(usize::from(state))
.is_none_or(|f| f & NON_AIR == 0)
}
fn section(
&self,
section: &Section,
chunk: &Chunk,
index: usize,
) -> (horizon_protocol::chunk::Section, bool) {
let mut values = Vec::with_capacity(BLOCKS);
let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, false);
let mut count = |state: u16, n: i16| {
let f = self.flags.get(usize::from(state)).copied().unwrap_or(0);
if f & NON_AIR != 0 {
non_empty += n;
if f & FLUID != 0 {
fluids += n;
}
}
f & ENTITY != 0
};
match &section.blocks {
Blocks::Uniform(v) => {
entities |= count(*v, BLOCKS as i16);
values.resize(BLOCKS, i32::from(*v));
}
Blocks::Full(a) => {
for &v in a.iter() {
entities |= count(v, 1);
values.push(i32::from(v));
}
}
}
let biome_values: Vec<i32> = (0..BIOMES)
.map(|j| {
let internal = chunk.biomes.get(index * BIOMES + j).copied().unwrap_or(0);
self.biome_ids
.get(usize::from(internal))
.copied()
.unwrap_or(0)
})
.collect();
(
horizon_protocol::chunk::Section {
non_empty,
fluids,
states: Paletted::from_values(&values, Strategy::Blocks, 16),
biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits),
},
entities,
)
}
/// The chunk column with its light and block entities.
pub fn encode(
&self,
chunk: &Chunk,
block_entities: &HashMap<(i32, i32, i32), BlockEntity>,
) -> LevelChunkWithLight {
let mut sections = Vec::with_capacity(SECTIONS);
let mut entity_infos = Vec::new();
for (i, s) in chunk.sections.iter().enumerate() {
let (encoded, has_entities) = self.section(s, chunk, i);
if has_entities {
for y in 0..16 {
for z in 0..16 {
for x in 0..16 {
let state = s.get(crate::chunk::index(x, y, z));
if let Some(kind) = self.entity_type(state) {
let wy = MIN_Y + (i as i32) * 16 + y;
let pos = (chunk.x * 16 + x, wy, chunk.z * 16 + z);
entity_infos.push(BlockEntityInfo {
packed_xz: ((x << 4) | z) as i8,
y: wy as i16,
kind,
tag: block_entities
.get(&pos)
.and_then(entity_tag)
.unwrap_or_else(
|| Tag::compound(Vec::<(&str, Tag)>::new()),
),
});
}
}
}
}
}
sections.push(encoded);
}
LevelChunkWithLight {
x: chunk.x,
z: chunk.z,
chunk: ChunkData {
heightmaps: Vec::new(),
buffer: ChunkData::from_sections(&sections),
block_entities: entity_infos,
},
light: light_data(chunk),
}
}
}
/// The update tag of a block entity (getUpdateTag) for what the client shows.
pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
match entity {
BlockEntity::Sign(sign) => Some(Tag::compound(sign.encode())),
BlockEntity::Jukebox(_) | BlockEntity::Lectern(_) => None,
_ => None,
}
}
/// Light sections run from one below the world to one above it.
fn light_data(chunk: &Chunk) -> LightData {
let mut data = LightData {
sky_mask: Vec::new(),
block_mask: Vec::new(),
empty_sky_mask: Vec::new(),
empty_block_mask: Vec::new(),
sky: Vec::new(),
block: Vec::new(),
};
// The section below the world has no sky light; the one above is full.
set_bit(&mut data.empty_sky_mask, 0);
set_bit(&mut data.empty_block_mask, 0);
for (i, s) in chunk.sections.iter().enumerate() {
let bit = i + 1;
let (mut sky, mut block) = (vec![0u8; 2048], vec![0u8; 2048]);
let (mut sky_any, mut block_any) = (false, false);
match &s.light {
Light::Uniform(v) => {
let (sk, bl) = (v >> 4, v & 15);
sky_any = sk != 0;
block_any = bl != 0;
let (sb, bb) = (sk | sk << 4, bl | bl << 4);
sky.fill(sb);
block.fill(bb);
}
Light::Full(a) => {
for (j, &v) in a.iter().enumerate() {
let (sk, bl) = (v >> 4, v & 15);
sky_any |= sk != 0;
block_any |= bl != 0;
if j & 1 == 0 {
sky[j >> 1] |= sk;
block[j >> 1] |= bl;
} else {
sky[j >> 1] |= sk << 4;
block[j >> 1] |= bl << 4;
}
}
}
}
if sky_any {
set_bit(&mut data.sky_mask, bit);
data.sky.push(sky);
} else {
set_bit(&mut data.empty_sky_mask, bit);
}
if block_any {
set_bit(&mut data.block_mask, bit);
data.block.push(block);
} else {
set_bit(&mut data.empty_block_mask, bit);
}
}
set_bit(&mut data.sky_mask, SECTIONS + 1);
data.sky.push(vec![0xFF; 2048]);
set_bit(&mut data.empty_block_mask, SECTIONS + 1);
data
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn block_entity_blocks_are_recognised() {
assert_eq!(
block_entity_type("minecraft:oak_sign"),
Some("minecraft:sign")
);
assert_eq!(
block_entity_type("minecraft:oak_wall_hanging_sign"),
Some("minecraft:hanging_sign")
);
assert_eq!(
block_entity_type("minecraft:red_shulker_box"),
Some("minecraft:shulker_box")
);
assert_eq!(block_entity_type("minecraft:stone"), None);
}
#[test]
fn light_masks_cover_the_world_plus_borders() {
let chunk = Chunk::empty(0, 0);
let data = light_data(&chunk);
// Default sections are full sky light and no block light.
assert_eq!(data.sky.len(), SECTIONS + 1);
assert_eq!(data.block.len(), 0);
assert_eq!(data.sky[0][0], 0xFF);
assert!(horizon_protocol::buf::bit(&data.empty_block_mask, 5));
}
}
+395
View File
@@ -0,0 +1,395 @@
//! One accepted connection: handshake, status ping, offline-mode login and the
//! configuration phase (ServerStatusPacketListenerImpl,
//! ServerLoginPacketListenerImpl, ServerConfigurationPacketListenerImpl). A
//! player that completes configuration continues in the play state: the
//! reader forwards decoded packets to the game thread while a writer thread
//! frames, compresses and encrypts what the game queues, and answers the
//! keep-alive schedule on its own so a long frame never times a client out.
use super::{
Joined, NetEvent, Out, Shared,
data::{CORE_PACK, SyncData},
};
use horizon_protocol::{
PROTOCOL_VERSION,
connection::{ConnReader, ConnWriter, Connection},
crypto::offline_uuid,
packets::{
Empty,
configuration::{self as cfg, ClientInformation, KnownPack},
handshake, login, play, status,
},
text::translatable,
};
use std::{
net::TcpStream,
sync::{
Arc,
atomic::{AtomicI32, AtomicI64, AtomicUsize, Ordering},
mpsc::{Receiver, RecvTimeoutError, Sender, channel},
},
time::{Duration, Instant},
};
/// ServerCommonPacketListenerImpl.KEEPALIVE_TIME and the disconnect timeout.
const KEEP_ALIVE_EVERY: Duration = Duration::from_secs(15);
const KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(30);
/// Packets queued for one client beyond this many bytes disconnect it.
const MAX_PENDING: usize = 96 << 20;
/// Connection.setupCompression threshold of the integrated server.
const COMPRESSION_THRESHOLD: i32 = 256;
/// Vanilla's server-side disconnect during login is a JSON component.
fn login_disconnect(c: &mut Connection, key: &str) {
let json = format!("{{\"translate\":\"{key}\"}}");
let _ =
c.send(&login::Clientbound::Disconnect(login::Disconnect { reason_json: json }).encode());
}
/// StringUtil.isValidPlayerName.
pub fn valid_name(name: &str) -> bool {
(1..=16).contains(&name.len()) && name.chars().all(|c| c as u32 > 32 && (c as u32) < 127)
}
/// The sending half given to the game thread.
#[derive(Clone)]
pub struct PlayerSender {
pub tx: Sender<Out>,
pub pending: Arc<AtomicUsize>,
}
impl PlayerSender {
pub fn send(&self, body: Vec<u8>) {
self.pending.fetch_add(body.len(), Ordering::Relaxed);
let _ = self.tx.send(Out::Packet(body));
}
}
pub fn serve(stream: TcpStream, shared: Arc<Shared>) -> Result<(), String> {
let e = |e: horizon_protocol::Error| e.to_string();
let mut c = Connection::from_stream(stream).map_err(e)?;
c.reader
.set_read_timeout(Some(Duration::from_secs(30)))
.map_err(e)?;
let (id, payload) = c.recv().map_err(e)?;
let intention = match handshake::Serverbound::decode(id, &payload).map_err(e)? {
handshake::Serverbound::Intention(i) => i,
_ => return Err("expected a handshake".into()),
};
match intention.intent {
handshake::STATUS => serve_status(&mut c, &shared),
handshake::LOGIN | handshake::TRANSFER => {
if intention.protocol != PROTOCOL_VERSION {
let key = if intention.protocol < PROTOCOL_VERSION {
"multiplayer.disconnect.outdated_client"
} else {
"multiplayer.disconnect.incompatible"
};
let json = format!(
"{{\"translate\":\"{key}\",\"with\":[\"{}\"]}}",
horizon_protocol::GAME_VERSION
);
let _ = c.send(
&login::Clientbound::Disconnect(login::Disconnect { reason_json: json })
.encode(),
);
return Ok(());
}
serve_login(c, &shared)
}
other => Err(format!("unknown intent {other}")),
}
}
fn serve_status(c: &mut Connection, shared: &Shared) -> Result<(), String> {
let e = |e: horizon_protocol::Error| e.to_string();
loop {
let (id, payload) = c.recv().map_err(e)?;
match status::Serverbound::decode(id, &payload).map_err(e)? {
status::Serverbound::StatusRequest(_) => {
let json = shared.status_json();
c.send(
&status::Clientbound::StatusResponse(status::StatusResponse { json }).encode(),
)
.map_err(e)?;
}
status::Serverbound::PingRequest(p) => {
c.send(&status::Clientbound::PongResponse(p).encode())
.map_err(e)?;
return Ok(());
}
status::Serverbound::Unknown(..) => return Ok(()),
}
}
}
fn serve_login(mut c: Connection, shared: &Arc<Shared>) -> Result<(), String> {
let e = |e: horizon_protocol::Error| e.to_string();
let (id, payload) = c.recv().map_err(e)?;
let hello = match login::Serverbound::decode(id, &payload).map_err(e)? {
login::Serverbound::Hello(h) => h,
_ => return Err("expected a login hello".into()),
};
if !valid_name(&hello.name) {
login_disconnect(&mut c, "multiplayer.disconnect.invalid_name");
return Ok(());
}
// Offline mode: the profile is derived from the name (PlayerList.canPlayerLogin
// then rejects duplicates and a full server).
let uuid = offline_uuid(&hello.name);
if let Some(reason) = shared.try_admit(uuid, &hello.name) {
login_disconnect(&mut c, reason);
return Ok(());
}
let result = login_and_configure(&mut c, shared, uuid, &hello.name);
match result {
Ok(Some(parts)) => {
play(c, shared, parts);
Ok(())
}
Ok(None) => {
shared.release(uuid);
Ok(())
}
Err(err) => {
shared.release(uuid);
Err(err)
}
}
}
struct Parts {
uuid: u128,
name: String,
info: ClientInformation,
brand: String,
}
fn login_and_configure(
c: &mut Connection,
shared: &Arc<Shared>,
uuid: u128,
name: &str,
) -> Result<Option<Parts>, String> {
let e = |e: horizon_protocol::Error| e.to_string();
c.send(
&login::Clientbound::Compression(login::Compression {
threshold: COMPRESSION_THRESHOLD,
})
.encode(),
)
.map_err(e)?;
c.set_compression(COMPRESSION_THRESHOLD);
c.send(
&login::Clientbound::LoginFinished(login::LoginFinished {
profile: login::GameProfile {
uuid,
name: name.to_owned(),
properties: Vec::new(),
},
session: uuid,
})
.encode(),
)
.map_err(e)?;
// The client may send its settings before acknowledging the login.
loop {
let (id, payload) = c.recv().map_err(e)?;
match login::Serverbound::decode(id, &payload).map_err(e)? {
login::Serverbound::LoginAcknowledged(_) => break,
login::Serverbound::CustomQueryAnswer(_) | login::Serverbound::CookieResponse(_) => {}
_ => return Err("unexpected packet during login".into()),
}
}
// Configuration.
let sync: &SyncData = &shared.sync;
let send = |c: &mut Connection, p: cfg::Clientbound| c.send(&p.encode()).map_err(e);
send(
c,
cfg::Clientbound::CustomPayload(cfg::CustomPayload {
channel: "minecraft:brand".into(),
data: {
let mut w = horizon_protocol::buf::Writer::new();
w.string("horizon");
w.data
},
}),
)?;
send(
c,
cfg::Clientbound::UpdateEnabledFeatures(cfg::UpdateEnabledFeatures {
features: sync.features.clone(),
}),
)?;
let core = KnownPack {
namespace: CORE_PACK.0.into(),
id: CORE_PACK.1.into(),
version: CORE_PACK.2.into(),
};
send(
c,
cfg::Clientbound::SelectKnownPacks(cfg::SelectKnownPacks {
packs: vec![core.clone()],
}),
)?;
let mut info = ClientInformation::new(10);
let mut brand = String::from("vanilla");
let known_pack = loop {
let (id, payload) = c.recv().map_err(e)?;
match cfg::Serverbound::decode(id, &payload).map_err(e)? {
cfg::Serverbound::ClientInformation(i) => info = i,
cfg::Serverbound::CustomPayload(p) if p.channel == "minecraft:brand" => {
brand = horizon_protocol::buf::Reader::new(&p.data)
.string(32767)
.unwrap_or(brand);
}
cfg::Serverbound::SelectKnownPacks(p) => break p.packs == vec![core.clone()],
_ => {}
}
};
for packet in sync.registry_packets(known_pack) {
send(c, cfg::Clientbound::RegistryData(packet))?;
}
send(c, cfg::Clientbound::UpdateTags(sync.tags.clone()))?;
send(c, cfg::Clientbound::FinishConfiguration(Empty))?;
loop {
let (id, payload) = c.recv().map_err(e)?;
match cfg::Serverbound::decode(id, &payload).map_err(e)? {
cfg::Serverbound::FinishConfiguration(_) => break,
cfg::Serverbound::ClientInformation(i) => info = i,
_ => {}
}
}
Ok(Some(Parts {
uuid,
name: name.to_owned(),
info,
brand,
}))
}
fn play(c: Connection, shared: &Arc<Shared>, parts: Parts) {
let conn_id = shared.next_id();
let events = shared.events.clone();
let _ = c.reader.set_read_timeout(Some(KEEP_ALIVE_TIMEOUT));
let (mut reader, writer) = c.split();
let (tx, rx) = channel();
let pending = Arc::new(AtomicUsize::new(0));
let latency = Arc::new(AtomicI32::new(0));
let alive = Arc::new(AtomicI64::new(-1));
let sender = PlayerSender {
tx: tx.clone(),
pending: pending.clone(),
};
let writer_thread = {
let (alive, latency, pending) = (alive.clone(), latency.clone(), pending.clone());
std::thread::Builder::new()
.name(format!("horizon-lan-out-{conn_id}"))
.spawn(move || write_loop(writer, rx, alive, latency, pending))
.ok()
};
let joined = Joined {
conn: conn_id,
uuid: parts.uuid,
name: parts.name,
info: parts.info,
brand: parts.brand,
sender,
latency,
};
let reason = if events.send(NetEvent::Joined(Box::new(joined))).is_ok() {
read_loop(&mut reader, conn_id, &events, &alive)
} else {
"server closed".to_owned()
};
let _ = tx.send(Out::Close);
let _ = events.send(NetEvent::Left(conn_id, reason));
if let Some(t) = writer_thread {
let _ = t.join();
}
shared.release(parts.uuid);
}
fn read_loop(
reader: &mut ConnReader,
conn: u32,
events: &Sender<NetEvent>,
alive: &AtomicI64,
) -> String {
loop {
let (id, payload) = match reader.recv() {
Ok(p) => p,
Err(e) => return e.to_string(),
};
match play::Serverbound::decode(id, &payload) {
Ok(play::Serverbound::KeepAlive(k)) => alive.store(k.id, Ordering::Relaxed),
Ok(p) => {
if events.send(NetEvent::Packet(conn, Box::new(p))).is_err() {
return "server closed".to_owned();
}
}
// A malformed packet disconnects like vanilla's decoder exception.
Err(e) => return format!("Invalid packet {id}: {e}"),
}
}
}
fn write_loop(
mut writer: ConnWriter,
rx: Receiver<Out>,
alive: Arc<AtomicI64>,
latency: Arc<AtomicI32>,
pending: Arc<AtomicUsize>,
) {
let start = Instant::now();
let mut sent_at: Option<(i64, Instant)> = None;
let mut next = Instant::now() + KEEP_ALIVE_EVERY;
loop {
match rx.recv_timeout(Duration::from_millis(200)) {
Ok(Out::Packet(body)) => {
pending.fetch_sub(body.len(), Ordering::Relaxed);
if writer.send(&body).is_err() {
break;
}
if pending.load(Ordering::Relaxed) > MAX_PENDING {
break;
}
}
Ok(Out::Disconnect(reason)) => {
let _ = writer
.send(&play::Clientbound::Disconnect(cfg::Disconnect { reason }).encode());
std::thread::sleep(Duration::from_millis(50));
break;
}
Ok(Out::Close) | Err(RecvTimeoutError::Disconnected) => break,
Err(RecvTimeoutError::Timeout) => {}
}
let now = Instant::now();
if let Some((id, at)) = sent_at {
if alive.load(Ordering::Relaxed) == id {
let ms = i32::try_from(at.elapsed().as_millis()).unwrap_or(i32::MAX);
let old = latency.load(Ordering::Relaxed);
latency.store((old * 3 + ms) / 4, Ordering::Relaxed);
sent_at = None;
} else if at.elapsed() > KEEP_ALIVE_TIMEOUT {
let _ = writer.send(
&play::Clientbound::Disconnect(cfg::Disconnect {
reason: translatable("disconnect.timeout", &[]),
})
.encode(),
);
break;
}
}
if sent_at.is_none() && now >= next {
let id = i64::try_from(start.elapsed().as_millis()).unwrap_or(0);
if writer
.send(&play::Clientbound::KeepAlive(cfg::KeepAlive { id }).encode())
.is_err()
{
break;
}
sent_at = Some((id, now));
next = now + KEEP_ALIVE_EVERY;
}
}
writer.shutdown();
}
+282
View File
@@ -0,0 +1,282 @@
//! What the configuration phase sends: the synchronized registries (names in
//! network order, with their data for clients that do not know the vanilla
//! pack) and the tags of every registry, loaded from the prepared resources
//! (`data/minecraft/...`) and the registries report.
use horizon_protocol::{
packets::configuration::{RegistryData, RegistryEntry, RegistryTags, TagEntry, UpdateTags},
registry::{Builtin, Dynamic},
};
use horizon_world::nbt::{JavaString, Tag};
use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap, HashSet},
path::{Path, PathBuf},
};
/// RegistryDataLoader.SYNCHRONIZED_REGISTRIES, in vanilla's order.
pub const SYNCHRONIZED: &[&str] = &[
"minecraft:worldgen/biome",
"minecraft:chat_type",
"minecraft:trim_pattern",
"minecraft:trim_material",
"minecraft:wolf_variant",
"minecraft:wolf_sound_variant",
"minecraft:pig_variant",
"minecraft:pig_sound_variant",
"minecraft:frog_variant",
"minecraft:cat_variant",
"minecraft:cat_sound_variant",
"minecraft:cow_sound_variant",
"minecraft:cow_variant",
"minecraft:chicken_sound_variant",
"minecraft:chicken_variant",
"minecraft:zombie_nautilus_variant",
"minecraft:painting_variant",
"minecraft:sulfur_cube_archetype",
"minecraft:dimension_type",
"minecraft:damage_type",
"minecraft:banner_pattern",
"minecraft:enchantment",
"minecraft:jukebox_song",
"minecraft:instrument",
"minecraft:test_environment",
"minecraft:test_instance",
"minecraft:dialog",
"minecraft:world_clock",
"minecraft:timeline",
"minecraft:decorated_pot_pattern",
"minecraft:block_transformer",
"minecraft:worldgen/block_state_provider",
];
/// KnownPack.vanilla("core") for this version.
pub const CORE_PACK: (&str, &str, &str) = ("minecraft", "core", horizon_protocol::GAME_VERSION);
/// A data-driven registry: entry names in network order and their JSON.
struct Entries {
names: Vec<String>,
json: Vec<Value>,
}
pub struct SyncData {
pub builtin: Builtin,
/// Entry names per synchronized registry (for id lookups).
pub dynamic: Dynamic,
registries: Vec<(String, Entries)>,
pub tags: UpdateTags,
pub features: Vec<String>,
}
/// Every `*.json` under `dir`, as (path without extension relative to dir, value), sorted.
fn walk(dir: &Path, prefix: &str, out: &mut BTreeMap<String, Value>) {
let Ok(read) = std::fs::read_dir(dir) else {
return;
};
for entry in read.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
if path.is_dir() {
walk(&path, &format!("{prefix}{name}/"), out);
} else if let Some(stem) = name.strip_suffix(".json")
&& let Ok(text) = std::fs::read_to_string(&path)
&& let Ok(value) = serde_json::from_str::<Value>(&text)
{
out.insert(format!("{prefix}{stem}"), value);
}
}
}
/// A JSON value as the NBT that vanilla's NbtOps would produce from the codec
/// (integers are ints, other numbers doubles, booleans bytes).
pub fn json_to_nbt(v: &Value) -> Tag {
match v {
Value::Null => Tag::compound(Vec::<(&str, Tag)>::new()),
Value::Bool(b) => Tag::Byte(i8::from(*b)),
Value::Number(n) => match n.as_i64() {
Some(i) => match i32::try_from(i) {
Ok(i) => Tag::Int(i),
Err(_) => Tag::Long(i),
},
None => Tag::Double(n.as_f64().unwrap_or(0.0).to_bits()),
},
Value::String(s) => Tag::String(JavaString::from(s.as_str())),
Value::Array(a) => Tag::List(a.iter().map(json_to_nbt).collect()),
Value::Object(o) => Tag::compound(o.iter().map(|(k, v)| (k.as_str(), json_to_nbt(v)))),
}
}
impl SyncData {
pub fn load(resources: &Path) -> Result<Self, String> {
let builtin = Builtin::find(resources)
.and_then(|p| Builtin::load(&p).ok())
.ok_or("registries.json not found next to the resources")?;
let root: PathBuf = resources.join("data/minecraft");
let mut registries = Vec::new();
let mut dynamic = Dynamic::default();
for key in SYNCHRONIZED {
let path = key.trim_start_matches("minecraft:");
let mut found = BTreeMap::new();
walk(&root.join(path), "", &mut found);
let (names, json): (Vec<_>, Vec<_>) = found
.into_iter()
.map(|(n, v)| (format!("minecraft:{n}"), v))
.unzip();
dynamic.registries.insert(
(*key).to_owned(),
names.iter().map(|n| (n.clone(), None)).collect(),
);
registries.push(((*key).to_owned(), Entries { names, json }));
}
let tags = Self::load_tags(&root, &builtin, &dynamic);
Ok(Self {
builtin,
dynamic,
registries,
tags,
features: vec!["minecraft:vanilla".to_owned()],
})
}
/// The id of a name in a built-in or synchronized registry.
pub fn id(&self, registry: &str, name: &str) -> Option<i32> {
if let Some(ids) = self.builtin.get(registry) {
return ids.id(name);
}
self.dynamic
.registries
.get(registry)?
.iter()
.position(|(n, _)| n == name)
.map(|i| i as i32)
}
/// ClientboundRegistryDataPacket per registry. With `known_pack` the
/// client rebuilds the entries from its own data, so none is sent.
pub fn registry_packets(&self, known_pack: bool) -> Vec<RegistryData> {
self.registries
.iter()
.map(|(key, e)| RegistryData {
registry: key.clone(),
entries: e
.names
.iter()
.zip(&e.json)
.map(|(name, json)| RegistryEntry {
id: name.clone(),
data: if known_pack {
None
} else {
Some(json_to_nbt(json))
},
})
.collect(),
})
.collect()
}
fn registry_names<'a>(
builtin: &'a Builtin,
dynamic: &'a Dynamic,
key: &str,
) -> Option<HashMap<&'a str, i32>> {
if let Some(ids) = builtin.get(key) {
return Some(
ids.names
.iter()
.enumerate()
.map(|(i, n)| (n.as_str(), i as i32))
.collect(),
);
}
dynamic.registries.get(key).map(|v| {
v.iter()
.enumerate()
.map(|(i, (n, _))| (n.as_str(), i as i32))
.collect()
})
}
/// TagNetworkSerialization.serializeTagsToNetwork from the tag files.
fn load_tags(root: &Path, builtin: &Builtin, dynamic: &Dynamic) -> UpdateTags {
let tag_root = root.join("tags");
let mut registries = Vec::new();
let mut keys: Vec<String> = builtin
.registries
.keys()
.chain(dynamic.registries.keys())
.cloned()
.collect();
keys.sort();
for key in keys {
let dir = tag_root.join(key.trim_start_matches("minecraft:"));
if !dir.is_dir() {
continue;
}
let mut files = BTreeMap::new();
walk(&dir, "", &mut files);
if files.is_empty() {
continue;
}
let Some(names) = Self::registry_names(builtin, dynamic, &key) else {
continue;
};
let mut tags = Vec::new();
for name in files.keys() {
let mut ids = Vec::new();
let mut seen = HashSet::new();
Self::expand(&files, name, &names, &mut ids, &mut seen);
tags.push(TagEntry {
name: format!("minecraft:{name}"),
ids,
});
}
registries.push(RegistryTags {
registry: key,
tags,
});
}
UpdateTags { registries }
}
fn expand(
files: &BTreeMap<String, Value>,
tag: &str,
names: &HashMap<&str, i32>,
out: &mut Vec<i32>,
seen: &mut HashSet<String>,
) {
if !seen.insert(tag.to_owned()) {
return;
}
let Some(values) = files.get(tag).and_then(|v| v["values"].as_array()) else {
return;
};
for value in values {
let id = value
.as_str()
.or_else(|| value["id"].as_str())
.unwrap_or_default();
if let Some(reference) = id.strip_prefix('#') {
let reference = reference.trim_start_matches("minecraft:");
Self::expand(files, reference, names, out, seen);
} else if let Some(&n) = names.get(id)
&& !out.contains(&n)
{
out.push(n);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn json_becomes_nbt() {
let v: Value = serde_json::from_str(r#"{"a":1,"b":[true,2.5],"c":"x"}"#).unwrap();
let t = json_to_nbt(&v);
assert!(matches!(t.get("a"), Some(Tag::Int(1))));
assert!(matches!(t.get("c"), Some(Tag::String(_))));
assert!(matches!(t.get("b"), Some(Tag::List(l)) if l.len() == 2));
}
}
+314
View File
@@ -0,0 +1,314 @@
//! Entity tracking (ServerEntity / TrackedEntity): the game describes every
//! entity it simulates as an `EntityState` each tick; a `Tracker` remembers
//! what one client has been told and produces the spawn, movement, metadata,
//! equipment and removal packets that bring it up to date.
use horizon_protocol::{
buf::pack_degrees,
entity_data::Value,
item::Stack,
packets::play::{
self, AddEntity, MoveEntity, MoveEntityPos, MoveEntityPosRot, MoveEntityRot, RotateHead,
SetEntityData, SetEntityMotion, SetEquipment, TeleportEntity, VecDelta,
},
};
/// What the game says about one entity this tick.
#[derive(Clone, Debug)]
pub struct EntityState {
pub id: i32,
pub uuid: u128,
/// Registry id of the entity type (`minecraft:zombie`).
pub kind: String,
pub position: [f64; 3],
pub yaw: f32,
pub pitch: f32,
pub head_yaw: f32,
pub on_ground: bool,
pub velocity: [f64; 3],
/// ClientboundAddEntityPacket.data (item frame direction, block state ...).
pub data: i32,
/// SynchedEntityData entries that differ from the defaults.
pub meta: Vec<(u8, i32, Value)>,
/// EquipmentSlot ordinals (0 main hand, 1 off hand, 2 feet, 3 legs,
/// 4 chest, 5 head) and their stacks.
pub equipment: Vec<(u8, Option<Stack>)>,
/// Whether movement packets should include a velocity (items, projectiles).
pub send_velocity: bool,
}
/// What a client was last told about one entity.
struct Sent {
/// The position in 1/4096 blocks (VecDeltaCodec base).
base: [i64; 3],
position: [f64; 3],
rotation: (i8, i8),
head: i8,
velocity: [f64; 3],
meta: Vec<(u8, i32, Value)>,
equipment: Vec<(u8, Option<Stack>)>,
on_ground: bool,
ticks: u32,
}
#[derive(Default)]
pub struct Tracker {
sent: std::collections::HashMap<i32, Sent>,
}
fn quantize(p: [f64; 3]) -> [i64; 3] {
[
(p[0] * 4096.0).round() as i64,
(p[1] * 4096.0).round() as i64,
(p[2] * 4096.0).round() as i64,
]
}
fn dequantize(q: [i64; 3]) -> [f64; 3] {
[
q[0] as f64 / 4096.0,
q[1] as f64 / 4096.0,
q[2] as f64 / 4096.0,
]
}
impl Tracker {
pub fn is_tracking(&self, id: i32) -> bool {
self.sent.contains_key(&id)
}
pub fn ids(&self) -> Vec<i32> {
self.sent.keys().copied().collect()
}
pub fn forget(&mut self, id: i32) {
self.sent.remove(&id);
}
pub fn clear(&mut self) {
self.sent.clear();
}
pub fn len(&self) -> usize {
self.sent.len()
}
pub fn is_empty(&self) -> bool {
self.sent.is_empty()
}
/// The packets that introduce an entity (ServerEntity.sendPairingData).
pub fn spawn(&mut self, e: &EntityState, entity_type: i32) -> Vec<play::Clientbound> {
let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw));
let head = pack_degrees(e.head_yaw);
let mut out = vec![play::Clientbound::AddEntity(AddEntity {
id: e.id,
uuid: e.uuid,
kind: entity_type,
position: e.position,
velocity: e.velocity,
pitch: rotation.0,
yaw: rotation.1,
head_yaw: head,
data: e.data,
})];
if !e.meta.is_empty() {
out.push(play::Clientbound::SetEntityData(SetEntityData {
id: e.id,
values: e.meta.clone(),
}));
}
if !e.equipment.is_empty() {
out.push(play::Clientbound::SetEquipment(SetEquipment {
id: e.id,
slots: e.equipment.clone(),
}));
}
self.sent.insert(
e.id,
Sent {
base: quantize(e.position),
position: e.position,
rotation,
head,
velocity: e.velocity,
meta: e.meta.clone(),
equipment: e.equipment.clone(),
on_ground: e.on_ground,
ticks: 0,
},
);
out
}
/// Changes since the last update (ServerEntity.sendChanges).
pub fn update(&mut self, e: &EntityState) -> Vec<play::Clientbound> {
let Some(s) = self.sent.get_mut(&e.id) else {
return Vec::new();
};
let mut out = Vec::new();
s.ticks += 1;
let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw));
let rotated = rotation != s.rotation;
let now = quantize(e.position);
let delta = [now[0] - s.base[0], now[1] - s.base[1], now[2] - s.base[2]];
let moved = delta != [0; 3];
let fits = delta.iter().all(|d| i16::try_from(*d).is_ok());
if moved && !fits {
out.push(play::Clientbound::TeleportEntity(TeleportEntity {
id: e.id,
position: e.position,
delta: e.velocity,
yaw: e.yaw,
pitch: e.pitch,
relatives: 0,
on_ground: e.on_ground,
}));
s.base = now;
} else if moved || rotated || e.on_ground != s.on_ground {
let d = VecDelta::Linear([delta[0] as i16, delta[1] as i16, delta[2] as i16]);
let rot = Some((rotation.1, rotation.0));
let packet = if moved && rotated {
play::Clientbound::MoveEntityPosRot(MoveEntityPosRot(MoveEntity {
id: e.id,
delta: Some(d),
rotation: rot,
on_ground: e.on_ground,
}))
} else if moved {
play::Clientbound::MoveEntityPos(MoveEntityPos(MoveEntity {
id: e.id,
delta: Some(d),
rotation: None,
on_ground: e.on_ground,
}))
} else {
play::Clientbound::MoveEntityRot(MoveEntityRot(MoveEntity {
id: e.id,
delta: None,
rotation: rot,
on_ground: e.on_ground,
}))
};
out.push(packet);
if moved {
s.base = now;
}
}
if moved || rotated || e.on_ground != s.on_ground {
s.rotation = rotation;
s.on_ground = e.on_ground;
}
s.position = dequantize(s.base);
let head = pack_degrees(e.head_yaw);
if head != s.head {
out.push(play::Clientbound::RotateHead(RotateHead {
id: e.id,
head_yaw: head,
}));
s.head = head;
}
if e.send_velocity {
let dv: f64 = (0..3)
.map(|i| (e.velocity[i] - s.velocity[i]).powi(2))
.sum();
if dv > 1.0e-7 || (e.velocity == [0.0; 3] && s.velocity != [0.0; 3]) {
out.push(play::Clientbound::SetEntityMotion(SetEntityMotion {
id: e.id,
velocity: e.velocity,
}));
s.velocity = e.velocity;
}
}
if e.meta != s.meta {
let changed: Vec<_> = e
.meta
.iter()
.filter(|m| !s.meta.contains(m))
.cloned()
.collect();
if !changed.is_empty() {
out.push(play::Clientbound::SetEntityData(SetEntityData {
id: e.id,
values: changed,
}));
}
s.meta = e.meta.clone();
}
if e.equipment != s.equipment {
// Cleared slots are sent as empty stacks.
let mut slots: Vec<(u8, Option<Stack>)> = e
.equipment
.iter()
.filter(|m| !s.equipment.contains(m))
.cloned()
.collect();
for (slot, _) in &s.equipment {
if !e.equipment.iter().any(|(k, _)| k == slot) {
slots.push((*slot, None));
}
}
if !slots.is_empty() {
out.push(play::Clientbound::SetEquipment(SetEquipment {
id: e.id,
slots,
}));
}
s.equipment = e.equipment.clone();
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn state(x: f64) -> EntityState {
EntityState {
id: 7,
uuid: 1,
kind: "minecraft:zombie".into(),
position: [x, 64.0, 0.0],
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: true,
velocity: [0.0; 3],
data: 0,
meta: Vec::new(),
equipment: Vec::new(),
send_velocity: false,
}
}
#[test]
fn small_moves_are_relative_and_large_ones_teleport() {
let mut t = Tracker::default();
let spawn = t.spawn(&state(0.0), 100);
assert!(matches!(spawn[0], play::Clientbound::AddEntity(_)));
assert!(t.update(&state(0.0)).is_empty());
let step = t.update(&state(0.5));
assert!(matches!(step[0], play::Clientbound::MoveEntityPos(_)));
let jump = t.update(&state(40.0));
assert!(matches!(jump[0], play::Clientbound::TeleportEntity(_)));
}
#[test]
fn metadata_and_equipment_send_only_the_changes() {
let mut t = Tracker::default();
let mut e = state(0.0);
t.spawn(&e, 100);
e.meta.push((0, 0, Value::Byte(1)));
e.equipment.push((0, Some(Stack::new(5, 1))));
let out = t.update(&e);
assert!(
out.iter()
.any(|p| matches!(p, play::Clientbound::SetEntityData(_)))
);
assert!(
out.iter()
.any(|p| matches!(p, play::Clientbound::SetEquipment(_)))
);
assert!(t.update(&e).is_empty());
e.equipment.clear();
let out = t.update(&e);
let Some(play::Clientbound::SetEquipment(eq)) = out.first() else {
panic!("expected equipment");
};
assert_eq!(eq.slots, vec![(0, None)]);
}
}
+244
View File
@@ -0,0 +1,244 @@
//! A remote player: connection, position, chunk and entity views, and the
//! player state (inventory, health, game mode) that the host's gameplay code
//! operates on when it acts for them.
use super::{Joined, PlayerSender, entity::Tracker};
use crate::{items::ItemStack, motion::PlayerMotion};
use horizon_protocol::{
item::Stack,
packets::{configuration::ClientInformation, play},
};
use std::{
collections::{HashSet, VecDeque},
sync::{Arc, atomic::AtomicI32},
};
/// GameType ids.
pub const SURVIVAL: i32 = 0;
pub const CREATIVE: i32 = 1;
pub const ADVENTURE: i32 = 2;
pub const SPECTATOR: i32 = 3;
pub struct Guest {
pub conn: u32,
pub uuid: u128,
pub name: String,
pub entity_id: i32,
pub sender: PlayerSender,
pub latency: Arc<AtomicI32>,
pub info: ClientInformation,
pub brand: String,
/// The chunk radius this client is sent.
pub view_distance: i32,
pub position: [f64; 3],
pub previous_position: [f64; 3],
pub yaw: f32,
pub pitch: f32,
pub head_yaw: f32,
pub on_ground: bool,
pub game_mode: i32,
pub sneaking: bool,
pub sprinting: bool,
pub fall_flying: bool,
pub flying: bool,
pub sleeping: bool,
/// Pending ClientboundPlayerPositionPacket id; movement is ignored until
/// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient).
pub awaiting_teleport: Option<(i32, [f64; 3])>,
pub teleport_counter: i32,
/// The client finished loading terrain (ServerboundPlayerLoadedPacket).
pub loaded: bool,
// Chunks.
pub center: Option<(i32, i32)>,
pub sent_chunks: HashSet<(i32, i32)>,
pub chunk_queue: Vec<(i32, i32)>,
pub unacknowledged: u32,
pub chunks_per_tick: f32,
pub chunk_credit: f32,
// Entities.
pub tracker: Tracker,
// Player state the gameplay code reads and writes.
pub motion: Option<Box<PlayerMotion>>,
/// The 36 inventory slots (hotbar first), armor (head..feet) and off hand.
pub inventory: Vec<Option<ItemStack>>,
pub armor: [Option<ItemStack>; 4],
pub offhand: Option<ItemStack>,
pub selected: usize,
pub carried: Option<ItemStack>,
pub health: f32,
pub food: i32,
pub saturation: f32,
pub xp_level: i32,
pub xp_progress: f32,
pub xp_total: i32,
/// What the client believes the inventory menu holds (for change detection).
pub menu_sent: Vec<Option<ItemStack>>,
pub menu_state: i32,
pub sent_health: Option<(f32, i32, f32)>,
pub sent_xp: Option<(f32, i32, i32)>,
pub sent_selected: usize,
pub inbox: VecDeque<play::Serverbound>,
pub joined_tick: u64,
pub ticks: u64,
pub dead: bool,
/// The join packets were sent (PlayerList.placeNewPlayer ran).
pub placed: bool,
/// The compound this player was loaded from, for fields Horizon does not model.
pub saved: Option<horizon_world::nbt::Tag>,
}
impl Guest {
pub fn new(j: Joined, entity_id: i32, position: [f64; 3], view_distance: i32) -> Self {
Self {
conn: j.conn,
uuid: j.uuid,
name: j.name,
entity_id,
sender: j.sender,
latency: j.latency,
view_distance: (i32::from(j.info.view_distance)).clamp(2, view_distance),
info: j.info,
brand: j.brand,
position,
previous_position: position,
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: false,
game_mode: SURVIVAL,
sneaking: false,
sprinting: false,
fall_flying: false,
flying: false,
sleeping: false,
awaiting_teleport: None,
teleport_counter: 0,
loaded: false,
center: None,
sent_chunks: HashSet::new(),
chunk_queue: Vec::new(),
unacknowledged: 0,
chunks_per_tick: 9.0,
chunk_credit: 0.0,
tracker: Tracker::default(),
motion: None,
inventory: vec![None; 36],
armor: [None, None, None, None],
offhand: None,
selected: 0,
carried: None,
health: 20.0,
food: 20,
saturation: 5.0,
xp_level: 0,
xp_progress: 0.0,
xp_total: 0,
menu_sent: vec![None; 46],
menu_state: 0,
sent_health: None,
sent_xp: None,
sent_selected: 0,
inbox: VecDeque::new(),
joined_tick: 0,
ticks: 0,
dead: false,
placed: false,
saved: None,
}
}
pub fn send(&self, packet: &play::Clientbound) {
self.sender.send(packet.encode());
}
pub fn send_all(&self, packets: &[play::Clientbound]) {
for p in packets {
self.send(p);
}
}
pub fn chunk(&self) -> (i32, i32) {
(
(self.position[0].floor() as i32) >> 4,
(self.position[2].floor() as i32) >> 4,
)
}
pub fn creative(&self) -> bool {
self.game_mode == CREATIVE
}
pub fn spectator(&self) -> bool {
self.game_mode == SPECTATOR
}
/// PlayerAbilities flags (invulnerable, flying, may fly, instabuild).
pub fn ability_flags(&self) -> i8 {
let mut f = 0;
if self.creative() || self.spectator() {
f |= 1;
}
if self.flying || self.spectator() {
f |= 2;
}
if self.creative() || self.spectator() {
f |= 4;
}
if self.creative() {
f |= 8;
}
f
}
pub fn eye_height(&self) -> f64 {
if self.sneaking { 1.27 } else { 1.62 }
}
/// The inventory menu's 46 slots (ServerPlayer.inventoryMenu): 0 crafting
/// result, 1..=4 crafting grid, 5..=8 armor, 9..=35 main, 36..=44 hotbar,
/// 45 off hand.
pub fn menu_slot(&self, slot: usize) -> Option<ItemStack> {
match slot {
0..=4 => None,
5..=8 => self.armor[slot - 5].clone(),
9..=35 => self.inventory.get(slot).cloned().flatten(),
36..=44 => self.inventory.get(slot - 36).cloned().flatten(),
45 => self.offhand.clone(),
_ => None,
}
}
pub fn set_menu_slot(&mut self, slot: usize, item: Option<ItemStack>) {
match slot {
5..=8 => self.armor[slot - 5] = item,
9..=35 => self.inventory[slot] = item,
36..=44 => self.inventory[slot - 36] = item,
45 => self.offhand = item,
_ => {}
}
}
}
/// The off hand slot is conventionally 40 in saves and 45 in the menu.
pub fn stack_to_network(
item_id: impl Fn(&str) -> i32,
enchantment_id: impl Fn(&str) -> Option<i32>,
s: &Option<ItemStack>,
) -> Option<Stack> {
let s = s.as_ref()?;
let mut stack = Stack::new(item_id(&s.item), s.count as i32);
if s.damage > 0 {
stack.added.push((
horizon_protocol::item::component::DAMAGE,
horizon_protocol::item::Component::Int(s.damage as i32),
));
}
let enchantments: Vec<(i32, i32)> = s
.enchantments()
.iter()
.filter_map(|(e, level)| Some((enchantment_id(e)?, *level as i32)))
.collect();
if !enchantments.is_empty() {
stack.added.push((
horizon_protocol::item::component::ENCHANTMENTS,
horizon_protocol::item::Component::Enchantments(enchantments),
));
}
if let Some(name) = s.custom_name() {
stack.added.push((
horizon_protocol::item::component::CUSTOM_NAME,
horizon_protocol::item::Component::Text(horizon_protocol::text::literal(name)),
));
}
Some(stack)
}
File diff suppressed because it is too large Load Diff
+199
View File
@@ -0,0 +1,199 @@
//! Hosting a world on the local network. The network side lives here: the
//! listener, the per-connection handshake/login/configuration threads and the
//! writer threads (`conn`), plus the data the configuration phase sends
//! (`data`). The play state is driven by the game thread (`hub`), which only
//! ever exchanges decoded packets with these threads through channels, so a
//! world that is not open to the network pays nothing.
pub mod chunks;
pub mod conn;
pub mod data;
pub mod entity;
pub mod guest;
pub mod hub;
pub mod playerdata;
pub use conn::PlayerSender;
use horizon_protocol::packets::play;
use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION, packets::configuration::ClientInformation};
use std::{
collections::HashSet,
io,
net::{SocketAddr, TcpListener, TcpStream},
sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering},
mpsc::{Receiver, Sender, channel},
},
thread::JoinHandle,
time::Duration,
};
/// IntegratedServer.MAX_PLAYERS.
pub const MAX_PLAYERS: usize = 8;
/// Messages from the connection threads to the game thread.
pub enum NetEvent {
/// A client finished configuration and enters the play state.
Joined(Box<Joined>),
Packet(u32, Box<play::Serverbound>),
/// The connection ended (reason for the log).
Left(u32, String),
}
pub struct Joined {
pub conn: u32,
pub uuid: u128,
pub name: String,
pub info: ClientInformation,
pub brand: String,
pub sender: PlayerSender,
/// Smoothed keep-alive round trip in milliseconds.
pub latency: Arc<AtomicI32>,
}
/// Queued for a connection's writer thread.
pub enum Out {
/// A packet body: VarInt id and payload.
Packet(Vec<u8>),
/// Send a play disconnect with this component, then close.
Disconnect(horizon_world::nbt::Tag),
Close,
}
/// State shared with the connection threads.
pub struct Shared {
pub sync: Arc<data::SyncData>,
pub events: Sender<NetEvent>,
motd: Mutex<String>,
online: Mutex<HashSet<u128>>,
max_players: usize,
next: AtomicU32,
stop: AtomicBool,
}
impl Shared {
pub fn next_id(&self) -> u32 {
self.next.fetch_add(1, Ordering::Relaxed)
}
/// PlayerList.canPlayerLogin: duplicates and a full server are refused.
pub fn try_admit(&self, uuid: u128, _name: &str) -> Option<&'static str> {
let mut online = self.online.lock().unwrap();
if online.contains(&uuid) {
return Some("multiplayer.disconnect.duplicate_login");
}
if online.len() >= self.max_players {
return Some("multiplayer.disconnect.server_full");
}
online.insert(uuid);
None
}
pub fn release(&self, uuid: u128) {
self.online.lock().unwrap().remove(&uuid);
}
pub fn online(&self) -> usize {
self.online.lock().unwrap().len()
}
/// The status response (ServerStatus): version, players and the MOTD.
pub fn status_json(&self) -> String {
let motd = self.motd.lock().unwrap().clone();
serde_json::json!({
"version": { "name": GAME_VERSION, "protocol": PROTOCOL_VERSION },
"players": { "max": self.max_players, "online": self.online() },
"description": { "text": motd },
"enforcesSecureChat": false,
})
.to_string()
}
}
/// A running LAN server.
pub struct Lan {
pub shared: Arc<Shared>,
events: Receiver<NetEvent>,
pub port: u16,
listener: Option<JoinHandle<()>>,
}
impl Lan {
/// Listen on `port` (0 picks a free one).
pub fn start(
sync: Arc<data::SyncData>,
port: u16,
motd: String,
max_players: usize,
) -> io::Result<Self> {
let listener = TcpListener::bind(("0.0.0.0", port))?;
listener.set_nonblocking(true)?;
let port = listener.local_addr()?.port();
let (tx, events) = channel();
let shared = Arc::new(Shared {
sync,
events: tx,
motd: Mutex::new(motd),
online: Mutex::new(HashSet::new()),
max_players,
next: AtomicU32::new(1),
stop: AtomicBool::new(false),
});
let accept_shared = shared.clone();
let listener = std::thread::Builder::new()
.name("horizon-lan-accept".into())
.spawn(move || accept_loop(listener, accept_shared))?;
Ok(Self {
shared,
events,
port,
listener: Some(listener),
})
}
/// Everything the connection threads reported since the last call.
pub fn poll(&self) -> Vec<NetEvent> {
self.events.try_iter().collect()
}
/// Reserve a uuid for the host so a guest cannot take the name.
pub fn reserve(&self, uuid: u128) {
self.shared.online.lock().unwrap().insert(uuid);
}
pub fn set_motd(&self, motd: &str) {
*self.shared.motd.lock().unwrap() = motd.to_owned();
}
pub fn stop(&mut self) {
self.shared.stop.store(true, Ordering::Relaxed);
if let Some(t) = self.listener.take() {
let _ = t.join();
}
}
}
impl Drop for Lan {
fn drop(&mut self) {
self.stop();
}
}
fn accept_loop(listener: TcpListener, shared: Arc<Shared>) {
while !shared.stop.load(Ordering::Relaxed) {
match listener.accept() {
Ok((stream, addr)) => {
let shared = shared.clone();
let _ = std::thread::Builder::new()
.name("horizon-lan-conn".into())
.spawn(move || handle(stream, addr, shared));
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(25));
}
Err(_) => std::thread::sleep(Duration::from_millis(100)),
}
}
}
fn handle(stream: TcpStream, addr: SocketAddr, shared: Arc<Shared>) {
let _ = stream.set_nonblocking(false);
if let Err(e) = conn::serve(stream, shared)
&& std::env::var_os("HORIZON_NET_DEBUG").is_some()
{
eprintln!("[lan] {addr}: {e}");
}
}
/// HttpUtil.getAvailablePort: a free local port.
pub fn available_port() -> u16 {
TcpListener::bind(("0.0.0.0", 0))
.and_then(|l| l.local_addr())
.map_or(25565, |a| a.port())
}
+130
View File
@@ -0,0 +1,130 @@
//! Guests' saved state: `players/data/<uuid>.dat` in the vanilla player
//! compound, through the same code that saves the host.
use super::guest::Guest;
use crate::{
items::ItemStack,
save::{Level, read_dat, write_dat},
};
use horizon_protocol::crypto::uuid_string;
use std::{
path::{Path, PathBuf},
sync::Arc,
};
pub fn path(world: &Path, uuid: u128) -> PathBuf {
world
.join("players")
.join("data")
.join(format!("{}.dat", uuid_string(uuid)))
}
fn uuid_ints(uuid: u128) -> [i32; 4] {
[
(uuid >> 96) as i32,
(uuid >> 64) as i32,
(uuid >> 32) as i32,
uuid as i32,
]
}
/// Whether a saved file exists for this player.
pub fn exists(world: &Path, uuid: u128) -> bool {
path(world, uuid).is_file()
}
/// Load a guest's saved state, if they have been here before.
pub fn load(guest: &mut Guest, world: &Path) -> bool {
let Some(tag) = read_dat(&path(world, guest.uuid)) else {
return false;
};
let mut level = Level {
health: 20.0,
food: 20,
saturation: 5.0,
..Level::default()
};
level.read_player(&tag);
if let Some(p) = level.position {
guest.position = p;
guest.previous_position = p;
}
guest.yaw = level.rotation[0];
guest.pitch = level.rotation[1];
guest.head_yaw = guest.yaw;
guest.on_ground = level.on_ground;
guest.health = level.health;
guest.food = level.food;
guest.saturation = level.saturation;
guest.xp_level = level.xp_level;
guest.xp_progress = level.xp_progress;
guest.xp_total = level.xp_total;
guest.game_mode = level.mode();
guest.selected = (level.selected_slot.max(0) as usize).min(8);
guest.saved = Some(tag);
for (slot, item, count, damage) in &level.inventory {
let mut stack = ItemStack {
item: Arc::from(item.as_str()),
count: *count,
damage: *damage,
extra: level.inventory_components.get(slot).cloned(),
};
if stack.count == 0 {
stack.count = 1;
}
match *slot {
0..=35 => guest.inventory[usize::from(*slot)] = Some(stack),
100 => guest.armor[3] = Some(stack),
101 => guest.armor[2] = Some(stack),
102 => guest.armor[1] = Some(stack),
103 => guest.armor[0] = Some(stack),
150 => guest.offhand = Some(stack),
_ => {}
}
}
true
}
/// Save a guest (PlayerDataStorage.save).
pub fn save(guest: &Guest, world: &Path) {
let mut level = Level {
player_uuid: Some(uuid_ints(guest.uuid)),
position: Some(guest.position),
rotation: [guest.yaw, guest.pitch],
health: guest.health,
food: guest.food,
saturation: guest.saturation,
xp_level: guest.xp_level,
xp_progress: guest.xp_progress,
xp_total: guest.xp_total,
game_mode: guest.game_mode,
creative: guest.game_mode == 1,
selected_slot: guest.selected as i32,
on_ground: guest.on_ground,
dimension: "minecraft:overworld".into(),
player_extra: guest.saved.clone(),
..Level::default()
};
let mut put = |slot: u8, stack: &Option<ItemStack>| {
if let Some(s) = stack {
level
.inventory
.push((slot, s.item.to_string(), s.count, s.damage));
if let Some(extra) = &s.extra {
level.inventory_components.insert(slot, extra.clone());
}
}
};
for (i, s) in guest.inventory.iter().enumerate() {
put(i as u8, s);
}
put(103, &guest.armor[0]);
put(102, &guest.armor[1]);
put(101, &guest.armor[2]);
put(100, &guest.armor[3]);
put(150, &guest.offhand);
let file = path(world, guest.uuid);
if let Some(dir) = file.parent() {
let _ = std::fs::create_dir_all(dir);
}
let _ = write_dat(&file, level.player_tag());
}
+1
View File
@@ -37,6 +37,7 @@ pub mod input;
pub mod item_data;
pub mod items;
pub mod keybinds;
pub mod lan;
pub mod landing;
pub mod lang;
pub mod light;
+3 -3
View File
@@ -1176,7 +1176,7 @@ pub fn random_uuid() -> [i32; 4] {
let b = (b & !(0xC000_0000_0000_0000)) | 0x8000_0000_0000_0000;
[(a >> 32) as i32, a as i32, (b >> 32) as i32, b as i32]
}
fn uuid_tag(u: [i32; 4]) -> Tag {
pub(crate) fn uuid_tag(u: [i32; 4]) -> Tag {
Tag::IntArray(u.to_vec())
}
pub(crate) fn uuid_from_tag(tag: Option<&Tag>) -> Option<[i32; 4]> {
@@ -1455,7 +1455,7 @@ impl Level {
level.player_extra = player;
Some(level)
}
fn read_player(&mut self, p: &Tag) {
pub fn read_player(&mut self, p: &Tag) {
let n = |k: &str| number(p.get(k));
let f = |k: &str| float(p.get(k));
self.position = read_doubles::<3>(p.get("Pos"));
@@ -1543,7 +1543,7 @@ impl Level {
};
}
/// The player compound: the loaded one with Horizon's state written over it.
fn player_tag(&self) -> Tag {
pub fn player_tag(&self) -> Tag {
let mut p = compound_or_empty(self.player_extra.clone());
// Keys rewritten from scratch.
if let Tag::Compound(map) = &mut p {
+49 -19
View File
@@ -121,6 +121,9 @@ pub struct Streaming {
/// Chunks come from a server (`insert_remote`/`forget`): nothing is
/// generated and columns are only unloaded when the server says so.
pub remote: bool,
/// More areas to keep loaded (centre chunk, radius), e.g. around guests
/// of a world open to the network. They are generated and kept but not meshed.
pub extra: Vec<((i32, i32), i32)>,
}
pub struct WorkerContext {
pub assets: Arc<crate::assets::Assets>,
@@ -228,6 +231,7 @@ impl Streaming {
generated_total: 0,
meshed_total: 0,
remote: false,
extra: Vec::new(),
}
}
/// A column received from a server: store it and relight it and its neighbours.
@@ -262,8 +266,14 @@ impl Streaming {
self.shared.ready.notify_one();
}
fn distance(&self, x: i32, z: i32) -> i64 {
let (dx, dz) = (i64::from(x - self.center.0), i64::from(z - self.center.1));
dx * dx + dz * dz
let d = |c: (i32, i32)| {
let (dx, dz) = (i64::from(x - c.0), i64::from(z - c.1));
dx * dx + dz * dz
};
self.extra
.iter()
.map(|(c, _)| d(*c))
.fold(d(self.center), i64::min)
}
fn region(world: &World, x: i32, z: i32) -> Option<Box<Region>> {
let mut region: Region = Default::default();
@@ -392,10 +402,15 @@ impl Streaming {
self.meshed.remove(key);
}
// Drop far proto chunks that are not checked out.
let (cx, cz, r4) = (self.center.0, self.center.1, i64::from(self.radius + 4));
let areas: Vec<((i32, i32), i64)> =
std::iter::once((self.center, i64::from(self.radius + 4)))
.chain(self.extra.iter().map(|&(c, r)| (c, i64::from(r + 4))))
.collect();
self.protos.retain(|&(x, z), p| {
let d = i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2);
p.is_none() || d <= r4 * r4
p.is_none()
|| areas.iter().any(|&((cx, cz), r4)| {
i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2) <= r4 * r4
})
});
let (protos, finishing) = (&self.protos, &self.finishing);
self.decorated.retain(|k| {
@@ -475,23 +490,29 @@ impl Streaming {
// Generation (load or proto), closest first, bounded in flight.
let margin = if self.decorates { 3 } else { 1 };
if !self.remote && self.generating.len() < workers * 3 {
let r = self.radius + margin;
let mut wanted = Vec::new();
for dz in -r..=r {
for dx in -r..=r {
let (x, z) = (self.center.0 + dx, self.center.1 + dz);
if !self.in_range(x, z, margin)
|| world.chunks.contains_key(&(x, z))
|| self.generating.contains(&(x, z))
|| self.protos.contains_key(&(x, z))
|| self.finishing.contains(&(x, z))
{
continue;
let areas: Vec<((i32, i32), i32)> = std::iter::once((self.center, self.radius))
.chain(self.extra.iter().copied())
.collect();
for (center, radius) in areas {
let r = radius + margin;
for dz in -r..=r {
for dx in -r..=r {
let (x, z) = (center.0 + dx, center.1 + dz);
if !self.in_range(x, z, margin)
|| world.chunks.contains_key(&(x, z))
|| self.generating.contains(&(x, z))
|| self.protos.contains_key(&(x, z))
|| self.finishing.contains(&(x, z))
{
continue;
}
wanted.push((self.distance(x, z), x, z));
}
wanted.push((self.distance(x, z), x, z));
}
}
wanted.sort_unstable();
wanted.dedup();
for (d, x, z) in wanted.into_iter().take(workers * 3 - self.generating.len()) {
self.generating.insert((x, z));
self.submit(d * 4, Job::Generate(x, z));
@@ -521,7 +542,7 @@ impl Streaming {
let dirty: Vec<_> = world.dirty_sections.iter().copied().collect();
let mut columns: HashMap<(i32, i32), Option<Box<Region>>> = HashMap::new();
for (x, sy, z) in dirty {
if !world.chunks.contains_key(&(x, z)) || !self.in_range(x, z, 0) {
if !world.chunks.contains_key(&(x, z)) || !self.in_main_range(x, z, 0) {
world.dirty_sections.remove(&(x, sy, z));
continue;
}
@@ -627,8 +648,17 @@ impl Streaming {
}
}
fn in_range(&self, x: i32, z: i32, margin: i32) -> bool {
self.in_main_range(x, z, margin)
|| self.extra.iter().any(|&(c, radius)| {
let r = i64::from(radius + margin);
let (dx, dz) = (i64::from(x - c.0), i64::from(z - c.1));
dx * dx + dz * dz <= r * r
})
}
fn in_main_range(&self, x: i32, z: i32, margin: i32) -> bool {
let r = i64::from(self.radius + margin);
self.distance(x, z) <= r * r
let (dx, dz) = (i64::from(x - self.center.0), i64::from(z - self.center.1));
dx * dx + dz * dz <= r * r
}
}
impl Drop for Streaming {
+7
View File
@@ -32,6 +32,9 @@ pub struct World {
pub game_time: i64,
pub day_time: i64,
pub weather: Weather,
/// Every block position written since the log was last drained, kept
/// only while the world is open to the network (see `lan`).
pub block_log: Option<Vec<(i32, i32, i32)>>,
}
/// ServerLevel weather state (advanceWeatherCycle).
#[derive(Clone, Copy, Debug, Default)]
@@ -110,6 +113,7 @@ impl World {
game_time: 0,
day_time: 1000,
weather: Weather::default(),
block_log: None,
}
}
/// A controlled blockstate scene for the native scene probes: material
@@ -178,6 +182,9 @@ impl World {
let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0 as u16);
if u32::from(previous) != state.0 {
self.revision = self.revision.wrapping_add(1);
if let Some(log) = &mut self.block_log {
log.push((x, y, z));
}
self.modified.insert((x >> 4, z >> 4));
let sy = (y - MIN_Y) >> 4;
for dz in -1..=1 {
+495
View File
@@ -0,0 +1,495 @@
//! A protocol bot joins a hosted world the way a vanilla client does:
//! handshake, status, offline login, configuration (registries and tags),
//! then the play state (login, chunks with light, player list, entities,
//! block changes). Needs the prepared resources; skipped without them.
use horizon_client::{
chunk::{Chunk, MIN_Y},
lan::{
Lan,
chunks::ChunkEncoder,
data::SyncData,
entity::EntityState,
hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
},
world::World,
};
use horizon_protocol::{
PROTOCOL_VERSION,
connection::Connection,
crypto::offline_uuid,
packets::{
Empty,
configuration::{self as cfg, ClientInformation},
handshake, login,
play::{self, Clientbound as C, Serverbound as S},
status,
},
};
use horizon_world::registry::BlockStateId;
use std::{
path::Path,
sync::Arc,
thread,
time::{Duration, Instant},
};
fn resources() -> Option<std::path::PathBuf> {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
root.join("items.json").exists().then_some(root)
}
const STONE: u16 = 1;
fn flat_world() -> World {
let mut world = World::new(BlockStateId(0), 0);
for cz in -4..=4 {
for cx in -4..=4 {
let mut chunk = Chunk::empty(cx, cz);
for z in 0..16 {
for x in 0..16 {
chunk.set(x, MIN_Y + 4, z, STONE);
}
}
chunk.lit = true;
world.chunks.insert((cx, cz), Arc::new(chunk));
}
}
world
}
struct Bot {
c: Connection,
name: String,
}
impl Bot {
fn recv_play(&mut self) -> Result<C, String> {
let (id, payload) = self.c.recv().map_err(|e| e.to_string())?;
match C::decode(id, &payload) {
Ok(p) => Ok(p),
// The command tree has argument nodes the client side does not decode.
Err(e) if id == horizon_protocol::ids::play::clientbound::COMMANDS => {
let _ = e;
Ok(C::Unknown(id, payload))
}
Err(e) => Err(format!("packet {id}: {e}")),
}
}
fn send(&mut self, p: S) {
self.c.send(&p.encode()).unwrap();
}
}
fn connect(port: u16, name: &str, known_pack: bool) -> Result<Bot, String> {
let e = |e: horizon_protocol::Error| e.to_string();
let mut c = Connection::connect("127.0.0.1", port, Duration::from_secs(5)).map_err(e)?;
c.reader
.set_read_timeout(Some(Duration::from_secs(20)))
.map_err(e)?;
c.send(
&handshake::Serverbound::Intention(handshake::Intention {
protocol: PROTOCOL_VERSION,
host: "127.0.0.1".into(),
port,
intent: handshake::LOGIN,
})
.encode(),
)
.map_err(e)?;
c.send(
&login::Serverbound::Hello(login::ServerHello {
name: name.into(),
uuid: offline_uuid(name),
})
.encode(),
)
.map_err(e)?;
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) => {
assert_eq!(p.profile.name, name);
assert_eq!(p.profile.uuid, offline_uuid(name));
c.send(&login::Serverbound::LoginAcknowledged(Empty).encode())
.map_err(e)?;
break;
}
login::Clientbound::Disconnect(d) => return Err(d.reason_json),
other => return Err(format!("unexpected login packet {other:?}")),
}
}
c.send(&cfg::Serverbound::ClientInformation(ClientInformation::new(4)).encode())
.map_err(e)?;
let (mut registries, mut tags, mut features) = (0, 0, 0);
loop {
let (id, payload) = c.recv().map_err(e)?;
match cfg::Clientbound::decode(id, &payload).map_err(e)? {
cfg::Clientbound::SelectKnownPacks(p) => {
assert_eq!(p.packs.len(), 1);
assert_eq!(p.packs[0].id, "core");
let reply = if known_pack { p.packs } else { Vec::new() };
c.send(
&cfg::Serverbound::SelectKnownPacks(cfg::SelectKnownPacks { packs: reply })
.encode(),
)
.map_err(e)?;
}
cfg::Clientbound::RegistryData(r) => {
registries += 1;
let has_data = r.entries.iter().any(|e| e.data.is_some());
assert_eq!(has_data, !known_pack, "{}", r.registry);
}
cfg::Clientbound::UpdateTags(t) => tags += t.registries.len(),
cfg::Clientbound::UpdateEnabledFeatures(_) => features += 1,
cfg::Clientbound::FinishConfiguration(_) => {
c.send(&cfg::Serverbound::FinishConfiguration(Empty).encode())
.map_err(e)?;
break;
}
_ => {}
}
}
assert!(registries >= 28, "registries: {registries}");
assert!(tags >= 5, "tag registries: {tags}");
assert_eq!(features, 1);
Ok(Bot {
c,
name: name.into(),
})
}
/// Drive the hub like the game loop does until `done` is true.
struct Server {
hub: Hub,
world: World,
next_entity: u32,
placed: Vec<(u32, [i32; 3], u16, i32)>,
}
impl Server {
fn tick(&mut self, entities: &[EntityState]) {
let host = HostState {
uuid: 42,
name: "Host".into(),
entity_id: 1,
position: [0.5, -59.0, 0.5],
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: true,
game_mode: 1,
sneaking: false,
sprinting: false,
equipment: Default::default(),
health: 20.0,
};
let mut ctx = TickCtx {
world: &mut self.world,
host: &host,
entities,
next_entity: &mut self.next_entity,
spawn: [8.5, f64::from(MIN_Y + 5), 8.5],
difficulty: 2,
difficulty_locked: false,
clock_rate: 1.0,
};
let events = self.hub.tick(&mut ctx);
for event in events {
match event {
HostEvent::Joined(conn) => self.hub.place_new_player(conn, &mut ctx),
HostEvent::Packet(conn, packet) => {
if let S::UseItemOn(p) = *packet {
let at = [p.pos[0], p.pos[1] + 1, p.pos[2]];
ctx.world
.set(at[0], at[1], at[2], BlockStateId(u32::from(STONE)))
.unwrap();
self.placed.push((conn, at, STONE, p.sequence));
self.hub.ack(conn, p.sequence);
}
}
_ => {}
}
}
}
}
fn server(resources: &Path) -> Server {
let sync = Arc::new(SyncData::load(resources).expect("sync data"));
let lan = Lan::start(sync.clone(), 0, "Test - World".into(), 8).unwrap();
let biomes: Vec<String> = sync
.dynamic
.registries
.get("minecraft:worldgen/biome")
.map(|v| v.iter().map(|(n, _)| n.clone()).collect())
.unwrap_or_default();
let states = vec![
(Arc::<str>::from("minecraft:air"), false),
(Arc::<str>::from("minecraft:stone"), false),
(Arc::<str>::from("minecraft:chest"), false),
];
let encoder = ChunkEncoder::new(states, &sync.builtin, &biomes, &biomes);
let hub = Hub::new(
lan,
sync,
encoder,
HubConfig {
default_game_mode: 1,
guest_commands: true,
force_game_mode: false,
hardcore: false,
view_distance: 3,
simulation_distance: 3,
dimension: "minecraft:overworld".into(),
seed: 1234,
max_players: 8,
},
);
Server {
hub,
world: flat_world(),
next_entity: 100,
placed: Vec::new(),
}
}
/// Tick the server while a bot thread runs.
fn run<T: Send + 'static>(
s: &mut Server,
bot: impl FnOnce() -> Result<T, String> + Send + 'static,
) -> T {
let handle = thread::spawn(bot);
let start = Instant::now();
while !handle.is_finished() {
s.tick(&[]);
thread::sleep(Duration::from_millis(10));
assert!(start.elapsed() < Duration::from_secs(40), "timed out");
}
handle.join().unwrap().unwrap()
}
#[test]
fn status_and_join() {
let Some(resources) = resources() else {
return;
};
let mut s = server(&resources);
let port = s.hub.lan.port;
// Server list ping.
let json = run(&mut s, move || {
let mut c = Connection::connect("127.0.0.1", port, Duration::from_secs(5))
.map_err(|e| e.to_string())?;
c.send(
&handshake::Serverbound::Intention(handshake::Intention {
protocol: PROTOCOL_VERSION,
host: "127.0.0.1".into(),
port,
intent: handshake::STATUS,
})
.encode(),
)
.unwrap();
c.send(&status::Serverbound::StatusRequest(Empty).encode())
.unwrap();
let (id, payload) = c.recv().map_err(|e| e.to_string())?;
let status::Clientbound::StatusResponse(r) =
status::Clientbound::decode(id, &payload).map_err(|e| e.to_string())?
else {
return Err("no status".into());
};
Ok(r.json)
});
let v: serde_json::Value = serde_json::from_str(&json).unwrap();
assert_eq!(v["version"]["protocol"], 777);
assert_eq!(v["description"]["text"], "Test - World");
// Join, receive the world, place a block, see another player arrive.
let report = run(&mut s, move || {
let mut bot = connect(port, "Steve", true)?;
let mut chunks = 0;
let (mut login_seen, mut teleported, mut time, mut info) = (false, false, false, false);
let mut commands = false;
let deadline = Instant::now() + Duration::from_secs(15);
let mut sent_loaded = false;
let mut block_update = None;
while Instant::now() < deadline {
match bot.recv_play()? {
C::Login(l) => {
assert_eq!(l.chunk_radius, 3);
assert_eq!(l.spawn.dimension, "minecraft:overworld");
assert_eq!(l.spawn.game_type, 1);
login_seen = true;
}
C::PlayerPosition(p) => {
assert_eq!(p.position[0], 8.5);
bot.send(S::AcceptTeleportation(play::AcceptTeleportation {
id: p.teleport,
x: p.position[0],
y: p.position[1],
z: p.position[2],
yaw: 0.0,
pitch: 0.0,
}));
teleported = true;
}
C::SetTime(t) => {
assert!(!t.clocks.is_empty());
time = true;
}
C::PlayerInfoUpdate(u) => {
info |= u.entries.iter().any(|e| e.name.as_deref() == Some("Host"));
}
C::Unknown(id, _) if id == horizon_protocol::ids::play::clientbound::COMMANDS => {
commands = true
}
C::LevelChunkWithLight(l) => {
chunks += 1;
let sections = l.chunk.sections(24, 16, 7).map_err(|e| e.to_string())?;
// The floor is in the lowest section.
assert_eq!(sections[0].states.get(4 * 256), i32::from(STONE));
assert_eq!(sections[0].non_empty, 256);
assert_eq!(sections[1].non_empty, 0);
assert!(!l.light.sky.is_empty());
}
C::ChunkBatchFinished(b) => {
assert!(b.size > 0);
bot.send(S::ChunkBatchReceived(play::ChunkBatchReceived {
chunks_per_tick: 20.0,
}));
if !sent_loaded && chunks >= 9 {
bot.send(S::PlayerLoaded(Empty));
sent_loaded = true;
bot.send(S::MovePlayerPosRot(play::MovePlayerPosRot {
x: 9.5,
y: f64::from(MIN_Y + 5),
z: 9.5,
yaw: 90.0,
pitch: 10.0,
flags: 1,
}));
bot.send(S::UseItemOn(play::UseItemOn {
hand: 0,
pos: [9, MIN_Y + 4, 9],
face: 1,
cursor: [0.5, 1.0, 0.5],
inside: false,
world_border: false,
sequence: 77,
}));
}
}
C::BlockUpdate(u) => {
block_update = Some((u.pos, u.state));
}
C::BlockChangedAck(a) if a.sequence == 77 && block_update.is_some() => break,
_ => {}
}
}
assert!(
login_seen && teleported && time && info && commands,
"missing login data"
);
assert!(chunks >= 9, "only {chunks} chunks");
assert_eq!(
block_update,
Some(([9, MIN_Y + 5, 9], i32::from(STONE))),
"placed block was not broadcast"
);
Ok(bot.name)
});
assert_eq!(report, "Steve");
assert_eq!(s.placed.len(), 1);
}
#[test]
fn guests_see_each_other_and_the_world_entities() {
let Some(resources) = resources() else {
return;
};
let mut s = server(&resources);
let port = s.hub.lan.port;
let zombie = EntityState {
id: 500,
uuid: 9,
kind: "minecraft:zombie".into(),
position: [12.0, f64::from(MIN_Y + 5), 12.0],
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: true,
velocity: [0.0; 3],
data: 0,
meta: Vec::new(),
equipment: Vec::new(),
send_velocity: false,
};
let first = thread::spawn(move || {
let mut bot = connect(port, "Alex", false)?;
let mut zombies = 0;
let mut players = 0;
let mut moves = 0;
let deadline = Instant::now() + Duration::from_secs(20);
while Instant::now() < deadline && !(zombies > 0 && players > 0 && moves > 0) {
match bot.recv_play()? {
C::PlayerPosition(p) => {
bot.send(S::AcceptTeleportation(play::AcceptTeleportation {
id: p.teleport,
x: p.position[0],
y: p.position[1],
z: p.position[2],
yaw: 0.0,
pitch: 0.0,
}))
}
C::AddEntity(a) if a.id == 500 => zombies += 1,
C::AddEntity(a) if a.uuid == offline_uuid("Bob") => players += 1,
C::MoveEntityPos(_) | C::MoveEntityPosRot(_) => moves += 1,
_ => {}
}
}
if zombies > 0 && players > 0 && moves > 0 {
Ok(())
} else {
Err(format!("zombies {zombies} players {players} moves {moves}"))
}
});
let second = thread::spawn(move || {
thread::sleep(Duration::from_millis(600));
let mut bot = connect(port, "Bob", true)?;
let deadline = Instant::now() + Duration::from_secs(20);
let mut x = 8.5;
while Instant::now() < deadline {
// Keep reading and walking so the other player sees movement.
bot.c
.reader
.set_read_timeout(Some(Duration::from_millis(200)))
.unwrap();
if let Ok((id, payload)) = bot.c.recv()
&& let Ok(C::PlayerPosition(p)) = C::decode(id, &payload)
{
bot.send(S::AcceptTeleportation(play::AcceptTeleportation {
id: p.teleport,
x: p.position[0],
y: p.position[1],
z: p.position[2],
yaw: 0.0,
pitch: 0.0,
}));
}
x += 0.2;
bot.send(S::MovePlayerPos(play::MovePlayerPos {
x,
y: f64::from(MIN_Y + 5),
z: 8.5,
flags: 1,
}));
}
Ok::<(), String>(())
});
let start = Instant::now();
while !first.is_finished() {
s.tick(std::slice::from_ref(&zombie));
thread::sleep(Duration::from_millis(10));
assert!(start.elapsed() < Duration::from_secs(40), "timed out");
}
first.join().unwrap().unwrap();
drop(second);
}
+142
View File
@@ -567,6 +567,139 @@ packet!(TeleportEntity {
on_ground: bool => Bool,
});
packet!(BlockEvent { pos: [i32; 3] => Pos, b0: u8 => UByte, b1: u8 => UByte, block: i32 => VarInt });
packet!(
/// ClientboundInitializeBorderPacket.
InitializeBorder {
center_x: f64 => Double,
center_z: f64 => Double,
old_size: f64 => Double,
new_size: f64 => Double,
lerp_time: i64 => VarLong,
absolute_max_size: i32 => VarInt,
warning_blocks: i32 => VarInt,
warning_time: i32 => VarInt,
}
);
packet!(TabList { header: Tag => Nbt, footer: Tag => Nbt });
packet!(ServerData { motd: Tag => Nbt, icon: Option<Vec<u8>> => Opt<crate::buf::Bytes> });
packet!(
/// ClientboundUpdateMobEffectPacket; flags: 1 ambient, 2 visible, 4 icon, 8 blend.
UpdateMobEffect { id: i32 => VarInt, effect: i32 => VarInt, amplifier: i32 => VarInt, duration: i32 => VarInt, flags: i8 => Byte }
);
packet!(RemoveMobEffect { id: i32 => VarInt, effect: i32 => VarInt });
packet!(
/// ClientboundSwingAnimationPacket: hand (0 main, 1 off) and the swing
/// type (0 none, 1 whack, 2 stab) with its duration in ticks.
SwingAnimation { id: i32 => VarInt, hand: i32 => VarInt, kind: i32 => VarInt, duration: i32 => VarInt }
);
packet!(SoundEntity {
sound: (i32, Option<(String, Option<f32>)>) => SoundHolder,
source: i32 => VarInt,
id: i32 => VarInt,
volume: f32 => Float,
pitch: f32 => Float,
seed: i64 => Long,
});
/// One entry of ClientboundCommandsPacket: a literal or an argument node.
#[derive(Clone, Debug, PartialEq)]
pub struct CommandNode {
/// 0 root, 1 literal, 2 argument.
pub kind: u8,
pub executable: bool,
pub restricted: bool,
pub children: Vec<i32>,
pub redirect: Option<i32>,
pub name: String,
/// Argument parser registry id and its raw property bytes.
pub parser: Option<(i32, Vec<u8>)>,
/// Custom suggestion provider (`minecraft:ask_server`).
pub suggestions: Option<String>,
}
/// The command tree: nodes and the index of the root.
#[derive(Clone, Debug, PartialEq)]
pub struct Commands {
pub nodes: Vec<CommandNode>,
pub root: i32,
}
impl Codec<Commands> for Commands {
fn read(r: &mut Reader) -> Result<Self> {
let n = r.count(r.remaining())?;
let mut nodes = Vec::with_capacity(n.min(4096));
for _ in 0..n {
let flags = r.u8()?;
let count = r.count(r.remaining())?;
let children = (0..count).map(|_| r.varint()).collect::<Result<_>>()?;
let redirect = if flags & 8 != 0 {
Some(r.varint()?)
} else {
None
};
let kind = flags & 3;
let (mut name, mut parser, mut suggestions) = (String::new(), None, None);
if kind >= 1 {
name = r.string(32767)?;
}
if kind == 2 {
// Properties are parser specific; only the property-less parsers
// can be skipped without a table, so keep the rest of the packet.
return Err(crate::Error::new("argument nodes are not decoded"));
}
let _ = (&mut parser, &mut suggestions);
nodes.push(CommandNode {
kind,
executable: flags & 4 != 0,
restricted: flags & 32 != 0,
children,
redirect,
name,
parser,
suggestions,
});
}
Ok(Self {
nodes,
root: r.varint()?,
})
}
fn write(v: &Self, w: &mut Writer) {
w.varint(v.nodes.len() as i32);
for n in &v.nodes {
let mut flags = n.kind & 3;
if n.executable {
flags |= 4;
}
if n.redirect.is_some() {
flags |= 8;
}
if n.suggestions.is_some() {
flags |= 16;
}
if n.restricted {
flags |= 32;
}
w.u8(flags);
w.varint(n.children.len() as i32);
n.children.iter().for_each(|c| w.varint(*c));
if let Some(r) = n.redirect {
w.varint(r);
}
if n.kind >= 1 {
w.string(&n.name);
}
if n.kind == 2 {
let (id, props) = n.parser.clone().unwrap_or((5, Vec::new()));
w.varint(id);
w.bytes(&props);
if let Some(s) = &n.suggestions {
w.string(s);
}
}
}
w.varint(v.root);
}
}
packet_enum!(Clientbound, crate::ids::play::clientbound {
BundleDelimiter(Empty) = BUNDLE_DELIMITER,
AddEntity(AddEntity) = ADD_ENTITY,
@@ -574,11 +707,13 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
BlockChangedAck(BlockChangedAck) = BLOCK_CHANGED_ACK,
BlockDestruction(BlockDestruction) = BLOCK_DESTRUCTION,
BlockEntityData(BlockEntityData) = BLOCK_ENTITY_DATA,
BlockEvent(BlockEvent) = BLOCK_EVENT,
BlockUpdate(BlockUpdate) = BLOCK_UPDATE,
ChangeDifficulty(ChangeDifficulty) = CHANGE_DIFFICULTY,
ChunkBatchFinished(ChunkBatchFinished) = CHUNK_BATCH_FINISHED,
ChunkBatchStart(Empty) = CHUNK_BATCH_START,
ClearTitles(Bool1) = CLEAR_TITLES,
Commands(Commands) = COMMANDS,
ContainerClose(ContainerClose) = CONTAINER_CLOSE,
ContainerSetContent(ContainerSetContent) = CONTAINER_SET_CONTENT,
ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA,
@@ -592,6 +727,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
GameEvent(GameEvent) = GAME_EVENT,
HurtAnimation(HurtAnimation) = HURT_ANIMATION,
KeepAlive(KeepAlive) = KEEP_ALIVE,
InitializeBorder(InitializeBorder) = INITIALIZE_BORDER,
LevelChunkWithLight(LevelChunkWithLight) = LEVEL_CHUNK_WITH_LIGHT,
LevelEvent(LevelEvent) = LEVEL_EVENT,
LightUpdate(LightUpdate) = LIGHT_UPDATE,
@@ -609,10 +745,12 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
PlayerPosition(PlayerPosition) = PLAYER_POSITION,
PlayerRotation(PlayerRotation) = PLAYER_ROTATION,
RemoveEntities(RemoveEntities) = REMOVE_ENTITIES,
RemoveMobEffect(RemoveMobEffect) = REMOVE_MOB_EFFECT,
ResourcePackPush(ResourcePackPush) = RESOURCE_PACK_PUSH,
Respawn(Respawn) = RESPAWN,
RotateHead(RotateHead) = ROTATE_HEAD,
SectionBlocksUpdate(SectionBlocksUpdate) = SECTION_BLOCKS_UPDATE,
ServerData(ServerData) = SERVER_DATA,
SetActionBarText(Text) = SET_ACTION_BAR_TEXT,
SetChunkCacheCenter(SetChunkCacheCenter) = SET_CHUNK_CACHE_CENTER,
SetChunkCacheRadius(Distance) = SET_CHUNK_CACHE_RADIUS,
@@ -631,10 +769,14 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
SetTitleText(Text) = SET_TITLE_TEXT,
SetTitlesAnimation(TitlesAnimation) = SET_TITLES_ANIMATION,
Sound(Sound) = SOUND,
SoundEntity(SoundEntity) = SOUND_ENTITY,
StartConfiguration(Empty) = START_CONFIGURATION,
SwingAnimation(SwingAnimation) = SWING_ANIMATION,
SystemChat(SystemChat) = SYSTEM_CHAT,
TabList(TabList) = TAB_LIST,
TakeItemEntity(TakeItemEntity) = TAKE_ITEM_ENTITY,
TeleportEntity(TeleportEntity) = TELEPORT_ENTITY,
UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT,
UpdateTags(UpdateTags) = UPDATE_TAGS,
});
packet!(