diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 0d1f409e6..2d7dd251c 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -1219,6 +1219,30 @@ where }); columns } + /// ChunkGenerator.getBaseColumn's blocks, by what structures test + /// (BlockState.isSolid is blocksMotion for the noise's blocks, which + /// are never cobwebs or bamboo saplings). + fn noise_blocks(&self, x: i32, z: i32) -> super::structure::start::NoiseColumn { + use super::structure::start::{NoiseBlock, NoiseColumn}; + let (min, height) = (self.settings.noise_min_y, self.settings.noise_height); + let mut blocks = vec![NoiseBlock::Air; height as usize]; + let registry = self.data.registry; + self.noise_column(x, z, &mut |y, state| { + let props = self.data.states.get(state); + blocks[(y - min) as usize] = if props.is_air() { + NoiseBlock::Air + } else { + match registry.state(state).map(|s| s.name.as_str()) { + Some("minecraft:water") => NoiseBlock::Water, + Some("minecraft:lava") => NoiseBlock::Lava, + _ if props.blocks_motion_in_heightmap() => NoiseBlock::Solid, + _ => NoiseBlock::Other, + } + }; + false + }); + NoiseColumn { min, blocks } + } /// iterateNoiseColumn from the top down until `visit` returns true. fn noise_column(&self, x: i32, z: i32, visit: &mut dyn FnMut(i32, BlockStateId) -> bool) { let (min, height) = (self.settings.noise_min_y, self.settings.noise_height); @@ -1327,6 +1351,9 @@ where fn base_columns(&mut self, x: i32, z: i32, kinds: &[HeightmapType]) -> Vec> { self.pipeline.base_columns(x, z, kinds) } + fn noise_column(&mut self, x: i32, z: i32) -> super::structure::start::NoiseColumn { + self.pipeline.noise_blocks(x, z) + } fn cold_enough_to_snow(&mut self, biome: BiomeId, pos: [i32; 3]) -> bool { let sea = self.pipeline.settings.sea_level; self.worker.temperatures[biome.0 as usize] diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index 61a48f3ea..405073450 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -3,6 +3,7 @@ pub mod end_city; pub mod enhanced_terrain; pub mod features; +pub mod formations; pub mod fortress; pub mod jigsaw; pub mod legacy; diff --git a/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs b/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs index 404b9ecca..ac4d01e98 100644 --- a/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs +++ b/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs @@ -308,6 +308,7 @@ mod tests { waterlogging: None, yung: None, enhanced_terrain: own.map(Arc::new), + ground_level: 1, }) } diff --git a/crates/horizon-world/src/worldgen/structure/formations.rs b/crates/horizon-world/src/worldgen/structure/formations.rs new file mode 100644 index 000000000..b93268116 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/formations.rs @@ -0,0 +1,340 @@ +//! Formations' SimpleStructure (`horizon:formations`, which +//! `horizon-port-pack` writes for its `formations:simple`; docs/modpacks.md): +//! one pool element at a random spot of the chunk, at a height its +//! placement finds in the noise columns under the element's corners and +//! centre ([`StartContext::noise_column`]). +use super::{ + BoundingBox, Rotation, StructureResources, + jigsaw::{PoolElement, PoolPiece, Pools}, + start::{NoiseBlock, NoiseColumn, StartContext}, +}; +use crate::{ + heightmap::HeightmapType, + worldgen::{DecodeError, block_feature::FeatureBlockBindings}, +}; +use horizon_core::position::ChunkPos; +use horizon_core::random::RandomSource; +use serde_json::Value; + +/// StructurePlacement: how the height is found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Placement { + Surface, + Ceiling, + OnWater, + OnLava, + Underground, + UndergroundSurface, + UndergroundCeiling, + UndergroundBuried, + UndergroundOnLava, +} +impl Placement { + pub fn decode(name: &str) -> Result { + Ok(match name { + "surface" => Self::Surface, + "ceiling" => Self::Ceiling, + "on_water" => Self::OnWater, + "on_lava" => Self::OnLava, + "underground" => Self::Underground, + "underground_surface" => Self::UndergroundSurface, + "underground_ceiling" => Self::UndergroundCeiling, + "underground_buried" => Self::UndergroundBuried, + "underground_on_lava" => Self::UndergroundOnLava, + _ => return Err(DecodeError::Field("formations placement")), + }) + } +} + +/// The structure: a pool to draw the element from, and its placement. +#[derive(Clone, Debug)] +pub struct Def { + pub pool: String, + pub placement: Placement, +} +impl Def { + pub fn decode(v: &Value) -> Result { + Ok(Self { + // An inline element is never written by Formations' generators. + pool: v["template"] + .as_str() + .ok_or(DecodeError::Field("formations template"))? + .to_owned(), + placement: Placement::decode(v["placement"].as_str().unwrap_or_default())?, + }) + } +} + +/// SimpleStructure.findGenerationPoint: the start's position and piece. +pub fn generate( + def: &Def, + context: &mut impl StartContext, + pools: &Pools, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + random: &mut impl RandomSource, + chunk: ChunkPos, +) -> Option<([i32; 3], PoolPiece)> { + let element = pools + .get(&def.pool, resources, bindings)? + .random_template(random); + if matches!(element.as_ref(), PoolElement::Empty) { + return None; + } + let x = chunk.x * 16 + random.next_int_bound(16).ok()?; + let z = chunk.z * 16 + random.next_int_bound(16).ok()?; + let rotation = Rotation::random(random); + let b = element.bounding_box([x, 0, z], rotation); + let height = find_height(def.placement, context, b, random)?; + let ground = element.ground_level_delta(); + let y = height - ground + 1; + if y < context.min_y() { + return None; + } + let piece = PoolPiece { + bounding_box: b.moved([0, y, 0]), + ground_level_delta: ground, + element, + position: [x, y, z], + rotation, + junctions: Vec::new(), + // LiquidSettings.APPLY_WATERLOGGING. + waterlogging: true, + }; + Some(([x, y, z], piece)) +} + +/// The four corners (min x min z, min x max z, max x max z, max x min z) +/// and the centre, as Formations' cornersAndCenter. +fn corners_and_center(b: BoundingBox) -> [[i32; 2]; 5] { + let c = b.center(); + [ + [b.min[0], b.min[2]], + [b.min[0], b.max[2]], + [b.max[0], b.max[2]], + [b.max[0], b.min[2]], + [c[0], c[2]], + ] +} + +/// ChunkGenerator.getFirstOccupiedHeight on WORLD_SURFACE_WG. +fn first_occupied(context: &mut impl StartContext, x: i32, z: i32) -> i32 { + context.base_height(x, z, HeightmapType::WorldSurfaceWg) - 1 +} + +/// (int) Math.round of the heights' mean. +fn average(heights: &[i32]) -> i32 { + let mean = heights.iter().map(|h| f64::from(*h)).sum::() / heights.len() as f64; + (mean + 0.5).floor() as i32 +} + +/// The largest and the mean distance of the heights from `average`. +fn spread(heights: &[i32], average: i32) -> (i32, f64) { + let d: Vec = heights.iter().map(|h| (average - h).abs()).collect(); + let max = d.iter().copied().max().unwrap_or(0); + let mean = d.iter().map(|v| f64::from(*v)).sum::() / d.len() as f64; + (max, mean) +} + +fn find_height( + placement: Placement, + context: &mut impl StartContext, + b: BoundingBox, + random: &mut impl RandomSource, +) -> Option { + let solid = NoiseBlock::is_solid; + match placement { + Placement::Surface => from_top(context, b, 10, 3.0, solid), + Placement::OnWater => from_top(context, b, 1, 1.0, |n| n == NoiseBlock::Water), + Placement::OnLava => from_top(context, b, 1, 1.0, |n| n == NoiseBlock::Lava), + Placement::Ceiling => { + let min = context.min_y(); + let top = context.max_y() + 1; + let mut heights = Vec::with_capacity(5); + for [x, z] in corners_and_center(b) { + let highest = first_occupied(context, x, z).min(top); + let column = context.noise_column(x, z); + heights.push(((min + 1)..highest).find(|y| column.get(*y) != NoiseBlock::Air)?); + } + let average = average(&heights); + (spread(&heights, average).1 <= 4.0).then_some(average) + } + _ => underground(placement, context, b, random), + } +} + +/// findFromTop: every column's top block (WORLD_SURFACE_WG) passes +/// `target`, and the heights are close enough. +fn from_top( + context: &mut impl StartContext, + b: BoundingBox, + max_offset: i32, + max_average_offset: f64, + target: impl Fn(NoiseBlock) -> bool, +) -> Option { + let min = context.min_y(); + let points = corners_and_center(b); + let heights: Vec = points + .iter() + .map(|[x, z]| first_occupied(context, *x, *z)) + .collect(); + if heights.iter().any(|y| *y <= min) { + return None; + } + for ([x, z], y) in points.iter().zip(&heights) { + if !target(context.noise_column(*x, *z).get(*y)) { + return None; + } + } + let average = average(&heights); + let (max, mean) = spread(&heights, average); + (max <= max_offset && mean <= max_average_offset).then_some(average) +} + +/// The underground placements: the space between the highest first block +/// above the bottom and the lowest surface of the five columns, then a +/// random height in it, which each column adjusts to its floor (or +/// ceiling, or lava), within limits. +fn underground( + placement: Placement, + context: &mut impl StartContext, + b: BoundingBox, + random: &mut impl RandomSource, +) -> Option { + let (bottom, top) = (context.min_y(), context.max_y() + 1); + let mut columns: Vec<(NoiseColumn, i32, i32)> = Vec::with_capacity(5); + for [x, z] in corners_and_center(b) { + let highest = first_occupied(context, x, z).min(top); + let column = context.noise_column(x, z); + let lowest = ((bottom + 1)..highest).find(|y| column.get(*y) != NoiseBlock::Air)?; + columns.push((column, highest, lowest)); + } + let min = columns.iter().map(|c| c.2).max()?; + let max = columns.iter().map(|c| c.1).min()?; + let span = b.span()[1]; + if max - min - 2 <= span { + return None; + } + let draw = random.next_int_bound(max - min - span - 2).ok()?; + let air = |c: &NoiseColumn, y: i32| c.get(y) == NoiseBlock::Air; + let solid = |c: &NoiseColumn, y: i32| c.get(y).is_solid(); + // A floor (or lava) under air near `height`: down through up to 10 + // blocks (`step` -1) or up (`step` 1, the ceiling), then through up to + // `reach` blocks of air. + let floor = |c: &NoiseColumn, height: i32, step: i32, reach: i32, lava: bool| { + let mut y = height; + let mut i = 0; + while i < 10 && y > min && !air(c, y) { + y += step; + i += 1; + } + if !air(c, y) { + return None; + } + y += step; + let mut i = 0; + while i < reach && air(c, y) { + y += step; + i += 1; + } + let ok = if lava { + c.get(y) == NoiseBlock::Lava + } else { + solid(c, y) + }; + ok.then_some(y) + }; + let heights: Option> = match placement { + Placement::Underground => return Some(min + 1 + draw), + Placement::UndergroundSurface => { + let h = min + 1 + draw; + columns + .iter() + .map(|c| floor(&c.0, h, -1, 20, false)) + .collect() + } + Placement::UndergroundCeiling => { + let h = min + 1 + draw; + columns + .iter() + .map(|c| floor(&c.0, h, 1, 30, false)) + .collect() + } + Placement::UndergroundOnLava => { + let h = min + 1 + draw; + columns + .iter() + .map(|c| floor(&c.0, h, -1, 40, true)) + .collect() + } + Placement::UndergroundBuried => { + let h = min + span + 1 + draw; + let heights: Option> = columns + .iter() + .map(|(c, _, _)| { + let mut y = h; + let mut i = 0; + while i < 10 && y > min && !solid(c, y) { + y -= 1; + i += 1; + } + if !solid(c, y) { + return None; + } + y -= 2; + for _ in 0..span { + if !solid(c, y) { + return None; + } + y -= 1; + } + (solid(c, y) && solid(c, y - 1)).then_some(y) + }) + .collect(); + let heights = heights?; + let average = average(&heights); + let held = columns + .iter() + .all(|(c, _, _)| solid(c, average) && solid(c, average + span)); + return held.then_some(average); + } + _ => None, + }; + let heights = heights?; + let average = average(&heights); + let (max, mean) = spread(&heights, average); + (max <= 5 && mean <= 3.0).then_some(average) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn averages_round_as_math_round() { + assert_eq!(average(&[1, 2]), 2); + assert_eq!(average(&[-1, -2]), -1); + assert_eq!(average(&[64, 64, 65, 66, 64]), 65); + assert_eq!(spread(&[61, 64, 66], 63), (3, 2.0)); + } + + #[test] + fn corners_then_centre() { + let b = BoundingBox::new([0, 0, 10], [6, 4, 13]); + assert_eq!( + corners_and_center(b), + [[0, 10], [0, 13], [6, 13], [6, 10], [3, 12]] + ); + } + + #[test] + fn placements_by_name() { + assert_eq!( + Placement::decode("underground_on_lava").unwrap(), + Placement::UndergroundOnLava + ); + assert!(Placement::decode("floating").is_err()); + let def = Def::decode(&serde_json::json!({"template": "a:b", "placement": "surface"})); + assert_eq!(def.unwrap().placement, Placement::Surface); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs index 8e2b96e63..add246517 100644 --- a/crates/horizon-world/src/worldgen/structure/jigsaw.rs +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -45,6 +45,9 @@ pub enum PoolElement { /// The piece's own terrain kernel in a structure that has one /// (`"horizon:enhanced_terrain_adaptation"`). enhanced_terrain: Option>, + /// getGroundLevelDelta: 1, or Formations' `ground_level` + /// (`"horizon:ground_level"`). + ground_level: i32, }, Feature { feature: String, @@ -150,6 +153,13 @@ impl PoolElement { .get("horizon:enhanced_terrain_adaptation") .map(|a| super::enhanced_terrain::Adaptation::decode(a).map(Arc::new)) .transpose()?, + ground_level: match value.get("horizon:ground_level") { + None => 1, + Some(v) => v + .as_u64() + .and_then(|g| i32::try_from(g).ok()) + .ok_or(DecodeError::Field("horizon:ground_level"))?, + }, } } "minecraft:feature_pool_element" => Self::Feature { @@ -246,7 +256,10 @@ impl PoolElement { } } pub fn ground_level_delta(&self) -> i32 { - 1 + match self { + Self::Single { ground_level, .. } => *ground_level, + _ => 1, + } } /// YUNG's API's rules, on a piece of one of its structures. pub fn yung(&self) -> Option<&super::yung::Rules> { diff --git a/crates/horizon-world/src/worldgen/structure/piece_limited.rs b/crates/horizon-world/src/worldgen/structure/piece_limited.rs index 687c01cd8..12a6e3f17 100644 --- a/crates/horizon-world/src/worldgen/structure/piece_limited.rs +++ b/crates/horizon-world/src/worldgen/structure/piece_limited.rs @@ -1027,6 +1027,7 @@ mod tests { waterlogging: None, yung: None, enhanced_terrain: None, + ground_level: 1, }); let piece = || PoolPiece { bounding_box: BoundingBox::new([0; 3], [4; 3]), diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index ef360372e..b3dbe363f 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -92,6 +92,8 @@ pub enum StructureKind { Fortress, NetherFossil(HeightProvider), EndCity, + /// `horizon:formations`: Formations' SimpleStructure. + Formations(super::formations::Def), /// A structure type whose generator is not implemented yet. Unsupported(String), } @@ -367,6 +369,10 @@ impl StructureRegistry { "minecraft:nether_fossil" => StructureKind::NetherFossil( HeightProvider::from_json(&v["height"].to_string())?, ), + "horizon:formations" => match super::formations::Def::decode(&v) { + Ok(def) => StructureKind::Formations(def), + Err(_) => StructureKind::Unsupported("horizon:formations".into()), + }, other => StructureKind::Unsupported(other.to_owned()), }; defs.push(StructureDef { @@ -701,6 +707,41 @@ pub struct StructureStart { pub bounding_box: BoundingBox, } +/// A block of a noise column (ChunkGenerator.getBaseColumn), by what +/// structures ask of it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NoiseBlock { + Air, + /// The water block (`is(Blocks.WATER)`), as the aquifers and the sea + /// fill it. + Water, + Lava, + /// BlockState.isSolid: the noise's own blocks (stone, deepslate, ore + /// veins, netherrack...). + Solid, + Other, +} +impl NoiseBlock { + pub fn is_solid(self) -> bool { + self == Self::Solid + } +} +/// ChunkGenerator.getBaseColumn's blocks from `min` up; past its ends a +/// NoiseColumn reads air. +#[derive(Clone, Debug, Default)] +pub struct NoiseColumn { + pub min: i32, + pub blocks: Vec, +} +impl NoiseColumn { + pub fn get(&self, y: i32) -> NoiseBlock { + usize::try_from(y - self.min) + .ok() + .and_then(|i| self.blocks.get(i).copied()) + .unwrap_or(NoiseBlock::Air) + } +} + /// Biome and height queries for one structure generation attempt. pub trait StartContext: JigsawContext { fn seed(&self) -> i64; @@ -709,6 +750,9 @@ pub trait StartContext: JigsawContext { fn base_column(&mut self, x: i32, z: i32, kind: HeightmapType) -> Vec; /// base_column for several heightmap kinds from one noise-column pass. fn base_columns(&mut self, x: i32, z: i32, kinds: &[HeightmapType]) -> Vec>; + /// ChunkGenerator.getBaseColumn's blocks: the noise column's states, as + /// mods' placements test them (Formations'). + fn noise_column(&mut self, x: i32, z: i32) -> NoiseColumn; /// Biome.coldEnoughToSnow at a position. fn cold_enough_to_snow(&mut self, biome: BiomeId, pos: [i32; 3]) -> bool; fn generation(&self) -> WorldGenerationContext; @@ -1099,6 +1143,18 @@ fn try_generate( let piece = super::nether_fossil::piece(resources, &mut random, position)?; (position, legacy(vec![piece])) } + StructureKind::Formations(formations) => { + let (position, piece) = super::formations::generate( + formations, + context, + ®istry.pools, + resources, + bindings, + &mut random, + chunk, + )?; + (position, vec![Piece::Pool(piece)]) + } StructureKind::Unsupported(_) => return None, }; let quart = position.map(|v| v >> 2); diff --git a/crates/horizon-world/src/worldgen/structure/yung.rs b/crates/horizon-world/src/worldgen/structure/yung.rs index 861266253..efd66fdc3 100644 --- a/crates/horizon-world/src/worldgen/structure/yung.rs +++ b/crates/horizon-world/src/worldgen/structure/yung.rs @@ -916,6 +916,7 @@ mod tests { waterlogging: None, yung: rules.map(Box::new), enhanced_terrain: None, + ground_level: 1, }) }