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) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M3pNrSHA2ifNrH7SAMHgSW
This commit is contained in:
Claude
2026-10-22 06:26:11 +00:00
parent e730dc1426
commit bc9e5afacc
5 changed files with 133 additions and 31 deletions
@@ -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 {
@@ -58,7 +58,13 @@ impl From<RegionError> for PlacementQueryError {
}
}
pub struct TerrainRegion<'r, B: TerrainBlockStates> {
chunks: BTreeMap<(i32, i32), TerrainChunk<'r, B>>,
/// Ordered by X then Z.
chunks: Vec<TerrainChunk<'r, B>>,
/// 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<u32>,
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<Self, RegionError> {
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<TerrainChunk<'r, B>> {
self.chunks.into_values().collect()
self.chunks
}
pub fn chunks(&self) -> impl Iterator<Item = &TerrainChunk<'r, B>> {
self.chunks.values()
self.chunks.iter()
}
fn index(&self, x: i32, z: i32) -> Option<usize> {
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<BlockStateId, RegionError> {
Ok(self.chunk(x >> 4, z >> 4)?.block(x, y, z))
@@ -302,12 +337,7 @@ impl<B: TerrainBlockStates> 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))?;
@@ -1116,4 +1116,41 @@ impl PlacementContext for World<'_> {
fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result<i32, PlacementQueryError> {
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<Option<bool>, 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))
}
}
@@ -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)
@@ -344,6 +344,18 @@ pub trait PlacementContext {
/// World minimum, which can differ from the generator's minimum.
fn min_y(&mut self) -> Result<i32, PlacementQueryError>;
fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result<i32, PlacementQueryError>;
/// 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<Option<bool>, PlacementQueryError> {
Ok(None)
}
}
impl PlacementContext for WorldGenerationContext {
fn max_y(&mut self) -> Result<i32, PlacementQueryError> {