Merge perf/sp-open-to-lan (with main) into perf/sp-server-state

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 03:41:08 +02:00
60 changed files with 6774 additions and 131 deletions
@@ -2985,6 +2985,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static
K::Explosion if player => "minecraft:player_explosion",
K::Explosion => "minecraft:explosion",
K::Fall => "minecraft:fall",
K::FallingBlock => "minecraft:falling_block",
K::OnFire => "minecraft:on_fire",
K::InFire => "minecraft:in_fire",
K::Lava => "minecraft:lava",
+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;
@@ -29,6 +29,8 @@ use std::{
time::{Duration, Instant},
};
mod status;
/// Double.toString for the magnitudes positions have (no exponent form
/// between 1e-3 and 1e7).
pub(super) fn java_double(v: f64) -> String {
@@ -64,6 +66,11 @@ pub(super) fn log(level: &str, message: &str) {
_ => ::log::Level::Info,
};
horizon_client::logging::write_only(file_level, message);
CAPTURE.with_borrow_mut(|lines| {
if let Some(lines) = lines {
lines.push(message.to_owned());
}
});
let secs = now_millis().div_euclid(1000).rem_euclid(86_400);
println!(
"[{:02}:{:02}:{:02}] [Server thread/{level}]: {message}",
@@ -73,6 +80,18 @@ pub(super) fn log(level: &str, message: &str) {
);
}
thread_local! {
/// The lines logged while a control request runs a console command.
static CAPTURE: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
}
/// Runs `f` and returns the lines it logged.
fn capture_log(f: impl FnOnce()) -> Vec<String> {
CAPTURE.set(Some(Vec::new()));
f();
CAPTURE.take().unwrap_or_default()
}
/// Main.main up to the server start: arguments, server.properties (stored
/// back at once), eula.txt. False when the process should stop here.
pub(super) fn preflight(options: &mut Options) -> Result<bool> {
@@ -289,6 +308,9 @@ struct ServerState {
stop: bool,
autosave: bool,
empty_ticks: i32,
/// When the last passes of the loop ended, for the tick rate horizon-server shows.
ticks: std::collections::VecDeque<Instant>,
paused: bool,
}
impl Game<'_> {
@@ -471,14 +493,18 @@ impl Game<'_> {
stop: false,
autosave: true,
empty_ticks: 0,
ticks: Default::default(),
paused: false,
};
let pause_after = props.pause_when_empty_seconds * 20;
let idle_timeout = props.player_idle_timeout;
let mut next = Instant::now();
while !state.stop {
let tick_start = Instant::now();
while let Ok(line) = state.console.try_recv() {
self.console_command(&mut state, &line);
}
self.poll_server_control(&mut state);
let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len());
if pause_after > 0 {
if players == 0 {
@@ -488,6 +514,7 @@ impl Game<'_> {
}
}
let paused = pause_after > 0 && state.empty_ticks >= pause_after;
state.paused = paused;
if paused && state.empty_ticks == pause_after {
log(
"INFO",
@@ -513,6 +540,9 @@ impl Game<'_> {
if idle_timeout > 0 {
self.kick_idle(idle_timeout);
}
// MinecraftServer.tickServer records each tick's time, for /tick query (and the status).
self.clock.record(tick_start.elapsed());
state.ticked(Instant::now());
let rate = self.clock.rate().max(1.0);
next += Duration::from_secs_f64(1.0 / f64::from(rate));
let now = Instant::now();
@@ -0,0 +1,100 @@
//! What `horizon-server` asks the dedicated server on its control endpoint (`--control-socket`, docs/server.md
//! section 2): `server-status` answers with the tick rate, the tick times `/tick query` reports, the players
//! and the loaded chunks; `console <line>` runs a console command and answers with the lines it logged.
use super::{ServerState, capture_log};
use crate::game::Game;
use serde_json::{Value, json};
use std::{
sync::atomic::Ordering,
time::{Duration, Instant},
};
/// The window the tick rate is measured over.
const TPS_WINDOW: Duration = Duration::from_secs(5);
impl ServerState {
/// One pass of the server loop ended.
pub(super) fn ticked(&mut self, at: Instant) {
self.ticks.push_back(at);
while self
.ticks
.front()
.is_some_and(|t| at.duration_since(*t) > TPS_WINDOW)
{
self.ticks.pop_front();
}
}
/// Ticks per second over the last few seconds.
fn tps(&self) -> f64 {
match (self.ticks.front(), self.ticks.back()) {
(Some(first), Some(last)) if self.ticks.len() > 1 => {
(self.ticks.len() - 1) as f64 / last.duration_since(*first).as_secs_f64().max(1e-9)
}
_ => 0.0,
}
}
}
impl Game<'_> {
/// Answers the requests waiting on the control endpoint.
pub(super) fn poll_server_control(&mut self, state: &mut ServerState) {
while let Some(request) = self.control.as_ref().and_then(|c| c.try_recv()) {
let reply = match request.line.trim().split_once(' ') {
_ if request.line.trim() == "server-status" => self.server_status(state),
Some(("console", line)) => {
// Command feedback is logged as system chat; the reply carries the text alone.
let output: Vec<String> = capture_log(|| self.console_command(state, line))
.into_iter()
.map(|l| {
l.strip_prefix("System chat: ")
.map_or(l.clone(), str::to_owned)
})
.collect();
json!({ "output": output })
}
_ => json!({ "error": format!("unknown request {:?}", request.line) }),
};
let _ = request.reply.send(reply.to_string());
}
}
fn server_status(&self, state: &ServerState) -> Value {
let millis = |nanos: u64| nanos as f64 / 1e6;
let samples = self.clock.sorted_samples();
// The percentiles `/tick query` prints (TickCommand.percentileToString).
let at = |q: f64| {
let i = ((samples.len() as f64 * q) as usize).min(samples.len().saturating_sub(1));
samples.get(i).copied().map_or(0.0, millis)
};
let (players, max_players) = self.lan.as_ref().map_or((Vec::new(), 0), |h| {
let players = h
.hub
.guests
.iter()
.map(|g| {
json!({
"name": g.name,
"uuid": horizon_protocol::crypto::uuid_string(g.uuid),
"address": g.address.ip().to_string(),
"ping_ms": g.latency.load(Ordering::Relaxed),
})
})
.collect();
(players, h.hub.lan.shared.max_players())
});
json!({
"tps": state.tps(),
"target_tps": self.clock.rate(),
"mspt": {
"average": millis(self.clock.average_nanos()),
"p50": at(0.5),
"p95": at(0.95),
"p99": at(0.99),
},
"players": players,
"max_players": max_players,
"chunks": self.world.chunks.len(),
"paused": state.paused,
})
}
}
@@ -0,0 +1,123 @@
//! Landing impacts for falling blocks, before their placement/drop decision.
use super::{FallingBlock, Game, Landing};
use horizon_client::{falling_block, items::ItemStack};
use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource};
use horizon_world::level::LevelEvent;
impl Game<'_> {
pub(super) fn finish_falling_block(&mut self, mut block: FallingBlock, pos: [i32; 3]) {
let anvil = self.res.facts.get(block.state).name.ends_with("anvil");
if let Some(impact) = block.damage.impact(block.fall_distance) {
if impact.amount > 0.0 {
falling_block::hurt_mobs(&mut self.mobs, block.position, impact.amount);
let kind = if anvil {
"minecraft:falling_anvil"
} else {
"minecraft:falling_block"
};
self.falling_hurt_player(block.position, impact.amount, kind);
if let Some(mut host) = self.lan.take() {
let bounds = falling_block::bounds(block.position);
let conns = host
.hub
.guests
.iter()
.filter(|g| {
g.placed
&& g.loaded
&& !g.dead
&& !g.creative()
&& !g.spectator()
&& bounds.intersects(super::lan_mobs::guest_bounds(g))
})
.map(|g| g.conn)
.collect::<Vec<_>>();
for conn in conns {
self.guest_hit_by(&mut host, conn, |g| {
g.falling_hurt_player(block.position, impact.amount, kind)
});
}
self.lan = Some(host);
}
}
if anvil
&& impact.wear_chance > 0.0
&& self.world.random.next_float() < impact.wear_chance
&& let Some(mut state) = self.pack.assets.registry.state(block.state).cloned()
{
if falling_block::wear_anvil(&mut state) {
block.state = self
.pack
.assets
.registry
.resolve(&state)
.unwrap_or(block.state);
} else {
block.damage.cancel_drop = true;
}
}
}
if block.damage.cancel_drop {
if anvil {
self.level_events.push(LevelEvent::LevelEvent {
id: 1029,
pos: BlockPos::new(pos[0], pos[1], pos[2]),
data: 0,
});
}
return;
}
let landing = self.with_level(|b, level, ticks| {
b.falling_block_landed(
level,
ticks,
BlockPos::new(pos[0], pos[1], pos[2]),
block.state,
false,
)
});
if matches!(landing, Landing::Broken)
&& block.drop_item
&& self.ui.rules.bool("entity_drops")
{
let item = self.res.facts.get(block.state).item.clone();
if &*item != "minecraft:air" {
self.pop_resource(
pos,
ItemStack {
item,
count: 1,
damage: 0,
extra: None,
},
);
}
}
}
fn falling_hurt_player(&mut self, position: Vec3, amount: f32, kind: &str) {
if self.creative || self.spectator() {
return;
}
if self.player.as_ref().is_none_or(|p| {
p.health.dead_or_dying() || !falling_block::bounds(position).intersects(p.bounds())
}) {
return;
}
let amount = if self.armor[0].is_some() {
amount * 0.75
} else {
amount
};
let hurt = if let Some(p) = self.player.as_mut()
&& let Some(id) = self.motion.health.damage.id(kind)
{
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
.unwrap_or(false)
} else {
false
};
if hurt {
self.hurt_armor(amount);
}
}
}
+12
View File
@@ -30,6 +30,18 @@ fn attack_range_contains(range: &serde_json::Value, distance: f64, creative: boo
}
impl Game<'_> {
/// Opening a screen stops breaking before the next game tick (which may pause).
pub(super) fn stop_mining(&mut self) {
let mut destroying = std::mem::take(&mut self.clicks.destroying);
destroying.stop(&mut GameHands {
game: self,
error: None,
});
self.clicks.destroying = destroying;
self.attack_clicks = 0;
self.stop_remote_mining();
self.mining = None;
}
/// `LivingEntity.swing` with `getModifiedSwingDuration`.
pub(super) fn swing_hand(&mut self, hand: Hand, animation: SwingAnimation) {
let effects = &self.potions.effects;
+11 -1
View File
@@ -31,7 +31,7 @@ use std::{
path::Path,
sync::{
Arc,
atomic::{AtomicBool, AtomicU16, Ordering},
atomic::{AtomicBool, AtomicU16, AtomicU32, Ordering},
mpsc::{Receiver, Sender, channel, sync_channel},
},
thread::JoinHandle,
@@ -47,6 +47,7 @@ struct Flags {
/// `IntegratedServer.getPort`: the port it is open to the LAN on, 0
/// while it is not.
published: AtomicU16,
smoothed_tick_ms: AtomicU32,
}
/// Work the window hands its server thread (`MinecraftServer.execute`).
@@ -61,6 +62,9 @@ pub(super) struct Integrated {
pub world_name: String,
}
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);
@@ -322,7 +326,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,
);
}
self.apply_publish();
let rate = self.clock.rate().max(1.0);
+11
View File
@@ -17,6 +17,17 @@ pub(super) const CONTROL_HELP: &[&str] = &[
];
impl Game<'_> {
pub(super) fn save_title_options(&mut self) {
if let Some(title) = &self.title
&& title.last_server != self.settings.file.string("lastServer")
{
self.settings.file.set(
"lastServer",
horizon_client::options_file::V::Str(title.last_server.clone()),
);
self.settings.save(&Self::options_path());
}
}
/// `options-get` and `options-set`; None for other commands.
pub(super) fn options_control(&mut self, words: &[&str], line: &str) -> Result<Option<Value>> {
match words[0] {
+1
View File
@@ -354,6 +354,7 @@ impl Game<'_> {
}
if let Some(title) = self.title.as_mut() {
title.escape();
self.save_title_options();
return Ok(());
}
if self.sign_edit.is_some() {
+9 -12
View File
@@ -49,16 +49,7 @@ fn with_raw(modelled: Tag, raw: Option<&Tag>) -> Tag {
// Defaults Horizon invents for fields it does not simulate give way to the save.
let invented = matches!(
k.to_string_lossy().as_str(),
"Fire"
| "Air"
| "Invulnerable"
| "PortalCooldown"
| "HasBeenShot"
// FallingBlockEntity fields Horizon does not simulate.
| "HurtEntities"
| "CancelDrop"
| "FallHurtAmount"
| "FallHurtMax"
"Fire" | "Air" | "Invulnerable" | "PortalCooldown" | "HasBeenShot"
);
if !(invented && out.contains_key(k)) {
out.insert(k.clone(), v.clone());
@@ -199,7 +190,7 @@ impl Game<'_> {
}
}
"minecraft:falling_block" => {
if let Some((state, position, velocity, age)) =
if let Some((state, position, velocity, age, fall_distance)) =
entity_nbt::falling_block_from_nbt(&tag)
&& let Some(state) = self.state_from_nbt(&state)
{
@@ -214,7 +205,11 @@ impl Game<'_> {
age,
no_gravity,
drop_item,
fall_distance: 0.0,
fall_distance,
damage: horizon_client::falling_block::Damage::from_nbt(
&tag,
self.res.facts.get(state).name.ends_with("anvil"),
),
saved: uuid.map(|u| Box::new((u, tag.clone()))),
});
}
@@ -620,6 +615,8 @@ impl Game<'_> {
f.velocity,
f.age,
f.drop_item,
f.damage,
f.fall_distance,
uuid,
);
out.entry(chunk_of(f.position))
+35 -10
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>,
@@ -153,7 +154,20 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo
impl Game<'_> {
/// Leave the title for a server (ConnectScreen): an empty world fed by the connection.
pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> {
self.join_server(address, name, None)
if let Err(error) = self.join_server(address, name, None) {
log::warn!("Horizon: could not join server: {error}");
if self.title.is_none() {
self.title = Some(horizon_client::title::Title::new(
std::env::current_dir()?.join("saves"),
&self.options.resources,
));
}
if let Some(title) = &mut self.title {
title.failed(error);
}
self.capture(false);
}
Ok(())
}
/// Join single player's integrated server through memory.
pub(super) fn connect_local(
@@ -173,7 +187,7 @@ impl Game<'_> {
let root = self.options.resources.clone();
let builtin = Builtin::find(&root)
.and_then(|p| Builtin::load(&p).ok())
.ok_or("registries.json not found next to the resources; run the data generator reports (horizon-prepare)")?;
.ok_or("Resources are incomplete: registries.json is missing or invalid. Click \"Prepare again\" in the launcher (or run horizon-prepare), then try again.")?;
let lang = Arc::new(horizon_client::net::load_language(&root));
let view = self.settings.render_distance.clamp(2, 32) as i8;
if local.is_none() {
@@ -238,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()),
@@ -330,6 +345,7 @@ impl Game<'_> {
}
let saves = std::env::current_dir()?.join("saves");
let mut title = horizon_client::title::Title::new(saves.clone(), &self.options.resources);
title.last_server = self.settings.file.string("lastServer");
if single_player && reason.is_none() {
self.title = Some(title);
self.capture(false);
@@ -467,6 +483,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() {
@@ -2101,6 +2122,17 @@ impl Game<'_> {
}
}
pub(super) fn stop_remote_mining(&mut self) {
if let Some((pos, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) {
self.send(S::PlayerAction(play::PlayerAction {
action: 2,
pos,
direction: 0,
sequence: 0,
}));
}
}
/// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock.
fn remote_mining(&mut self) {
let Some(r) = self.remote.as_mut() else {
@@ -2111,14 +2143,7 @@ impl Game<'_> {
}
let chatting = r.chat_input.is_some();
if !self.left || self.screen != Screen::Playing || chatting {
if let Some((pos, _, _)) = r.destroying.take() {
self.send(S::PlayerAction(play::PlayerAction {
action: 2,
pos,
direction: 0,
sequence: 0,
}));
}
self.stop_remote_mining();
self.mining = None;
return;
}
+6 -6
View File
@@ -146,9 +146,6 @@ impl Game<'_> {
.find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
.map(|b| b.4)
};
if hit.is_some() && !horizon_client::ui_theme::horizon() {
self.audio.play_button_click();
}
match hit {
Some(0) => {
self.screen = Screen::Playing;
@@ -168,6 +165,9 @@ impl Game<'_> {
Some(2) => self.close_world()?,
_ => {}
}
if hit.is_some() && !horizon_client::ui_theme::horizon() {
self.audio.play_button_click();
}
Ok(())
}
/// DeathScreen: gradient, the title at double size, the cause and score.
@@ -260,9 +260,6 @@ impl Game<'_> {
.into_iter()
.find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0))
.map(|d| d.3);
if hit.is_some() {
self.audio.play_button_click();
}
match hit {
Some(0) if self.remote.is_some() => {
self.ui.death_text = None;
@@ -292,6 +289,9 @@ impl Game<'_> {
Some(1) => self.close_world()?,
_ => {}
}
if hit.is_some() {
self.audio.play_button_click();
}
Ok(())
}
}