diff --git a/crates/horizon-world/examples/chunkgen_bench.rs b/crates/horizon-world/examples/chunkgen_bench.rs index 7fb326643..e38b01392 100644 --- a/crates/horizon-world/examples/chunkgen_bench.rs +++ b/crates/horizon-world/examples/chunkgen_bench.rs @@ -96,7 +96,7 @@ fn verify(data: &std::sync::Arc, parity: &Path) -> Result<(), Err ]; let mut expected = Vec::new(); for (seed, x, z) in cases { - let generator = OverworldGenerator::new(data.clone(), seed)?; + let generator = OverworldGenerator::without_structures(data.clone(), seed)?; let lines = dump(&generator.worker().generate_proto(ChunkPos::new(x, z))?); if let Ok(path) = std::env::var("HORIZON_VERIFY_DUMP") { fs::write(format!("{path}{seed}.txt"), lines.join("\n") + "\n")?; @@ -165,6 +165,11 @@ fn glyph(name: &str) -> char { match name { "water" => '~', "lava" => '!', + "dirt_path" => '_', + "cobblestone" | "mossy_cobblestone" => 'o', + "hay_block" => 'h', + _ if name.ends_with("planks") || name.ends_with("stairs") || name.ends_with("slab") => 'P', + _ if name.contains("glass") => 'g', "grass_block" => '"', "sand" | "suspicious_sand" => '.', "red_sand" => ',', @@ -350,6 +355,21 @@ fn main() -> Result<(), Error> { ); } } + let mut structures = BTreeMap::<(String, i32, i32), [[i32; 3]; 2]>::new(); + for chunk in chunks.iter().flatten() { + for (name, start, min, max) in chunk.structures() { + structures.insert((name.to_owned(), start.x, start.z), [min, max]); + } + } + for ((name, x, z), [min, max]) in &structures { + println!("structure {name} start chunk ({x}, {z}) box {min:?}..{max:?}"); + } + let block_entities: usize = chunks + .iter() + .flatten() + .map(|c| c.block_entities.len()) + .sum(); + println!("block entities: {block_entities}"); let mut legend = BTreeMap::>::new(); let step = (size * 16 / 96).max(1); for bz in (0..size * 16).step_by(step as usize) { diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index a58b25457..ec7eeda6f 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -40,6 +40,7 @@ pub mod fungus; pub mod generator; mod generator_blocks; mod generator_decoration; +mod generator_structures; pub mod height_provider; pub mod iceberg; pub mod material_condition; diff --git a/crates/horizon-world/src/worldgen/decoration.rs b/crates/horizon-world/src/worldgen/decoration.rs index 0963e3f8b..901a19f53 100644 --- a/crates/horizon-world/src/worldgen/decoration.rs +++ b/crates/horizon-world/src/worldgen/decoration.rs @@ -75,6 +75,33 @@ impl FeatureDecorationPlan { world: &mut W, chunk: ChunkPos, world_seed: i64, + place: impl FnMut( + &mut W, + &mut FeaturePlacer, + &mut WorldgenRandom, + FeatureIdentity, + [i32; 3], + ) -> Result, + ) -> Result<(), DecorationError> { + self.decorate(world, chunk, world_seed, 0, |_, _, _, _| Ok(()), place) + } + + /// Like `decorate_features`, running `structures` at the start of each of + /// `max(structure_steps, feature steps)` steps, before that step's + /// features (vanilla applyBiomeDecoration). It receives the shared random + /// and decoration seed; it seeds per structure itself. + pub fn decorate( + &self, + world: &mut W, + chunk: ChunkPos, + world_seed: i64, + structure_steps: usize, + mut structures: impl FnMut( + &mut W, + &mut WorldgenRandom, + i64, + usize, + ) -> Result<(), W::Error>, mut place: impl FnMut( &mut W, &mut FeaturePlacer, @@ -114,7 +141,11 @@ impl FeatureDecorationPlan { } } let mut placer = FeaturePlacer::new(); - for (step, data) in self.steps.iter().enumerate() { + for step in 0..structure_steps.max(self.steps.len()) { + structures(world, &mut random, seed, step).map_err(DecorationError::World)?; + let Some(data) = self.steps.get(step) else { + continue; + }; let mut selected = BTreeSet::new(); for biome in &present { if let Some(features) = self.biomes[biome].get(step) { diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 2458cb705..7a1708599 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -147,6 +147,13 @@ pub(super) struct FeatureResources { pub(super) blocks: Option, } +/// Raw structure, structure-set and template-pool resources. +pub(super) struct StructureBundles { + pub(super) structures: BTreeMap, + pub(super) sets: BTreeMap, + pub(super) pools: BTreeMap, +} + /// Seed-independent generation resources, loaded once and shared by every /// generator. Biome identities are indices into the sorted biome registry. pub struct GeneratorData { @@ -172,6 +179,7 @@ pub struct GeneratorData { pub(super) feature_resources: Option, /// Templates, processor lists and per-state template transforms. pub(super) structures: Option>, + pub(super) structure_resources: Option, } type Bundle = BTreeMap; fn read_bundle(dir: &Path, name: &str) -> Result { @@ -405,7 +413,20 @@ impl GeneratorData { ))), Err(_) => None, }; + let structure_resources = match ( + read_optional_bundle(dir, "structures")?, + read_optional_bundle(dir, "structure_sets")?, + read_optional_bundle(dir, "template_pools")?, + ) { + (Some(structures), Some(sets), Some(pools)) => Some(StructureBundles { + structures, + sets, + pools, + }), + _ => None, + }; Ok(Arc::new(Self { + structure_resources, structures, registry, states: GenBlockStates(states.into()), @@ -468,6 +489,8 @@ pub struct ProtoChunk { /// Block-entity data placed by structures and template features, in /// placement order (positions are absolute block coordinates). pub block_entities: Vec<([i32; 3], crate::nbt::Compound)>, + /// Structure starts referencing this chunk (STRUCTURE_REFERENCES). + pub(super) structure_starts: Vec>, } impl ProtoChunk { pub fn position(&self) -> ChunkPos { @@ -498,6 +521,21 @@ impl ProtoChunk { pub fn data(&self) -> &Arc { &self.data } + /// Structure starts referencing this chunk: (structure id, start chunk, + /// inclusive bounding box min/max). + pub fn structures(&self) -> Vec<(&str, ChunkPos, [i32; 3], [i32; 3])> { + self.structure_starts + .iter() + .map(|s| { + ( + s.name.as_str(), + s.chunk, + s.bounding_box.min, + s.bounding_box.max, + ) + }) + .collect() + } pub fn is_decorated(&self) -> bool { self.decorated } @@ -543,6 +581,7 @@ struct Pipeline { biome_cache: BiomeCache, carver_cache: Mutex>, pub(super) decoration: Option, + pub(super) structures: Option, } const CACHE_LIMIT: usize = 16384; type BiomeCache = Mutex>>>; @@ -583,6 +622,7 @@ where mut random: R, generator: &Value, settings_json: &Value, + with_structures: bool, ) -> Result { let registry = data.registry; let noise = &settings_json["noise"]; @@ -707,9 +747,20 @@ where biome_cache: Mutex::new(HashMap::new()), carver_cache: Mutex::new(HashMap::new()), decoration: None, + structures: None, }; pipeline.decoration = super::generator_decoration::Decoration::new(&pipeline.data, &pipeline.source)?; + if with_structures { + let possible = pipeline + .source + .possible_biomes() + .into_iter() + .filter_map(|name| pipeline.data.biome_id(name)) + .collect(); + pipeline.structures = + super::generator_structures::StructureState::new(&pipeline.data, &possible)?; + } Ok(pipeline) } fn generation(&self) -> WorldGenerationContext { @@ -823,7 +874,31 @@ where let mut chunk = TerrainChunk::new(pos, min, height, data.registry, data.states.clone()) .map_err(stage("noise"))?; chunk.set_generation_stage(PreLightChunkStage::Biomes); + let references = match &self.structures { + Some(structures) => structures.references( + &mut StructureQueries { + pipeline: self, + worker, + valid: BTreeSet::new(), + }, + pos, + ), + None => Vec::new(), + }; let mut context = SamplerContext::cached(); + if let Some(beard) = self + .structures + .as_ref() + .and_then(|s| s.beardifier(&references, pos)) + { + context = context.with_world_fields( + horizon_core::density::WorldFields::default().with_field( + horizon_core::density::WorldField::Beardifier, + Arc::new(beard), + ), + ); + } + worker.timings.structures += lap(&mut clock); let volume = DensityVolume::new( [16, height, 16], [pos.x.wrapping_shl(4), min, pos.z.wrapping_shl(4)], @@ -936,10 +1011,134 @@ where data: data.clone(), decorated: false, block_entities: Vec::new(), + structure_starts: references, }) } } +impl Pipeline +where + R::Positional: Clone + Send + Sync, +{ + /// ChunkGenerator.getBaseHeight: the first free Y above the noise column + /// (with aquifers, without terrain adaptation) for a heightmap type. + fn base_height(&self, x: i32, z: i32, kind: HeightmapType) -> i32 { + let (min, height) = (self.settings.min_y, self.settings.height); + let Ok(volume) = DensityVolume::new([1, height, 1], [x, min, z], [1; 3]) else { + return min; + }; + let mut context = SamplerContext::cached(); + let mut aquifer: Box = match &self.aquifer { + Some(samplers) => match RegistryAquiferBlockStates::new(self.data.registry) + .ok() + .and_then(|blocks| { + NoiseBasedAquifer::new( + AquiferSamplers::new(samplers.clone()), + self.picker, + self.root + .from_hash_of("minecraft:aquifer") + .fork_positional(), + blocks, + volume, + &mut context, + ) + .ok() + }) { + Some(aquifer) => Box::new(aquifer), + None => return min, + }, + None => Box::new(DisabledAquifer::new( + self.picker, + self.data.registry.default_state("minecraft:air").unwrap(), + )), + }; + let mut density = vec![0.; height as usize]; + if self + .router + .get(RouterField::FinalDensity) + .sample_volume(&mut context, &mut density, volume) + .is_err() + { + return min; + } + for y in (0..height).rev() { + let state = aquifer + .compute_substance( + &mut context, + [x, min + y, z], + f64::from(density[y as usize]), + ) + .ok() + .flatten() + .unwrap_or(self.settings.default_block); + if kind.is_opaque(self.data.states.get(state)) { + return min + y + 1; + } + } + min + } +} +/// Biome and height queries for structure generation on one worker. +pub(super) struct StructureQueries<'a, R: RandomSource> { + pipeline: &'a Pipeline, + worker: &'a mut WorkerState, + valid: BTreeSet, +} +impl super::structure::jigsaw::JigsawContext for StructureQueries<'_, R> +where + R::Positional: Clone + Send + Sync, +{ + fn min_y(&self) -> i32 { + self.pipeline.settings.min_y + } + fn max_y(&self) -> i32 { + self.pipeline.settings.min_y + self.pipeline.settings.height - 1 + } + fn base_height(&mut self, x: i32, z: i32, kind: HeightmapType) -> i32 { + if let Some(h) = self.worker.heights.get(&(x, z, kind as u8)) { + return *h; + } + let h = self.pipeline.base_height(x, z, kind); + if self.worker.heights.len() > 65536 { + self.worker.heights.clear(); + } + self.worker.heights.insert((x, z, kind as u8), h); + h + } + fn column_has_valid_biome(&mut self, x: i32, z: i32, min_y: i32, max_y: i32) -> bool { + use super::structure::start::StartContext; + ((min_y >> 2)..=(max_y >> 2)).any(|qy| { + let id = self.noise_biome([x >> 2, qy, z >> 2]); + self.valid.contains(&id) + }) + } +} +impl super::structure::start::StartContext for StructureQueries<'_, R> +where + R::Positional: Clone + Send + Sync, +{ + fn seed(&self) -> i64 { + self.pipeline.seed + } + fn generation(&self) -> WorldGenerationContext { + self.pipeline.generation() + } + fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId { + let mut resolver = self.pipeline.source.resolver( + &self.pipeline.climate, + self.pipeline.router.get(RouterField::Erosion).as_ref(), + ); + resolver + .sample(&mut self.worker.carver_context, quart) + .ok() + .and_then(|name| self.pipeline.data.biome_id(name)) + .unwrap_or(BiomeId(0)) + } + fn set_valid_biomes(&mut self, biomes: &BTreeSet) { + self.valid = biomes.clone(); + } +} + enum Biomes<'a, 'b> { Region(&'a BiomeRegion), Resolver( @@ -1037,6 +1236,8 @@ pub struct StageTimings { /// Noise fill including aquifer setup. pub noise: std::time::Duration, pub surface: std::time::Duration, + /// Structure starts/references and terrain adaptation. + pub structures: std::time::Duration, /// Carving mask generation/application and final heightmap priming. pub carvers: std::time::Duration, } @@ -1047,6 +1248,7 @@ pub(super) struct WorkerState { biome_context: SamplerContext, carver_context: SamplerContext, timings: StageTimings, + heights: HashMap<(i32, i32, u8), i32>, } trait SeededPipeline: Send + Sync { @@ -1100,6 +1302,7 @@ where worker, region, || random.next_boolean(), + self.structures.as_ref(), ) } None => Err(resource("decoration resources were not loaded")), @@ -1143,12 +1346,26 @@ impl OverworldGenerator { pub fn new(data: Arc, seed: i64) -> Result { Self::for_dimension(data, seed, "minecraft:normal", "minecraft:overworld") } + /// The overworld without structures (no starts, terrain adaptation or + /// structure pieces), as in a world with structure generation disabled. + pub fn without_structures(data: Arc, seed: i64) -> Result { + Self::build(data, seed, "minecraft:normal", "minecraft:overworld", false) + } /// Any noise-generator dimension of a bundled world preset. pub fn for_dimension( data: Arc, seed: i64, preset: &str, dimension: &str, + ) -> Result { + Self::build(data, seed, preset, dimension, true) + } + fn build( + data: Arc, + seed: i64, + preset: &str, + dimension: &str, + with_structures: bool, ) -> Result { let preset_json: Value = serde_json::from_str( data.world_presets @@ -1177,6 +1394,7 @@ impl OverworldGenerator { LegacyRandom::new(seed), &generator, &settings_json, + with_structures, )?) } else { Arc::new(Pipeline::new( @@ -1185,6 +1403,7 @@ impl OverworldGenerator { XoroshiroRandom::new(seed), &generator, &settings_json, + with_structures, )?) }; Ok(Self { pipeline }) @@ -1214,6 +1433,7 @@ impl OverworldGenerator { biome_context: SamplerContext::cached(), carver_context: SamplerContext::default(), timings: StageTimings::default(), + heights: HashMap::new(), }, } } diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index 047bd7053..b2da351c2 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -4,6 +4,10 @@ //! Roots whose algorithm or bindings are not implemented are left out of //! execution (but keep their place in vanilla's per-step feature ordering, so //! decoration seeds of the remaining features are unchanged). +use super::structure::{ + BoundingBox, + start::{STEPS, place_in_chunk}, +}; use super::{ anchor::WorldGenerationContext, biome::BiomeId, @@ -41,12 +45,14 @@ use crate::{ heightmap::{HeightmapState, HeightmapType}, registry::BlockStateId, }; +use horizon_core::random::{WorldgenRandom, XoroshiroRandom}; use horizon_core::{ biome::obfuscate_seed, geometry::{Axis, Direction, VoxelShape}, position::{BlockPos, ChunkPos}, }; use serde_json::Value; +use std::collections::HashMap; use std::{ collections::{BTreeMap, BTreeSet}, sync::Arc, @@ -62,6 +68,9 @@ pub(super) struct Decoration { bindings: FeatureBlockBindings<'static>, weather: Option, blocks: FeatureBlocks, + catalog: FeatureCatalog, + /// Placed features referenced by name (feature pool elements), decoded lazily. + named: std::sync::Mutex>>>, } fn resource(message: impl Into) -> GeneratorError { GeneratorError::Resource(message.into()) @@ -213,8 +222,22 @@ impl Decoration { weather, blocks: FeatureBlocks::from_registry(registry)?, bindings, + catalog, + named: std::sync::Mutex::new(HashMap::new()), })) } + fn named_feature(&self, name: &str) -> Option> { + let mut named = self.named.lock().unwrap(); + named + .entry(name.to_owned()) + .or_insert_with(|| { + self.catalog + .placed_feature_with_blocks(&Value::from(name).to_string(), &self.bindings) + .ok() + .map(Arc::new) + }) + .clone() + } /// Placed-feature roots that cannot run, with their decode errors. pub(super) fn unsupported(&self) -> Vec<(String, String)> { self.names @@ -231,6 +254,7 @@ impl Decoration { worker: &mut WorkerState, region: &mut [ProtoChunk; 9], next_boolean: impl FnMut() -> bool, + structures: Option<&super::generator_structures::StructureState>, ) -> Result { let center = region[4].position(); for (i, chunk) in region.iter().enumerate() { @@ -291,10 +315,59 @@ impl Decoration { }; let mut stats = DecorateStats::default(); let blocks = self.blocks; - let result = self.plan.decorate_features( + let references = region[4].structure_starts.clone(); + let chunk_box = BoundingBox::new( + [center.x * 16, generation.min_y + 1, center.z * 16], + [ + center.x * 16 + 15, + generation.min_y + generation.height - 1, + center.z * 16 + 15, + ], + ); + let mut structure_errors = 0; + let result = self.plan.decorate( &mut world, center, seed, + STEPS.len(), + |world, random, decoration_seed, step| { + let Some(structures) = structures else { + return Ok(()); + }; + let Some(in_step) = structures.by_step.get(step) else { + return Ok(()); + }; + for (index, &structure) in in_step.iter().enumerate() { + random.set_feature_seed(decoration_seed, index as i32, step as i32); + for start in references.iter().filter(|s| s.structure == structure) { + let mut place_feature = + |world: &mut World<'_>, + random: &mut WorldgenRandom, + name: &str, + pos: [i32; 3]| { + match self.named_feature(name) { + Some(feature) => feature + .place(world, random, pos, blocks) + .map_err(|e| PlacementQueryError::Failed(e.to_string())), + None => Ok(false), + } + }; + if place_in_chunk( + start, + world, + &structures.resources, + random, + chunk_box, + &mut place_feature, + ) + .is_err() + { + structure_errors += 1; + } + } + } + Ok(()) + }, |world, placer, random, id, origin| { let Ok(feature) = &self.features[id.0 as usize] else { stats.unsupported += 1; @@ -331,6 +404,7 @@ impl Decoration { region[index as usize].terrain = terrain; } result.map_err(|e| GeneratorError::Stage("features", e.to_string()))?; + stats.failed += structure_errors; region[4] .terrain .set_generation_stage(PreLightChunkStage::Features); diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs new file mode 100644 index 000000000..d772d7859 --- /dev/null +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -0,0 +1,152 @@ +//! STRUCTURE_STARTS / STRUCTURE_REFERENCES for the chunk generator. +use super::{ + biome::BiomeId, + block_feature::FeatureBlockBindings, + generator::{GeneratorData, GeneratorError}, + structure::{ + StructureResources, + start::{StructureRegistry, StructureStart, beardifier, create_starts}, + }, +}; +use horizon_core::{density::Beardifier, position::ChunkPos}; +use serde_json::Value; +use std::{ + collections::{BTreeSet, HashMap}, + sync::{Arc, Mutex}, +}; + +pub(super) type Starts = Arc>>; +pub(super) struct StructureState { + pub(super) registry: StructureRegistry, + pub(super) resources: Arc, + pub(super) bindings: FeatureBlockBindings<'static>, + possible_sets: Vec, + /// Structure indices of each decoration step, in registry order. + pub(super) by_step: Vec>, + starts: Mutex>, +} +const START_CACHE_LIMIT: usize = 65536; + +fn biome_set(data: &GeneratorData, value: &Value) -> Result, super::DecodeError> { + let names: Vec<&str> = match value { + Value::String(s) => vec![s.as_str()], + Value::Array(a) => a.iter().filter_map(Value::as_str).collect(), + _ => Vec::new(), + }; + let mut out = BTreeSet::new(); + for name in names { + match name.strip_prefix('#') { + Some(tag) => { + for biome in data.biome_tags.get(tag).into_iter().flatten() { + out.extend(data.biome_id(biome)); + } + } + None => out.extend(data.biome_id(name)), + } + } + Ok(out) +} +impl StructureState { + pub(super) fn new( + data: &Arc, + possible_biomes: &BTreeSet, + ) -> Result, GeneratorError> { + let (Some(resources), Some(raw)) = (&data.structures, &data.structure_resources) else { + return Ok(None); + }; + let registry = + StructureRegistry::new(&raw.structures, &raw.sets, raw.pools.clone(), &|value| { + biome_set(data, value) + })?; + let possible_sets = registry + .sets + .iter() + .enumerate() + .filter(|(_, set)| { + set.structures + .iter() + .any(|(s, _)| !registry.structures[*s].biomes.is_disjoint(possible_biomes)) + }) + .map(|(i, _)| i) + .collect(); + let mut by_step = vec![Vec::new(); super::structure::start::STEPS.len()]; + for (i, def) in registry.structures.iter().enumerate() { + by_step[def.step].push(i); + } + let bindings = FeatureBlockBindings::with_tags( + data.registry(), + data.integers().clone(), + &data.block_tags, + )?; + Ok(Some(Self { + registry, + resources: resources.clone(), + bindings, + possible_sets, + by_step, + starts: Mutex::new(HashMap::new()), + })) + } + /// The (cached) structure starts owned by a chunk. + pub(super) fn starts_at( + &self, + 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(); + } + let starts: Starts = Arc::new( + create_starts( + &self.registry, + &self.resources, + &self.bindings, + context, + &self.possible_sets, + &[], + chunk, + ) + .into_iter() + .map(Arc::new) + .collect(), + ); + let mut cache = self.starts.lock().unwrap(); + if cache.len() >= START_CACHE_LIMIT { + cache.clear(); + } + cache.insert((chunk.x, chunk.z), starts.clone()); + starts + } + /// ChunkGenerator.createReferences: starts within 8 chunks whose box + /// intersects this chunk's column. + pub(super) fn references( + &self, + context: &mut impl super::structure::start::StartContext, + chunk: ChunkPos, + ) -> Vec> { + let (bx, bz) = (chunk.x * 16, chunk.z * 16); + let mut out = Vec::new(); + for sx in chunk.x - 8..=chunk.x + 8 { + for sz in chunk.z - 8..=chunk.z + 8 { + for start in self.starts_at(context, ChunkPos::new(sx, sz)).iter() { + let b = start.bounding_box; + if b.max[0] >= bx + && b.min[0] <= bx + 15 + && b.max[2] >= bz + && b.min[2] <= bz + 15 + { + out.push(start.clone()); + } + } + } + } + out + } + pub(super) fn beardifier( + &self, + references: &[Arc], + chunk: ChunkPos, + ) -> Option { + beardifier(&self.registry, references, chunk) + } +} diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index ee12ef5ff..5e10c7ec3 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -1,7 +1,9 @@ //! Structure templates, processors and placement shared by template features //! and structure pieces. pub mod features; +pub mod jigsaw; pub mod processor; +pub mod start; pub mod template; use crate::{ diff --git a/crates/horizon-world/src/worldgen/structure/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs new file mode 100644 index 000000000..76035582e --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -0,0 +1,849 @@ +//! Template pools, pool elements and JigsawPlacement. +use super::{ + BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate, + processor::{PlaceSettings, Processor, ProcessorList, place_in_world}, +}; +use crate::{ + heightmap::HeightmapType, + worldgen::{ + DecodeError, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + placement::{PlacementContext, PlacementQueryError}, + }, +}; +use horizon_core::{ + geometry::Direction, + position::BlockPos, + random::{LegacyRandom, RandomSource, position_seed}, +}; +use serde_json::Value; +use std::{ + cell::RefCell, + collections::{BTreeMap, HashMap, VecDeque}, + rc::Rc, + sync::{Arc, OnceLock, RwLock}, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Projection { + Rigid, + TerrainMatching, +} +#[derive(Debug)] +pub enum PoolElement { + Empty, + Single { + template: Arc, + processors: ProcessorList, + legacy: bool, + projection: Projection, + waterlogging: Option, + }, + Feature { + feature: String, + projection: Projection, + }, + List { + elements: Vec, + projection: Projection, + }, +} +#[derive(Clone, Debug)] +pub struct Jigsaw { + pub pos: [i32; 3], + pub front: Direction, + pub top: Direction, + pub rollable: bool, + pub name: Option, + pub pool: String, + pub target: String, + pub placement_priority: i32, + pub selection_priority: i32, +} +fn direction(name: &str) -> Direction { + match name { + "down" => Direction::Down, + "up" => Direction::Up, + "north" => Direction::North, + "south" => Direction::South, + "west" => Direction::West, + _ => Direction::East, + } +} +fn opposite(d: Direction) -> Direction { + match d { + Direction::Down => Direction::Up, + Direction::Up => Direction::Down, + Direction::North => Direction::South, + Direction::South => Direction::North, + Direction::West => Direction::East, + Direction::East => Direction::West, + } +} +fn step(d: Direction) -> [i32; 3] { + let n = d.normal(); + [n[0], n[1], n[2]] +} +fn shuffle(list: &mut [T], random: &mut impl RandomSource) { + for i in (2..=list.len()).rev() { + let swap = random.next_int_bound(i as i32).unwrap_or(0) as usize; + list.swap(i - 1, swap); + } +} +fn projection(value: &Value) -> Result { + match value["projection"].as_str() { + Some("rigid") => Ok(Projection::Rigid), + Some("terrain_matching") => Ok(Projection::TerrainMatching), + _ => Err(DecodeError::Field("pool element projection")), + } +} +impl PoolElement { + fn decode( + value: &Value, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + inherited: Option, + ) -> Result { + let kind = value["element_type"].as_str().unwrap_or_default(); + let projection = || match inherited { + Some(p) => Ok(p), + None => projection(value), + }; + Ok(match kind { + "minecraft:empty_pool_element" => Self::Empty, + "minecraft:single_pool_element" | "minecraft:legacy_single_pool_element" => { + let location = value["location"] + .as_str() + .ok_or(DecodeError::Field("location"))?; + Self::Single { + template: resources.template(location).ok_or_else(|| { + DecodeError::Registry(format!("missing template {location}")) + })?, + processors: ProcessorList::decode( + &value["processors"].to_string(), + resources, + bindings, + )?, + legacy: kind == "minecraft:legacy_single_pool_element", + projection: projection()?, + waterlogging: match value + .get("override_liquid_settings") + .and_then(Value::as_str) + { + Some("apply_waterlogging") => Some(true), + Some("ignore_waterlogging") => Some(false), + _ => None, + }, + } + } + "minecraft:feature_pool_element" => Self::Feature { + feature: value["feature"].as_str().unwrap_or_default().to_owned(), + projection: projection()?, + }, + "minecraft:list_pool_element" => { + let p = projection()?; + Self::List { + elements: value["elements"] + .as_array() + .ok_or(DecodeError::Field("list elements"))? + .iter() + .map(|e| Self::decode(e, resources, bindings, Some(p))) + .collect::>()?, + projection: p, + } + } + _ => return Err(DecodeError::Field("pool element type")), + }) + } + pub fn projection(&self) -> Projection { + match self { + Self::Empty => Projection::TerrainMatching, + Self::Single { projection, .. } + | Self::Feature { projection, .. } + | Self::List { projection, .. } => *projection, + } + } + pub fn size(&self, rotation: Rotation) -> [i32; 3] { + match self { + Self::Empty | Self::Feature { .. } => [0; 3], + Self::Single { template, .. } => template.size(rotation), + Self::List { elements, .. } => elements.iter().fold([0; 3], |acc, e| { + let s = e.size(rotation); + std::array::from_fn(|i| acc[i].max(s[i])) + }), + } + } + pub fn bounding_box(&self, position: [i32; 3], rotation: Rotation) -> BoundingBox { + match self { + Self::Empty => BoundingBox::new(position, position), + Self::Feature { .. } => BoundingBox::new(position, position), + Self::Single { template, .. } => { + template.bounding_box(position, rotation, [0; 3], Mirror::None) + } + Self::List { elements, .. } => { + let mut boxes = elements + .iter() + .filter(|e| !matches!(e, Self::Empty)) + .map(|e| e.bounding_box(position, rotation)); + let mut first = boxes.next().unwrap_or(BoundingBox::new(position, position)); + for b in boxes { + first.encapsulate(&b); + } + first + } + } + } + /// getShuffledJigsawBlocks. + pub fn shuffled_jigsaws( + &self, + resources: &StructureResources, + position: [i32; 3], + rotation: Rotation, + random: &mut impl RandomSource, + ) -> Vec { + match self { + Self::Empty => Vec::new(), + Self::Feature { .. } => vec![Jigsaw { + pos: position, + front: Direction::Down, + top: Direction::South, + rollable: true, + name: None, + pool: "minecraft:empty".into(), + target: "minecraft:empty".into(), + placement_priority: 0, + selection_priority: 0, + }], + Self::List { elements, .. } => elements + .first() + .map(|e| e.shuffled_jigsaws(resources, position, rotation, random)) + .unwrap_or_default(), + Self::Single { template, .. } => { + let mut jigsaws = template_jigsaws(resources, template, position, rotation); + shuffle(&mut jigsaws, random); + jigsaws.sort_by_key(|j| std::cmp::Reverse(j.selection_priority)); + jigsaws + } + } + } + pub fn ground_level_delta(&self) -> i32 { + 1 + } +} +/// StructureTemplate.getJigsaws: palette chosen by a position-seeded random. +fn template_jigsaws( + resources: &StructureResources, + template: &StructureTemplate, + position: [i32; 3], + rotation: Rotation, +) -> Vec { + if template.palettes().is_empty() { + return Vec::new(); + } + let palette = LegacyRandom::new(position_seed(BlockPos::new( + position[0], + position[1], + position[2], + ))) + .next_int_bound(template.palettes().len() as i32) + .unwrap_or(0) as usize; + template + .jigsaws(palette, &|state| resources.jigsaw_horizontal(state)) + .iter() + .map(|j| { + let relative = StructureTemplate::transform(j.info.pos, Mirror::None, rotation, [0; 3]); + let state = resources.transforms.rotate(j.info.state, rotation); + let orientation = resources + .registry + .state(state) + .and_then(|s| s.properties.get("orientation").cloned()) + .unwrap_or_default(); + let (front, top) = orientation.split_once('_').unwrap_or(("north", "up")); + Jigsaw { + pos: std::array::from_fn(|i| relative[i] + position[i]), + front: direction(front), + top: direction(top), + rollable: j.rollable, + name: Some(j.name.clone()), + pool: j.pool.clone(), + target: j.target.clone(), + placement_priority: j.placement_priority, + selection_priority: j.selection_priority, + } + }) + .collect() +} +fn can_attach(source: &Jigsaw, target: &Jigsaw) -> bool { + source.front == opposite(target.front) + && (source.rollable || source.top == target.top) + && target + .name + .as_ref() + .is_none_or(|name| *name == source.target) +} + +#[derive(Debug)] +pub struct Pool { + templates: Vec>, + fallback: String, + max_size: OnceLock, +} +impl Pool { + fn random_template(&self, random: &mut impl RandomSource) -> Arc { + if self.templates.is_empty() { + return Arc::new(PoolElement::Empty); + } + self.templates[random + .next_int_bound(self.templates.len() as i32) + .unwrap_or(0) as usize] + .clone() + } + fn shuffled(&self, random: &mut impl RandomSource) -> Vec> { + let mut copy = self.templates.clone(); + shuffle(&mut copy, random); + copy + } + fn max_size(&self) -> i32 { + *self.max_size.get_or_init(|| { + self.templates + .iter() + .filter(|t| !matches!(t.as_ref(), PoolElement::Empty)) + .map(|t| t.bounding_box([0; 3], Rotation::None).span()[1]) + .max() + .unwrap_or(0) + }) + } +} +/// Lazily decoded template pools. +pub struct Pools { + raw: BTreeMap, + decoded: RwLock>>>, +} +impl std::fmt::Debug for Pools { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Pools") + } +} +impl Pools { + pub fn new(raw: BTreeMap) -> Self { + Self { + raw, + decoded: RwLock::new(HashMap::new()), + } + } + pub fn get( + &self, + name: &str, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + ) -> Option> { + if let Some(found) = self.decoded.read().unwrap().get(name) { + return found.clone(); + } + let pool = self.raw.get(name).and_then(|json| { + let value: Value = serde_json::from_str(json).ok()?; + let mut templates = Vec::new(); + for entry in value["elements"].as_array()? { + let element = Arc::new( + PoolElement::decode(&entry["element"], resources, bindings, None).ok()?, + ); + for _ in 0..entry["weight"].as_i64().unwrap_or(1) { + templates.push(element.clone()); + } + } + Some(Arc::new(Pool { + templates, + fallback: value["fallback"] + .as_str() + .unwrap_or("minecraft:empty") + .to_owned(), + max_size: OnceLock::new(), + })) + }); + self.decoded + .write() + .unwrap() + .insert(name.to_owned(), pool.clone()); + pool + } +} + +#[derive(Clone, Copy, Debug)] +pub struct Junction { + pub source_x: i32, + pub source_ground_y: i32, + pub source_z: i32, +} +#[derive(Debug)] +pub struct PoolPiece { + pub element: Arc, + pub position: [i32; 3], + pub ground_level_delta: i32, + pub rotation: Rotation, + pub bounding_box: BoundingBox, + pub junctions: Vec, + pub waterlogging: bool, +} +impl PoolPiece { + fn moved(&mut self, dy: i32) { + self.position[1] += dy; + self.bounding_box = self.bounding_box.moved([0, dy, 0]); + } + /// PoolElementStructurePiece.postProcess. + #[allow(clippy::too_many_arguments)] + pub fn place( + &self, + world: &mut W, + resources: &StructureResources, + random: &mut R, + chunk_box: BoundingBox, + reference: [i32; 3], + place_feature: &mut dyn FnMut( + &mut W, + &mut R, + &str, + [i32; 3], + ) -> Result, + ) -> Result { + place_element( + &self.element, + world, + resources, + random, + chunk_box, + self.position, + reference, + self.rotation, + self.waterlogging, + place_feature, + ) + } +} +static GRAVITY: OnceLock = OnceLock::new(); +static IGNORE_STRUCTURE_BLOCK: OnceLock = OnceLock::new(); +static IGNORE_STRUCTURE_AND_AIR: OnceLock = OnceLock::new(); +#[allow(clippy::too_many_arguments)] +fn place_element( + element: &PoolElement, + world: &mut W, + resources: &StructureResources, + random: &mut R, + chunk_box: BoundingBox, + position: [i32; 3], + reference: [i32; 3], + rotation: Rotation, + waterlogging: bool, + place_feature: &mut dyn FnMut( + &mut W, + &mut R, + &str, + [i32; 3], + ) -> Result, +) -> Result { + match element { + PoolElement::Empty => Ok(true), + PoolElement::Feature { feature, .. } => place_feature(world, random, feature, position), + PoolElement::List { elements, .. } => { + for e in elements { + if !place_element( + e, + world, + resources, + random, + chunk_box, + position, + reference, + rotation, + waterlogging, + place_feature, + )? { + return Ok(false); + } + } + Ok(true) + } + PoolElement::Single { + template, + processors, + legacy, + projection, + waterlogging: override_liquid, + } => { + let ignore = if *legacy { + IGNORE_STRUCTURE_AND_AIR.get_or_init(|| { + Processor::BlockIgnore( + [ + "minecraft:structure_block".to_owned(), + "minecraft:air".to_owned(), + ] + .into(), + ) + }) + } else { + IGNORE_STRUCTURE_BLOCK.get_or_init(|| { + Processor::BlockIgnore(["minecraft:structure_block".to_owned()].into()) + }) + }; + let mut settings = PlaceSettings::new(rotation); + settings.bounding_box = Some(chunk_box); + settings.waterlogging = override_liquid.unwrap_or(waterlogging); + settings.processors.push(ignore); + settings.processors.push(&Processor::JigsawReplacement); + settings.processors.extend(processors.0.iter()); + if *projection == Projection::TerrainMatching { + settings + .processors + .push(GRAVITY.get_or_init(|| Processor::Gravity { + heightmap: HeightmapType::WorldSurfaceWg, + offset: -1, + })); + } + place_in_world( + world, + resources, + template, + position, + reference, + &mut settings, + Some(random), + 18, + ) + } + } +} + +/// The world queries jigsaw assembly needs from the chunk generator. +pub trait JigsawContext { + fn min_y(&self) -> i32; + fn max_y(&self) -> i32; + /// ChunkGenerator.getBaseHeight (getFirstFreeHeight). + fn base_height(&mut self, x: i32, z: i32, kind: HeightmapType) -> i32; + /// couldStructureExistInColumn over inclusive block Y bounds. + fn column_has_valid_biome(&mut self, x: i32, z: i32, min_y: i32, max_y: i32) -> bool; +} +pub struct JigsawConfig<'a> { + pub start_pool: &'a str, + pub start_jigsaw: Option<&'a str>, + pub max_depth: i32, + pub use_expansion_hack: bool, + pub project_to: Option, + pub max_distance: [i32; 2], + pub aliases: &'a BTreeMap, + pub padding: [i32; 2], + pub waterlogging: bool, +} + +/// Free space for children: an inclusive container box minus placed boxes. +#[derive(Debug)] +struct Free { + container: BoundingBox, + removed: Vec, +} +impl Free { + /// Whether every point of the (0.25-deflated) box lies in free space. + fn fits(&self, b: &BoundingBox) -> bool { + (0..3).all(|i| b.min[i] >= self.container.min[i] && b.max[i] <= self.container.max[i]) + && !self.removed.iter().any(|r| r.intersects(b)) + } +} +struct PieceState { + piece: usize, + free: Rc>, + depth: i32, +} + +/// JigsawPlacement.addPieces. Returns the structure start position and the +/// pieces, or None when the start is invalid. +pub fn assemble( + config: &JigsawConfig<'_>, + context: &mut impl JigsawContext, + pools: &Pools, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + random: &mut impl RandomSource, + position: [i32; 3], +) -> Option<([i32; 3], Vec)> { + let alias = |name: &str| { + config + .aliases + .get(name) + .cloned() + .unwrap_or_else(|| name.to_owned()) + }; + let rotation = Rotation::random(random); + let center_pool = pools.get(&alias(config.start_pool), resources, bindings)?; + let element = center_pool.random_template(random); + if matches!(element.as_ref(), PoolElement::Empty) { + return None; + } + let anchored = match config.start_jigsaw { + Some(name) => { + element + .shuffled_jigsaws(resources, position, rotation, random) + .into_iter() + .find(|j| j.name.as_deref() == Some(name))? + .pos + } + None => position, + }; + let local: [i32; 3] = std::array::from_fn(|i| anchored[i] - position[i]); + let adjusted: [i32; 3] = std::array::from_fn(|i| position[i] - local[i]); + let mut center = PoolPiece { + bounding_box: element.bounding_box(adjusted, rotation), + ground_level_delta: element.ground_level_delta(), + element: element.clone(), + position: adjusted, + rotation, + junctions: Vec::new(), + waterlogging: config.waterlogging, + }; + let b = center.bounding_box; + let cx = (b.max[0] + b.min[0]) / 2; + let cz = (b.max[2] + b.min[2]) / 2; + let bottom = match config.project_to { + None => adjusted[1], + Some(kind) => { + if !context.column_has_valid_biome(cx, cz, context.min_y(), context.max_y()) { + return None; + } + position[1] + context.base_height(cx, cz, kind) + } + }; + let old_ground = b.min[1] + center.ground_level_delta; + center.moved(bottom - old_ground); + let b = center.bounding_box; + if config.padding != [0, 0] + && (b.min[1] < context.min_y() + config.padding[0] + || b.max[1] > context.max_y() - config.padding[1]) + { + return None; + } + let cy = bottom + local[1]; + let mut pieces = vec![center]; + if config.max_depth > 0 { + let [h, v] = config.max_distance; + let low_y = (cy - v).max(context.min_y() + config.padding[0]); + let high_y = (cy + v + 1).min(context.max_y() + 1 - config.padding[1]); + let free = Rc::new(RefCell::new(Free { + container: BoundingBox::new([cx - h, low_y, cz - h], [cx + h, high_y - 1, cz + h]), + removed: vec![pieces[0].bounding_box], + })); + let mut placer = Placer { + config, + pools, + resources, + bindings, + pieces: &mut pieces, + queue: BTreeMap::new(), + }; + placer.children(0, free, 0, context, random); + while let Some(state) = placer.next() { + placer.children(state.piece, state.free, state.depth, context, random); + } + } + Some(([cx, cy, cz], pieces)) +} +struct Placer<'a, 'p> { + config: &'a JigsawConfig<'a>, + pools: &'a Pools, + resources: &'a StructureResources, + bindings: &'a FeatureBlockBindings<'a>, + pieces: &'p mut Vec, + /// SequencedPriorityIterator: highest priority first, FIFO within one. + queue: BTreeMap>, +} +impl Placer<'_, '_> { + fn next(&mut self) -> Option { + let mut entry = self.queue.last_entry()?; + let state = entry.get_mut().pop_front(); + if entry.get().is_empty() { + entry.remove(); + } + state + } + fn pool(&self, name: &str) -> Option> { + let name = self.config.aliases.get(name).map_or(name, String::as_str); + self.pools.get(name, self.resources, self.bindings) + } + fn children( + &mut self, + source_index: usize, + context_free: Rc>, + depth: i32, + context: &mut impl JigsawContext, + random: &mut impl RandomSource, + ) { + let (source_element, source_position, source_rotation, source_box, source_ground) = { + let s = &self.pieces[source_index]; + ( + s.element.clone(), + s.position, + s.rotation, + s.bounding_box, + s.ground_level_delta, + ) + }; + let source_rigid = source_element.projection() == Projection::Rigid; + let mut source_free: Option>> = None; + let source_y = source_box.min[1]; + 'jigsaws: for jigsaw in source_element.shuffled_jigsaws( + self.resources, + source_position, + source_rotation, + random, + ) { + let direction = jigsaw.front; + let s = step(direction); + let target_pos: [i32; 3] = std::array::from_fn(|i| jigsaw.pos[i] + s[i]); + let local_y = jigsaw.pos[1] - source_y; + let mut base_height = i32::MIN; + let Some(target_pool) = self.pool(&jigsaw.pool) else { + continue; + }; + if target_pool.templates.is_empty() && jigsaw.pool != "minecraft:empty" { + continue; + } + let Some(fallback) = self.pool(&target_pool.fallback) else { + continue; + }; + if fallback.templates.is_empty() && target_pool.fallback != "minecraft:empty" { + continue; + } + let children_free = if source_box.is_inside(target_pos) { + source_free + .get_or_insert_with(|| { + Rc::new(RefCell::new(Free { + container: source_box, + removed: Vec::new(), + })) + }) + .clone() + } else { + context_free.clone() + }; + let mut targets = Vec::new(); + if depth != self.config.max_depth { + targets.extend(target_pool.shuffled(random)); + } + targets.extend(fallback.shuffled(random)); + for target in targets { + if matches!(target.as_ref(), PoolElement::Empty) { + break; + } + let mut rotations = Rotation::ALL; + shuffle(&mut rotations, random); + for rotation in rotations { + let target_jigsaws = + target.shuffled_jigsaws(self.resources, [0; 3], rotation, random); + let hack_box = target.bounding_box([0; 3], rotation); + let expand_to = if self.config.use_expansion_hack && hack_box.span()[1] <= 16 { + target_jigsaws + .iter() + .map(|tj| { + let st = step(tj.front); + if !hack_box.is_inside(std::array::from_fn(|i| tj.pos[i] + st[i])) { + return 0; + } + let child = self.pool(&tj.pool); + let child_size = child.as_ref().map_or(0, |p| p.max_size()); + let fallback_size = child + .and_then(|p| self.pool(&p.fallback)) + .map_or(0, |p| p.max_size()); + child_size.max(fallback_size) + }) + .max() + .unwrap_or(0) + } else { + 0 + }; + for target_jigsaw in &target_jigsaws { + if !can_attach(&jigsaw, target_jigsaw) { + continue; + } + let target_local = target_jigsaw.pos; + let raw_position: [i32; 3] = + std::array::from_fn(|i| target_pos[i] - target_local[i]); + let raw_box = target.bounding_box(raw_position, rotation); + let raw_y = raw_box.min[1]; + let target_rigid = target.projection() == Projection::Rigid; + let target_local_y = target_local[1]; + let delta_y = local_y - target_local_y + step(jigsaw.front)[1]; + let target_y = if source_rigid && target_rigid { + source_y + delta_y + } else { + if base_height == i32::MIN { + base_height = context.base_height( + jigsaw.pos[0], + jigsaw.pos[2], + HeightmapType::WorldSurfaceWg, + ); + } + base_height - target_local_y + }; + let offset = target_y - raw_y; + let mut target_box = raw_box.moved([0, offset, 0]); + let target_position = + [raw_position[0], raw_position[1] + offset, raw_position[2]]; + if expand_to > 0 { + let size = (expand_to + 1).max(target_box.max[1] - target_box.min[1]); + target_box.max[1] = target_box.max[1].max(target_box.min[1] + size); + } + if !children_free.borrow().fits(&target_box) { + continue; + } + children_free.borrow_mut().removed.push(target_box); + let target_ground = if target_rigid { + source_ground - delta_y + } else { + target.ground_level_delta() + }; + let junction_y = if source_rigid { + source_y + local_y + } else if target_rigid { + target_y + target_local_y + } else { + if base_height == i32::MIN { + base_height = context.base_height( + jigsaw.pos[0], + jigsaw.pos[2], + HeightmapType::WorldSurfaceWg, + ); + } + base_height + delta_y / 2 + }; + self.pieces[source_index].junctions.push(Junction { + source_x: target_pos[0], + source_ground_y: junction_y - local_y + source_ground, + source_z: target_pos[2], + }); + self.pieces.push(PoolPiece { + element: target.clone(), + position: target_position, + ground_level_delta: target_ground, + rotation, + bounding_box: target_box, + junctions: vec![Junction { + source_x: jigsaw.pos[0], + source_ground_y: junction_y - target_local_y + target_ground, + source_z: jigsaw.pos[2], + }], + waterlogging: self.config.waterlogging, + }); + if depth < self.config.max_depth { + self.queue + .entry(jigsaw.placement_priority) + .or_default() + .push_back(PieceState { + piece: self.pieces.len() - 1, + free: children_free.clone(), + depth: depth + 1, + }); + } + continue 'jigsaws; + } + } + } + } + } +} diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs new file mode 100644 index 000000000..b7c693c51 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -0,0 +1,620 @@ +//! Structures, structure sets and their placements, structure starts, +//! references, terrain adaptation and per-chunk piece placement. +use super::{ + BoundingBox, StructureResources, + jigsaw::{JigsawConfig, JigsawContext, PoolPiece, Pools, Projection, assemble}, +}; +use crate::{ + heightmap::HeightmapType, + worldgen::{ + DecodeError, + anchor::WorldGenerationContext, + biome::BiomeId, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + height_provider::HeightProvider, + placement::{PlacementContext, PlacementQueryError}, + weighted::WeightedList, + }, +}; +use horizon_core::{ + density::{Beardifier, JigsawJunction, RigidPiece, StructureBounds, TerrainAdjustment}, + position::{BlockPos, ChunkPos}, + random::{LegacyRandom, PositionalRandom, RandomSource, WorldgenRandom}, +}; +use serde_json::{Value, value::RawValue}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; + +pub const STEPS: [&str; 11] = [ + "raw_generation", + "lakes", + "local_modifications", + "underground_structures", + "surface_structures", + "strongholds", + "underground_ores", + "underground_decoration", + "fluid_springs", + "vegetal_decoration", + "top_layer_modification", +]; + +#[derive(Debug)] +pub struct JigsawDef { + start_pool: String, + start_jigsaw: Option, + max_depth: i32, + start_height: HeightProvider, + use_expansion_hack: bool, + project_to: Option, + max_distance: [i32; 2], + aliases: Vec, + padding: [i32; 2], + waterlogging: bool, +} +#[derive(Debug)] +pub enum StructureKind { + Jigsaw(JigsawDef), + /// A structure type whose generator is not implemented yet. + Unsupported(String), +} +#[derive(Debug)] +pub struct StructureDef { + pub name: String, + pub kind: StructureKind, + pub biomes: BTreeSet, + pub step: usize, + pub terrain: TerrainAdjustment, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Reduction { + Default, + Legacy1, + Legacy2, + Legacy3, +} +#[derive(Debug)] +enum Placement { + RandomSpread { + spacing: i32, + separation: i32, + triangular: bool, + }, + ConcentricRings, + Unsupported, +} +#[derive(Debug)] +pub struct StructureSet { + pub name: String, + pub structures: Vec<(usize, i32)>, + placement: Placement, + salt: i32, + frequency: f32, + reduction: Reduction, + exclusion: Option<(String, i32)>, +} + +fn heightmap(name: &str) -> Option { + HeightmapType::ALL.into_iter().find(|k| k.name() == name) +} +fn terrain(name: Option<&str>) -> TerrainAdjustment { + match name { + Some("bury") => TerrainAdjustment::Bury, + Some("beard_thin") => TerrainAdjustment::BeardThin, + Some("beard_box") => TerrainAdjustment::BeardBox, + Some("encapsulate") => TerrainAdjustment::Encapsulate, + _ => TerrainAdjustment::None, + } +} +fn pair(value: Option<&Value>, a: &str, b: &str, default: i32) -> [i32; 2] { + match value { + Some(Value::Number(n)) => [n.as_i64().unwrap_or(0) as i32; 2], + Some(Value::Object(o)) => { + let get = |k: &str| o.get(k).and_then(Value::as_i64).unwrap_or(0) as i32; + let first = get(a); + [ + first, + o.get(b).and_then(Value::as_i64).map_or(first, |v| v as i32), + ] + } + _ => [default; 2], + } +} + +/// All structures and structure sets of a resource bundle, in registry +/// (identifier) order. +#[derive(Debug)] +pub struct StructureRegistry { + pub structures: Vec, + pub sets: Vec, + pub pools: Pools, +} +impl StructureRegistry { + pub fn new( + structures: &BTreeMap, + sets: &BTreeMap, + pools: BTreeMap, + biome_set: &dyn Fn(&Value) -> Result, DecodeError>, + ) -> Result { + let mut defs = Vec::new(); + for (name, json) in structures { + let v: Value = serde_json::from_str(json)?; + let kind = match v["type"].as_str().unwrap_or_default() { + "minecraft:jigsaw" => StructureKind::Jigsaw(JigsawDef { + start_pool: v["start_pool"].as_str().unwrap_or_default().to_owned(), + start_jigsaw: v["start_jigsaw_name"].as_str().map(str::to_owned), + max_depth: v["size"].as_i64().unwrap_or(0) as i32, + start_height: HeightProvider::from_json(&v["start_height"].to_string())?, + use_expansion_hack: v["use_expansion_hack"].as_bool().unwrap_or(false), + project_to: v["project_start_to_heightmap"].as_str().and_then(heightmap), + max_distance: pair( + v.get("max_distance_from_center"), + "horizontal", + "vertical", + 80, + ), + aliases: v["pool_aliases"].as_array().cloned().unwrap_or_default(), + padding: pair(v.get("dimension_padding"), "bottom", "top", 0), + waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"), + }), + other => StructureKind::Unsupported(other.to_owned()), + }; + defs.push(StructureDef { + name: name.clone(), + kind, + biomes: biome_set(&v["biomes"])?, + step: STEPS + .iter() + .position(|s| Some(*s) == v["step"].as_str()) + .unwrap_or(4), + terrain: terrain(v["terrain_adaptation"].as_str()), + }); + } + let index = |name: &str| defs.iter().position(|d| d.name == name); + let mut out = Vec::new(); + for (name, json) in sets { + let v: Value = serde_json::from_str(json)?; + let p = &v["placement"]; + let placement = match p["type"].as_str().unwrap_or_default() { + "minecraft:random_spread" => Placement::RandomSpread { + spacing: p["spacing"].as_i64().unwrap_or(1) as i32, + separation: p["separation"].as_i64().unwrap_or(0) as i32, + triangular: p["spread_type"].as_str() == Some("triangular"), + }, + "minecraft:concentric_rings" => Placement::ConcentricRings, + _ => Placement::Unsupported, + }; + out.push(StructureSet { + name: name.clone(), + structures: v["structures"] + .as_array() + .into_iter() + .flatten() + .filter_map(|e| { + Some(( + index(e["structure"].as_str()?)?, + e["weight"].as_i64().unwrap_or(1) as i32, + )) + }) + .collect(), + placement, + salt: p["salt"].as_i64().unwrap_or(0) as i32, + frequency: p["frequency"].as_f64().unwrap_or(1.) as f32, + reduction: match p["frequency_reduction_method"].as_str() { + Some("legacy_type_1") => Reduction::Legacy1, + Some("legacy_type_2") => Reduction::Legacy2, + Some("legacy_type_3") => Reduction::Legacy3, + _ => Reduction::Default, + }, + exclusion: p.get("exclusion_zone").map(|z| { + ( + z["other_set"].as_str().unwrap_or_default().to_owned(), + z["chunk_count"].as_i64().unwrap_or(0) as i32, + ) + }), + }); + } + Ok(Self { + structures: defs, + sets: out, + pools: Pools::new(pools), + }) + } + /// RandomSpreadStructurePlacement.getPotentialStructureChunk et al. + pub fn is_structure_chunk( + &self, + set: &StructureSet, + seed: i64, + x: i32, + z: i32, + rings: &[ChunkPos], + ) -> bool { + let placed = match set.placement { + Placement::RandomSpread { + spacing, + separation, + triangular, + } => { + let (gx, gz) = (x.div_euclid(spacing), z.div_euclid(spacing)); + let mut random = WorldgenRandom::new(LegacyRandom::new(0)); + random.set_large_feature_with_salt(seed, gx, gz, set.salt); + let limit = spacing - separation; + let spread = |r: &mut WorldgenRandom| { + if triangular { + (r.next_int_bound(limit).unwrap_or(0) + + r.next_int_bound(limit).unwrap_or(0)) + / 2 + } else { + r.next_int_bound(limit).unwrap_or(0) + } + }; + let sx = spread(&mut random); + let sz = spread(&mut random); + gx * spacing + sx == x && gz * spacing + sz == z + } + Placement::ConcentricRings => rings.contains(&ChunkPos::new(x, z)), + Placement::Unsupported => false, + }; + if !placed { + return false; + } + if set.frequency < 1. && !reduce(set.reduction, seed, set.salt, x, z, set.frequency) { + return false; + } + match &set.exclusion { + Some((other, range)) => { + let Some(other) = self.sets.iter().find(|s| s.name == *other) else { + return true; + }; + for tx in x - range..=x + range { + for tz in z - range..=z + range { + if self.is_structure_chunk(other, seed, tx, tz, rings) { + return false; + } + } + } + true + } + None => true, + } + } +} +fn reduce(method: Reduction, seed: i64, salt: i32, x: i32, z: i32, probability: f32) -> bool { + let mut random = WorldgenRandom::new(LegacyRandom::new(0)); + match method { + Reduction::Default => { + random.set_large_feature_with_salt(seed, salt, x, z); + random.next_float() < probability + } + Reduction::Legacy1 => { + let (cx, cz) = (x >> 4, z >> 4); + random.set_seed(i64::from(cx ^ (cz << 4)) ^ seed); + random.next_int(); + random + .next_int_bound((1. / probability) as i32) + .unwrap_or(1) + == 0 + } + Reduction::Legacy2 => { + random.set_large_feature_with_salt(seed, x, z, 10_387_320); + random.next_float() < probability + } + Reduction::Legacy3 => { + random.set_large_feature_seed(seed, x, z); + random.next_double() < f64::from(probability) + } + } +} + +#[derive(Debug)] +pub enum Piece { + Pool(PoolPiece), +} +impl Piece { + pub fn bounding_box(&self) -> BoundingBox { + match self { + Self::Pool(p) => p.bounding_box, + } + } +} +#[derive(Debug)] +pub struct StructureStart { + pub structure: usize, + pub name: String, + pub chunk: ChunkPos, + pub pieces: Vec, + /// Piece union, inflated by 12 for terrain-adapting structures. + pub bounding_box: BoundingBox, +} + +/// Biome and height queries for one structure generation attempt. +pub trait StartContext: JigsawContext { + fn seed(&self) -> i64; + fn generation(&self) -> WorldGenerationContext; + /// Noise biome at a quart position (caching resolver, no zoom). + fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId; + fn set_valid_biomes(&mut self, biomes: &BTreeSet); +} + +/// ChunkGenerator.createStructures for one chunk: the starts it owns. +pub fn create_starts( + registry: &StructureRegistry, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + context: &mut impl StartContext, + possible_sets: &[usize], + rings: &[ChunkPos], + chunk: ChunkPos, +) -> Vec { + let seed = context.seed(); + let mut starts = Vec::new(); + for &set_index in possible_sets { + let set = ®istry.sets[set_index]; + if !registry.is_structure_chunk(set, seed, chunk.x, chunk.z, rings) { + continue; + } + if set.structures.len() == 1 { + if let Some(start) = try_generate( + registry, + resources, + bindings, + context, + set.structures[0].0, + chunk, + ) { + starts.push(start); + } + continue; + } + let mut options = set.structures.clone(); + let mut random = WorldgenRandom::new(LegacyRandom::new(0)); + random.set_large_feature_seed(seed, chunk.x, chunk.z); + let mut total: i32 = options.iter().map(|o| o.1).sum(); + while !options.is_empty() { + let mut choice = random.next_int_bound(total).unwrap_or(0); + let mut index = 0; + for option in &options { + choice -= option.1; + if choice < 0 { + break; + } + index += 1; + } + let selected = options[index]; + if let Some(start) = + try_generate(registry, resources, bindings, context, selected.0, chunk) + { + starts.push(start); + break; + } + options.remove(index); + total -= selected.1; + } + } + starts +} +fn try_generate( + registry: &StructureRegistry, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + context: &mut impl StartContext, + structure: usize, + chunk: ChunkPos, +) -> Option { + let def = ®istry.structures[structure]; + context.set_valid_biomes(&def.biomes); + let seed = context.seed(); + let mut random = WorldgenRandom::new(LegacyRandom::new(0)); + random.set_large_feature_seed(seed, chunk.x, chunk.z); + let (position, pieces) = match &def.kind { + StructureKind::Jigsaw(jigsaw) => { + let height = jigsaw + .start_height + .sample(&mut random, context.generation()) + .ok()?; + let start = [chunk.x * 16, height, chunk.z * 16]; + let aliases = resolve_aliases(&jigsaw.aliases, start, seed); + let config = JigsawConfig { + start_pool: &jigsaw.start_pool, + start_jigsaw: jigsaw.start_jigsaw.as_deref(), + max_depth: jigsaw.max_depth, + use_expansion_hack: jigsaw.use_expansion_hack, + project_to: jigsaw.project_to, + max_distance: jigsaw.max_distance, + aliases: &aliases, + padding: jigsaw.padding, + waterlogging: jigsaw.waterlogging, + }; + let (position, mut pieces) = assemble( + &config, + context, + ®istry.pools, + resources, + bindings, + &mut random, + start, + )?; + if jigsaw.max_depth <= 0 { + pieces.clear(); + } + ( + position, + pieces.into_iter().map(Piece::Pool).collect::>(), + ) + } + StructureKind::Unsupported(_) => return None, + }; + let quart = position.map(|v| v >> 2); + if !def.biomes.contains(&context.noise_biome(quart)) || pieces.is_empty() { + return None; + } + let mut bounding_box = pieces[0].bounding_box(); + for piece in &pieces[1..] { + bounding_box.encapsulate(&piece.bounding_box()); + } + if def.terrain != TerrainAdjustment::None { + bounding_box = bounding_box.inflated(12, 12); + } + Some(StructureStart { + structure, + name: def.name.clone(), + chunk, + pieces, + bounding_box, + }) +} +/// PoolAliasLookup.create. +fn resolve_aliases(bindings: &[Value], position: [i32; 3], seed: i64) -> BTreeMap { + let mut map = BTreeMap::new(); + if bindings.is_empty() { + return map; + } + let mut random = LegacyRandom::new(seed).fork_positional().at(BlockPos::new( + position[0], + position[1], + position[2], + )); + fn visit(binding: &Value, random: &mut LegacyRandom, map: &mut BTreeMap) { + let weighted = |key: &str| -> Option> { + let raw: Box = serde_json::from_str(&binding[key].to_string()).ok()?; + WeightedList::decode(&raw, |v| Ok(serde_json::from_str::(v.get())?)).ok() + }; + match binding["type"].as_str().unwrap_or_default() { + "minecraft:direct" => { + map.insert( + binding["alias"].as_str().unwrap_or_default().to_owned(), + binding["target"].as_str().unwrap_or_default().to_owned(), + ); + } + "minecraft:random" => { + if let Some(target) = + weighted("targets").and_then(|w| w.sample(random).ok().cloned()) + { + map.insert( + binding["alias"].as_str().unwrap_or_default().to_owned(), + target.as_str().unwrap_or_default().to_owned(), + ); + } + } + "minecraft:random_group" => { + if let Some(group) = weighted("groups").and_then(|w| w.sample(random).ok().cloned()) + { + for b in group.as_array().into_iter().flatten() { + visit(b, random, map); + } + } + } + _ => {} + } + } + for binding in bindings { + visit(binding, &mut random, &mut map); + } + map +} + +/// Beardifier.forStructuresInChunk over the starts referencing a chunk. +pub fn beardifier( + registry: &StructureRegistry, + starts: &[Arc], + chunk: ChunkPos, +) -> Option { + let (bx, bz) = (chunk.x * 16, chunk.z * 16); + let mut rigids = Vec::new(); + let mut junctions = Vec::new(); + let mut any: Option = None; + let include = |b: BoundingBox, any: &mut Option| match any { + Some(a) => a.encapsulate(&b), + None => *any = Some(b), + }; + for start in starts { + let adjustment = registry.structures[start.structure].terrain; + if adjustment == TerrainAdjustment::None { + continue; + } + for piece in &start.pieces { + let b = piece.bounding_box(); + let near = b.max[0] >= bx - 12 + && b.min[0] <= bx + 15 + 12 + && b.max[2] >= bz - 12 + && b.min[2] <= bz + 15 + 12; + if !near { + continue; + } + let Piece::Pool(pool) = piece; + if pool.element.projection() == Projection::Rigid { + rigids.push(RigidPiece { + bounds: StructureBounds::new(b.min, b.max)?, + adjustment, + ground_level_delta: pool.ground_level_delta, + }); + include(b, &mut any); + } + for j in &pool.junctions { + if j.source_x > bx - 12 + && j.source_z > bz - 12 + && j.source_x < bx + 15 + 12 + && j.source_z < bz + 15 + 12 + { + junctions.push(JigsawJunction { + source_x: j.source_x, + source_ground_y: j.source_ground_y, + source_z: j.source_z, + }); + let p = [j.source_x, j.source_ground_y, j.source_z]; + include(BoundingBox::new(p, p), &mut any); + } + } + } + } + let any = any?; + let affected = any.inflated(24, 24); + Some(Beardifier::new( + rigids, + junctions, + StructureBounds::new(affected.min, affected.max), + )) +} + +/// StructureStart.placeInChunk for pieces intersecting the chunk's writable box. +#[allow(clippy::too_many_arguments)] +pub fn place_in_chunk( + start: &StructureStart, + world: &mut W, + resources: &StructureResources, + random: &mut R, + chunk_box: BoundingBox, + place_feature: &mut dyn FnMut( + &mut W, + &mut R, + &str, + [i32; 3], + ) -> Result, +) -> Result<(), PlacementQueryError> { + let Some(first) = start.pieces.first() else { + return Ok(()); + }; + let center_box = first.bounding_box(); + let center = center_box.center(); + let reference = [center[0], center_box.min[1], center[2]]; + for piece in &start.pieces { + if piece.bounding_box().intersects(&chunk_box) { + match piece { + Piece::Pool(p) => { + p.place( + world, + resources, + random, + chunk_box, + reference, + place_feature, + )?; + } + } + } + } + Ok(()) +}