Merge remote-tracking branch 'origin/main' into perf/shared-block-json-20261017

This commit is contained in:
rdbtCVS
2026-10-17 02:37:52 +01:00
6 changed files with 131 additions and 18 deletions
+39
View File
@@ -74,6 +74,10 @@ pub struct DebugCharts {
pub bandwidth: SampleLogger,
/// `MinecraftServer.smoothedTickTimeMillis`.
pub smoothed_tick_ms: f32,
/// Connection's smoothed packets per second, sent then received.
pub packet_rates: [f32; 2],
packet_totals: [i64; 2],
packet_tick: u8,
previous_tick: Option<Instant>,
bytes_seen: Option<i64>,
}
@@ -113,6 +117,9 @@ impl DebugCharts {
self.previous_tick = None;
self.bytes_seen = None;
self.smoothed_tick_ms = 0.0;
self.packet_rates = [0.0; 2];
self.packet_totals = [0; 2];
self.packet_tick = 0;
}
/// One integrated server tick that started at `started` and ran its
/// tick method for `method` (`MinecraftServer.logFullTickTime` and
@@ -136,6 +143,17 @@ impl DebugCharts {
}
self.bytes_seen = Some(total);
}
/// `Connection.tickSecond`: sampled on the first tick, then every 20 ticks.
pub fn log_packets(&mut self, totals: [i64; 2]) {
if self.packet_tick == 0 {
for (i, total) in totals.into_iter().enumerate() {
let count = (total - self.packet_totals[i]).max(0) as f32;
self.packet_rates[i] = count + 0.75 * (self.packet_rates[i] - count);
}
self.packet_totals = totals;
}
self.packet_tick = (self.packet_tick + 1) % 20;
}
/// The charts along the bottom of the screen (`extractRenderState`):
/// frame times left and tick times right, or bandwidth left (remote
/// servers only) and ping right. `mspt` is the level's milliseconds
@@ -524,6 +542,27 @@ mod tests {
assert!(draws.contains(&fill(361, 174, 365, 178, 0xFF0A_141E)));
}
#[test]
fn packet_rates_follow_connection_smoothing_and_reset_between_worlds() {
let mut charts = DebugCharts::default();
charts.log_packets([80, 400]);
assert_eq!(charts.packet_rates, [20.0, 100.0]);
for _ in 1..20 {
charts.log_packets([180, 800]);
}
assert_eq!(charts.packet_rates, [20.0, 100.0]);
charts.log_packets([180, 800]);
assert_eq!(charts.packet_rates, [40.0, 175.0]);
for _ in 0..20 {
charts.log_packets([180, 800]);
}
assert_eq!(charts.packet_rates, [30.0, 131.25]);
charts.reset();
assert_eq!(charts.packet_rates, [0.0, 0.0]);
charts.log_packets([4, 8]);
assert_eq!(charts.packet_rates, [1.0, 2.0]);
}
#[test]
fn ticks_and_bandwidth_log_their_differences() {
let mut c = DebugCharts::default();
+30 -15
View File
@@ -194,15 +194,17 @@ impl Game<'_> {
}
return;
};
let received = r
.session
.counters
.lock()
.unwrap()
.as_ref()
.map(|c| c.bytes_in.load(std::sync::atomic::Ordering::Relaxed));
if let Some(total) = received {
self.debug_charts.log_bandwidth(total);
let received = r.session.counters.lock().unwrap().as_ref().map(|c| {
let order = std::sync::atomic::Ordering::Relaxed;
[
c.bytes_in.load(order),
c.sent.load(order),
c.received.load(order),
]
});
if let Some([bytes, sent, received]) = received {
self.debug_charts.log_bandwidth(bytes);
self.debug_charts.log_packets([sent, received]);
}
if shown {
use horizon_protocol::packets::{play::Serverbound, status::Ping};
@@ -403,8 +405,9 @@ impl Game<'_> {
],
);
}
// tps: DebugEntryTps for the integrated server (it counts no packets).
if self.player.is_some() && self.remote.is_none() {
// tps: DebugEntryTps for local and remote connections.
if self.player.is_some() {
let [tx, rx] = self.debug_charts.packet_rates.map(|n| n.round() as i64);
let (target, status) = if self.clock.sprinting() {
("-".to_owned(), " (sprinting)")
} else if self.clock.stepping() {
@@ -417,10 +420,22 @@ impl Game<'_> {
} else {
(format!("{:.1}", 1000.0 / self.clock.rate()), "")
};
d.line(format!(
"Integrated server @ {:.1}/{target} ms{status}, 0 tx, 0 rx",
self.debug_charts.smoothed_tick_ms
));
if self.remote.is_none() || self.integrated.is_some() {
let tick_ms = self
.integrated
.as_ref()
.map_or(self.debug_charts.smoothed_tick_ms, |server| {
server.smoothed_tick_ms()
});
d.line(format!(
"Integrated server @ {tick_ms:.1}/{target} ms{status}, {tx} tx, {rx} rx",
));
} else if let Some(remote) = &self.remote {
d.line(format!(
"\"{}\" server{status}, {tx} tx, {rx} rx",
remote.brand
));
}
}
let (left, right) = d.columns(&self.debug_chart_lines());
let atlas = &self.atlas;
+11 -1
View File
@@ -26,7 +26,7 @@ use std::{
path::Path,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
atomic::{AtomicBool, AtomicU32, Ordering},
mpsc::{Sender, channel},
},
thread::JoinHandle,
@@ -39,6 +39,7 @@ struct Flags {
/// `Minecraft.pause`: a single-player pause screen is open.
paused: AtomicBool,
stop: AtomicBool,
smoothed_tick_ms: AtomicU32,
}
/// The window's handle on its server thread.
@@ -47,6 +48,9 @@ pub(super) struct Integrated {
thread: Option<JoinHandle<()>>,
}
impl Integrated {
pub fn smoothed_tick_ms(&self) -> f32 {
f32::from_bits(self.flags.smoothed_tick_ms.load(Ordering::Relaxed))
}
/// `IntegratedServer.tickServer` skips the world while the game is paused.
pub fn set_paused(&self, paused: bool) {
self.flags.paused.store(paused, Ordering::Relaxed);
@@ -233,7 +237,13 @@ impl Game<'_> {
// Only the connections run.
self.tick_lan();
} else {
let started = Instant::now();
self.tick()?;
self.debug_charts.log_tick(started, started.elapsed());
flags.smoothed_tick_ms.store(
self.debug_charts.smoothed_tick_ms.to_bits(),
Ordering::Relaxed,
);
}
let rate = self.clock.rate().max(1.0);
next += Duration::from_secs_f64(1.0 / f64::from(rate));
+7
View File
@@ -68,6 +68,7 @@ struct Lerp {
pub(super) struct Remote {
pub session: Session,
pub brand: String,
builtin: Arc<Builtin>,
lang: Arc<Language>,
registries: Arc<Dynamic>,
@@ -251,6 +252,7 @@ impl Game<'_> {
self.apply_settings();
self.remote = Some(Remote {
session,
brand: "unknown".into(),
builtin: Arc::new(builtin),
lang,
registries: Arc::new(Dynamic::default()),
@@ -456,6 +458,11 @@ impl Game<'_> {
r.status = format!("Joined as {name}; loading terrain...");
}
}
Event::Brand(brand) => {
if let Some(remote) = &mut self.remote {
remote.brand = brand;
}
}
Event::Reconfigured(registries) => self.set_registries(registries),
Event::DecodeError(e) => {
if let Some(r) = self.remote.as_mut() {
+42 -2
View File
@@ -29,6 +29,8 @@ use std::{
pub enum Event {
/// Progress text for the connecting screen.
Status(String),
/// The server's `minecraft:brand` custom payload.
Brand(String),
/// Configuration finished: the play state begins with these registries.
Joined {
registries: Arc<Dynamic>,
@@ -374,7 +376,7 @@ fn run(
.map_err(e)?;
let (mut reader, writer) = c.split();
*shared_writer.lock().unwrap() = Some(writer);
let registries = configure(&mut reader, shared_writer, lang)?;
let registries = configure(&mut reader, shared_writer, lang, send)?;
let _ = send.send(Event::Joined {
registries: Arc::new(registries),
uuid: profile.uuid,
@@ -413,10 +415,13 @@ fn run(
}
play::Clientbound::StartConfiguration(_) => {
reply(play::Serverbound::ConfigurationAcknowledged(Empty));
let registries = configure(&mut reader, shared_writer, lang)?;
let registries = configure(&mut reader, shared_writer, lang, send)?;
let _ = send.send(Event::Reconfigured(Arc::new(registries)));
}
play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)),
play::Clientbound::CustomPayload(p) if p.channel == "minecraft:brand" => {
receive_brand(&p, send);
}
other => {
if send.send(Event::Packet(Box::new(other))).is_err() {
return Ok("Disconnected".into());
@@ -432,6 +437,7 @@ fn configure(
reader: &mut ConnReader,
writer: &Mutex<Option<ConnWriter>>,
lang: &Language,
send: &Sender<Event>,
) -> Result<Dynamic, String> {
let mut registries = Dynamic::default();
let reply = |p: cfg::Serverbound| -> Result<(), String> {
@@ -444,6 +450,7 @@ fn configure(
let (id, payload) = reader.recv().map_err(|e| e.to_string())?;
match cfg::Clientbound::decode(id, &payload).map_err(|e| e.to_string())? {
cfg::Clientbound::KeepAlive(k) => reply(cfg::Serverbound::KeepAlive(k))?,
cfg::Clientbound::CustomPayload(p) => receive_brand(&p, send),
cfg::Clientbound::Ping(p) => reply(cfg::Serverbound::Pong(p))?,
// Know no packs: the server then sends every registry entry in full.
cfg::Clientbound::SelectKnownPacks(_) => {
@@ -477,6 +484,14 @@ fn configure(
}
}
fn receive_brand(payload: &cfg::CustomPayload, send: &Sender<Event>) {
if payload.channel == "minecraft:brand"
&& let Ok(brand) = horizon_protocol::buf::Reader::new(&payload.data).string(32767)
{
let _ = send.send(Event::Brand(brand));
}
}
/// The minecraft:brand payload: a string naming the client.
fn brand() -> Vec<u8> {
let mut w = horizon_protocol::buf::Writer::new();
@@ -565,3 +580,28 @@ pub fn ping(address: &str, timeout: Duration) -> Result<(serde_json::Value, u128
let _ = c.recv().map_err(e)?;
Ok((json, start.elapsed().as_millis()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn server_brand_payload_is_decoded_and_invalid_or_unrelated_payloads_are_ignored() {
let (send, events) = channel();
let mut writer = horizon_protocol::buf::Writer::new();
writer.string("vanilla");
let mut payload = cfg::CustomPayload {
channel: "minecraft:brand".into(),
data: writer.data,
};
receive_brand(&payload, &send);
assert!(matches!(events.try_recv(), Ok(Event::Brand(brand)) if brand == "vanilla"));
payload.channel = "example:other".into();
receive_brand(&payload, &send);
assert!(events.try_recv().is_err());
payload.channel = "minecraft:brand".into();
payload.data = vec![0xff];
receive_brand(&payload, &send);
assert!(events.try_recv().is_err());
}
}
@@ -355,6 +355,8 @@ mod tests {
big.extend(std::iter::repeat_n(3u8, 1000));
c.send(&big).unwrap();
assert_eq!(c.recv().unwrap(), (9, vec![1, 2]));
assert_eq!(c.reader.counters.sent.load(Ordering::Relaxed), 1);
assert_eq!(c.reader.counters.received.load(Ordering::Relaxed), 1);
server.join().unwrap();
assert!(c.recv().is_err());
}