diff --git a/crates/horizon-core/src/density/beardifier.rs b/crates/horizon-core/src/density/beardifier.rs index 73b94a066..92a20fbf5 100644 --- a/crates/horizon-core/src/density/beardifier.rs +++ b/crates/horizon-core/src/density/beardifier.rs @@ -2,7 +2,7 @@ //! Discovery/filtering of live structure starts is a separate world subsystem. use super::{DensitySampler, SampleError, SamplerContext, check_buffer}; use crate::noise::DensityVolume; -use std::sync::OnceLock; +use std::sync::{Arc, OnceLock}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct StructureBounds { @@ -52,10 +52,93 @@ pub struct JigsawJunction { pub source_z: i32, } +/// A structure library's terrain kernel: YUNG's API's and MoogsStructureLib's +/// enhanced terrain adaptation (EnhancedTerrainAdaptation.computeDensityFactor). +/// Like vanilla's beard, but with its own size and falloff, and an action +/// above the piece's floor and one below it: bury adds terrain, carve takes +/// it away. +#[derive(Debug)] +pub struct TerrainKernel { + size: i32, + /// Density sign above the floor and below it: 1 buries, -1 carves, 0 none. + top: i32, + bottom: i32, + weights: Vec, +} +impl TerrainKernel { + /// A kernel `size` blocks across whose weights fall off as + /// e^(-d²/`distance`). Size 0 is the libraries' NONE: no density. + pub fn new(size: i32, distance: i32, top: i32, bottom: i32) -> Self { + let size = size.max(0); + let radius = size / 2; + let mut weights = vec![0.; (size as usize).pow(3)]; + for x in 0..size { + for y in 0..size { + for z in 0..size { + let (kx, ky, kz) = ( + f64::from(x - radius), + f64::from(y - radius) + 0.5, + f64::from(z - radius), + ); + let squared = kx * kx + ky * ky + kz * kz; + weights[((z * size + x) * size + y) as usize] = + crate::jmath::pow(std::f64::consts::E, -squared / f64::from(distance)) + as f32; + } + } + } + Self { + size, + top, + bottom, + weights, + } + } + pub fn radius(&self) -> i32 { + self.size / 2 + } + /// The libraries' NONE: no kernel at all. + pub fn is_none(&self) -> bool { + self.size == 0 + } + /// The density at (`dx`, `dy`, `dz`) from the nearest point of a piece + /// (or a junction), `floor` blocks above the piece's floor. + fn factor(&self, dx: i32, dy: i32, dz: i32, floor: i32) -> f64 { + let radius = self.radius(); + let k = [dx, dy, dz].map(|v| v.wrapping_add(radius)); + if k.iter().any(|v| !(0..self.size).contains(v)) { + return 0.; + } + let weight = self.weights[((k[2] * self.size + k[0]) * self.size + k[1]) as usize]; + let floor = f64::from(floor) + 0.5; + let squared = f64::from(dx) * f64::from(dx) + floor * floor + f64::from(dz) * f64::from(dz); + // Mth.invSqrt(double): 1 / sqrt, not vanilla beard's fast estimate. + let multiplier = (floor * (1. / (squared / 2.).sqrt()) / 2.).abs(); + let sign = if floor > 0. { self.top } else { self.bottom }; + multiplier * f64::from(weight) * f64::from(sign) + } +} +/// A rigid piece's box under a terrain kernel (already moved, padded or cut +/// to a band as the piece's adaptation says). +#[derive(Clone, Debug)] +pub struct KernelPiece { + pub bounds: StructureBounds, + pub kernel: Arc, +} +/// A jigsaw junction under a terrain kernel; `source` holds the ground +/// height with the adaptation's offset. +#[derive(Clone, Debug)] +pub struct KernelJunction { + pub source: [i32; 3], + pub kernel: Arc, +} + #[derive(Clone, Debug, Default)] pub struct Beardifier { pieces: Vec, junctions: Vec, + kernel_pieces: Vec, + kernel_junctions: Vec, affected: Option, } impl Beardifier { @@ -70,8 +153,21 @@ impl Beardifier { pieces, junctions, affected, + ..Self::default() } } + /// Adds terrain kernels' pieces and junctions, summed after vanilla's + /// density in double precision as the libraries' Beardifier mixins do. + /// `affected` must cover them. + pub fn with_kernels( + mut self, + pieces: Vec, + junctions: Vec, + ) -> Self { + self.kernel_pieces = pieces; + self.kernel_junctions = junctions; + self + } pub fn affected_bounds(&self) -> Option { self.affected } @@ -111,7 +207,30 @@ impl Beardifier { let dz = z.wrapping_sub(junction.source_z); value += beard(dx, dy, dz, dy) * 0.4; } - value + if self.kernel_pieces.is_empty() && self.kernel_junctions.is_empty() { + return value; + } + let mut density = f64::from(value); + for piece in &self.kernel_pieces { + let (low, high) = (piece.bounds.minimum, piece.bounds.maximum); + let d: [i32; 3] = std::array::from_fn(|i| { + 0.max( + low[i] + .wrapping_sub([x, y, z][i]) + .max([x, y, z][i].wrapping_sub(high[i])), + ) + }); + density += piece + .kernel + .factor(d[0], d[1], d[2], y.wrapping_sub(low[1])) + * 0.8; + } + for junction in &self.kernel_junctions { + let d: [i32; 3] = + std::array::from_fn(|i| [x, y, z][i].wrapping_sub(junction.source[i])); + density += junction.kernel.factor(d[0], d[1], d[2], d[1]) * 0.4; + } + density as f32 } } impl DensitySampler for Beardifier { @@ -212,3 +331,54 @@ fn kernel() -> &'static [f32; 13824] { }) }) } + +#[cfg(test)] +mod tests { + use super::*; + + fn sample(beardifier: &Beardifier, position: [i32; 3]) -> f32 { + beardifier + .sample_value(&mut SamplerContext::default(), position) + .unwrap() + } + + /// YUNG's carved top (kernel 24, distance 24, carve above, nothing + /// below) around a 5-block cube, values worked out from + /// EnhancedTerrainAdaptation.computeDensityFactor. + #[test] + fn kernel_pieces_carve_above_the_floor_only() { + let kernel = Arc::new(TerrainKernel::new(24, 24, -1, 0)); + let bounds = StructureBounds::new([0; 3], [4; 3]).unwrap(); + let affected = StructureBounds::new([-20; 3], [20; 3]); + let b = Beardifier::new(Vec::new(), Vec::new(), affected) + .with_kernels(vec![KernelPiece { bounds, kernel }], Vec::new()); + // Inside, on the floor: |0.5 / sqrt(0.125) / 2| * e^(-0.25/24) * -0.8. + assert!((sample(&b, [2, 0, 2]) + 0.559_823_4).abs() < 1e-6); + // Three blocks east: |0.5 / sqrt(4.625) / 2| * e^(-9.25/24) * -0.8. + assert!((sample(&b, [7, 0, 2]) + 0.063_254_3).abs() < 1e-6); + // Below the floor the bottom action (none) applies; past the radius + // nothing does. + assert_eq!(sample(&b, [2, -3, 2]), 0.); + assert_eq!(sample(&b, [17, 2, 2]), 0.); + } + + #[test] + fn kernel_junctions_bury_at_four_tenths() { + let kernel = Arc::new(TerrainKernel::new(24, 24, 1, 1)); + let b = Beardifier::new( + Vec::new(), + Vec::new(), + StructureBounds::new([-20; 3], [80; 3]), + ) + .with_kernels( + Vec::new(), + vec![KernelJunction { + source: [0, 64, 0], + kernel, + }], + ); + assert!((sample(&b, [0, 64, 0]) - 0.279_911_7).abs() < 1e-6); + assert!(sample(&b, [0, 60, 0]) > 0.); + assert!(TerrainKernel::new(0, 0, 1, 1).is_none()); + } +} diff --git a/crates/horizon-core/src/density/mod.rs b/crates/horizon-core/src/density/mod.rs index 6bc84a8d1..01137e9a1 100644 --- a/crates/horizon-core/src/density/mod.rs +++ b/crates/horizon-core/src/density/mod.rs @@ -9,7 +9,10 @@ use crate::{ use std::sync::Arc; mod beardifier; -pub use beardifier::{Beardifier, JigsawJunction, RigidPiece, StructureBounds, TerrainAdjustment}; +pub use beardifier::{ + Beardifier, JigsawJunction, KernelJunction, KernelPiece, RigidPiece, StructureBounds, + TerrainAdjustment, TerrainKernel, +}; mod cache; mod world_fields; pub use world_fields::{ diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index 4dbbc9ade..61a48f3ea 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -1,6 +1,7 @@ //! Structure templates, processors and placement shared by template features //! and structure pieces. pub mod end_city; +pub mod enhanced_terrain; pub mod features; pub mod fortress; pub mod jigsaw; diff --git a/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs b/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs new file mode 100644 index 000000000..404b9ecca --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs @@ -0,0 +1,355 @@ +//! Structure libraries' enhanced terrain adaptation: YUNG's API's and +//! MoogsStructureLib's, which their Beardifier mixins add to vanilla's +//! density. Carried as `"horizon:enhanced_terrain_adaptation"` on a structure +//! and on its pool elements (docs/mods.md); the kernel itself is +//! [`TerrainKernel`]. +use super::{ + BoundingBox, Rotation, + jigsaw::Projection, + start::{Piece, StructureStart}, +}; +use crate::worldgen::DecodeError; +use horizon_core::{ + density::{KernelJunction, KernelPiece, StructureBounds, TerrainKernel}, + position::ChunkPos, +}; +use serde_json::Value; +use std::sync::Arc; + +/// One adaptation: the kernel, and how a piece's box is moved, padded or +/// cut to a band before the kernel measures from it. +#[derive(Debug)] +pub struct Adaptation { + kernel: Arc, + /// `bottom_offset`, cast to whole blocks as the libraries do. + offset: i32, + /// `padding`: x, top, bottom, z. + padding: [i32; 4], + band: Option, +} +/// MoogsStructureLib's band: the kernel measures from `bottom..=top` above +/// the piece's floor instead of its whole height, for pieces as tall as one +/// of `heights` (any piece without it), and junctions add nothing. +#[derive(Debug)] +struct Band { + bottom: i32, + top: i32, + heights: Option>, +} +impl Adaptation { + pub fn decode(v: &Value) -> Result { + let int = |v: &Value, key: &'static str| -> Result { + v[key] + .as_i64() + .and_then(|n| i32::try_from(n).ok()) + .ok_or(DecodeError::Field(key)) + }; + let optional = |v: &Value, key: &str| v[key].as_i64().map_or(0, |n| n as i32); + let action = |key: &'static str| match v[key].as_str() { + Some("bury") => Ok(1), + Some("carve") => Ok(-1), + Some("none") => Ok(0), + _ => Err(DecodeError::Field(key)), + }; + let size = int(v, "kernel_size")?; + let distance = int(v, "kernel_distance")?; + if size < 0 || distance < 0 { + return Err(DecodeError::Field("kernel_size")); + } + let padding = &v["padding"]; + let band = match v.get("band") { + Some(b) => Some(Band { + bottom: int(b, "bottom")?, + top: int(b, "top")?, + heights: b["piece_heights"].as_array().map(|h| { + h.iter() + .filter_map(Value::as_i64) + .map(|n| n as i32) + .collect() + }), + }), + None => None, + }; + Ok(Self { + kernel: Arc::new(TerrainKernel::new( + size, + distance, + action("top")?, + action("bottom")?, + )), + offset: v["bottom_offset"].as_f64().unwrap_or(0.) as i32, + padding: ["x", "top", "bottom", "z"].map(|k| optional(padding, k)), + band, + }) + } + fn radius(&self) -> i32 { + self.kernel.radius() + } + /// The box the kernel measures from for a piece with this box and + /// rotation; `None` for a band piece of another height. + fn piece_box(&self, original: BoundingBox, rotation: Rotation) -> Option { + let [x, top, bottom, z] = self.padding; + // The x padding runs along the axis the piece's east turned to. + let (px, pz) = match rotation { + Rotation::None | Rotation::Clockwise180 => (x, z), + Rotation::Clockwise90 | Rotation::Counterclockwise90 => (z, x), + }; + let mut b = original.moved([0, self.offset, 0]); + b.min[0] -= px; + b.max[0] += px; + b.min[2] -= pz; + b.max[2] += pz; + match &self.band { + Some(band) => { + let height = original.max[1] - original.min[1] + 1; + if band.heights.as_ref().is_some_and(|h| !h.contains(&height)) { + return None; + } + let floor = original.min[1] + self.offset; + b.min[1] = floor + band.bottom; + b.max[1] = floor + band.top; + } + None => { + b.max[1] += top; + b.min[1] -= bottom; + } + } + Some(b) + } +} + +/// A structure's adaptation and its library's rules. +#[derive(Debug)] +pub struct StructureAdaptation { + adaptation: Arc, + /// YUNG's API adds rigid pieces' junctions too; MoogsStructureLib only + /// terrain-matching pieces'. + rigid_junctions: bool, + /// YUNG's API grows the start's box by the kernel radius, so chunks that + /// far out reference the start. + pub inflate: bool, +} +impl StructureAdaptation { + pub fn decode(v: &Value) -> Result { + Ok(Self { + adaptation: Arc::new(Adaptation::decode(v)?), + rigid_junctions: v["rigid_junctions"].as_bool().unwrap_or(false), + inflate: v["inflate"].as_bool().unwrap_or(false), + }) + } + pub fn radius(&self) -> i32 { + self.adaptation.radius() + } + /// EnhancedBeardifierHelper.forStructuresInChunk for one start: its + /// kernel pieces and junctions near `chunk`, and the box they reach. + pub fn collect( + &self, + start: &StructureStart, + chunk: ChunkPos, + pieces: &mut Vec, + junctions: &mut Vec, + ) -> Option { + let reach = start + .pieces + .iter() + .filter_map(|piece| match piece { + Piece::Pool(p) => p.element.enhanced_terrain().map(Adaptation::radius), + Piece::Legacy(_) => None, + }) + .fold(self.radius(), i32::max); + if reach <= 0 { + return None; + } + let (bx, bz) = (chunk.x * 16, chunk.z * 16); + let mut affected: Option = None; + let mut include = |b: BoundingBox, radius: i32| { + let b = b.inflated(radius, radius); + match &mut affected { + Some(a) => a.encapsulate(&b), + None => affected = Some(b), + } + }; + for piece in &start.pieces { + let b = piece.bounding_box(); + // StructurePiece.isCloseToChunk. + if !(b.max[0] >= bx - reach + && b.min[0] <= bx + 15 + reach + && b.max[2] >= bz - reach + && b.min[2] <= bz + 15 + reach) + { + continue; + } + let Piece::Pool(pool) = piece else { + if let Some(b) = self + .adaptation + .piece_box(b, Rotation::None) + .filter(|_| !self.adaptation.kernel.is_none()) + { + push_piece(pieces, &self.adaptation, b, &mut include); + } + continue; + }; + let adaptation = pool.element.enhanced_terrain().unwrap_or(&self.adaptation); + if adaptation.kernel.is_none() { + continue; + } + let rigid = pool.element.projection() == Projection::Rigid; + if rigid { + if let Some(b) = adaptation.piece_box(b, pool.rotation) { + push_piece(pieces, adaptation, b, &mut include); + } + } + if (rigid && !self.rigid_junctions) || adaptation.band.is_some() { + continue; + } + let radius = adaptation.radius(); + for j in &pool.junctions { + if j.source_x > bx - radius + && j.source_z > bz - radius + && j.source_x < bx + 15 + radius + && j.source_z < bz + 15 + radius + { + let source = [ + j.source_x, + j.source_ground_y + adaptation.offset, + j.source_z, + ]; + junctions.push(KernelJunction { + source, + kernel: adaptation.kernel.clone(), + }); + include(BoundingBox::new(source, source), radius); + } + } + } + affected + } +} + +fn push_piece( + pieces: &mut Vec, + adaptation: &Adaptation, + b: BoundingBox, + include: &mut impl FnMut(BoundingBox, i32), +) { + // Java's BoundingBox puts inverted bounds (a padding below zero) in order. + let b = BoundingBox::from_corners(b.min, b.max); + let Some(bounds) = StructureBounds::new(b.min, b.max) else { + return; + }; + pieces.push(KernelPiece { + bounds, + kernel: adaptation.kernel.clone(), + }); + include(b, adaptation.radius()); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::worldgen::structure::{ + StructureTemplate, + jigsaw::{Junction, PoolElement, PoolPiece}, + }; + use serde_json::json; + + fn adaptation(v: Value) -> Adaptation { + Adaptation::decode(&v).unwrap() + } + + #[test] + fn piece_boxes_move_pad_and_cut_to_bands() { + let a = adaptation( + json!({"kernel_size": 24, "kernel_distance": 24, "top": "carve", + "bottom": "none", "bottom_offset": 2.9, + "padding": {"x": 2, "z": 5, "top": 3, "bottom": 1}}), + ); + let b = BoundingBox::new([0, 10, 0], [9, 19, 9]); + // Offset 2 (truncated), then the paddings. + let none = a.piece_box(b, Rotation::None).unwrap(); + assert_eq!((none.min, none.max), ([-2, 11, -5], [11, 24, 14])); + // A quarter turn puts the x padding along z. + let turned = a.piece_box(b, Rotation::Clockwise90).unwrap(); + assert_eq!((turned.min, turned.max), ([-5, 11, -2], [14, 24, 11])); + let band = adaptation( + json!({"kernel_size": 16, "kernel_distance": 8, "top": "carve", + "bottom": "carve", "band": {"bottom": 17, "top": 23, "piece_heights": [24, 25]}}), + ); + let tall = band + .piece_box(BoundingBox::new([0, 30, 0], [9, 53, 9]), Rotation::None) + .unwrap(); + assert_eq!((tall.min[1], tall.max[1]), (47, 53)); + assert!(band.piece_box(b, Rotation::None).is_none()); + assert!(Adaptation::decode(&json!({"kernel_size": 24})).is_err()); + } + + fn piece(element: &Arc, x: i32, junction: [i32; 3]) -> Piece { + Piece::Pool(PoolPiece { + element: element.clone(), + position: [x, 64, 0], + ground_level_delta: 1, + rotation: Rotation::None, + bounding_box: BoundingBox::new([x, 64, 0], [x + 9, 73, 9]), + junctions: vec![Junction { + source_x: junction[0], + source_ground_y: junction[1], + source_z: junction[2], + }], + waterlogging: false, + }) + } + + fn element(projection: Projection, own: Option) -> Arc { + Arc::new(PoolElement::Single { + template: Arc::new(StructureTemplate::empty()), + processors: Default::default(), + legacy: false, + projection, + waterlogging: None, + yung: None, + enhanced_terrain: own.map(Arc::new), + }) + } + + /// YUNG's API adds every piece's junctions, MoogsStructureLib only those + /// of pieces that follow the terrain; a piece's own NONE adds nothing, + /// and pieces beyond the kernel's reach of the chunk are left out. + #[test] + fn collects_pieces_and_junctions_as_each_library_does() { + let rigid = element(Projection::Rigid, None); + let matching = element(Projection::TerrainMatching, None); + let none = element( + Projection::Rigid, + Some(adaptation(json!({"kernel_size": 0, "kernel_distance": 0, + "top": "none", "bottom": "none"}))), + ); + let start = StructureStart { + structure: 0, + name: "test".into(), + chunk: ChunkPos::new(0, 0), + pieces: vec![ + piece(&rigid, 0, [5, 64, 5]), + piece(&matching, 10, [12, 65, 5]), + piece(&none, 20, [22, 64, 5]), + piece(&rigid, 60, [62, 64, 5]), + ], + bounding_box: BoundingBox::new([0, 64, 0], [69, 73, 9]), + }; + let kernel = json!({"kernel_size": 24, "kernel_distance": 24, "top": "carve", + "bottom": "none", "bottom_offset": -1}); + for (yung, junctions) in [(true, 2), (false, 1)] { + let mut v = kernel.clone(); + v["rigid_junctions"] = yung.into(); + let s = StructureAdaptation::decode(&v).unwrap(); + let (mut pieces, mut found) = (Vec::new(), Vec::new()); + let affected = s + .collect(&start, ChunkPos::new(0, 0), &mut pieces, &mut found) + .unwrap(); + assert_eq!(pieces.len(), 1, "the rigid piece near the chunk"); + assert_eq!(pieces[0].bounds.minimum(), [0, 63, 0]); + assert_eq!(found.len(), junctions); + assert_eq!(found.last().unwrap().source, [12, 64, 5]); + assert_eq!((affected.min, affected.max), ([-12, 51, -12], [24, 84, 21])); + } + } +} diff --git a/crates/horizon-world/src/worldgen/structure/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs index 34a2728f4..9c2924110 100644 --- a/crates/horizon-world/src/worldgen/structure/jigsaw.rs +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -42,6 +42,9 @@ pub enum PoolElement { /// YUNG's API's rules on the piece (`"horizon:yungsapi"`), read only /// by its assembler ([`super::yung`]). yung: Option>, + /// The piece's own terrain kernel in a structure that has one + /// (`"horizon:enhanced_terrain_adaptation"`). + enhanced_terrain: Option>, }, Feature { feature: String, @@ -143,6 +146,10 @@ impl PoolElement { .get("horizon:yungsapi") .map(|rules| super::yung::Rules::decode(rules, resources).map(Box::new)) .transpose()?, + enhanced_terrain: value + .get("horizon:enhanced_terrain_adaptation") + .map(|a| super::enhanced_terrain::Adaptation::decode(a).map(Arc::new)) + .transpose()?, } } "minecraft:feature_pool_element" => Self::Feature { @@ -248,6 +255,15 @@ impl PoolElement { _ => None, } } + /// The piece's own terrain kernel, in place of its structure's. + pub fn enhanced_terrain(&self) -> Option<&super::enhanced_terrain::Adaptation> { + match self { + Self::Single { + enhanced_terrain, .. + } => enhanced_terrain.as_deref(), + _ => None, + } + } } /// StructureTemplate.getJigsaws: palette chosen by a position-seeded random. fn template_jigsaws( diff --git a/crates/horizon-world/src/worldgen/structure/piece_limited.rs b/crates/horizon-world/src/worldgen/structure/piece_limited.rs index 753df0258..687c01cd8 100644 --- a/crates/horizon-world/src/worldgen/structure/piece_limited.rs +++ b/crates/horizon-world/src/worldgen/structure/piece_limited.rs @@ -1026,6 +1026,7 @@ mod tests { projection: Projection::Rigid, waterlogging: None, yung: None, + enhanced_terrain: None, }); 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 3d61bf168..904efb749 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -102,6 +102,9 @@ pub struct StructureDef { pub biomes: BTreeSet, pub step: usize, pub terrain: TerrainAdjustment, + /// A structure library's terrain kernel + /// (`"horizon:enhanced_terrain_adaptation"`). + pub enhanced_terrain: Option, /// Another loaded structure turns this one's type off /// (`"horizon:disables"`): it never starts. pub disabled: bool, @@ -375,6 +378,10 @@ impl StructureRegistry { .position(|s| Some(*s) == v["step"].as_str()) .unwrap_or(4), terrain: terrain(v["terrain_adaptation"].as_str()), + enhanced_terrain: v + .get("horizon:enhanced_terrain_adaptation") + .map(super::enhanced_terrain::StructureAdaptation::decode) + .transpose()?, disabled: false, }); } @@ -1101,6 +1108,10 @@ fn try_generate( if def.terrain != TerrainAdjustment::None { bounding_box = bounding_box.inflated(12, 12); } + if let Some(enhanced) = def.enhanced_terrain.as_ref().filter(|e| e.inflate) { + let r = enhanced.radius(); + bounding_box = bounding_box.inflated(r, r); + } Some(StructureStart { structure, name: def.name.clone(), @@ -1173,8 +1184,18 @@ pub fn beardifier( Some(a) => a.encapsulate(&b), None => *any = Some(b), }; + let (mut kernel_pieces, mut kernel_junctions) = (Vec::new(), Vec::new()); + let mut kernels: Option = None; for start in starts { - let adjustment = registry.structures[start.structure].terrain; + let def = ®istry.structures[start.structure]; + if let Some(enhanced) = &def.enhanced_terrain { + if let Some(b) = + enhanced.collect(start, chunk, &mut kernel_pieces, &mut kernel_junctions) + { + include(b, &mut kernels); + } + } + let adjustment = def.terrain; if adjustment == TerrainAdjustment::None { continue; } @@ -1221,13 +1242,20 @@ pub fn beardifier( } } } - let any = any?; - let affected = any.inflated(24, 24); - Some(Beardifier::new( - rigids, - junctions, - StructureBounds::new(affected.min, affected.max), - )) + // The libraries' kernels reach as far as their radius, beyond vanilla's. + let mut affected = any.map(|a| a.inflated(24, 24)); + if let Some(k) = kernels { + include(k, &mut affected); + } + let affected = affected?; + Some( + Beardifier::new( + rigids, + junctions, + StructureBounds::new(affected.min, affected.max), + ) + .with_kernels(kernel_pieces, kernel_junctions), + ) } /// StructureStart.placeInChunk for pieces intersecting the chunk's writable box. diff --git a/crates/horizon-world/src/worldgen/structure/yung.rs b/crates/horizon-world/src/worldgen/structure/yung.rs index 07b363cfb..851e5389f 100644 --- a/crates/horizon-world/src/worldgen/structure/yung.rs +++ b/crates/horizon-world/src/worldgen/structure/yung.rs @@ -615,6 +615,7 @@ mod tests { projection: Projection::Rigid, waterlogging: None, yung: rules.map(Box::new), + enhanced_terrain: None, }) } diff --git a/docs/mods.md b/docs/mods.md index bdf45f620..97abb36aa 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -303,6 +303,23 @@ A pool addition holds `"elements"` as a pool does. This is what lithostitched's `add_structure_set_entries` and `add_template_pool_elements` modifiers do on NeoForge and Fabric, and `horizon-port-pack carry` writes them from those. +A structure (and any of its pool elements, in place of the structure's) may +hold `horizon:enhanced_terrain_adaptation`: YUNG's API's and +MoogsStructureLib's terrain kernel, which carves or buries terrain around the +pieces on top of vanilla's `terrain_adaptation`. `kernel_size` and +`kernel_distance` shape the kernel; `top` and `bottom` (`carve`, `bury` or +`none`) act above and below a piece's floor; `bottom_offset`, `padding` +(`x`, `top`, `bottom`, `z`) and MoogsStructureLib's `band` (`bottom`, `top`, +`piece_heights`) move the box it measures from. On a structure, +`rigid_junctions` (YUNG's API) adds rigid pieces' junctions as well and +`inflate` grows the start's box by the kernel radius. `kernel_size` 0 is +none. + +```json +{ "horizon:enhanced_terrain_adaptation": { "kernel_size": 24, "kernel_distance": 24, + "top": "carve", "bottom": "none", "rigid_junctions": true, "inflate": true } } +``` + ## Versions and compatibility - The API is the WIT package `horizon:mods@0.1.0`. New functions and