Merge pull request #586 from ludovic111/feat/server-move-checks

Dedicated server: vanilla's chunk pacing and movement checks
This commit is contained in:
Ludovic Marie
2026-10-17 17:27:33 +02:00
committed by GitHub
7 changed files with 299 additions and 42 deletions
+2 -1
View File
@@ -121,6 +121,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
clock_rate: 1.0,
tick_rate: 20.0,
tick_frozen: false,
collision: None,
};
for event in hub.tick(&mut ctx) {
match event {
@@ -132,7 +133,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
eprintln!("[lan] {packet:?}");
}
}
HostEvent::Chat(line) => println!("{line}"),
HostEvent::Chat(line) | HostEvent::Warn(line) => println!("{line}"),
HostEvent::Left(_) => {}
}
}
+10
View File
@@ -788,7 +788,12 @@ impl Game<'_> {
},
tick_rate: self.clock.rate(),
tick_frozen: self.clock.frozen(),
collision: Some(self.collision),
};
host.hub.movement_checks = (
self.ui.rules.bool("player_movement_check"),
self.ui.rules.bool("elytra_movement_check"),
);
host.hub.tick(&mut ctx)
};
if let Some(state) = &state
@@ -852,6 +857,10 @@ impl Game<'_> {
super::dedicated::log("INFO", &format!("[Not Secure] {line}"));
}
HostEvent::Chat(line) => self.system_message(Text::literal(line)),
HostEvent::Warn(line) if self.options.dedicated.is_some() => {
super::dedicated::log("WARN", &line);
}
HostEvent::Warn(line) => log::warn!("{line}"),
HostEvent::Packet(conn, packet) => {
self.lan_guest_packet(&mut host, conn, *packet);
}
@@ -918,6 +927,7 @@ impl Game<'_> {
clock_rate: self.ui.clock.rate,
tick_rate: self.clock.rate(),
tick_frozen: self.clock.frozen(),
collision: Some(self.collision),
};
host.hub.place_new_player(conn, &mut ctx);
}
@@ -944,6 +944,7 @@ impl Game<'_> {
},
tick_rate: self.clock.rate(),
tick_frozen: self.clock.frozen(),
collision: Some(self.collision),
};
host.hub.respawn(i, spawn, &ctx);
}
@@ -243,6 +243,7 @@ impl Game<'_> {
},
tick_rate: self.clock.rate(),
tick_frozen: self.clock.frozen(),
collision: Some(self.collision),
}
}
}
+24 -2
View File
@@ -73,15 +73,31 @@ pub struct Guest {
/// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient).
pub awaiting_teleport: Option<(i32, [f64; 3])>,
pub teleport_counter: i32,
/// The hub tick the pending teleport was (re)sent on (awaitingTeleportTime).
pub teleport_tick: u64,
/// Where the player was when this tick's packets began (firstGoodX/Y/Z),
/// for the moved-too-quickly check.
pub first_good: [f64; 3],
/// Position moves received in all and by the start of this tick
/// (receivedMovePacketCount, knownMovePacketCount).
pub received_moves: i32,
pub known_moves: i32,
/// A position move arrived since the client's last ClientTickEnd
/// (receivedPositionThisTick): a second one is a protocol error.
pub position_this_tick: bool,
/// The client finished loading terrain (ServerboundPlayerLoadedPacket).
pub loaded: bool,
// Chunks.
pub center: Option<(i32, i32)>,
pub sent_chunks: crate::fast_hash::FxHashSet<(i32, i32)>,
pub chunk_queue: Vec<(i32, i32)>,
/// PlayerChunkSender: batches sent but not yet acknowledged, how many
/// may be (1 until the client's first acknowledgement, then 10), the
/// rate the client asks for and the chunks the next batch may hold.
pub unacknowledged: u32,
pub max_unacknowledged: u32,
pub chunks_per_tick: f32,
pub chunk_credit: f32,
pub batch_quota: f32,
// Entities.
pub tracker: Tracker,
// Player state the gameplay code reads and writes.
@@ -187,13 +203,19 @@ impl Guest {
sleeping: false,
awaiting_teleport: None,
teleport_counter: 0,
teleport_tick: 0,
first_good: position,
received_moves: 0,
known_moves: 0,
position_this_tick: false,
loaded: false,
center: None,
sent_chunks: Default::default(),
chunk_queue: Vec::new(),
unacknowledged: 0,
max_unacknowledged: 1,
chunks_per_tick: 9.0,
chunk_credit: 0.0,
batch_quota: 0.0,
tracker: Tracker::default(),
motion: None,
inventory: vec![None; 36],
+260 -39
View File
@@ -12,17 +12,24 @@ use super::{
guest::{Guest, SentEffect, stack_to_network},
};
use crate::{
collisions::SceneCollisions,
effects::{EffectInstance, PlayerEffects},
items::ItemStack,
world::World,
};
use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape};
use horizon_protocol::ids::play::clientbound as ids;
use horizon_protocol::{
entity_data::{Value, serializer},
packets::play::{self, Clientbound as C, Serverbound as S},
text::{literal, translatable},
};
use horizon_world::nbt::{JavaString, Tag};
use horizon_world::{
block_collision::BlockCollisionRegistry,
block_collision_scan::BlockCollisionScan,
collision_context::CollisionContext,
nbt::{JavaString, Tag},
};
use std::sync::{Arc, atomic::Ordering};
/// GameEvent types (ClientboundGameEventPacket).
@@ -88,6 +95,9 @@ pub struct TickCtx<'a> {
/// TickRateManager: the tick rate and whether the game is frozen.
pub tick_rate: f32,
pub tick_frozen: bool,
/// Block collisions, for ServerGamePacketListenerImpl's moved-wrongly
/// check (none: moves are not checked against blocks).
pub collision: Option<&'a BlockCollisionRegistry<'a>>,
}
/// What the gameplay code has to do for a guest.
@@ -99,6 +109,8 @@ pub enum HostEvent {
Packet(u32, Box<S>),
/// A chat line to show on the host (already broadcast to the guests).
Chat(String),
/// A server log warning (ServerGamePacketListenerImpl's LOGGER.warn).
Warn(String),
}
pub struct Hub {
@@ -108,6 +120,9 @@ pub struct Hub {
pub guests: Vec<Guest>,
pub(super) sync: Arc<SyncData>,
pub ticks: u64,
/// The `player_movement_check` and `elytra_movement_check` game rules,
/// set by the game before each tick.
pub movement_checks: (bool, bool),
last_clock: i64,
last_rate: f32,
ticking: (f32, bool),
@@ -199,6 +214,7 @@ impl Hub {
guests: Vec::new(),
sync,
ticks: 0,
movement_checks: (true, true),
last_clock: i64::MIN,
last_rate: 0.0,
ticking: (20.0, false),
@@ -727,7 +743,9 @@ impl Hub {
/// ServerGamePacketListenerImpl.teleport: move the client and wait for its confirmation.
pub fn teleport(&mut self, i: usize, position: Option<[f64; 3]>) {
let ticks = self.ticks;
let g = &mut self.guests[i];
g.teleport_tick = ticks;
if let Some(p) = position {
g.position = p;
g.previous_position = p;
@@ -1082,15 +1100,16 @@ impl Hub {
g.chunk_queue
.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2));
}
// Send ready chunks, closest first, in batches.
if g.chunk_queue.is_empty() || g.unacknowledged >= 10 || self.ticks <= g.placed_at + 1 {
// PlayerChunkSender.sendNextChunks: ready chunks, closest first, in
// batches the client's acknowledgements pace.
if self.ticks <= g.placed_at + 1 || g.unacknowledged >= g.max_unacknowledged {
return;
}
g.chunk_credit = (g.chunk_credit + g.chunks_per_tick).min(g.chunks_per_tick.max(1.0) * 2.0);
let budget = g.chunk_credit.floor() as usize;
if budget == 0 {
g.batch_quota = (g.batch_quota + g.chunks_per_tick).min(g.chunks_per_tick.max(1.0));
if g.batch_quota < 1.0 || g.chunk_queue.is_empty() {
return;
}
let budget = g.batch_quota.floor() as usize;
let mut packets = Vec::new();
let mut taken = Vec::new();
for (idx, key) in g.chunk_queue.iter().enumerate() {
@@ -1111,7 +1130,7 @@ impl Hub {
if packets.is_empty() {
return;
}
g.chunk_credit -= packets.len() as f32;
g.batch_quota -= packets.len() as f32;
g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty));
for p in &packets {
g.send(p);
@@ -1574,6 +1593,11 @@ impl Hub {
}
fn process_inbox(&mut self, i: usize, ctx: &mut TickCtx, events: &mut Vec<HostEvent>) {
// ServerGamePacketListenerImpl.tickPlayer ran between the last
// tick's packets and these: resetPosition, and the moves it counted.
let g = &mut self.guests[i];
g.first_good = g.position;
g.known_moves = g.received_moves;
let mut budget = 400;
while budget > 0 {
let Some(packet) = self.guests[i].inbox.pop_front() else {
@@ -1602,23 +1626,42 @@ impl Hub {
self.guests[i].last_action_tick = self.ticks;
}
match packet {
// handleAcceptTeleportPacket.
S::AcceptTeleportation(p) => {
let g = &mut self.guests[i];
if g.awaiting_teleport.is_some_and(|(id, _)| id == p.id) {
if let Some((id, at)) = g.awaiting_teleport
&& id == p.id
{
if p.x.is_nan()
|| p.y.is_nan()
|| p.z.is_nan()
|| !p.yaw.is_finite()
|| !p.pitch.is_finite()
{
self.kick(conn, invalid_movement());
continue;
}
g.position = at;
g.awaiting_teleport = None;
let rot = (p.yaw, p.pitch);
self.position_change(i, [p.x, p.y, p.z], rot, 0, ctx, events);
}
}
S::MovePlayerPos(p) => {
self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags);
self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags, ctx, events);
}
S::MovePlayerPosRot(p) => {
self.move_player(i, Some([p.x, p.y, p.z]), Some((p.yaw, p.pitch)), p.flags);
let (pos, rot) = ([p.x, p.y, p.z], (p.yaw, p.pitch));
self.move_player(i, Some(pos), Some(rot), p.flags, ctx, events);
}
S::MovePlayerRot(p) => {
self.move_player(i, None, Some((p.yaw, p.pitch)), p.flags);
self.move_player(i, None, Some((p.yaw, p.pitch)), p.flags, ctx, events);
}
S::MovePlayerStatus(p) => {
self.move_player(i, None, None, p.flags, ctx, events);
}
S::MovePlayerStatus(p) => self.move_player(i, None, None, p.flags),
S::PlayerLoaded(_) => self.guests[i].loaded = true,
// PlayerChunkSender.onChunkBatchReceivedByClient.
S::ChunkBatchReceived(p) => {
let g = &mut self.guests[i];
g.unacknowledged = g.unacknowledged.saturating_sub(1);
@@ -1627,7 +1670,12 @@ impl Hub {
} else {
p.chunks_per_tick.clamp(0.01, 64.0)
};
if g.unacknowledged == 0 {
g.batch_quota = 1.0;
}
g.max_unacknowledged = 10;
}
S::ClientTickEnd(_) => self.guests[i].position_this_tick = false,
S::ClientInformation(info) => {
let g = &mut self.guests[i];
g.view_distance =
@@ -1646,7 +1694,6 @@ impl Hub {
0 => self.guests[i].sleeping = false,
_ => {}
},
S::ClientTickEnd(_) => {}
S::Chat(c) => {
let text: String = c.message.chars().filter(|c| !c.is_control()).collect();
if !text.is_empty() {
@@ -1658,48 +1705,205 @@ impl Hub {
other => events.push(HostEvent::Packet(conn, Box::new(other))),
}
}
let _ = ctx;
}
/// ServerGamePacketListenerImpl.handleMovePlayer.
fn move_player(&mut self, i: usize, pos: Option<[f64; 3]>, rot: Option<(f32, f32)>, flags: u8) {
let g = &mut self.guests[i];
if g.awaiting_teleport.is_some() || !g.loaded && g.ticks == 0 && pos.is_none() {
fn move_player(
&mut self,
i: usize,
pos: Option<[f64; 3]>,
rot: Option<(f32, f32)>,
flags: u8,
ctx: &TickCtx,
events: &mut Vec<HostEvent>,
) {
let conn = self.guests[i].conn;
// containsInvalidValues, on the packet's values (0 where it has none).
let (yaw, pitch) = rot.unwrap_or_default();
if pos.is_some_and(|p| p.iter().any(|v| v.is_nan()))
|| !yaw.is_finite()
|| !pitch.is_finite()
{
self.kick(conn, invalid_movement());
return;
}
if let Some(p) = pos {
if p.iter().any(|v| !v.is_finite() || v.abs() > 3.0e7) {
let g = &mut self.guests[i];
if pos.is_some() {
if g.position_this_tick {
self.kick(conn, invalid_movement());
return;
}
// A jump of more than a hundred blocks is a rejected move.
let d2: f64 = (0..3).map(|k| (p[k] - g.position[k]).powi(2)).sum();
if d2 > 100.0 * 100.0 {
let at = g.position;
self.teleport(i, Some(at));
return;
}
g.previous_position = g.position;
g.position = p;
g.position_this_tick = true;
}
let moved = pos.map_or([0.0; 3], |_| {
[0, 1, 2].map(|k| g.position[k] - g.previous_position[k])
});
if !g.loaded && g.ticks == 0 && pos.is_none() {
return;
}
// updateAwaitingTeleport: moves wait for the client to accept the
// teleport, which is sent again after 20 ticks without an answer.
if let Some((_, at)) = g.awaiting_teleport {
if self.ticks - g.teleport_tick > 20 {
self.teleport(i, Some(at));
}
return;
}
let to = pos.unwrap_or(g.position);
let rot = rot.unwrap_or((g.yaw, g.pitch));
self.position_change(i, to, rot, flags, ctx, events);
}
/// ServerGamePacketListenerImpl.handlePlayerPositionChange.
fn position_change(
&mut self,
i: usize,
to: [f64; 3],
(yaw, pitch): (f32, f32),
flags: u8,
ctx: &TickCtx,
events: &mut Vec<HostEvent>,
) {
let (frozen, (check, elytra_check)) = (self.ticking.1, self.movement_checks);
let g = &mut self.guests[i];
let to = [
to[0].clamp(-3.0E7, 3.0E7),
to[1].clamp(-2.0E7, 2.0E7),
to[2].clamp(-3.0E7, 3.0E7),
];
let (yaw, pitch) = (wrap_degrees(yaw), wrap_degrees(pitch));
let d = [0, 1, 2].map(|k| to[k] - g.first_good[k]);
let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
if g.sleeping {
if moved > 1.0 {
(g.yaw, g.pitch) = (yaw, pitch);
self.teleport(i, None);
}
return;
}
// TickRateManager.runsNormally: not frozen (a frozen game's steps
// are not counted either; Horizon's hub does not see them).
if !frozen {
g.received_moves += 1;
let mut packets = g.received_moves - g.known_moves;
if packets > 5 {
packets = 1;
}
// shouldCheckPlayerMovement. The server holds no velocity for a
// guest (getDeltaMovement), so nothing is expected.
if check && (!g.fall_flying || elytra_check) {
let limit = if g.fall_flying { 300.0 } else { 100.0 };
if moved > limit * f64::from(packets) {
events.push(HostEvent::Warn(format!(
"{} moved too quickly! {},{},{}",
g.name,
crate::java_text::double_to_string(d[0]),
crate::java_text::double_to_string(d[1]),
crate::java_text::double_to_string(d[2])
)));
self.teleport(i, None);
return;
}
}
}
let start = g.position;
let (wrongly, refused) = self.collide(i, to, ctx);
if wrongly {
let line = format!("{} moved wrongly!", self.guests[i].name);
events.push(HostEvent::Warn(line));
}
if refused {
let g = &mut self.guests[i];
(g.yaw, g.pitch) = (yaw, pitch);
self.teleport(i, Some(start));
return;
}
let g = &mut self.guests[i];
g.previous_position = g.position;
g.position = to;
let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]);
if g.moves.is_empty() {
g.moves_from_ground = g.on_ground;
}
g.moves.push((moved, flags & 1 != 0));
if let Some((yaw, pitch)) = rot
&& yaw.is_finite()
&& pitch.is_finite()
{
g.yaw = yaw % 360.0;
g.pitch = pitch.clamp(-90.0, 90.0);
g.head_yaw = g.yaw;
}
g.yaw = yaw;
g.pitch = pitch.clamp(-90.0, 90.0);
g.head_yaw = g.yaw;
g.on_ground = flags & 1 != 0;
g.ticks = g.ticks.max(1);
}
/// The collision part of handlePlayerPositionChange: whether the move
/// counts as moved wrongly (logged), and whether it is refused (the
/// player is sent back where they were).
fn collide(&self, i: usize, to: [f64; 3], ctx: &TickCtx) -> (bool, bool) {
let g = &self.guests[i];
// noPhysics (spectators) and sleepers move freely.
let Some(binding) = ctx.collision else {
return (false, false);
};
if g.spectator() || g.sleeping {
return (false, false);
}
let height = if g.fall_flying {
0.6
} else if g.sneaking {
1.5
} else {
1.8
};
let at = |p: [f64; 3]| {
Aabb::new(
Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3),
Vec3::new(p[0] + 0.3, p[1] + height, p[2] + 0.3),
)
};
let (old, new) = (at(g.position), at(to));
let mut scene = SceneCollisions {
world: ctx.world,
binding,
subject: None,
};
// player.move, then how far from the target it ended (vanilla drops
// the vertical part: `yDist > -0.5 || yDist < 0.5` always holds).
let movement = Vec3::new(
to[0] - g.position[0],
to[1] - g.position[1],
to[2] - g.position[2],
);
let fail = !g.creative()
&& scene
.resolve(old, movement, 0.6, g.on_ground)
.is_ok_and(|done| {
let (dx, dz) = (movement.x - done.x, movement.z - done.z);
dx * dx + dz * dz > 0.0625
});
if fail && scene.unobstructed(old).unwrap_or(true) {
return (true, true);
}
// isEntityCollidingWithAnythingNew: a block the old box did not
// already touch.
let shrink = f64::from(1.0E-5_f32);
let shrink = Vec3::new(shrink, shrink, shrink);
let Ok(old_shape) = VoxelShape::from_box(old.deflate(shrink)) else {
return (fail, false);
};
let context = CollisionContext::position(g.position[1]);
let Ok(scan) =
BlockCollisionScan::new(&mut scene, context, new.deflate(shrink), false, 1 << 20)
else {
return (fail, false);
};
for hit in scan {
let Ok(hit) = hit else { break };
if !hit
.shape
.join_is_not_empty(&old_shape, ShapeOp::AND)
.unwrap_or(true)
{
return (fail, true);
}
}
(fail, false)
}
/// Acknowledge a block interaction (ClientboundBlockChangedAckPacket).
/// ServerGamePacketListenerImpl.ackBlockChangesUpTo: sent with the next tick's block
/// changes (`tick`).
@@ -1927,6 +2131,23 @@ impl Hub {
}
/// A packet Horizon sends as raw bytes (no fields worth a type).
/// multiplayer.disconnect.invalid_player_movement.
/// Mth.wrapDegrees.
fn wrap_degrees(degrees: f32) -> f32 {
let mut wrapped = degrees % 360.0;
if wrapped >= 180.0 {
wrapped -= 360.0;
}
if wrapped < -180.0 {
wrapped += 360.0;
}
wrapped
}
fn invalid_movement() -> Tag {
translatable("multiplayer.disconnect.invalid_player_movement", &[])
}
fn raw(id: i32, payload: Vec<u8>) -> C {
C::Unknown(id, payload)
}
+1
View File
@@ -193,6 +193,7 @@ impl Server {
clock_rate: 1.0,
tick_rate: 20.0,
tick_frozen: false,
collision: None,
};
let events = self.hub.tick(&mut ctx);
for event in events {