Merge pull request #872 from ludovic111/perf/structure-start-shards

🤖 Agent: Merged. Game thread waiting on the structure-start cache lock while exploring: 194/57 → 1/0 samples; structures_reaching 260/127 → 15/50. structure_density, worldgen, chunk_stage and chunk_generation pass.
This commit is contained in:
Ludovic Marie
2026-10-18 16:50:12 +02:00
committed by GitHub
@@ -17,7 +17,7 @@ use std::collections::BTreeMap;
use std::{
collections::{BTreeSet, HashMap},
sync::{
Arc, Condvar, Mutex, OnceLock,
Arc, Condvar, Mutex, OnceLock, RwLock,
atomic::{AtomicUsize, Ordering},
},
};
@@ -30,7 +30,7 @@ pub(super) struct StructureState {
possible_sets: Vec<usize>,
/// Structure indices of each decoration step, in registry order.
pub(super) by_step: Vec<Vec<usize>>,
starts: Mutex<HashMap<(i32, i32), Starts>>,
starts: StartCache,
/// Concentric ring positions, computed on first use and shared with
/// later generators of the same seed and dimension.
rings: Arc<OnceLock<Rings>>,
@@ -108,6 +108,45 @@ impl RingWork {
}
}
const START_CACHE_LIMIT: usize = 65536;
const START_SHARDS: usize = 64;
/// The built starts by chunk, in shards: a lookup locks one shard for
/// reading. Each generated chunk reads the 289 start chunks around it
/// (`references`) and the server thread reads the starts of the chunks its
/// mobs and players are in; with one lock for all, the server thread waited
/// on the workers.
struct StartCache {
shards: Box<[RwLock<HashMap<(i32, i32), Starts>>]>,
}
impl StartCache {
fn new() -> Self {
Self {
shards: (0..START_SHARDS).map(|_| RwLock::default()).collect(),
}
}
fn shard(&self, key: (i32, i32)) -> &RwLock<HashMap<(i32, i32), Starts>> {
let hash =
(key.0 as u32).wrapping_mul(0x9E37_79B9) ^ (key.1 as u32).wrapping_mul(0x85EB_CA6B);
&self.shards[(hash >> (32 - START_SHARDS.trailing_zeros())) as usize]
}
fn get(&self, key: (i32, i32)) -> Option<Starts> {
self.shard(key).read().unwrap().get(&key).cloned()
}
/// Keeps `starts` unless another thread built the same chunk's first:
/// everyone keeps the first, so placement state on its pieces is shared.
fn insert_first(&self, key: (i32, i32), starts: Starts) -> Starts {
let mut shard = self.shard(key).write().unwrap();
if shard.len() >= START_CACHE_LIMIT / START_SHARDS {
shard.clear();
}
shard.entry(key).or_insert(starts).clone()
}
fn clear(&self) {
for shard in &self.shards {
shard.write().unwrap().clear();
}
}
}
fn biome_set(data: &GeneratorData, value: &Value) -> Result<BTreeSet<BiomeId>, super::DecodeError> {
let names: Vec<&str> = match value {
@@ -167,7 +206,7 @@ impl StructureState {
bindings,
possible_sets,
by_step,
starts: Mutex::new(HashMap::new()),
starts: StartCache::new(),
rings,
ring_work: OnceLock::new(),
}))
@@ -199,7 +238,7 @@ impl StructureState {
/// Drop the cached starts, so that later chunks build fresh pieces (the
/// pieces keep per-start placement state such as a shipwreck's height).
pub(super) fn forget_starts(&self) {
self.starts.lock().unwrap().clear();
self.starts.clear();
}
/// The (cached) structure starts owned by a chunk.
pub(super) fn starts_at(
@@ -207,8 +246,8 @@ impl StructureState {
context: &mut impl super::structure::start::StartContext,
chunk: ChunkPos,
) -> Starts {
if let Some(found) = self.starts.lock().unwrap().get(&(chunk.x, chunk.z)) {
return found.clone();
if let Some(found) = self.starts.get((chunk.x, chunk.z)) {
return found;
}
let rings = self.rings(context);
let starts: Starts = Arc::new(
@@ -225,13 +264,7 @@ impl StructureState {
.map(Arc::new)
.collect(),
);
let mut cache = self.starts.lock().unwrap();
if cache.len() >= START_CACHE_LIMIT {
cache.clear();
}
// Another thread may have built the same starts meanwhile: everyone
// keeps the first, so placement state on its pieces is shared.
cache.entry((chunk.x, chunk.z)).or_insert(starts).clone()
self.starts.insert_first((chunk.x, chunk.z), starts)
}
/// ChunkGenerator.findNearestMapStructure: the nearest start of one of
/// `names` from block `from` (rings: every ring chunk; random spreads:
@@ -385,6 +418,39 @@ mod tests {
use super::*;
use crate::worldgen::structure::stronghold::{ring_positions, ring_searches};
/// The start cache keeps the first starts built for a chunk, spreads a
/// chunk's 289 reference lookups over the shards, and forgets on clear.
#[test]
fn start_cache_keeps_first_and_spreads_neighbours() {
let cache = StartCache::new();
let first: Starts = Arc::new(Vec::new());
let second: Starts = Arc::new(Vec::new());
assert!(cache.get((3, -4)).is_none());
assert!(Arc::ptr_eq(
&cache.insert_first((3, -4), first.clone()),
&first
));
assert!(Arc::ptr_eq(&cache.insert_first((3, -4), second), &first));
assert!(Arc::ptr_eq(&cache.get((3, -4)).unwrap(), &first));
for (cx, cz) in [(0, 0), (-1000, 77), (i32::MAX - 8, i32::MIN + 8)] {
let mut used = vec![0; START_SHARDS];
for x in cx - 8..=cx + 8 {
for z in cz - 8..=cz + 8 {
let shard = cache.shard((x, z)) as *const _;
let i = cache
.shards
.iter()
.position(|s| std::ptr::eq(s, shard))
.unwrap();
used[i] += 1;
}
}
assert!(used.iter().all(|&n| n > 0 && n < 20), "{used:?}");
}
cache.clear();
assert!(cache.get((3, -4)).is_none());
}
/// Searches shared between threads give the positions of one thread
/// running them in order, set by set.
#[test]