From bc9e5afacce9cea888472491a83f57660c224dcf Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 06:26:11 +0000 Subject: [PATCH 1/2] Faster feature decoration: region grid, ore column fast path, lazy biome cache TerrainRegion indexes its chunks through a grid over their bounding box. OreFeature asks the world whether any column under its blob reaches the floor heightmap in one call, and tracks tested positions in a bitset. BiomeTemperature no longer preallocates its map and queue. Same output. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01M3pNrSHA2ifNrH7SAMHgSW --- .../src/worldgen/biome_temperature.rs | 6 +- .../src/worldgen/feature_region.rs | 76 +++++++++++++------ .../src/worldgen/generator_decoration.rs | 37 +++++++++ .../horizon-world/src/worldgen/ore_feature.rs | 33 ++++++-- .../src/worldgen/placement/context.rs | 12 +++ 5 files changed, 133 insertions(+), 31 deletions(-) diff --git a/crates/horizon-world/src/worldgen/biome_temperature.rs b/crates/horizon-world/src/worldgen/biome_temperature.rs index c7e22c985..7111214f4 100644 --- a/crates/horizon-world/src/worldgen/biome_temperature.rs +++ b/crates/horizon-world/src/worldgen/biome_temperature.rs @@ -123,10 +123,12 @@ pub struct BiomeTemperature { } impl BiomeTemperature { pub fn new(settings: BiomeTemperatureSettings) -> Self { + // Empty until used: a decoration region makes one per biome, and + // most biomes never ask for a temperature. Self { settings, - values: HashMap::with_capacity(1024), - order: VecDeque::with_capacity(1024), + values: HashMap::new(), + order: VecDeque::new(), } } pub fn settings(&self) -> BiomeTemperatureSettings { diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index 5ab361985..91de61905 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -58,7 +58,13 @@ impl From for PlacementQueryError { } } pub struct TerrainRegion<'r, B: TerrainBlockStates> { - chunks: BTreeMap<(i32, i32), TerrainChunk<'r, B>>, + /// Ordered by X then Z. + chunks: Vec>, + /// Each chunk's index in `chunks` over the chunks' bounding box, row by + /// row from `origin` (`u32::MAX`: none): every block access looks one up. + grid: Vec, + origin: (i32, i32), + columns: i32, min_y: i32, height: i32, generation: WorldGenerationContext, @@ -83,15 +89,32 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { }) { return Err(RegionError::InvalidChunks); } - let mut stored = BTreeMap::new(); - for chunk in chunks { + let mut chunks = chunks; + chunks.sort_by_key(|c| (c.position().x, c.position().z)); + let (xs, zs) = ( + chunks.iter().map(|c| c.position().x), + chunks.iter().map(|c| c.position().z), + ); + let origin = (xs.clone().min().unwrap(), zs.clone().min().unwrap()); + let columns = i64::from(xs.max().unwrap()) - i64::from(origin.0) + 1; + let rows = i64::from(zs.max().unwrap()) - i64::from(origin.1) + 1; + if columns * rows > 1 << 20 { + return Err(RegionError::InvalidChunks); + } + let mut grid = vec![u32::MAX; (columns * rows) as usize]; + for (i, chunk) in chunks.iter().enumerate() { let p = chunk.position(); - if stored.insert((p.x, p.z), chunk).is_some() { + let cell = (p.z - origin.1) as usize * columns as usize + (p.x - origin.0) as usize; + if grid[cell] != u32::MAX { return Err(RegionError::InvalidChunks); } + grid[cell] = i as u32; } Ok(Self { - chunks: stored, + chunks, + grid, + origin, + columns: columns as i32, sea_level: generator.sea_level, game_time: 0, next_tick_order: 0, @@ -114,10 +137,7 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { mut self, bindings: &super::block_feature::FeatureBlockBindings<'r>, ) -> Result { - if !std::ptr::eq( - self.chunks.first_key_value().unwrap().1.registry(), - bindings.registry(), - ) { + if !std::ptr::eq(self.chunks[0].registry(), bindings.registry()) { return Err(RegionError::InvalidBindings); } self.block_queries = Some(RegionBlockQueries { @@ -186,20 +206,35 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { } /// Release the resident chunks, ordered by X then Z; match them by position. pub fn into_chunks(self) -> Vec> { - self.chunks.into_values().collect() + self.chunks } pub fn chunks(&self) -> impl Iterator> { - self.chunks.values() + self.chunks.iter() + } + fn index(&self, x: i32, z: i32) -> Option { + let (dx, dz) = (x.wrapping_sub(self.origin.0), z.wrapping_sub(self.origin.1)); + if dx < 0 || dz < 0 || dx >= self.columns { + return None; + } + match *self + .grid + .get(dz as usize * self.columns as usize + dx as usize)? + { + u32::MAX => None, + i => Some(i as usize), + } } pub fn chunk(&self, x: i32, z: i32) -> Result<&TerrainChunk<'r, B>, RegionError> { - self.chunks - .get(&(x, z)) - .ok_or(RegionError::MissingChunk([x, z])) + match self.index(x, z) { + Some(i) => Ok(&self.chunks[i]), + None => Err(RegionError::MissingChunk([x, z])), + } } pub fn chunk_mut(&mut self, x: i32, z: i32) -> Result<&mut TerrainChunk<'r, B>, RegionError> { - self.chunks - .get_mut(&(x, z)) - .ok_or(RegionError::MissingChunk([x, z])) + match self.index(x, z) { + Some(i) => Ok(&mut self.chunks[i]), + None => Err(RegionError::MissingChunk([x, z])), + } } pub fn block(&self, [x, y, z]: [i32; 3]) -> Result { Ok(self.chunk(x >> 4, z >> 4)?.block(x, y, z)) @@ -302,12 +337,7 @@ impl PlacementContext for TerrainRegion<'_, B> { block: BlockStateId, delay: i32, ) -> Result<(), PlacementQueryError> { - let registry = self - .chunks - .first_key_value() - .expect("nonempty region") - .1 - .registry(); + let registry = self.chunks[0].registry(); let state = registry .state(block) .ok_or(RegionError::InvalidTickState(block))?; diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index bc5dbda70..a16baa506 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -1116,4 +1116,41 @@ impl PlacementContext for World<'_> { fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result { self.region.height(kind, x, z) } + /// OreFeature's search for a column under its blob, without a trait call + /// per column. Defers to `height` when a heightmap still has to be primed. + fn any_height_at_least( + &mut self, + kind: HeightmapType, + [x0, z0]: [i32; 2], + size: i32, + y: i32, + ) -> Result, PlacementQueryError> { + let (x1, z1) = (x0.wrapping_add(size), z0.wrapping_add(size)); + if size < 0 || x1 < x0 || z1 < z0 { + return Ok(None); + } + for cx in x0 >> 4..=x1 >> 4 { + for cz in z0 >> 4..=z1 >> 4 { + if !self + .region + .chunk(cx, cz) + .is_ok_and(|c| c.heightmap(kind).is_some()) + { + return Ok(None); + } + } + } + for x in x0..=x1 { + for z in z0..=z1 { + let map = self.region.chunk(x >> 4, z >> 4)?.heightmap(kind).unwrap(); + let floor = map + .first_available(x & 15, z & 15) + .map_err(|e| RegionError::from(super::terrain::TerrainError::from(e)))?; + if y <= floor { + return Ok(Some(true)); + } + } + } + Ok(Some(false)) + } } diff --git a/crates/horizon-world/src/worldgen/ore_feature.rs b/crates/horizon-world/src/worldgen/ore_feature.rs index 9d723ae40..d69874d76 100644 --- a/crates/horizon-world/src/worldgen/ore_feature.rs +++ b/crates/horizon-world/src/worldgen/ore_feature.rs @@ -180,6 +180,27 @@ impl OreFeature { let z_start = origin[2].wrapping_sub(spread_ceil).wrapping_sub(max_radius); let size_xz = 2 * (spread_ceil + max_radius); let size_y = 2 * (2 + max_radius); + if let Some(found) = world + .any_height_at_least( + HeightmapType::OceanFloorWg, + [x_start, z_start], + size_xz, + y_start, + ) + .map_err(FeatureExecutionError::Query)? + { + return match found { + true => self.do_place( + world, + random, + [x0, x1, z0, z1, y0, y1], + [x_start, y_start, z_start], + size_xz, + size_y, + ), + false => Ok(false), + }; + } for x in 0..=size_xz { for z in 0..=size_xz { let (px, pz) = (x_start.wrapping_add(x), z_start.wrapping_add(z)); @@ -243,7 +264,8 @@ impl OreFeature { } } } - let mut tested = vec![false; (size_xz as usize) * (size_y as usize) * (size_xz as usize)]; + let tested_len = (size_xz as usize) * (size_y as usize) * (size_xz as usize); + let mut tested = vec![0u64; tested_len.div_ceil(64)]; let mut placed = 0; for [xx, yy, zz, r] in data { if r < 0.0 { @@ -280,16 +302,15 @@ impl OreFeature { * i64::from(size_xz) * i64::from(size_y); // The sphere bounds keep indices inside the native BitSet. - let Some(bit) = usize::try_from(index) - .ok() - .and_then(|index| tested.get_mut(index)) + let Some(index) = usize::try_from(index).ok().filter(|&i| i < tested_len) else { return Err(FeatureExecutionError::WorkLimit); }; - if *bit { + let (word, bit) = (&mut tested[index / 64], 1u64 << (index % 64)); + if *word & bit != 0 { continue; } - *bit = true; + *word |= bit; let p = [x, y, z]; if !world .ensure_can_write(p) diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index 8d2a1dab7..73b9afd67 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -344,6 +344,18 @@ pub trait PlacementContext { /// World minimum, which can differ from the generator's minimum. fn min_y(&mut self) -> Result; fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result; + /// Whether any column of the square `x..=x + size`, `z..=z + size` has + /// `height(kind)` at least `y`, read faster than column by column; `None` + /// when the world can't (callers then ask `height` for each column). + fn any_height_at_least( + &mut self, + _kind: HeightmapType, + _corner: [i32; 2], + _size: i32, + _y: i32, + ) -> Result, PlacementQueryError> { + Ok(None) + } } impl PlacementContext for WorldGenerationContext { fn max_y(&mut self) -> Result { From ac60b337aa4374456664ed54c06f58e9bf9d2a56 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:40:07 +0200 Subject: [PATCH 2/2] worldgen: chunks far apart still make a region (map past the grid) TerrainRegion::new refused a region whose chunks bounding box passed 2^20 columns, where it took any set of distinct chunks before: the bulk_section parity fixture puts a chunk at x = 4194304 beside the origin and failed with InvalidChunks. Keep the grid for the usual small box and fall back to a map past it; both refuse a position twice. The lookup now subtracts in i64, so no coordinate can wrap into the grid. Co-Authored-By: Claude Opus 5.5 --- .../src/worldgen/feature_region.rs | 120 ++++++++++++------ crates/horizon-world/tests/feature_region.rs | 43 +++++++ 2 files changed, 124 insertions(+), 39 deletions(-) diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index 91de61905..b4e8c07b0 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -22,7 +22,7 @@ use horizon_core::{ }, }; use std::{ - collections::{BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, HashMap}, sync::Arc, }; @@ -60,11 +60,8 @@ impl From for PlacementQueryError { pub struct TerrainRegion<'r, B: TerrainBlockStates> { /// Ordered by X then Z. chunks: Vec>, - /// Each chunk's index in `chunks` over the chunks' bounding box, row by - /// row from `origin` (`u32::MAX`: none): every block access looks one up. - grid: Vec, - origin: (i32, i32), - columns: i32, + /// Each chunk's index in `chunks`: every block access looks one up. + index: ChunkIndex, min_y: i32, height: i32, generation: WorldGenerationContext, @@ -74,6 +71,77 @@ pub struct TerrainRegion<'r, B: TerrainBlockStates> { block_queries: Option, world_seed: Option, } +/// Where each chunk of a region sits in its list: a grid over the chunks' +/// bounding box while it is small (the usual square of neighbours), else a +/// map (chunks spread far apart). +enum ChunkIndex { + Grid { + origin: (i32, i32), + columns: i64, + rows: i64, + /// Row by row from `origin`; `u32::MAX` where no chunk is. + cells: Vec, + }, + Sparse(HashMap<(i32, i32), u32>), +} +impl ChunkIndex { + /// The largest grid, in chunk columns. + const GRID_CELLS: i64 = 1 << 20; + /// `None` when two chunks share a position. + fn new(positions: &[(i32, i32)]) -> Option { + let x0 = positions.iter().map(|p| p.0).min()?; + let z0 = positions.iter().map(|p| p.1).min()?; + let columns = i64::from(positions.iter().map(|p| p.0).max()?) - i64::from(x0) + 1; + let rows = i64::from(positions.iter().map(|p| p.1).max()?) - i64::from(z0) + 1; + if columns * rows > Self::GRID_CELLS { + let mut map = HashMap::with_capacity(positions.len()); + for (i, &p) in positions.iter().enumerate() { + if map.insert(p, i as u32).is_some() { + return None; + } + } + return Some(Self::Sparse(map)); + } + let mut cells = vec![u32::MAX; (columns * rows) as usize]; + for (i, &(x, z)) in positions.iter().enumerate() { + let cell = (i64::from(z) - i64::from(z0)) * columns + (i64::from(x) - i64::from(x0)); + let cell = &mut cells[cell as usize]; + if *cell != u32::MAX { + return None; + } + *cell = i as u32; + } + Some(Self::Grid { + origin: (x0, z0), + columns, + rows, + cells, + }) + } + fn get(&self, x: i32, z: i32) -> Option { + match self { + Self::Grid { + origin, + columns, + rows, + cells, + } => { + let (dx, dz) = ( + i64::from(x) - i64::from(origin.0), + i64::from(z) - i64::from(origin.1), + ); + if !(0..*columns).contains(&dx) || !(0..*rows).contains(&dz) { + return None; + } + match cells[(dz * columns + dx) as usize] { + u32::MAX => None, + i => Some(i as usize), + } + } + Self::Sparse(map) => map.get(&(x, z)).map(|&i| i as usize), + } + } +} impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { pub fn new( chunks: Vec>, @@ -91,30 +159,14 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { } let mut chunks = chunks; chunks.sort_by_key(|c| (c.position().x, c.position().z)); - let (xs, zs) = ( - chunks.iter().map(|c| c.position().x), - chunks.iter().map(|c| c.position().z), - ); - let origin = (xs.clone().min().unwrap(), zs.clone().min().unwrap()); - let columns = i64::from(xs.max().unwrap()) - i64::from(origin.0) + 1; - let rows = i64::from(zs.max().unwrap()) - i64::from(origin.1) + 1; - if columns * rows > 1 << 20 { - return Err(RegionError::InvalidChunks); - } - let mut grid = vec![u32::MAX; (columns * rows) as usize]; - for (i, chunk) in chunks.iter().enumerate() { - let p = chunk.position(); - let cell = (p.z - origin.1) as usize * columns as usize + (p.x - origin.0) as usize; - if grid[cell] != u32::MAX { - return Err(RegionError::InvalidChunks); - } - grid[cell] = i as u32; - } + let positions: Vec<(i32, i32)> = chunks + .iter() + .map(|c| (c.position().x, c.position().z)) + .collect(); + let index = ChunkIndex::new(&positions).ok_or(RegionError::InvalidChunks)?; Ok(Self { chunks, - grid, - origin, - columns: columns as i32, + index, sea_level: generator.sea_level, game_time: 0, next_tick_order: 0, @@ -212,17 +264,7 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { self.chunks.iter() } fn index(&self, x: i32, z: i32) -> Option { - let (dx, dz) = (x.wrapping_sub(self.origin.0), z.wrapping_sub(self.origin.1)); - if dx < 0 || dz < 0 || dx >= self.columns { - return None; - } - match *self - .grid - .get(dz as usize * self.columns as usize + dx as usize)? - { - u32::MAX => None, - i => Some(i as usize), - } + self.index.get(x, z) } pub fn chunk(&self, x: i32, z: i32) -> Result<&TerrainChunk<'r, B>, RegionError> { match self.index(x, z) { diff --git a/crates/horizon-world/tests/feature_region.rs b/crates/horizon-world/tests/feature_region.rs index c484393bf..7ff34da6f 100644 --- a/crates/horizon-world/tests/feature_region.rs +++ b/crates/horizon-world/tests/feature_region.rs @@ -385,3 +385,46 @@ fn retained_upgrade_status_allows_old_biome_reads() { } } } +#[test] +fn spread_out_regions_route_like_dense_ones() { + // Chunks too far apart for a grid over their bounding box (fixtures put + // one at the far edge of the world beside the origin's neighbours). + let registry = registry(); + let context = WorldGenerationContext::new(0, 16, 8); + let chunk = + |x, z| TerrainChunk::new(ChunkPos::new(x, z), 0, 16, ®istry, Properties).unwrap(); + for far in [4_194_304, -4_194_304] { + let mut region = TerrainRegion::new( + vec![chunk(0, 0), chunk(far, 0), chunk(1, -1), chunk(-1, 1)], + context, + ) + .unwrap(); + let x = far * 16 + 3; + region + .set_block_worldgen([x, 7, 5], BlockStateId(2)) + .unwrap(); + assert_eq!(region.block([x, 7, 5]).unwrap(), BlockStateId(2)); + assert_eq!(region.block([3, 7, 5]).unwrap(), BlockStateId(0)); + assert_eq!(region.block([16, 7, -1]).unwrap(), BlockStateId(0)); + assert!(matches!( + region.block([x + 16, 7, 5]), + Err(RegionError::MissingChunk([_, 0])) + )); + assert!(matches!( + region.block([0, 7, 16]), + Err(RegionError::MissingChunk([0, 1])) + )); + let order: Vec<_> = region + .into_chunks() + .iter() + .map(|c| (c.position().x, c.position().z)) + .collect(); + let mut sorted = order.clone(); + sorted.sort(); + assert_eq!(order, sorted, "into_chunks is ordered by X then Z"); + // A position twice is refused either way. + assert!( + TerrainRegion::new(vec![chunk(0, 0), chunk(far, 0), chunk(far, 0)], context).is_err() + ); + } +}