diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index d80a1f8f4..d13ed6b13 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -408,6 +408,9 @@ impl Game<'_> { } } } + if hits.is_empty() { + return; + } let date = now_text(); for (ai, ci) in hits { let a = &tree.list[ai]; diff --git a/crates/horizon-client/src/game/stats.rs b/crates/horizon-client/src/game/stats.rs index 8f642d97a..7a97416ca 100644 --- a/crates/horizon-client/src/game/stats.rs +++ b/crates/horizon-client/src/game/stats.rs @@ -20,22 +20,50 @@ pub(super) struct Stats { /// Statistic changes (type, key, amount; `None` = reset) for the /// scoreboard criteria to follow. pub(super) events: Vec<(String, String, Option)>, - /// Changed since the client was last sent them (`StatsCounter`'s dirty set). - pub(super) dirty: BTreeSet<(String, String)>, + /// Changed since the client was last sent them (`StatsCounter`'s dirty + /// set), by type. + dirty: BTreeMap>, } + +/// `minecraft:` and `name`, given to `f` from the stack when short: some +/// counters go up every tick for every player, and they are found without +/// a string made for each. +fn namespaced(name: &str, f: impl FnOnce(&str) -> T) -> T { + const NAMESPACE: &str = "minecraft:"; + let mut buf = [0u8; 96]; + let len = NAMESPACE.len() + name.len(); + if len > buf.len() { + return f(&format!("{NAMESPACE}{name}")); + } + buf[..NAMESPACE.len()].copy_from_slice(NAMESPACE.as_bytes()); + buf[NAMESPACE.len()..len].copy_from_slice(name.as_bytes()); + // Two strings one after the other are one. + f(std::str::from_utf8(&buf[..len]).unwrap_or_default()) +} + +/// The map under `key`, made when missing, found without an owned key +/// when there. +fn entry<'a, V: Default>(map: &'a mut BTreeMap, key: &str) -> &'a mut V { + if !map.contains_key(key) { + map.insert(key.to_owned(), V::default()); + } + map.get_mut(key).expect("just inserted") +} + impl Stats { pub(super) fn add(&mut self, ty: &str, key: &str, n: i32) { - let v = self - .values - .entry(format!("minecraft:{ty}")) - .or_default() - .entry(key.to_owned()) - .or_insert(0); - *v = v.saturating_add(n); - self.events - .push((format!("minecraft:{ty}"), key.to_owned(), Some(n))); - self.dirty - .insert((format!("minecraft:{ty}"), key.to_owned())); + namespaced(ty, |ty| { + let v = entry(entry(&mut self.values, ty), key); + *v = v.saturating_add(n); + self.events.push((ty.to_owned(), key.to_owned(), Some(n))); + self.mark_dirty(ty, key); + }); + } + fn mark_dirty(&mut self, ty: &str, key: &str) { + let keys = entry(&mut self.dirty, ty); + if !keys.contains(key) { + keys.insert(key.to_owned()); + } } pub(super) fn get(&self, ty: &str, key: &str) -> i32 { self.values @@ -48,20 +76,19 @@ impl Stats { if let Some(m) = self.values.get_mut(&format!("minecraft:{ty}")) { m.insert(key.to_owned(), 0); } - self.dirty - .insert((format!("minecraft:{ty}"), key.to_owned())); + self.mark_dirty(&format!("minecraft:{ty}"), key); self.events .push((format!("minecraft:{ty}"), key.to_owned(), None)); } pub(super) fn custom(&mut self, key: &str, n: i32) { - self.add("custom", &format!("minecraft:{key}"), n); + namespaced(key, |key| self.add("custom", key, n)); } /// `ServerStatsCounter.markAllDirty`: everything goes out on the next request. pub(super) fn mark_all_dirty(&mut self) { self.dirty = self .values .iter() - .flat_map(|(ty, m)| m.keys().map(|k| (ty.clone(), k.clone()))) + .map(|(ty, m)| (ty.clone(), m.keys().cloned().collect())) .collect(); } /// `ServerStatsCounter.sendStats`' entries: the dirty statistics and @@ -69,6 +96,7 @@ impl Stats { pub(super) fn take_dirty(&mut self) -> Vec<(String, String, i32)> { std::mem::take(&mut self.dirty) .into_iter() + .flat_map(|(ty, keys)| keys.into_iter().map(move |key| (ty.clone(), key))) .map(|(ty, key)| { let v = self.values.get(&ty).and_then(|m| m.get(&key)).copied(); (ty, key, v.unwrap_or(0)) @@ -344,3 +372,54 @@ impl Game<'_> { }) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counters_events_and_dirty_entries() { + let mut s = Stats::default(); + s.custom("play_time", 1); + s.custom("play_time", 1); + s.add("mined", "minecraft:stone", 2); + s.custom(&"x".repeat(100), 3); + assert_eq!(s.get("custom", "minecraft:play_time"), 2); + assert_eq!(s.get("mined", "minecraft:stone"), 2); + assert_eq!( + s.get("custom", &format!("minecraft:{}", "x".repeat(100))), + 3 + ); + assert_eq!(s.events.len(), 4); + assert_eq!( + s.events[1], + ( + "minecraft:custom".into(), + "minecraft:play_time".into(), + Some(1) + ) + ); + let long = format!("minecraft:{}", "x".repeat(100)); + let sent = |v: &[(&str, &str, i32)]| -> Vec<(String, String, i32)> { + v.iter() + .map(|&(t, k, n)| (t.to_owned(), k.to_owned(), n)) + .collect() + }; + assert_eq!( + s.take_dirty(), + sent(&[ + ("minecraft:custom", "minecraft:play_time", 2), + ("minecraft:custom", &long, 3), + ("minecraft:mined", "minecraft:stone", 2), + ]) + ); + assert!(s.take_dirty().is_empty()); + s.reset("mined", "minecraft:stone"); + assert_eq!( + s.take_dirty(), + sent(&[("minecraft:mined", "minecraft:stone", 0)]) + ); + s.mark_all_dirty(); + assert_eq!(s.take_dirty().len(), 3); + } +} diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index a9cf57a7d..35339a05c 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -15,7 +15,13 @@ use horizon_protocol::{ registry::{Builtin, ceil_log2}, }; use horizon_world::nbt::Tag; -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::HashMap, + sync::{ + Arc, OnceLock, + atomic::{AtomicUsize, Ordering}, + }, +}; const NON_AIR: u8 = 1; const FLUID: u8 = 2; @@ -83,12 +89,10 @@ pub fn block_entity_type(name: &str) -> Option<&'static str> { /// Per-state facts and registry ids for encoding chunks. pub struct ChunkEncoder { - flags: Vec, + /// What encoding a section needs, shared with the warm-up threads. + coder: Arc, /// Block entity type id per state (-1 for none). entity_types: Vec, - /// Network biome id per internal biome index. - pub biome_ids: Vec, - biome_bits: u8, /// The block registry id of each state's block, for BlockEvent. pub block_ids: Vec, /// The save's tables, for the heightmaps. @@ -104,6 +108,14 @@ pub struct ChunkEncoder { sky: bool, } +/// Per-state flags and biome ids: all a section's encoding reads. +struct SectionCoder { + flags: Vec, + /// Network biome id per internal biome index. + biome_ids: Vec, + biome_bits: u8, +} + /// A column's client heightmaps, valid while it holds the same sections. struct Heights { sections: Vec>, @@ -170,8 +182,151 @@ impl Layers { } } +impl SectionCoder { + /// LevelChunkSection.write, and its block entity blocks. + fn wire(&self, section: &Section) -> (Arc<[u8]>, Entities) { + let (encoded, entities) = self.section(section); + let mut w = horizon_protocol::buf::Writer::new(); + encoded.write(&mut w); + (w.data.into(), entities.into()) + } + + fn section(&self, section: &Section) -> (horizon_protocol::chunk::Section, Vec<(u16, u32)>) { + let mut values = Vec::with_capacity(BLOCKS); + let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, Vec::new()); + let mut count = |state: u32, n: i16| { + let f = self.flags.get(state as usize).copied().unwrap_or(0); + if f & NON_AIR != 0 { + non_empty += n; + if f & FLUID != 0 { + fluids += n; + } + } + f & ENTITY != 0 + }; + // One block everywhere (all air, mostly): what from_values would give. + let uniform = section.blocks.uniform(); + if let Some(v) = uniform { + if count(v, BLOCKS as i16) { + entities = (0..BLOCKS as u16).map(|i| (i, v)).collect(); + } + } else { + let mut unpacked = [0u32; BLOCKS]; + section.unpack(&mut unpacked); + for (i, &v) in unpacked.iter().enumerate() { + if count(v, 1) { + entities.push((i as u16, v)); + } + values.push(v as i32); + } + } + let biome_values: Vec = (0..BIOMES) + .map(|j| { + let internal = section.biomes.get(j) as u16; + self.biome_ids + .get(usize::from(internal)) + .copied() + .unwrap_or(0) + }) + .collect(); + ( + horizon_protocol::chunk::Section { + non_empty, + fluids, + states: match uniform { + Some(v) => Paletted { + bits: 0, + palette: vec![v as i32], + data: Vec::new(), + }, + None => Paletted::from_values( + &values, + Strategy::Blocks, + crate::chunk::block_strategy().global_bits, + ), + }, + biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits), + }, + entities, + ) + } +} + /// Sections kept before the ones no longer resident are dropped. const CACHE_SWEEP: usize = 1 << 15; + +/// Uncached sections below which a batch is encoded on the tick's thread +/// alone: waking the warm-up threads costs more than a few sections. +const WARM_MIN: usize = 16; + +/// Sections a batch needs, each taken by whichever thread is free first, +/// and what each gave: its wire bytes and, with varying light, its layers. +struct Warm { + coder: Arc, + sections: Vec>, + next: AtomicUsize, + done: Vec>, +} +type Warmed = ((Arc<[u8]>, Entities), Option>); +impl Warm { + /// Encode sections until none is left to take. + fn run(&self) { + loop { + let i = self.next.fetch_add(1, Ordering::Relaxed); + let Some(s) = self.sections.get(i) else { + return; + }; + let light = matches!(s.light, Light::Full(_)).then(|| Arc::new(Layers::of(&s.light))); + let _ = self.done[i].set((self.coder.wire(s), light)); + } + } +} + +/// The warm-up threads (one per core besides the tick's) and the job they +/// take: its number, and the job while it has sections left to take. +struct WarmPool { + job: std::sync::Mutex<(u64, Option>)>, + ready: std::sync::Condvar, +} + +/// The warm-up threads, started the first time; none on a single core or +/// when no thread could start. +fn warm_pool() -> Option<&'static WarmPool> { + static POOL: OnceLock>> = OnceLock::new(); + POOL.get_or_init(|| { + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()) - 1; + let pool = Arc::new(WarmPool { + job: Default::default(), + ready: Default::default(), + }); + let started = (0..threads) + .filter(|i| { + let pool = pool.clone(); + std::thread::Builder::new() + .name(format!("horizon-chunk-encode-{i}")) + .spawn(move || { + let mut done = 0; + loop { + let job = { + let mut slot = pool.job.lock().unwrap(); + while slot.0 == done { + slot = pool.ready.wait(slot).unwrap(); + } + done = slot.0; + slot.1.clone() + }; + if let Some(job) = job { + job.run(); + } + } + }) + .is_ok() + }) + .count(); + (started > 0).then_some(pool) + }) + .as_deref() +} impl ChunkEncoder { /// `biome_names`: the internal biome list in order; `biome_registry`: /// the synchronized biome entries in network order. @@ -218,10 +373,12 @@ impl ChunkEncoder { }) .collect(); Self { - flags, + coder: Arc::new(SectionCoder { + flags, + biome_ids, + biome_bits: ceil_log2(biome_registry.len()), + }), entity_types, - biome_ids, - biome_bits: ceil_log2(biome_registry.len()), block_ids, tables: None, cache: Default::default(), @@ -297,7 +454,8 @@ impl ChunkEncoder { /// LevelChunkSection.hasOnlyAir, negated. fn non_air(&self, section: &Section) -> bool { - let non_air = |v: u32| self.flags.get(v as usize).copied().unwrap_or(0) & NON_AIR != 0; + let non_air = + |v: u32| self.coder.flags.get(v as usize).copied().unwrap_or(0) & NON_AIR != 0; // The palette first: most sections are all air, or one block. if !section.blocks.maybe_has(non_air) { false @@ -314,10 +472,7 @@ impl ChunkEncoder { if let Some(wire) = self.cached(section, |e| e.wire.clone()) { return wire; } - let (encoded, entities) = self.section(section); - let mut w = horizon_protocol::buf::Writer::new(); - encoded.write(&mut w); - let wire: (Arc<[u8]>, Entities) = (w.data.into(), entities.into()); + let wire = self.coder.wire(section); self.cached(section, |e| e.wire = Some(wire.clone())); wire } @@ -340,71 +495,12 @@ impl ChunkEncoder { .map(|t| i32::from(*t)) } pub fn is_air(&self, state: u32) -> bool { - self.flags + self.coder + .flags .get(state as usize) .is_none_or(|f| f & NON_AIR == 0) } - fn section(&self, section: &Section) -> (horizon_protocol::chunk::Section, Vec<(u16, u32)>) { - let mut values = Vec::with_capacity(BLOCKS); - let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, Vec::new()); - let mut count = |state: u32, n: i16| { - let f = self.flags.get(state as usize).copied().unwrap_or(0); - if f & NON_AIR != 0 { - non_empty += n; - if f & FLUID != 0 { - fluids += n; - } - } - f & ENTITY != 0 - }; - // One block everywhere (all air, mostly): what from_values would give. - let uniform = section.blocks.uniform(); - if let Some(v) = uniform { - if count(v, BLOCKS as i16) { - entities = (0..BLOCKS as u16).map(|i| (i, v)).collect(); - } - } else { - let mut unpacked = [0u32; BLOCKS]; - section.unpack(&mut unpacked); - for (i, &v) in unpacked.iter().enumerate() { - if count(v, 1) { - entities.push((i as u16, v)); - } - values.push(v as i32); - } - } - let biome_values: Vec = (0..BIOMES) - .map(|j| { - let internal = section.biomes.get(j) as u16; - self.biome_ids - .get(usize::from(internal)) - .copied() - .unwrap_or(0) - }) - .collect(); - ( - horizon_protocol::chunk::Section { - non_empty, - fluids, - states: match uniform { - Some(v) => Paletted { - bits: 0, - palette: vec![v as i32], - data: Vec::new(), - }, - None => Paletted::from_values( - &values, - Strategy::Blocks, - crate::chunk::block_strategy().global_bits, - ), - }, - biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits), - }, - entities, - ) - } - /// 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 { @@ -442,6 +538,65 @@ impl ChunkEncoder { self.body(chunk, &world.block_entities, self.around(chunk, world)) } + /// Encode the sections of these columns not cached yet before their + /// bodies are made, shared out to the warm-up threads: a batch of new + /// terrain costs mostly its sections' first encoding. This thread takes + /// sections too until none is left, then caches what is done; it never + /// waits for the other threads (they keep their results to themselves + /// until then), and a section one of them is still on is encoded again + /// by `body_in`, with the same bytes. + pub fn warm(&self, columns: &[&Chunk]) { + let sections: Vec> = { + let cache = self.cache.lock().unwrap(); + columns + .iter() + .flat_map(|c| &c.sections[self.sections.clone()]) + .filter(|s| { + cache + .get(&(Arc::as_ptr(s) as usize)) + .is_none_or(|e| e.wire.is_none()) + }) + .cloned() + .collect() + }; + if sections.len() < WARM_MIN { + return; + } + let Some(pool) = warm_pool() else { + return; + }; + let job = Arc::new(Warm { + coder: self.coder.clone(), + done: sections.iter().map(|_| OnceLock::new()).collect(), + sections, + next: AtomicUsize::new(0), + }); + { + let mut slot = pool.job.lock().unwrap(); + slot.0 += 1; + slot.1 = Some(job.clone()); + } + pool.ready.notify_all(); + job.run(); + // Every section is claimed: the job leaves the slot. + { + let mut slot = pool.job.lock().unwrap(); + if slot.1.as_ref().is_some_and(|j| Arc::ptr_eq(j, &job)) { + slot.1 = None; + } + } + let mut cache = self.cache.lock().unwrap(); + for (s, done) in job.sections.iter().zip(&job.done) { + if let Some((wire, light)) = done.get() { + let e = self.entry(&mut cache, s); + e.wire = Some(wire.clone()); + if light.is_some() { + e.light = light.clone(); + } + } + } + } + fn body( &self, chunk: &Chunk, @@ -930,7 +1085,7 @@ mod tests { /// The bytes on the wire for a section, encoded afresh. fn fresh(encoder: &ChunkEncoder, section: &Section) -> Vec { let mut w = horizon_protocol::buf::Writer::new(); - encoder.section(section).0.write(&mut w); + encoder.coder.section(section).0.write(&mut w); w.data } @@ -1077,6 +1232,67 @@ mod tests { ); } + /// Columns whose sections the warm-up threads encoded give the bytes + /// each gives on its own, also with a column twice and its neighbours' + /// sections deciding the light layers. + #[test] + fn warmed_columns_give_the_same_bodies() { + let builtin = Builtin::parse( + r#"{"minecraft:block_entity_type": {"entries": { + "minecraft:sign": {"protocol_id": 7}}}}"#, + ) + .unwrap(); + let states = [ + "minecraft:air", + "minecraft:stone", + "minecraft:water", + "minecraft:oak_sign", + ] + .map(|n| (Arc::::from(n), n.ends_with("water"))); + let mut world = crate::world::World::new(horizon_world::registry::BlockStateId(0), 0); + for x in -2..2 { + for z in -2..2 { + let mut chunk = Chunk::empty(x, z); + let n = (x * 7 + z * 13).rem_euclid(17); + for i in 0..40 + n * 30 { + let (bx, bz) = ((i * 5 + n) % 16, (i * 11) % 16); + chunk.set(bx, MIN_Y + (i * 37 + n * 50) % 384, bz, 1 + (i % 3) as u32); + } + let mut light = Box::new([0u8; 4096]); + for (i, v) in light.iter_mut().enumerate() { + *v = (i * 31 + n as usize) as u8; + } + Arc::make_mut(&mut chunk.sections[(n % 24) as usize]).light = Light::Full(light); + world.block_entities.insert( + (x * 16 + 2, 70, z * 16 + 3), + BlockEntity::Sign(crate::signs::SignData::default()), + ); + chunk.set(2, 70, 3, 3); + world.chunks.insert((x, z), Arc::new(chunk)); + } + } + let mut keys: Vec<(i32, i32)> = + (-2..2).flat_map(|x| (-2..2).map(move |z| (x, z))).collect(); + keys.push(keys[5]); + let chunks: Vec<&Chunk> = keys + .iter() + .map(|k| &**world.chunks.get(k).unwrap()) + .collect(); + let alone = ChunkEncoder::new(states.clone(), &builtin, &[], &[]); + let expected: Vec> = chunks.iter().map(|c| alone.body_in(c, &world)).collect(); + let warmed = ChunkEncoder::new(states, &builtin, &[], &[]); + let bodies = |encoder: &ChunkEncoder| -> Vec> { + chunks.iter().map(|c| encoder.body_in(c, &world)).collect() + }; + assert!(chunks.len() * SECTIONS >= WARM_MIN); + warmed.warm(&chunks); + assert_eq!(bodies(&warmed), expected); + // Again, from the cache, with nothing left to warm. + warmed.warm(&chunks); + assert_eq!(bodies(&warmed), expected); + warmed.warm(&[]); + } + #[test] fn a_nether_column_sends_its_sixteen_sections_without_sky_light() { let chunk = Chunk::empty(0, 0); diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 6350cf6f9..9082e01fa 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -150,6 +150,14 @@ struct ServerEntity { seen: u32, index: usize, added: bool, + /// TrackedEntity.lastSectionPos: its pairs are checked again when it + /// moves to another section. + section: [i32; 3], +} + +/// SectionPos.of(entity). +fn section_of(position: [f64; 3]) -> [i32; 3] { + position.map(|v| (v.floor() as i32) >> 4) } /// VecDeltaCodec.encode. @@ -183,6 +191,7 @@ impl ServerEntity { seen: 0, index: 0, added: true, + section: section_of(e.position), } } @@ -486,6 +495,9 @@ impl Tracker { /// view distance and chunks. pub struct Viewer<'a> { pub entity_id: i32, + /// It accepted a move since the last tick (ChunkMap.move): every pair + /// of it is checked again. + pub moved: bool, pub position: [f64; 3], pub view_distance: i32, pub chunks: &'a crate::fast_hash::FxHashSet<(i32, i32)>, @@ -539,6 +551,11 @@ pub struct Entities { flags: Vec>, /// Whether a client starts tracking each entity this tick. pairs: Vec, + /// The entities that appeared or moved to another section this tick + /// (their pairs with every client are checked again), in order and as a + /// flag per entity. + moved: Vec, + is_moved: Vec, /// One entity's packets and their bodies, kept between entities. packets: Vec, bodies: Vec>, @@ -579,13 +596,25 @@ impl Entities { self.probes.clear(); self.chunks.clear(); self.chunk_index.clear(); + self.moved.clear(); + self.is_moved.clear(); + self.is_moved.resize(entities.len(), false); for (index, e) in entities.iter().enumerate() { - let s = self - .states - .entry(e.id) - .or_insert_with(|| ServerEntity::new(e, kind(&e.kind), riding)); + let mut added = false; + let s = self.states.entry(e.id).or_insert_with(|| { + added = true; + ServerEntity::new(e, kind(&e.kind), riding) + }); s.seen = now; s.index = index; + // ChunkMap.addEntity, and ChunkMap.tick's section change: + // updatePlayers. + let section = section_of(e.position); + if added || section != s.section { + s.section = section; + self.moved.push(index); + self.is_moved[index] = true; + } let at = ( (e.position[0].floor() as i32) >> 4, (e.position[2].floor() as i32) >> 4, @@ -612,17 +641,70 @@ impl Entities { self.held.resize(self.chunks.len(), 0); let (chunks, held, pairs) = (&self.chunks, &mut self.held, &mut self.pairs); let mut kept = 0; - flags.extend(self.probes.iter().zip(pairs.iter_mut()).map(|(p, pairs)| { - if p.id == v.entity_id || !sees(v, p, chunks, held) { - 0 - } else if v.tracker.seen.contains(&p.id) { - kept += 1; - SEES | TRACKS - } else { - *pairs = true; - SEES + // A client that moved (ChunkMap.move), or whose own entity + // appeared or changed section (ChunkMap.tick's movedPlayers), has + // every pair checked again. + let all = v.moved + || self + .states + .get(&v.entity_id) + .is_none_or(|s| s.seen != now || self.is_moved[s.index]); + if all { + flags.extend(self.probes.iter().zip(pairs.iter_mut()).map(|(p, pairs)| { + if p.id == v.entity_id || !sees(v, p, chunks, held) { + 0 + } else if v.tracker.seen.contains(&p.id) { + kept += 1; + SEES | TRACKS + } else { + *pairs = true; + SEES + } + })); + } else if v.tracker.seen.len() * 4 > self.probes.len() { + // Otherwise its pairs stay as they were, but for the entities + // that appeared or changed section; a client tracking much + // of the level goes through it in order. + let is_moved = &self.is_moved; + flags.extend(self.probes.iter().zip(pairs.iter_mut()).zip(is_moved).map( + |((p, pairs), &moved)| { + let tracks = v.tracker.seen.contains(&p.id); + if p.id == v.entity_id || (moved && !sees(v, p, chunks, held)) { + 0 + } else if tracks { + kept += 1; + SEES | TRACKS + } else if moved { + *pairs = true; + SEES + } else { + 0 + } + }, + )); + } else { + // One tracking little of it, from what it tracks. + flags.resize(self.probes.len(), 0); + for id in &v.tracker.seen { + if let Some(s) = self.states.get(id).filter(|s| s.seen == now) { + flags[s.index] = SEES | TRACKS; + kept += 1; + } } - })); + for &index in &self.moved { + let p = &self.probes[index]; + let tracks = flags[index] & TRACKS != 0; + if p.id != v.entity_id && sees(v, p, chunks, held) { + if !tracks { + flags[index] = SEES; + pairs[index] = true; + } + } else if tracks { + flags[index] = 0; + kept -= 1; + } + } + } // Usually the client still sees all it tracks. let mut removed = Vec::new(); if kept != v.tracker.seen.len() { @@ -896,6 +978,7 @@ mod tests { trackers: [Tracker; 2], out: [Vec>; 2], positions: [[f64; 3]; 2], + moved: [bool; 2], } impl Clients { @@ -905,6 +988,7 @@ mod tests { trackers: Default::default(), out: Default::default(), positions: [[0.0, 64.0, 0.0]; 2], + moved: [false; 2], } } fn tick(&mut self, level: &mut Entities, entities: &[&EntityState]) { @@ -916,6 +1000,7 @@ mod tests { let mut viewers = [ Viewer { entity_id: 1, + moved: self.moved[0], position: self.positions[0], view_distance: 10, chunks: &self.chunks, @@ -924,6 +1009,7 @@ mod tests { }, Viewer { entity_id: 2, + moved: self.moved[1], position: self.positions[1], view_distance: 10, chunks: &self.chunks, @@ -939,6 +1025,39 @@ mod tests { p.encode() } + /// ChunkMap checks a pair again only when one side moves: a zombie + /// walking into range within its section isn't paired with a client + /// standing still until the client moves, and one walking out stays + /// tracked until it changes section. + #[test] + fn pairs_are_checked_again_when_a_side_moves() { + let mut level = Entities::default(); + let mut clients = Clients::new(); + clients.positions[0] = [-108.0, 64.0, 0.0]; + let mut me = state(-108.0); + (me.id, me.kind) = (1, "minecraft:player".into()); + // 128.5 blocks away: past a zombie's 8 chunks. + let tracks = |clients: &Clients| clients.trackers[0].is_tracking(7); + clients.tick(&mut level, &[&me, &state(20.5)]); + assert!(!tracks(&clients)); + // 127.5 blocks away, in the same section: not checked again. + clients.tick(&mut level, &[&me, &state(19.5)]); + assert!(!tracks(&clients)); + // The client's move checks every pair of it. + clients.moved[0] = true; + clients.tick(&mut level, &[&me, &state(19.5)]); + assert!(tracks(&clients)); + clients.moved[0] = false; + clients.tick(&mut level, &[&me, &state(20.5)]); + assert!(tracks(&clients)); + // Into the next section, out of range: no longer tracked. + clients.tick(&mut level, &[&me, &state(40.0)]); + assert!(!tracks(&clients)); + // The other client (at the origin, its entity not in the level) + // checks every pair each tick. + assert!(clients.trackers[1].is_tracking(7)); + } + #[test] fn every_client_gets_the_same_changes_and_late_ones_are_paired() { let mut level = Entities::default(); diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index b39903f4d..91bf2709f 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -102,6 +102,9 @@ pub struct Guest { /// A position move arrived since the client's last ClientTickEnd /// (receivedPositionThisTick): a second one is a protocol error. pub position_this_tick: bool, + /// It accepted a move since the last entity range checks + /// (ServerChunkCache.move), which then check all of its pairs again. + pub moved: bool, /// The client finished loading terrain (ServerboundPlayerLoadedPacket). pub loaded: bool, // Chunks. @@ -237,6 +240,7 @@ impl Guest { received_moves: 0, known_moves: 0, position_this_tick: false, + moved: false, loaded: false, center: None, sent_chunks: Default::default(), diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index cab5a9d16..625f18eff 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -12,6 +12,7 @@ use super::{ guest::{Guest, SentEffect, stack_to_network}, }; use crate::{ + chunk::Chunk, collisions::SceneCollisions, effects::{EffectInstance, PlayerEffects}, items::ItemStack, @@ -1035,11 +1036,7 @@ impl Hub { ctx.world.light_log = Some(Default::default()); } self.sync_world(ctx); - for i in 0..self.guests.len() { - if self.here(&self.guests[i]) { - self.update_chunks(i, ctx); - } - } + crate::spans::time("lan_chunks", || self.update_chunks(ctx)); self.broadcast_light_changes(ctx.world); self.broadcast_block_changes(ctx.world); // ServerGamePacketListenerImpl.tick: the actions handled since the last tick are @@ -1178,86 +1175,140 @@ impl Hub { // ---- chunks -------------------------------------------------------- - fn update_chunks(&mut self, i: usize, ctx: &TickCtx) { + /// Every player's chunks here: their views, then the next batch of each + /// (PlayerChunkSender.sendNextChunks). The batches are chosen first, the + /// columns in them encoded once each, their new sections on the warm-up + /// threads too (`ChunkEncoder::warm`), then sent: nothing changes the + /// level in between, and each player's packets keep their order. + fn update_chunks(&mut self, ctx: &TickCtx) { + let world = &*ctx.world; + let mut batches = Vec::new(); + for i in 0..self.guests.len() { + if self.here(&self.guests[i]) { + self.update_view(i); + if let Some(batch) = self.next_batch(i, world) { + batches.push((i, batch)); + } + } + } + if batches.is_empty() { + return; + } + // Each column once, however many players it goes to, with the + // number of batches that take it. + let (mut columns, mut uses): (Vec<&Chunk>, Vec) = Default::default(); + let mut index = crate::fast_hash::FxHashMap::default(); + let batches: Vec<(usize, Vec, Vec)> = batches + .into_iter() + .map(|(i, batch)| { + let (taken, bodies) = batch + .into_iter() + .map(|(idx, chunk)| { + let j = *index.entry((chunk.x, chunk.z)).or_insert_with(|| { + columns.push(chunk); + uses.push(0); + columns.len() - 1 + }); + uses[j] += 1; + (idx, j) + }) + .unzip(); + (i, taken, bodies) + }) + .collect(); + self.encoder.warm(&columns); + let mut bodies: Vec> = columns + .iter() + .map(|c| self.encoder.body_in(c, world)) + .collect(); + for (i, taken, batch) in batches { + let g = &mut self.guests[i]; + let size = batch.len(); + g.batch_quota -= size as f32; + g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty)); + g.sender.send_many(batch.into_iter().map(|j| { + uses[j] -= 1; + if uses[j] == 0 { + std::mem::take(&mut bodies[j]) + } else { + bodies[j].clone() + } + })); + g.send(&C::ChunkBatchFinished(play::ChunkBatchFinished { + size: size as i32, + })); + g.unacknowledged += 1; + for idx in taken.into_iter().rev() { + let key = g.chunk_queue.remove(idx); + g.sent_chunks.insert(key); + } + } + } + + /// ChunkMap.move's view change: the new centre, the chunks that left + /// the view forgotten and the ones that entered it queued, closest first. + fn update_view(&mut self, i: usize) { let (cx, cz) = self.guests[i].chunk(); let r = self.guests[i].view_distance; let g = &mut self.guests[i]; - if g.center != Some((cx, cz)) { - g.center = Some((cx, cz)); - if g.center_sent.take() != Some((cx, cz)) { - g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { - x: cx, - z: cz, - })); - } - // Chunks that left the view. - let forget: Vec<_> = g - .sent_chunks - .iter() - .copied() - .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)| 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 tracked(cx, cz, r, key.0, key.1) - && !g.sent_chunks.contains(&key) - && !g.chunk_queue.contains(&key) - { - g.chunk_queue.push(key); - } + if g.center == Some((cx, cz)) { + return; + } + g.center = Some((cx, cz)); + if g.center_sent.take() != Some((cx, cz)) { + g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { + x: cx, + z: cz, + })); + } + // Chunks that left the view. + let forget: Vec<_> = g + .sent_chunks + .iter() + .copied() + .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)| 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 tracked(cx, cz, r, key.0, key.1) + && !g.sent_chunks.contains(&key) + && !g.chunk_queue.contains(&key) + { + g.chunk_queue.push(key); } } - g.chunk_queue - .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); } - // PlayerChunkSender.sendNextChunks: ready chunks, closest first, in - // batches the client's acknowledgements pace. + g.chunk_queue + .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); + } + + /// PlayerChunkSender.sendNextChunks' choice: ready chunks, closest first, + /// as many as the batch quota the client's acknowledgements pace allows, + /// with their places in the queue. + fn next_batch<'w>(&mut self, i: usize, world: &'w World) -> Option> { + let g = &mut self.guests[i]; if self.ticks <= g.placed_at + 1 || g.unacknowledged >= g.max_unacknowledged { - return; + return None; } 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; + return None; } 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() { - if packets.len() >= budget { - break; - } - let Some(chunk) = ctx.world.chunks.get(key) else { - continue; - }; - if !chunk.lit { - continue; - } - packets.push(self.encoder.body_in(chunk, ctx.world)); - taken.push(idx); - } - if packets.is_empty() { - return; - } - let size = packets.len(); - g.batch_quota -= size as f32; - g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty)); - for body in packets { - g.sender.send(body); - } - g.send(&C::ChunkBatchFinished(play::ChunkBatchFinished { - size: size as i32, - })); - g.unacknowledged += 1; - for idx in taken.into_iter().rev() { - let key = g.chunk_queue.remove(idx); - g.sent_chunks.insert(key); - } + let batch: Vec<_> = g + .chunk_queue + .iter() + .enumerate() + .filter_map(|(idx, key)| Some((idx, &**world.chunks.get(key).filter(|c| c.lit)?))) + .take(budget) + .collect(); + (!batch.is_empty()).then_some(batch) } /// Resend a chunk to everyone who has it (a block entity changed, relight). @@ -1559,6 +1610,7 @@ impl Hub { .zip(outs.iter_mut()) .map(|(g, out)| Viewer { entity_id: g.entity_id, + moved: std::mem::take(&mut g.moved), position: g.position, view_distance: g.view_distance, chunks: &g.sent_chunks, @@ -2000,6 +2052,8 @@ impl Hub { let g = &mut self.guests[i]; g.previous_position = g.position; g.position = to; + // ServerChunkCache.move: its pairs are checked again. + g.moved = true; 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; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 475bd7611..709a57619 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1026,14 +1026,11 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { || super::nautilus::is_nautilus(m.species()) && m.extra.tame || m.species() == Species::SulfurCube && (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0); - // removeWhenFarAway: animals, wardens, allays, patrols and raiders, - // zombie villagers being cured and ridden mobs stay; the wither's - // checkDespawn never removes it for distance. + // removeWhenFarAway: animals, villagers, golems, patrols and raiders, + // zombie villagers being cured and ridden mobs stay. let creature = m.kind.category == "creature"; - let removable = !(matches!( - m.species(), - Species::Warden | Species::Allay | Species::Wither - ) || creature && m.kind.flags.animal && !m.extra.jockey + let removable = !(never_removed_when_far(m.species()) + || creature && m.kind.flags.animal && !m.extra.jockey || super::raider::keeps_alive(m, d) || super::zombie_villager::keeps_alive(m) || super::riders::keeps_alive(m)); @@ -1059,6 +1056,24 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { } true } +/// The types whose `removeWhenFarAway` is always false (`Villager`, +/// `WanderingTrader`, `AbstractGolem`: iron, snow and copper golems and +/// shulkers; `Allay`, `Warden`), and the wither, whose `checkDespawn` never +/// removes it for distance. +fn never_removed_when_far(s: Species) -> bool { + matches!( + s, + Species::Villager + | Species::WanderingTrader + | Species::IronGolem + | Species::SnowGolem + | Species::CopperGolem + | Species::Shulker + | Species::Allay + | Species::Warden + | Species::Wither + ) +} /// Movement speed bonus multiplier (baby zombies are 50% faster, etc.). pub fn speed_bonus(m: &Mob) -> f64 { match m.species() { @@ -1579,3 +1594,25 @@ mod bucket_axolotl_tests { assert_eq!(family(Species::Axolotl), Family::Aquatic); } } +#[cfg(test)] +mod despawn_tests { + use super::*; + /// Village villagers are placed without PersistenceRequired (unlike the + /// village's iron golem), so they must never despawn for distance. + #[test] + fn villagers_traders_and_golems_never_despawn_for_distance() { + for s in [ + Species::Villager, + Species::WanderingTrader, + Species::IronGolem, + Species::SnowGolem, + Species::CopperGolem, + Species::Shulker, + ] { + assert!(never_removed_when_far(s), "{s:?}"); + } + for s in [Species::Zombie, Species::ZombieVillager, Species::Pillager] { + assert!(!never_removed_when_far(s), "{s:?}"); + } + } +} diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 3fdf67ca5..18af20343 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -429,13 +429,35 @@ fn guests_see_each_other_and_the_world_entities() { }; let first = thread::spawn(move || { let mut bot = connect(port, "Alex", false)?; + bot.c + .reader + .set_read_timeout(Some(Duration::from_millis(200))) + .unwrap(); let mut zombies = 0; let mut players = 0; let mut moves = 0; + let mut at: Option<[f64; 3]> = None; + let mut reminder = Instant::now(); let deadline = Instant::now() + Duration::from_secs(20); while Instant::now() < deadline && !(zombies > 0 && players > 0 && moves > 0) { - match bot.recv_play()? { + // A vanilla client sends its position at least every 20 ticks even + // when standing still (LocalPlayer's positionReminder), and the + // server checks which entities it sees again on each one. + if let Some([x, y, z]) = at + && reminder.elapsed() >= Duration::from_secs(1) + { + bot.send(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags: 1 })); + reminder = Instant::now(); + } + let Ok((id, payload)) = bot.c.recv() else { + continue; + }; + let Ok(packet) = C::decode(id, &payload) else { + continue; + }; + match packet { C::PlayerPosition(p) => { + at = Some(p.position); bot.send(S::AcceptTeleportation(play::AcceptTeleportation { id: p.teleport, x: p.position[0], diff --git a/crates/horizon-protocol/src/chunk.rs b/crates/horizon-protocol/src/chunk.rs index 32d7f98b6..165627d90 100644 --- a/crates/horizon-protocol/src/chunk.rs +++ b/crates/horizon-protocol/src/chunk.rs @@ -57,6 +57,19 @@ pub fn storage_len(bits: u8, entries: usize) -> usize { } } +/// SimpleBitStorage's longs for `values` at `bits` each, a long at a time. +fn pack(values: &[T], bits: u8, id: impl Fn(&T) -> u64) -> Vec { + let per = 64 / bits as usize; + values + .chunks(per) + .map(|word| { + word.iter() + .enumerate() + .fold(0u64, |w, (k, v)| w | id(v) << (k * bits as usize)) as i64 + }) + .collect() +} + /// One PalettedContainer as sent. #[derive(Clone, Debug, PartialEq)] pub struct Paletted { @@ -160,12 +173,11 @@ impl Paletted { data: Vec::new(), }; } - let mut data = vec![0i64; storage_len(bits, values.len())]; - let per = 64 / bits as usize; - for (i, (&v, &id)) in values.iter().zip(&ids).enumerate() { - let id = if has_palette { u64::from(id) } else { v as u64 }; - data[i / per] |= (id << ((i % per) * bits as usize)) as i64; - } + let data = if has_palette { + pack(&ids, bits, |&id| u64::from(id)) + } else { + pack(values, bits, |&v| v as u64) + }; Self { bits, palette: if has_palette { palette } else { Vec::new() }, diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 1398ef420..0f87d38ab 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -920,7 +920,15 @@ where Ok(chunk) } fn carver_biome(&self, worker: &mut WorkerState, origin: ChunkPos) -> Result { - if let Some(id) = self.carver_cache.lock().unwrap().get(&(origin.x, origin.z)) { + let key = (origin.x, origin.z); + if let Some(id) = worker.carver_biomes.get(&key) { + return Ok(*id); + } + if worker.carver_biomes.len() >= 4096 { + worker.carver_biomes.clear(); + } + if let Some(id) = self.carver_cache.lock().unwrap().get(&key) { + worker.carver_biomes.insert(key, *id); return Ok(*id); } let mut resolver = self.source.resolver( @@ -940,7 +948,8 @@ where if cache.len() >= CACHE_LIMIT * 4 { cache.clear(); } - cache.insert((origin.x, origin.z), id); + cache.insert(key, id); + worker.carver_biomes.insert(key, id); Ok(id) } fn generate( @@ -1407,6 +1416,9 @@ pub(super) struct WorkerState { pub(super) temperatures: Vec, biome_context: SamplerContext, carver_context: SamplerContext, + /// Seed/dimension-bound lookups avoid the shared mutex for overlapping + /// carver neighborhoods. Bounded independently of the shared cache. + carver_biomes: HashMap<(i32, i32), BiomeId>, timings: StageTimings, heights: HashMap<(i32, i32, u8), i32>, /// Decorate with structure pieces only (for structure parity checks). @@ -2197,6 +2209,7 @@ impl OverworldGenerator { .collect(), biome_context: SamplerContext::cached(), carver_context: SamplerContext::default(), + carver_biomes: HashMap::new(), timings: StageTimings::default(), structures_only: false, heights: HashMap::new(), @@ -2416,6 +2429,57 @@ mod tests { ); } + #[test] + fn local_carver_cache_is_worker_owned_and_eviction_preserves_terrain() { + let root = std::env::var_os("HORIZON_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); + if !root.join("worldgen/world_presets.json").exists() { + eprintln!("skipping: no worldgen bundle at {}", root.display()); + return; + } + let registry = Box::leak(Box::new( + crate::level::data::load_registry(&root).expect("registry"), + )); + let data = GeneratorData::load(&root.join("worldgen"), registry).unwrap(); + let generator = OverworldGenerator::new(data.clone(), 12345).unwrap(); + let mut first = generator.worker(); + let mut second = generator.worker(); + let pos = ChunkPos::new(0, 0); + let before = first.generate_proto(pos).unwrap(); + assert!(!first.state.carver_biomes.is_empty()); + assert!(second.state.carver_biomes.is_empty()); + second.generate_proto(pos).unwrap(); + assert_eq!(first.state.carver_biomes, second.state.carver_biomes); + let expected = first.state.carver_biomes.clone(); + first.state.carver_biomes.clear(); + // Fill unrelated origins to force eviction on the next local miss. + for x in 0..4096 { + first.state.carver_biomes.insert((x, 100_000), BiomeId(0)); + } + let after = first.generate_proto(pos).unwrap(); + assert_eq!(first.state.carver_biomes, expected); + for y in -64..320 { + for z in 0..16 { + for x in 0..16 { + assert_eq!(before.block(x, y, z), after.block(x, y, z)); + assert_eq!(before.biome_id_at(x, y, z), after.biome_id_at(x, y, z)); + } + } + } + assert!( + OverworldGenerator::new(data, -1) + .unwrap() + .worker() + .state + .carver_biomes + .is_empty() + ); + assert_eq!(second.state.carver_biomes, expected); + } + /// Generators of one seed and dimension share their ring positions; /// another seed or generator gets its own, and old entries go. #[test]