From a0bcc13f1c046f845b81c95bc7bfcc3903b6e7ff Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 18 Oct 2026 20:24:09 +0200 Subject: [PATCH] Tick blocks around every player, from vanilla's chunk tickets (#890) Without a local player (dedicated server, --server-thread) no block ticked: tick_blocks returned early, so crops, fluids, redstone, pistons and pressure plates stood still, and a LAN host ticked only around itself. ticket_levels ports DistanceManager's levels: PLAYER_LOADING at 31 within the view distance and PLAYER_SIMULATION at 31 - simulation distance for every player in the level (the local player, LAN guests, a server's players), and FORCED at 31. Random ticks run in simulation entity-ticking chunks that are ticking chunks, scheduled ticks, block events and block entities in block ticking ones, entities in entity ticking ones; the sculk blocks follow the same rule. Saved ticks unpack when a chunk starts ticking (startTickingChunk), not when it loads. The hub keeps the tick-rate state current while nobody is in the game, so a player joining a frozen server is told once (updateJoiningPlayer). dedicated_server parity froze nothing while the client was sent its chunks: saved fluid ticks there (a lava fall that never settles) ran before or after the chunk was sent depending on each server's loading speed, and it failed on main too. It now freezes the game until the client has its chunks. lan_e2e gets a growth check: water flows and wheat grows next to a guest 1000 blocks from the host. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 79 +++++- .../src/game/block_entity_ticks.rs | 25 +- crates/horizon-client/src/game/creatures.rs | 21 +- crates/horizon-client/src/game/levels.rs | 6 +- crates/horizon-client/src/game/persist.rs | 8 +- crates/horizon-client/src/game/sculk.rs | 14 +- .../horizon-client/src/game/sculk_fixture.rs | 2 + crates/horizon-client/src/lan/hub.rs | 6 + crates/horizon-client/src/lib.rs | 1 + .../src/tick_chunk_membership.rs | 45 ++++ crates/horizon-client/src/ticket_levels.rs | 232 ++++++++++++++++++ tools/lan_e2e.py | 48 +++- tools/test_dedicated_server_parity.py | 10 + 13 files changed, 431 insertions(+), 66 deletions(-) create mode 100644 crates/horizon-client/src/ticket_levels.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index dc56fc4fa..2cbdabaa4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -480,6 +480,8 @@ struct GameLevel<'w> { rand_sequences: &'w mut horizon_client::random_sequences::RandomSequences, pending: &'w mut spill::Pending, spill: &'w mut spill::Spill, + /// Where the chunk tickets let blocks tick. + tickets: horizon_client::ticket_levels::Levels, } struct PlayerCollision { y: f64, @@ -677,6 +679,11 @@ impl LevelAccess for GameLevel<'_> { ) .unwrap_or(false) } + /// `ServerLevel.isPositionTickingWithEntitiesLoaded`: block ticking, and + /// a ticking chunk. + fn is_ticking_chunk(&self, chunk: horizon_core::position::ChunkPos) -> bool { + self.tickets.block_ticking(chunk.x, chunk.z) && ticking_chunk(self.world, chunk.x, chunk.z) + } /// Entities that trigger pressure plates, tripwires and detector rails: /// the players (the host and the LAN guests, mobs) and the minecarts. fn count_entities(&self, area: Aabb, query: EntityQuery) -> usize { @@ -953,6 +960,12 @@ struct DragView { left: Option, } /// Ctrl+Q reads the physical keyboard, independently of sprint key mappings. +/// A chunk whose ticking future can complete (`ChunkMap.prepareTickingChunk`): +/// lit, with its neighbours loaded, as `postprocess_chunks` waits for. +fn ticking_chunk(world: &World, x: i32, z: i32) -> bool { + world.chunks.get(&(x, z)).is_some_and(|c| c.lit) + && (-1..=1).all(|dz| (-1..=1).all(|dx| world.chunks.contains_key(&(x + dx, z + dz)))) +} fn drop_whole_stack(physical_keys: &HashSet) -> bool { physical_keys.contains(&KeyCode::ControlLeft) || physical_keys.contains(&KeyCode::ControlRight) } @@ -1205,6 +1218,7 @@ struct Game<'a> { end: end::EndState, block_ticks: Ticks, tick_chunks: horizon_client::tick_chunk_membership::TickChunkMembership, + tickets: horizon_client::ticket_levels::ChunkTickets, random_tick_sections: horizon_client::random_tick_sections::RandomTickSections, level_events: Vec, falling: Vec, @@ -2038,6 +2052,7 @@ impl Game<'_> { rand_sequences: &mut self.rand_sequences, pending: &mut self.pending, spill: &mut self.spill, + tickets: self.tickets.levels(), }; let result = f(self.res.behaviours(), &mut level, &mut self.block_ticks); self.flush_spill(); @@ -2080,22 +2095,62 @@ impl Game<'_> { } self.tick_chunks.recycle_added(added); } - /// ServerLevel.tick block phases: scheduled ticks, random ticks within the - /// simulation distance, block events and moving pistons. + /// `DistanceManager`'s tickets of the level in place, from every player in + /// it (the local player, LAN guests, a server's players) and its forced + /// chunks. A game with neither a server nor a player (the headless + /// fixtures) ticks everywhere. + fn update_chunk_tickets(&mut self) { + let mut players: Vec<(i32, i32)> = self.lan.as_ref().map_or_else(Vec::new, |h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g)) + .map(|g| g.chunk()) + .collect() + }); + if let Some(p) = &self.player { + players.push(( + (p.position.x.floor() as i32) >> 4, + (p.position.z.floor() as i32) >> 4, + )); + } + let sources = (self.options.dedicated.is_some() || !players.is_empty()).then(|| { + horizon_client::ticket_levels::Sources { + players, + forced: self.streaming.forced.iter().copied().collect(), + view_distance: self.settings.render_distance.clamp(2, 32), + simulation_distance: self.settings.simulation_distance.max(2), + } + }); + self.tickets.update(sources); + } + /// `ServerLevel.startTickingChunk`: a loaded chunk's saved ticks are + /// scheduled from the game time at which it becomes a ticking chunk + /// (block ticking, with its neighbours loaded). Chunks become ticking + /// between ticks in vanilla: before this tick's clock advanced. + fn start_ticking_chunks(&mut self) { + let levels = self.tickets.levels(); + let world = &self.world; + let started = self + .tick_chunks + .start_ticking(|(x, z)| levels.loaded_ticking(x, z) && ticking_chunk(world, x, z)); + let time = self.world.game_time - 1; + for (x, z) in started { + let pos = horizon_core::position::ChunkPos::new(x, z); + self.block_ticks.blocks.unpack_chunk(pos, time); + self.block_ticks.fluids.unpack_chunk(pos, time); + } + } + /// ServerLevel.tick block phases: scheduled ticks, random ticks in the + /// chunks the tickets simulate, block events and moving pistons. fn tick_blocks(&mut self) -> Result<()> { self.sync_tick_chunks(); - let Some(p) = self.player.as_ref() else { - return Ok(()); - }; - let (pcx, pcz) = ( - (p.position.x.floor() as i32) >> 4, - (p.position.z.floor() as i32) >> 4, - ); - let simulation = self.settings.render_distance.min(8); + self.start_ticking_chunks(); + let levels = self.tickets.levels(); let mut ticking = Vec::new(); let facts = self.res.facts(); for (&(x, z), chunk) in &self.world.chunks { - if (x - pcx).abs() > simulation || (z - pcz).abs() > simulation || !chunk.lit { + if !levels.random_ticking(x, z) || !ticking_chunk(&self.world, x, z) { continue; } // Capture eligibility before inside-block and scheduled updates, as @@ -3872,6 +3927,7 @@ impl Game<'_> { /// What the tick runs after the local player's own update: effects, the /// world's entities and blocks, and the network hub. fn tick_world(&mut self, running: bool) -> Result<()> { + self.update_chunk_tickets(); horizon_client::spans::time("tick_effects", || self.tick_effects()); horizon_client::spans::time("tick_using", || self.tick_using()); horizon_client::spans::time("tick_hud", || self.tick_hud()); @@ -10683,6 +10739,7 @@ impl<'a> Game<'a> { end: Default::default(), block_ticks: Ticks::new(0), tick_chunks: Default::default(), + tickets: Default::default(), random_tick_sections: Default::default(), level_events: Vec::new(), falling: Vec::new(), diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs index 1c0258871..bb1cadd15 100644 --- a/crates/horizon-client/src/game/block_entity_ticks.rs +++ b/crates/horizon-client/src/game/block_entity_ticks.rs @@ -101,27 +101,12 @@ impl Game<'_> { }) .collect() } - /// `ServerLevel.shouldTickBlocksAt`: chunks within the simulation - /// distance plus one (`DistanceManager.inBlockTickingRange`, Chebyshev - /// in chunks) of the player or a guest. With nobody there, a dedicated - /// server ticks none; the game alone (no player yet, headless fixtures) - /// ticks every chunk. + /// `ServerLevel.shouldTickBlocksAt` in a block-ticking chunk + /// (`LevelChunk.isTicking`, block coordinates), from every player's + /// tickets (`update_chunk_tickets`). fn block_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> { - let d = self.settings.simulation_distance.max(2) + 1; - let mut centres: Vec<(i32, i32)> = self.streaming.extra.iter().map(|&(c, _)| c).collect(); - if let Some(p) = &self.player { - centres.push(( - (p.position.x.floor() as i32) >> 4, - (p.position.z.floor() as i32) >> 4, - )); - } - let everywhere = centres.is_empty() && self.options.dedicated.is_none(); - move |x, z| { - everywhere - || centres - .iter() - .any(|&(cx, cz)| ((x >> 4) - cx).abs().max(((z >> 4) - cz).abs()) <= d) - } + let levels = self.tickets.levels(); + move |x, z| levels.block_ticking_at(x, z) } /// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and /// its block's `lit` following it. diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 6e9b3d84a..422d050b6 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -475,24 +475,11 @@ impl Game<'_> { self.tick_raids(); self.tick_creature_entities() } - /// `DistanceManager.inEntityTickingRange`: chunks within the simulation - /// distance (Chebyshev, in chunks) of the player or of a guest. + /// `DistanceManager.inEntityTickingRange` in an entity-ticking chunk + /// (block coordinates), from every player's tickets (`update_chunk_tickets`). pub(super) fn entity_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> { - let d = self.settings.simulation_distance.max(2); - let mut centres: Vec<(i32, i32)> = self.streaming.extra.iter().map(|&(c, _)| c).collect(); - if let Some(p) = &self.player { - centres.push(( - (p.position.x.floor() as i32) >> 4, - (p.position.z.floor() as i32) >> 4, - )); - } - let everywhere = centres.is_empty(); - move |x, z| { - everywhere - || centres - .iter() - .any(|&(cx, cz)| ((x >> 4) - cx).abs().max(((z >> 4) - cz).abs()) <= d) - } + let levels = self.tickets.levels(); + move |x, z| levels.entity_ticking_at(x, z) } /// The entity phase of `tick_creatures`: every mob's tick, deaths, and the /// projectiles and effects that follow from them. diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index bd2f84efb..3225408f5 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -20,7 +20,8 @@ use super::{ }; use horizon_client::{ Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections, - save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, world::World, + save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, + ticket_levels::ChunkTickets, world::World, }; use horizon_world::level::{LevelEvent, Ticks}; use std::{collections::HashMap, sync::Arc, time::Instant}; @@ -37,6 +38,7 @@ pub(super) struct Parked { save: Arc, block_ticks: Ticks, tick_chunks: TickChunkMembership, + tickets: ChunkTickets, random_tick_sections: RandomTickSections, level_events: Vec, falling: Vec, @@ -113,6 +115,7 @@ impl Game<'_> { save, block_ticks: Ticks::new(self.level.seed as i32), tick_chunks: Default::default(), + tickets: Default::default(), random_tick_sections: Default::default(), level_events: Vec::new(), falling: Vec::new(), @@ -159,6 +162,7 @@ impl Game<'_> { swap(&mut self.save, &mut p.save); swap(&mut self.block_ticks, &mut p.block_ticks); swap(&mut self.tick_chunks, &mut p.tick_chunks); + swap(&mut self.tickets, &mut p.tickets); swap(&mut self.random_tick_sections, &mut p.random_tick_sections); swap(&mut self.level_events, &mut p.level_events); swap(&mut self.falling, &mut p.falling); diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 2574f45d7..7a967a024 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -105,7 +105,9 @@ impl Game<'_> { chunk.saved = Some(Arc::new(extras)); } /// Register a newly resident chunk with the tick scheduler, with the - /// block and fluid ticks it was saved with. + /// block and fluid ticks it was saved with (`LevelChunk.registerTickContainerInLevel` + /// at FULL). They are unpacked when the chunk starts ticking + /// (`start_ticking_chunks`). pub(super) fn register_chunk_ticks(&mut self, key: (i32, i32)) { let pos = ChunkPos::new(key.0, key.1); let saved = self.world.chunks.get(&key).and_then(|c| c.saved.clone()); @@ -130,9 +132,7 @@ impl Game<'_> { .is_ok() && loaded { - let time = self.world.game_time; - self.block_ticks.blocks.unpack_chunk(pos, time); - self.block_ticks.fluids.unpack_chunk(pos, time); + self.tick_chunks.wait(key); } // The saved list is consumed: later saves take the scheduler's ticks. if loaded && let Some(c) = self.world.chunks.get_mut(&key) { diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index fc6c03f9e..de7ea6df2 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -705,18 +705,10 @@ impl Game<'_> { } Ok(()) } - /// `ServerLevel.shouldTickBlocksAt`, as `tick_blocks` decides it. + /// `ServerLevel.shouldTickBlocksAt` in a block-ticking chunk, from every + /// player's tickets (`update_chunk_tickets`), once the chunk is lit. fn chunk_ticks(&self, cx: i32, cz: i32) -> bool { - let Some(p) = self.player.as_ref() else { - return false; - }; - let (pcx, pcz) = ( - (p.position.x.floor() as i32) >> 4, - (p.position.z.floor() as i32) >> 4, - ); - let simulation = self.settings.render_distance.min(8); - (cx - pcx).abs() <= simulation - && (cz - pcz).abs() <= simulation + self.tickets.levels().block_ticking(cx, cz) && self.world.chunks.get(&(cx, cz)).is_some_and(|c| c.lit) } fn tick_sculk_block(&mut self, key: (i32, i32, i32)) -> Result<()> { diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index b57f559b6..890e571b8 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -696,6 +696,8 @@ impl Game<'_> { seed_fresh(m, 0x5eed + (named + i + 1) as i64); } } + // The player's tickets, as `tick_world` takes them. + self.update_chunk_tickets(); // Entities: the player's warden spawn tracker, then the mobs. self.tick_sculk_entities(); // (ServerChunkCache.tick, natural spawning and its chunk shuffle, is not run.) diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 6456b1001..cab5a9d16 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1012,6 +1012,12 @@ impl Hub { } } if !self.guests.iter().any(|g| self.here(g)) { + // ServerTickRateManager broadcasts a change to the players there + // are; one who joins later is sent the state as it is then + // (`updateJoiningPlayer`). + if !self.guests.iter().any(|g| g.placed) { + self.ticking = (ctx.tick_rate, ctx.tick_frozen); + } if !self .guests .iter() diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 1e2c8c331..437fbfa9d 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -172,6 +172,7 @@ pub mod telemetry; pub mod testgen; pub mod text; pub mod tick_chunk_membership; +pub mod ticket_levels; pub mod title; pub mod title_edition; pub mod toasts; diff --git a/crates/horizon-client/src/tick_chunk_membership.rs b/crates/horizon-client/src/tick_chunk_membership.rs index 42785f289..a7e934443 100644 --- a/crates/horizon-client/src/tick_chunk_membership.rs +++ b/crates/horizon-client/src/tick_chunk_membership.rs @@ -10,6 +10,9 @@ pub struct TickChunkMembership { revision: Option, added: Vec, removed: Vec, + /// Loaded chunks with saved ticks that have not started ticking yet + /// (`LevelChunkTicks.pendingTicks`, unpacked by `startTickingChunk`). + waiting: HashSet, } impl TickChunkMembership { @@ -20,6 +23,7 @@ impl TickChunkMembership { self.revision = None; self.added.clear(); self.removed.clear(); + self.waiting.clear(); } /// Returns false in O(1) when resident membership is unchanged. On change, @@ -36,6 +40,7 @@ impl TickChunkMembership { true } else { self.removed.push(*key); + self.waiting.remove(key); false } }); @@ -62,6 +67,28 @@ impl TickChunkMembership { pub fn removed(&self) -> &[Key] { &self.removed } + + /// `key` was registered with saved ticks to unpack once it ticks. + pub fn wait(&mut self, key: Key) { + self.waiting.insert(key); + } + + /// The waiting chunks that `ticking` says now tick, no longer waiting. + pub fn start_ticking(&mut self, mut ticking: impl FnMut(Key) -> bool) -> Vec { + if self.waiting.is_empty() { + return Vec::new(); + } + let started: Vec = self + .waiting + .iter() + .copied() + .filter(|&k| ticking(k)) + .collect(); + for key in &started { + self.waiting.remove(key); + } + started + } } #[cfg(test)] @@ -124,6 +151,24 @@ mod tests { compare(&mut cache, &mut old, &map); } + #[test] + fn waiting_chunks_start_ticking_once_and_unloaded_ones_stop_waiting() { + let mut map = ChunkMap::default(); + let mut cache = TickChunkMembership::default(); + for key in [(0, 0), (1, 0), (2, 0)] { + map.insert(key, Arc::new(Chunk::empty(key.0, key.1))); + cache.wait(key); + } + cache.synchronize(&map); + assert_eq!(cache.start_ticking(|k| k == (0, 0)), vec![(0, 0)]); + assert!(cache.start_ticking(|k| k == (0, 0)).is_empty()); + map.remove(&(1, 0)); + cache.synchronize(&map); + let mut started = cache.start_ticking(|_| true); + started.sort_unstable(); + assert_eq!(started, vec![(2, 0)]); + } + #[test] fn scheduler_keeps_saved_ticks_on_stable_membership_and_removes_unloaded_chunks() { use horizon_core::{ diff --git a/crates/horizon-client/src/ticket_levels.rs b/crates/horizon-client/src/ticket_levels.rs new file mode 100644 index 000000000..216815de1 --- /dev/null +++ b/crates/horizon-client/src/ticket_levels.rs @@ -0,0 +1,232 @@ +//! Which chunks tick, from the chunk tickets of `DistanceManager`. +//! +//! Every player holds two kinds of ticket: +//! - `PLAYER_LOADING` at level 31 (`ENTITY_TICKING`) on every chunk within +//! the server's view distance (Chebyshev), from `PlayerTicketTracker`; +//! - `PLAYER_SIMULATION` at level `31 - simulationDistance` on its own chunk. +//! +//! A `/forceload`ed chunk holds a `FORCED` ticket at level 31 of both kinds. +//! Levels rise by one per chunk away from a ticket (`ChunkTracker`) and each +//! chunk takes the lowest. The loading level gives the chunk's +//! `FullChunkStatus` (`ChunkLevel.fullStatus`: 31 entity ticking, 32 block +//! ticking, 33 full) and the simulation level gives what +//! `inEntityTickingRange` (31 or less) and `inBlockTickingRange` (32 or less) +//! answer. Vanilla needs both: +//! - entities tick where both levels are entity ticking (`ServerLevel.tick`, +//! and `EntityTickList` holds only the entities of entity-ticking chunks); +//! - random ticks run in the simulation tracker's entity-ticking chunks that +//! have a ticking chunk (`ChunkMap.forEachBlockTickingChunk`); +//! - scheduled ticks, block events and block entities run where both are +//! block ticking (`isPositionTickingWithEntitiesLoaded`, +//! `shouldTickBlocksAt`, `LevelChunk.isTicking`). +//! +//! Whoever the players are (the local player, LAN guests, a dedicated +//! server's players), they count the same. +use crate::fast_hash::FxHashMap; +use std::sync::Arc; + +/// `ChunkLevel`'s levels. +pub const ENTITY_TICKING: u8 = 31; +pub const BLOCK_TICKING: u8 = 32; +/// What a chunk with no ticket near it has (`FULL` and above count as none). +const NONE: (u8, u8) = (BLOCK_TICKING + 1, BLOCK_TICKING + 1); + +/// The tickets of one level: where its players are, its forced chunks, and +/// the server's view and simulation distances. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Sources { + pub players: Vec<(i32, i32)>, + pub forced: Vec<(i32, i32)>, + pub view_distance: i32, + pub simulation_distance: i32, +} + +/// Each chunk's (loading, simulation) level, for the chunks where either is +/// block ticking or lower; `None` ticks everywhere (a game with no server and +/// no player: the headless fixtures). +#[derive(Clone, Default)] +pub struct Levels(Option>>); + +impl Levels { + /// Chunk coordinates. + fn get(&self, x: i32, z: i32) -> Option<(u8, u8)> { + let map = self.0.as_ref()?; + Some(map.get(&(x, z)).copied().unwrap_or(NONE)) + } + /// `DistanceManager.inEntityTickingRange`, in an entity-ticking chunk: + /// where entities tick. + pub fn entity_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z) + .is_none_or(|(l, s)| l <= ENTITY_TICKING && s <= ENTITY_TICKING) + } + /// `inBlockTickingRange` in a block-ticking chunk: where scheduled ticks, + /// block events and block entities run. + pub fn block_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z) + .is_none_or(|(l, s)| l <= BLOCK_TICKING && s <= BLOCK_TICKING) + } + /// `inEntityTickingRange` in a block-ticking chunk: where random ticks run. + pub fn random_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z) + .is_none_or(|(l, s)| l <= BLOCK_TICKING && s <= ENTITY_TICKING) + } + /// `ChunkHolder.getFullStatus` is block ticking or more: the chunk's + /// ticking future can complete (its saved ticks unpack then). + pub fn loaded_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z).is_none_or(|(l, _)| l <= BLOCK_TICKING) + } + /// The same as [`Self::entity_ticking`] at a block position. + pub fn entity_ticking_at(&self, x: i32, z: i32) -> bool { + self.entity_ticking(x >> 4, z >> 4) + } + /// The same as [`Self::block_ticking`] at a block position. + pub fn block_ticking_at(&self, x: i32, z: i32) -> bool { + self.block_ticking(x >> 4, z >> 4) + } +} + +/// The levels, rebuilt only when their sources change (a player crossing +/// into another chunk, a distance or a forced chunk changing). +#[derive(Default)] +pub struct ChunkTickets { + sources: Option, + levels: Levels, +} + +impl ChunkTickets { + /// `None`: tick everywhere. + pub fn update(&mut self, mut sources: Option) { + if let Some(s) = sources.as_mut() { + s.players.sort_unstable(); + s.players.dedup(); + s.forced.sort_unstable(); + } + if sources == self.sources { + return; + } + self.levels = Levels(sources.as_ref().map(|s| Arc::new(compute(s)))); + self.sources = sources; + } + pub fn levels(&self) -> Levels { + self.levels.clone() + } +} + +fn compute(s: &Sources) -> FxHashMap<(i32, i32), (u8, u8)> { + let view = s.view_distance.clamp(0, 32); + let simulation = s.simulation_distance.clamp(0, 32); + let mut levels: FxHashMap<(i32, i32), (u8, u8)> = FxHashMap::default(); + let mut lower = |key, loading: i32, sim: i32| { + let e = levels.entry(key).or_insert(NONE); + e.0 = e.0.min(loading.min(i32::from(NONE.0)) as u8); + e.1 = e.1.min(sim.min(i32::from(NONE.1)) as u8); + }; + // PLAYER_LOADING within the view distance, PLAYER_SIMULATION at the + // player's chunk (`getPlayerTicketLevel`: never below 0). + let player_sim = (i32::from(ENTITY_TICKING) - simulation).max(0); + let reach = (view + 1).max(i32::from(BLOCK_TICKING) - player_sim); + for &(px, pz) in &s.players { + for dz in -reach..=reach { + for dx in -reach..=reach { + let d = dx.abs().max(dz.abs()); + lower( + (px + dx, pz + dz), + i32::from(ENTITY_TICKING) + (d - view).max(0), + player_sim + d, + ); + } + } + } + for &(fx, fz) in &s.forced { + for dz in -1i32..=1 { + for dx in -1i32..=1 { + let level = i32::from(ENTITY_TICKING) + dx.abs().max(dz.abs()); + lower((fx + dx, fz + dz), level, level); + } + } + } + levels.retain(|_, l| *l != NONE); + levels +} + +#[cfg(test)] +mod tests { + use super::*; + + fn levels(players: &[(i32, i32)], forced: &[(i32, i32)], view: i32, sim: i32) -> Levels { + let mut t = ChunkTickets::default(); + t.update(Some(Sources { + players: players.to_vec(), + forced: forced.to_vec(), + view_distance: view, + simulation_distance: sim, + })); + t.levels() + } + + #[test] + fn simulation_distance_inside_the_view() { + // view 8, simulation 4: entities and random ticks out to 4 chunks, + // scheduled ticks out to 5. + let l = levels(&[(0, 0)], &[], 8, 4); + assert!(l.entity_ticking(4, -4) && !l.entity_ticking(5, 0)); + assert!(l.random_ticking(-4, 4) && !l.random_ticking(0, 5)); + assert!(l.block_ticking(5, 5) && !l.block_ticking(6, 0)); + assert!(l.loaded_ticking(9, 9) && !l.loaded_ticking(10, 0)); + } + + #[test] + fn view_distance_inside_the_simulation() { + // view 4, simulation 10: what isn't loaded at entity ticking (beyond + // the view distance) runs no entities, and block ticks stop where the + // chunk is only full (beyond the view distance + 1). + let l = levels(&[(0, 0)], &[], 4, 10); + assert!(l.entity_ticking(4, 0) && !l.entity_ticking(5, 0)); + assert!(l.random_ticking(5, 0) && !l.random_ticking(6, 0)); + assert!(l.block_ticking(5, 5) && !l.block_ticking(6, 0)); + } + + #[test] + fn every_player_and_forced_chunk() { + let l = levels(&[(0, 0), (40, 0)], &[(-100, 7)], 4, 4); + assert!(l.entity_ticking(44, 0) && l.entity_ticking(0, -4)); + assert!(!l.entity_ticking(20, 0)); + // A forced chunk entity ticks, its neighbours only block tick. + assert!(l.entity_ticking(-100, 7) && !l.entity_ticking(-101, 7)); + assert!(l.block_ticking(-101, 8) && !l.block_ticking(-102, 7)); + assert!(!l.random_ticking(-101, 7)); + assert!(l.entity_ticking_at(-1600, 112) && !l.block_ticking_at(-1617, 112)); + } + + #[test] + fn no_tickets_tick_nothing_and_no_sources_everything() { + let none = levels(&[], &[], 10, 10); + assert!(!none.block_ticking(0, 0) && !none.entity_ticking(0, 0)); + let everywhere = ChunkTickets::default().levels(); + assert!(everywhere.random_ticking(1000, -1000)); + } + + #[test] + fn rebuilt_only_when_sources_change() { + let mut t = ChunkTickets::default(); + let s = |players: Vec<(i32, i32)>| { + Some(Sources { + players, + forced: Vec::new(), + view_distance: 2, + simulation_distance: 2, + }) + }; + t.update(s(vec![(0, 0), (5, 5)])); + let first = t.levels(); + t.update(s(vec![(5, 5), (0, 0)])); + assert!(Arc::ptr_eq( + first.0.as_ref().unwrap(), + t.levels().0.as_ref().unwrap() + )); + t.update(s(vec![(1, 0), (5, 5)])); + assert!(t.levels().entity_ticking(3, 0) && !first.entity_ticking(3, 0)); + t.update(None); + assert!(t.levels().0.is_none()); + } +} diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index f0db98e40..144ed6961 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -69,6 +69,8 @@ address. The script then checks, from both sides, what a guest's game used to ge swing when its hoe tills dirt (the server's use) (#848). - time: the guest's clock is the host's: it stops with `/time pause`, and catches up with the server's game time after the guest's game stalls for a few seconds (#848). +- growth: far from the host, the chunks around the guest tick (#890): water placed there flows + and wheat on farmland grows (random ticks), however the host runs its world. - light: the guest's light matches the host's: around a torch placed near it, under a roof and once a block of the roof is removed under the sky, and in the last chunk it tracks next to glowstone in a chunk it doesn't (only the server's light updates bring that one). @@ -105,7 +107,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'plates', 'effects', 'portals', 'distance'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -1528,6 +1530,48 @@ def same_light(host, guest, lo, hi, what, ticks=100): f'{h["sky"][i]} block {h["block"][i]}, guest sky {g["sky"][i]} block {g["block"][i]}') +def check_growth(host, guest, out): + """Block ticks near a guest 1000 blocks from the host: only the guest's tickets tick them.""" + x0, y0, z0 = pos_of(guest) + guest('command', command='gamemode creative') + guest('command', command=f'tp @s {x0 + 1000:.2f} 200 {z0:.2f}') + guest.wait(100) + x, y, z = (int(v // 1) for v in pos_of(guest)) + # A platform in the air over wherever the guest landed: a water source two blocks east of the + # guest, wheat on farmland two blocks west. Vanilla's water spreads only towards the nearest + # drop (FlowingFluid.getSpread), so any of the source's four neighbours may take it. Wheat + # grows only in daylight (raw brightness 9 or more). + top = max(y + 12, 120) + water = (x + 2, top + 1, z) + beside = [(water[0] + dx, water[1], water[2] + dz) for dx, dz in ((1, 0), (-1, 0), (0, 1), (0, -1))] + wheat = (x - 2, top + 1, z) + flowed = [] + try: + host('command', command='time set noon') + guest('command', command=f'fill {x - 4} {top} {z - 2} {x + 4} {top} {z + 2} minecraft:stone') + guest('command', command=f'setblock {wheat[0]} {top} {wheat[2]} minecraft:farmland[moisture=7]') + guest('command', command=f'setblock {wheat[0]} {wheat[1]} {wheat[2]} minecraft:wheat[age=0]') + guest('command', command='gamerule random_tick_speed 1000') + guest('command', command=f'setblock {water[0]} {water[1]} {water[2]} minecraft:water') + for _ in range(40): + guest.wait(10) + flowed = [p for p in beside if guest.raw('block', *p).get('block') == 'minecraft:water'] + if flowed: + break + age = wait_state(guest, wheat, 'age', '7', 2400) + guest.shot(out, 'growth') + finally: + guest('command', command='gamerule random_tick_speed 3') + host('command', command='time set day') + guest('command', command=f'tp @s {x0:.2f} {y0:.2f} {z0:.2f}') + guest('command', command='gamemode survival') + guest.wait(40) + detail = {'flowed': flowed, 'wheat age': age} + assert flowed, f'the water beside the guest did not flow: {detail}' + assert age == '7', f'the wheat beside the guest did not grow: {detail}' + return detail + + def check_light(host, guest, out): gx, gy, gz = (int(v // 1) for v in pos_of(guest)) results = {} @@ -1591,7 +1635,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, 'swings': check_swings, - 'time': check_time} + 'time': check_time, 'growth': check_growth} def run(ctl, out, resources, checks): diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 6ac9aecbe..e8497d7f8 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -268,6 +268,12 @@ def run_side(label, command, directory, client): # it stays put; experience keeps its profession). server.console('summon minecraft:villager ~1 ~ ~ {NoAI:1b,Xp:1,VillagerData:' '{profession:"minecraft:librarian",level:2,type:"minecraft:plains"}}') + # The saved world still has fluid ticks due in the area the client is sent (a lava fall + # that never settles), and they run once their chunk ticks. When that is, against when the + # chunk is sent, follows how fast the server loads the chunks around the joining player: + # each run, vanilla sends a different set of them already flowed. Frozen until the client + # has its chunks, both servers send the world as saved; blocks tick again from the chat on. + server.console('tick freeze') port = int(PROPERTIES_PORTS[label]) legacy = legacy_ping(port) # The client asks to be made an operator once it has traded, runs /kill and respawns. @@ -282,7 +288,11 @@ def run_side(label, command, directory, client): joined = threading.Thread(target=join) joined.start() deadline = time.time() + 300 + frozen = True while joined.is_alive() and not any(' ready to respawn' in l for l in server.lines): + if frozen and any(' hello from the parity client' in l for l in server.lines): + server.console('tick unfreeze') + frozen = False if time.time() > deadline: break time.sleep(0.2)