Dedicated server: vanilla console lines, player chat, /list, legacy ping, chunk tracking, heightmaps and light layers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-13 00:32:29 +02:00
parent 8d16a937c5
commit 7ede56b596
10 changed files with 523 additions and 60 deletions
+39 -14
View File
@@ -29,6 +29,19 @@ use std::{
time::{Duration, Instant},
};
/// Double.toString for the magnitudes positions have (no exponent form
/// between 1e-3 and 1e7).
pub(super) fn java_double(v: f64) -> String {
if v == 0.0 || (1e-3..1e7).contains(&v.abs()) {
format!("{v:?}")
} else {
let s = format!("{v:E}");
let (m, e) = s.split_once('E').unwrap_or((&s, "0"));
let m = if m.contains('.') { m.to_owned() } else { format!("{m}.0") };
format!("{m}E{e}")
}
}
/// What the startup read before the game's resources were loaded.
struct Setup {
props: ServerProperties,
@@ -421,6 +434,9 @@ impl Game<'_> {
started.elapsed().as_secs_f64()
),
);
// DedicatedServer.initServer ends with saveEverything(false, true, true).
self.save_game()?;
self.log_saved_levels();
let mut state = ServerState {
lists,
console,
@@ -568,8 +584,9 @@ impl Game<'_> {
)
}
/// MinecraftServer.sendSystemMessage: what the console is told.
fn console_reply(&self, text: Text) {
log("INFO", &text.plain());
log("INFO", &format!("System chat: {}", text.plain()));
}
/// DedicatedServer.handleConsoleInputs: one console line, run as the
@@ -840,10 +857,12 @@ impl Game<'_> {
));
}
"say" if !rest.is_empty() => {
let message = format!("[Server] {}", rest.join(" "));
log("INFO", &message);
// SayCommand from the console: an unsigned system chat
// message of type say_command, logged as not secure.
let message = rest.join(" ");
log("INFO", &format!("[Not Secure] [Server] {message}"));
if let Some(h) = &self.lan {
h.hub.system_message(Tag::String(JavaString::from(message.as_str())));
h.hub.say("Server", &message);
}
}
_ => {
@@ -851,7 +870,7 @@ impl Game<'_> {
self.chat_capture = Some(Vec::new());
self.run_command(line);
for text in self.chat_capture.take().unwrap_or_default() {
log("INFO", &text.plain());
self.console_reply(text);
}
}
}
@@ -946,6 +965,20 @@ impl Game<'_> {
}
/// MinecraftServer.stopServer: players saved and sent away, worlds saved.
/// MinecraftServer.saveAllChunks, not silent: one line per level, in
/// the server's level order.
fn log_saved_levels(&self) {
for dimension in ["minecraft:overworld", "minecraft:the_nether", "minecraft:the_end"] {
log(
"INFO",
&format!(
"Saving chunks for level 'ServerLevel[{}]'/{dimension}",
self.level.name
),
);
}
}
fn stop_dedicated(&mut self) -> Result<()> {
log("INFO", "Stopping server");
log("INFO", "Saving players");
@@ -962,16 +995,8 @@ impl Game<'_> {
std::thread::sleep(Duration::from_millis(100));
log("INFO", "Saving worlds");
self.save_game()?;
log(
"INFO",
&format!(
"Saving chunks for level 'ServerLevel[{}]'/{}",
self.level.name,
self.dim.id()
),
);
self.log_saved_levels();
self.lan_close(false);
log("INFO", "ThreadedAnvilChunkStorage: All dimensions are saved");
Ok(())
}
}
+47 -3
View File
@@ -396,7 +396,7 @@ impl Game<'_> {
.get("minecraft:worldgen/biome")
.map(|v| v.iter().map(|(n, _)| n.clone()).collect())
.unwrap_or_default();
let encoder = ChunkEncoder::new(
let mut encoder = ChunkEncoder::new(
self.res
.facts
.states
@@ -406,6 +406,12 @@ impl Game<'_> {
&biome_names,
&registry,
);
encoder.tables = Some(
self.save
.tables
.get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.res.assets)))
.clone(),
);
let lan = Lan::start_with(sync.clone(), net)?;
if let Some(uuid) = host {
lan.reserve(uuid);
@@ -592,11 +598,47 @@ impl Game<'_> {
for event in events {
match event {
HostEvent::Joined(conn) => {
self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn)
self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn);
if self.options.dedicated.is_some()
&& let Some(g) = host.hub.guest(conn)
{
// PlayerList.placeNewPlayer, then the broadcast join message.
let [x, y, z] = g.position;
super::dedicated::log(
"INFO",
&format!(
"{}[/{}] logged in with entity id {} at ({}, {}, {})",
g.name,
g.address,
g.entity_id,
super::dedicated::java_double(x),
super::dedicated::java_double(y),
super::dedicated::java_double(z)
),
);
super::dedicated::log(
"INFO",
&format!("System chat: {} joined the game", g.name),
);
}
}
HostEvent::Left(guest) => {
playerdata::save(&guest, &self.world_root);
host.models.remove(&guest.conn);
if self.options.dedicated.is_some() && guest.placed {
super::dedicated::log(
"INFO",
&format!("{} lost connection: {}", guest.name, guest.left_reason),
);
super::dedicated::log(
"INFO",
&format!("System chat: {} left the game", guest.name),
);
}
}
// MinecraftServer.logChatMessage of an unsigned message.
HostEvent::Chat(line) if self.options.dedicated.is_some() => {
super::dedicated::log("INFO", &format!("[Not Secure] {line}"));
}
HostEvent::Chat(line) => self.system_message(Text::literal(line)),
HostEvent::Packet(conn, packet) => {
@@ -703,7 +745,9 @@ impl Game<'_> {
.guests
.iter()
.filter(|g| g.placed)
.map(|g| (g.chunk(), g.view_distance + 1))
// The tracked square's corners and their lit neighbours lie
// within (view distance + 2) * √2 of the player's chunk.
.map(|g| (g.chunk(), (g.view_distance + 2) * 3 / 2 + 1))
.collect();
}
@@ -511,6 +511,15 @@ impl Game<'_> {
/// Commands.performCommand for a guest with command access.
fn guest_command(&mut self, host: &mut LanHost, conn: u32, command: &str) {
// ListPlayersCommand needs no permission and lists every player.
let words: Vec<&str> = command.trim_start_matches('/').split(' ').collect();
if words[0] == "list" && (words.len() == 1 || words[1..] == ["uuids"]) {
let me = (self.options.dedicated.is_none() && self.player.is_some())
.then_some((host.host_uuid, super::chat::PLAYER_NAME));
let content = host.hub.list_reply(me, words.len() == 2);
host.hub.send_to(conn, &C::SystemChat(play::SystemChat { content, overlay: false }));
return;
}
if !host.settings.guest_commands || !self.cheats {
host.hub.send_to(
conn,
+92 -23
View File
@@ -88,6 +88,8 @@ pub struct ChunkEncoder {
biome_bits: u8,
/// The block registry id of each state's block, for BlockEvent.
pub block_ids: Vec<i32>,
/// The save's tables, for the heightmaps.
pub tables: Option<Arc<crate::save::SaveTables>>,
}
impl ChunkEncoder {
/// `biome_names`: the internal biome list in order; `biome_registry`:
@@ -140,6 +142,7 @@ impl ChunkEncoder {
biome_ids,
biome_bits: ceil_log2(biome_registry.len()),
block_ids,
tables: None,
}
}
pub fn entity_type(&self, state: u16) -> Option<i32> {
@@ -194,6 +197,38 @@ impl ChunkEncoder {
}
/// The chunk column with its light and block entities.
/// The non-air sections of a column as bits (LevelChunkSection.hasOnlyAir).
fn occupied(&self, chunk: &Chunk) -> u64 {
let mut bits = 0u64;
for (i, s) in chunk.sections.iter().enumerate() {
let mut unpacked = [0u16; BLOCKS];
s.unpack(&mut unpacked);
let any = unpacked.iter().any(|&v| {
self.flags.get(usize::from(v)).copied().unwrap_or(0) & NON_AIR != 0
});
if any {
bits |= 1 << i;
}
}
bits
}
/// The chunk column with its light and block entities. `world` gives the
/// neighbouring columns, whose sections decide which light layers exist.
pub fn encode_in(&self, chunk: &Chunk, world: &crate::world::World) -> LevelChunkWithLight {
let mut around = 0u64;
for dz in -1..=1 {
for dx in -1..=1 {
if let Some(c) = world.chunks.get(&(chunk.x + dx, chunk.z + dz)) {
around |= self.occupied(c);
}
}
}
let mut packet = self.encode(chunk, &world.block_entities);
packet.light = light_data(chunk, around);
packet
}
pub fn encode(
&self,
chunk: &Chunk,
@@ -215,12 +250,8 @@ impl ChunkEncoder {
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()),
),
// BlockEntityInfo.create: an empty update tag is not sent.
tag: block_entities.get(&pos).and_then(entity_tag).unwrap_or(Tag::End),
});
}
}
@@ -229,19 +260,46 @@ impl ChunkEncoder {
}
sections.push(encoded);
}
java_hash_order(&mut entity_infos, |e| {
(
chunk.x * 16 + i32::from(e.packed_xz as u8 >> 4),
i32::from(e.y),
chunk.z * 16 + i32::from(e.packed_xz as u8 & 15),
)
});
LevelChunkWithLight {
x: chunk.x,
z: chunk.z,
chunk: ChunkData {
heightmaps: Vec::new(),
heightmaps: self
.tables
.as_ref()
.map(|t| crate::save::client_heightmaps(chunk, t))
.unwrap_or_default(),
buffer: ChunkData::from_sections(&sections),
block_entities: entity_infos,
},
light: light_data(chunk),
light: light_data(chunk, u64::MAX),
}
}
}
/// The iteration order of a java.util.HashMap keyed by BlockPos (LevelChunk's
/// block entities) filled in the given order: by bucket at the capacity the
/// map grew to, insertion order within a bucket (resizes keep it).
fn java_hash_order<T>(items: &mut [T], pos: impl Fn(&T) -> (i32, i32, i32)) {
let mut capacity = 16usize;
while items.len() * 4 > capacity * 3 {
capacity *= 2;
}
items.sort_by_key(|item| {
let (x, y, z) = pos(item);
// Vec3i.hashCode, then HashMap.hash.
let h = y.wrapping_add(z.wrapping_mul(31)).wrapping_mul(31).wrapping_add(x);
((h ^ ((h as u32) >> 16) as i32) as u32 as usize) & (capacity - 1)
});
}
/// The update tag of a block entity (getUpdateTag) for what the client shows.
pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
match entity {
@@ -251,8 +309,12 @@ pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
}
}
/// Light sections run from one below the world to one above it.
fn light_data(chunk: &Chunk) -> LightData {
/// Light sections run from one below the world to one above it. A layer
/// exists where vanilla's light storage keeps one: within one section of a
/// non-air section of this column or a neighbouring one (`around`, bit i for
/// section i; LayerLightSectionStorage.updateSectionStatus). An existing
/// layer is sent, or marked empty when all dark; the others are left out.
fn light_data(chunk: &Chunk, around: u64) -> LightData {
let mut data = LightData {
sky_mask: Vec::new(),
block_mask: Vec::new(),
@@ -261,14 +323,24 @@ fn light_data(chunk: &Chunk) -> LightData {
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;
// Light section b holds chunk section b - 1.
let exists = |b: usize| {
(b.saturating_sub(2)..=b.min(SECTIONS - 1)).any(|s| s + 2 >= b && around >> s & 1 != 0)
};
let full_sky = Light::Uniform(0xF0);
for b in 0..SECTIONS + 2 {
if !exists(b) {
continue;
}
let light = match b {
// Below the world nothing is lit; above it the sky is full.
0 => &Light::Uniform(0),
_ if b == SECTIONS + 1 => &full_sky,
_ => &chunk.sections[b - 1].light,
};
let (mut sky, mut block) = (vec![0u8; 2048], vec![0u8; 2048]);
let (mut sky_any, mut block_any) = (false, false);
match &s.light {
match light {
Light::Uniform(v) => {
let (sk, bl) = (v >> 4, v & 15);
sky_any = sk != 0;
@@ -293,21 +365,18 @@ fn light_data(chunk: &Chunk) -> LightData {
}
}
if sky_any {
set_bit(&mut data.sky_mask, bit);
set_bit(&mut data.sky_mask, b);
data.sky.push(sky);
} else {
set_bit(&mut data.empty_sky_mask, bit);
set_bit(&mut data.empty_sky_mask, b);
}
if block_any {
set_bit(&mut data.block_mask, bit);
set_bit(&mut data.block_mask, b);
data.block.push(block);
} else {
set_bit(&mut data.empty_block_mask, bit);
set_bit(&mut data.empty_block_mask, b);
}
}
set_bit(&mut data.sky_mask, SECTIONS + 1);
data.sky.push(vec![0xFF; 2048]);
set_bit(&mut data.empty_block_mask, SECTIONS + 1);
data
}
+81 -1
View File
@@ -108,12 +108,82 @@ impl PlayerSender {
}
}
/// LegacyQueryHandler: the pre-1.7 server list ping. What the first read
/// holds decides the reply (1.3 and older: no more bytes; 1.4 and 1.5: 0x01;
/// 1.6: 0x01 then the MC|PingHost payload); anything else gets no reply.
fn serve_legacy(mut stream: TcpStream, shared: &Shared) -> Result<(), String> {
use std::io::{Read, Write};
let _ = stream.set_read_timeout(Some(Duration::from_millis(100)));
let mut data = Vec::new();
let mut chunk = [0u8; 1024];
// The bytes of the first read: what arrived together.
if let Ok(n) = stream.read(&mut chunk) {
data.extend_from_slice(&chunk[..n]);
}
let in_string = |d: &[u8], at: &mut usize| -> Option<String> {
let len = usize::from(u16::from_be_bytes([*d.get(*at)?, *d.get(*at + 1)?]));
let bytes = d.get(*at + 2..*at + 2 + len * 2)?;
*at += 2 + len * 2;
Some(String::from_utf16_lossy(
&bytes.chunks(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect::<Vec<_>>(),
))
};
let motd = shared.motd();
let (online, max) = (shared.online(), shared.max_players());
let body = if data.len() == 1 {
format!("{motd}\u{a7}{online}\u{a7}{max}")
} else {
if data[1] != 1 {
return Ok(());
}
if data.len() > 2 {
// readCustomPayloadPacket.
let mut at = 3;
let valid = data[2] == 0xFA
&& in_string(&data, &mut at).as_deref() == Some("MC|PingHost")
&& data
.get(at..at + 2)
.map(|b| usize::from(u16::from_be_bytes([b[0], b[1]])))
== Some(data.len().saturating_sub(at + 2))
&& {
at += 2;
data.get(at).is_some_and(|v| *v >= 73)
}
&& {
at += 1;
in_string(&data, &mut at).is_some()
}
&& data
.get(at..at + 4)
.is_some_and(|b| i32::from_be_bytes([b[0], b[1], b[2], b[3]]) <= 65535);
if !valid {
return Ok(());
}
}
format!("\u{a7}1\0127\026.3\0{motd}\0{online}\0{max}")
};
let units: Vec<u16> = body.encode_utf16().collect();
let mut out = vec![0xFF];
out.extend_from_slice(&(units.len() as u16).to_be_bytes());
for u in units {
out.extend_from_slice(&u.to_be_bytes());
}
stream.write_all(&out).map_err(|e| e.to_string())?;
let _ = stream.shutdown(std::net::Shutdown::Both);
Ok(())
}
pub fn serve(
stream: TcpStream,
address: std::net::SocketAddr,
shared: Arc<Shared>,
) -> Result<(), String> {
let e = |e: horizon_protocol::Error| e.to_string();
// LegacyQueryHandler, ahead of the frame decoder while status is on.
let mut first = [0u8; 1];
if shared.config.enable_status && stream.peek(&mut first).is_ok_and(|n| n == 1) && first[0] == 0xFE {
return serve_legacy(stream, &shared);
}
let mut c = Connection::from_stream(stream).map_err(e)?;
c.reader
.set_read_timeout(Some(Duration::from_secs(30)))
@@ -276,7 +346,8 @@ fn login_and_configure(
channel: "minecraft:brand".into(),
data: {
let mut w = horizon_protocol::buf::Writer::new();
w.string("horizon");
// MinecraftServer.getServerModName.
w.string("vanilla");
w.data
},
}),
@@ -386,6 +457,15 @@ fn read_loop(
loop {
let (id, payload) = match reader.recv() {
Ok(p) => p,
// The client closed the connection: Connection.channelInactive
// without details, multiplayer.disconnect.generic.
Err(e)
if e.0 == "Connection closed by the server"
|| e.0.contains("reset by peer")
|| e.0.contains("aborted") =>
{
return "Disconnected".to_owned();
}
Err(e) => return e.to_string(),
};
match play::Serverbound::decode(id, &payload) {
+6
View File
@@ -25,6 +25,10 @@ pub struct Guest {
/// The hub tick of the player's last action (ServerPlayer.lastActionTime),
/// for player-idle-timeout.
pub last_action_tick: u64,
/// The next ClientboundPlayerChatPacket.globalIndex for this connection.
pub chat_index: i32,
/// Why the connection closed (the console's "lost connection").
pub left_reason: String,
pub uuid: u128,
pub name: String,
pub entity_id: i32,
@@ -104,6 +108,8 @@ impl Guest {
conn: j.conn,
address: j.address,
last_action_tick: 0,
chat_index: 0,
left_reason: String::new(),
uuid: j.uuid,
name: j.name,
entity_id,
+167 -19
View File
@@ -126,6 +126,49 @@ pub fn yellow_translation(key: &str, args: &[&str]) -> Tag {
t
}
/// Player.getDisplayName for a player in no team: the name, suggesting
/// `/tell NAME `, showing the player on hover and inserting the name.
pub fn display_name(uuid: u128, name: &str) -> Tag {
let words = [(uuid >> 96) as i32, (uuid >> 64) as i32, (uuid >> 32) as i32, uuid as i32];
Tag::compound([
("text", string(name)),
(
"click_event",
Tag::compound([
("action", string("suggest_command")),
("command", string(&format!("/tell {name} "))),
]),
),
(
"hover_event",
Tag::compound([
("action", string("show_entity")),
("id", string("minecraft:player")),
("uuid", Tag::IntArray(words.to_vec())),
("name", string(name)),
]),
),
("insertion", string(name)),
])
}
/// A yellow translation of player names (`multiplayer.player.joined`).
fn yellow_names(key: &str, names: Vec<Tag>) -> Tag {
Tag::compound([
("translate", string(key)),
("with", Tag::List(names)),
("color", string("yellow")),
])
}
/// ChunkTrackingView.contains: the chunks a player at (cx, cz) with view
/// distance `r` is sent (isWithinDistance with the neighbours' buffer).
fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool {
let dx = i64::from(((x - cx).abs() - 2).max(0));
let dz = i64::from(((z - cz).abs() - 2).max(0));
dx * dx + dz * dz < i64::from(r) * i64::from(r)
}
impl Hub {
pub fn new(lan: Lan, sync: Arc<SyncData>, encoder: ChunkEncoder, config: HubConfig) -> Self {
let chat_type = sync
@@ -214,19 +257,115 @@ impl Hub {
overlay: false,
}));
}
/// A chat message from `sender` (PlayerChatMessage as a disguised chat).
/// A chat message from the host (a disguised chat: the host has no
/// connection to sign with).
pub fn chat(&self, sender: &str, text: &str) {
self.broadcast(&self.chat_packet(sender, text));
}
fn chat_packet(&self, sender: &str, text: &str) -> C {
C::DisguisedChat(play::DisguisedChat {
self.broadcast(&C::DisguisedChat(play::DisguisedChat {
message: literal(text),
chat_type: play::ChatTypeBound {
chat_type: self.chat_type,
name: literal(sender),
target: None,
},
})
}));
}
/// ListPlayersCommand's reply: the players in join order (the host of a
/// LAN world first), as display names or names with ids, joined by
/// gray commas (ComponentUtils.formatList).
pub fn list_reply(&self, host: Option<(u128, &str)>, uuids: bool) -> Tag {
let players: Vec<(u128, &str)> = host
.into_iter()
.chain(self.guests.iter().filter(|g| g.placed).map(|g| (g.uuid, g.name.as_str())))
.collect();
let format = |(uuid, name): (u128, &str)| {
if uuids {
Tag::compound([
("translate", string("commands.list.nameAndId")),
(
"with",
Tag::List(vec![
string(name),
string(&horizon_protocol::crypto::uuid_string(uuid)),
]),
),
])
} else {
display_name(uuid, name)
}
};
let names = match players.len() {
0 => string(""),
1 => format(players[0]),
_ => {
let mut extra = Vec::new();
for (k, p) in players.iter().enumerate() {
if k > 0 {
extra.push(Tag::compound([("text", string(", ")), ("color", string("gray"))]));
}
extra.push(format(*p));
}
Tag::compound([("text", string("")), ("extra", Tag::List(extra))])
}
};
Tag::compound([
("translate", string("commands.list.players")),
(
"with",
Tag::List(vec![
Tag::Int(players.len() as i32),
Tag::Int(self.lan.shared.max_players() as i32),
names,
]),
),
])
}
/// SayCommand from a source without a player: a disguised chat of type
/// say_command named after the source.
pub fn say(&self, source: &str, text: &str) {
let chat_type = self
.sync
.id("minecraft:chat_type", "minecraft:say_command")
.unwrap_or(self.chat_type);
self.broadcast(&C::DisguisedChat(play::DisguisedChat {
message: literal(text),
chat_type: play::ChatTypeBound {
chat_type,
name: literal(source),
target: None,
},
}));
}
/// PlayerList.broadcastChatMessage of a guest's unsigned message
/// (PlayerChatMessage.unsigned): a ClientboundPlayerChatPacket to every
/// player, each connection numbering its messages.
pub fn player_chat(&mut self, from: usize, text: &str) {
let (uuid, name) = (self.guests[from].uuid, self.guests[from].name.clone());
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64);
let bound = play::ChatTypeBound {
chat_type: self.chat_type,
name: display_name(uuid, &name),
target: None,
};
for g in self.guests.iter_mut().filter(|g| g.placed) {
let packet = C::PlayerChat(play::PlayerChat {
global_index: g.chat_index,
sender: uuid,
index: 0,
signature: None,
content: text.to_owned(),
timestamp,
salt: 0,
last_seen: Vec::new(),
unsigned_content: None,
filter: (0, Vec::new()),
chat_type: bound.clone(),
});
g.chat_index += 1;
g.send(&packet);
}
}
/// Disconnect a guest with a reason (ServerGamePacketListenerImpl.disconnect).
@@ -357,7 +496,10 @@ impl Hub {
self.broadcast_except(
conn,
&C::SystemChat(play::SystemChat {
content: yellow_translation("multiplayer.player.joined", &[&name]),
content: yellow_names(
"multiplayer.player.joined",
vec![display_name(self.guests[i].uuid, &name)],
),
overlay: false,
}),
);
@@ -366,7 +508,7 @@ impl Hub {
let g = &self.guests[i];
g.send(&C::ServerData(play::ServerData {
motd: literal(&self.lan.shared.motd()),
icon: None,
icon: self.lan.shared.config.favicon.clone(),
}));
// The player list: everyone already here, then the newcomer to all.
let mut entries = Vec::new();
@@ -652,7 +794,8 @@ impl Hub {
}
fn remove_guest(&mut self, i: usize, reason: &str) -> Guest {
let g = self.guests.remove(i);
let mut g = self.guests.remove(i);
g.left_reason = reason.to_owned();
if std::env::var_os("HORIZON_NET_DEBUG").is_some() {
eprintln!("[lan] {} left: {reason}", g.name);
}
@@ -665,7 +808,10 @@ impl Hub {
self.broadcast(&C::RemoveEntities(play::RemoveEntities {
ids: vec![g.entity_id],
}));
self.system_message(yellow_translation("multiplayer.player.left", &[&g.name]));
self.system_message(yellow_names(
"multiplayer.player.left",
vec![display_name(g.uuid, &g.name)],
));
g
}
@@ -751,18 +897,20 @@ impl Hub {
.sent_chunks
.iter()
.copied()
.filter(|&(x, z)| (x - cx).abs().max((z - cz).abs()) > r)
.filter(|&(x, z)| !tracked(cx, cz, r, x, z))
.collect();
for (x, z) in forget {
g.sent_chunks.remove(&(x, z));
g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] }));
}
g.chunk_queue
.retain(|&(x, z)| (x - cx).abs().max((z - cz).abs()) <= r);
for dz in -r..=r {
for dx in -r..=r {
g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z));
for dz in -r - 2..=r + 2 {
for dx in -r - 2..=r + 2 {
let key = (cx + dx, cz + dz);
if !g.sent_chunks.contains(&key) && !g.chunk_queue.contains(&key) {
if tracked(cx, cz, r, key.0, key.1)
&& !g.sent_chunks.contains(&key)
&& !g.chunk_queue.contains(&key)
{
g.chunk_queue.push(key);
}
}
@@ -792,7 +940,7 @@ impl Hub {
continue;
}
packets.push(C::LevelChunkWithLight(
self.encoder.encode(chunk, &ctx.world.block_entities),
self.encoder.encode_in(chunk, ctx.world),
));
taken.push(idx);
}
@@ -819,7 +967,7 @@ impl Hub {
let Some(chunk) = world.chunks.get(&(x, z)) else {
return;
};
let packet = C::LevelChunkWithLight(self.encoder.encode(chunk, &world.block_entities));
let packet = C::LevelChunkWithLight(self.encoder.encode_in(chunk, world));
let body = packet.encode();
for g in self
.guests
@@ -1242,7 +1390,7 @@ impl Hub {
let text: String = c.message.chars().filter(|c| !c.is_control()).collect();
if !text.is_empty() {
let name = self.guests[i].name.clone();
self.chat(&name, &text);
self.player_chat(i, &text);
events.push(HostEvent::Chat(format!("<{name}> {text}")));
}
}
+22
View File
@@ -640,6 +640,28 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag {
)
}))
}
/// The heightmaps a ClientboundLevelChunkPacketData carries (the types with
/// sendToClient: WORLD_SURFACE, MOTION_BLOCKING, MOTION_BLOCKING_NO_LEAVES),
/// as (network id, packed longs) in Heightmap.Types order.
pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec<i64>)> {
let kinds = [
(1, HeightmapType::WorldSurface),
(4, HeightmapType::MotionBlocking),
(5, HeightmapType::MotionBlockingNoLeaves),
];
let mut maps: Vec<(i32, Heightmap)> = kinds
.iter()
.filter_map(|(id, k)| Heightmap::new(*k, MIN_Y, SECTIONS as i32 * 16).ok().map(|m| (*id, m)))
.collect();
let view = HeightmapView { chunk, tables };
let mut refs: Vec<&mut Heightmap> = maps.iter_mut().map(|(_, m)| m).collect();
if Heightmap::prime(&view, &mut refs).is_err() {
return Vec::new();
}
maps.iter()
.map(|(id, m)| (*id, m.raw_data().iter().map(|&w| w as i64).collect()))
.collect()
}
/// Vanilla light layer (nibbles, index y<<8|z<<4|x, low nibble first).
fn nibbles(light: &Light, sky: bool) -> Vec<u8> {
let mut out = vec![0u8; 2048];
@@ -30,7 +30,10 @@ import java.util.zip.Deflater;
import java.util.zip.Inflater;
import net.minecraft.SharedConstants;
import net.minecraft.core.UUIDUtil;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.PalettedContainerFactory;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentSerialization;
import net.minecraft.network.chat.LastSeenMessages;
@@ -424,6 +427,9 @@ public final class VanillaProtocolClient {
} else if (packet instanceof ClientboundLevelChunkWithLightPacket p) {
chunks.put(p.x() + "," + p.z(), sha(r.payload));
lastChunk = now;
int px = (int) Math.floor(position.position().x) >> 4;
int pz = (int) Math.floor(position.position().z) >> 4;
if (p.x() == px && p.z() == pz) chunkParts(p);
} else if (packet instanceof ClientboundSystemChatPacket p && step > 0) {
record("play-chat", "system " + p.overlay() + " " + json(p.content()));
} else if (packet instanceof ClientboundPlayerChatPacket p && step > 0) {
@@ -460,6 +466,49 @@ public final class VanillaProtocolClient {
record("error", "timed out in play, step " + step + ", chunks " + chunks.size());
}
/** The player's chunk part by part, so a difference in its bytes can be told apart. */
private void chunkParts(ClientboundLevelChunkWithLightPacket p) {
var data = p.chunkData();
for (var e : new TreeMap<>(data.getHeightmaps().entrySet().stream()
.collect(java.util.stream.Collectors.toMap(x -> x.getKey().getSerializedName(), x -> x.getValue()))).entrySet()) {
record("chunk-heightmap", e.getKey() + " " + java.util.Arrays.toString(e.getValue()).hashCode());
}
FriendlyByteBuf buf = data.getReadBuffer();
byte[] all = new byte[buf.readableBytes()];
buf.getBytes(buf.readerIndex(), all);
var factory = PalettedContainerFactory.create(ParityData.access);
int index = 0;
while (buf.isReadable()) {
int start = buf.readerIndex();
LevelChunkSection section = new LevelChunkSection(factory);
section.read(buf);
StringBuilder states = new StringBuilder();
for (int y = 0; y < 16; y++) for (int z = 0; z < 16; z++) for (int x = 0; x < 16; x++) {
states.append(net.minecraft.world.level.block.Block.getId(section.getBlockState(x, y, z))).append(',');
}
StringBuilder biomes = new StringBuilder();
for (int y = 0; y < 4; y++) for (int z = 0; z < 4; z++) for (int x = 0; x < 4; x++) {
biomes.append(section.getNoiseBiome(x, y, z).getRegisteredName()).append(',');
}
byte[] bytes = new byte[buf.readerIndex() - start];
buf.getBytes(start, bytes);
record("chunk-section", index++ + " states=" + sha(states.toString().getBytes()) + " biomes=" + sha(biomes.toString().getBytes())
+ " count=" + (((bytes[0] & 0xFF) << 8) | (bytes[1] & 0xFF)) + " bytes=" + sha(bytes));
}
StringBuilder entities = new StringBuilder();
data.forEachBlockEntityTag(p.x(), p.z(), (pos, type, tag) -> entities.append(pos.toShortString()).append(' ')
.append(net.minecraft.core.registries.BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(type)).append(' ').append(tag).append(';'));
record("chunk-block-entities", entities.toString());
var light = p.lightData();
record("chunk-light-masks", light.skyYMask() + " " + light.blockYMask() + " " + light.emptySkyYMask() + " " + light.emptyBlockYMask());
StringBuilder sky = new StringBuilder();
for (byte[] b : light.skyUpdates()) sky.append(sha(b)).append(' ');
record("chunk-light-sky", sky.toString());
StringBuilder block = new StringBuilder();
for (byte[] b : light.blockUpdates()) block.append(sha(b)).append(' ');
record("chunk-light-block", block.toString());
}
/** The first play packets: entity ids, seeds and times aside. */
private String summary(Received r) {
String t = r.type;
+11
View File
@@ -174,6 +174,15 @@ def console_lines(lines):
text = re.sub(r'/127\.0\.0\.1:\d+', '/127.0.0.1:_', m.group(2))
text = re.sub(r'entity id \d+', 'entity id _', text)
out.append(f'[{m.group(1)}] {text}')
# Vanilla saves its levels in the order of an identity-hashed map, which
# changes between runs: each block of saves is compared sorted.
i = 0
while i < len(out):
j = i
while j < len(out) and 'Saving chunks for level' in out[j]:
j += 1
out[i:j] = sorted(out[i:j])
i = j + 1 if j == i else j
return out
@@ -188,6 +197,8 @@ def server_files(directory):
if name in ('server.properties', 'eula.txt'):
# The second comment line is the date Properties.store wrote.
text = re.sub(r'^(#[^\n]*\n)#[^\n]*\n', r'\1#<date>\n', text)
# Random per server, and each side has its own port.
text = re.sub(r'\n(management-server-secret|server-port)=[^\n]*', r'\n\1=<varies>', text)
out.append(f'{name}: {text!r}')
return out