From f9fc6c8ffa206114145283d43036278b7994d260 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 02:17:49 +0200 Subject: [PATCH 1/4] Add structure templates, processors and template/fossil features Load gzip NBT structure templates lazily with vanilla palette ordering, apply processors (rule, block_ignore, block_rot, gravity, protected_blocks, capped, jigsaw_replacement, block_age, lava_submerged) and place them with rotation/mirror, waterlogging and block-entity data (loot seeds). Per-state rotate/mirror tables and template ordering flags come from a new vanilla exporter. Template and fossil features now decode, so desert wells, fossils and sulfur springs generate; their block entities are kept on the ProtoChunk. The prepare script bundles templates, processor lists, pools, structures and structure sets. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/horizon-world/src/worldgen.rs | 1 + .../src/worldgen/block_feature.rs | 10 + .../src/worldgen/feature_graph.rs | 18 + .../horizon-world/src/worldgen/generator.rs | 17 + .../src/worldgen/generator_decoration.rs | 27 + .../src/worldgen/placement/context.rs | 9 + .../horizon-world/src/worldgen/structure.rs | 340 ++++++++ .../src/worldgen/structure/features.rs | 231 +++++ .../src/worldgen/structure/processor.rs | 788 ++++++++++++++++++ .../src/worldgen/structure/template.rs | 302 +++++++ .../parity/VanillaStructureBlockExporter.java | 40 + tools/prepare_native_client.py | 40 +- 12 files changed, 1820 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-world/src/worldgen/structure.rs create mode 100644 crates/horizon-world/src/worldgen/structure/features.rs create mode 100644 crates/horizon-world/src/worldgen/structure/processor.rs create mode 100644 crates/horizon-world/src/worldgen/structure/template.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index f26871605..a58b25457 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -61,6 +61,7 @@ pub mod speleothem; pub mod spike; pub mod spring; pub mod state_provider; +pub mod structure; pub mod tags; pub mod terrain; pub mod tree; diff --git a/crates/horizon-world/src/worldgen/block_feature.rs b/crates/horizon-world/src/worldgen/block_feature.rs index ee61e3f35..a901a583d 100644 --- a/crates/horizon-world/src/worldgen/block_feature.rs +++ b/crates/horizon-world/src/worldgen/block_feature.rs @@ -30,10 +30,19 @@ pub struct FeatureBlockBindings<'r> { pub(crate) tags: BTreeMap>>, pub(crate) air: [BlockStateId; 3], tree_blocks: std::sync::OnceLock>, + pub(crate) structures: Option>, } impl<'r> FeatureBlockBindings<'r> { /// Shared tree/vegetation classifications, built on first use. Requires /// state-provider and block-property bindings. + /// Bind structure templates and processor lists for template features. + pub fn with_structures( + mut self, + structures: Arc, + ) -> Self { + self.structures = Some(structures); + self + } pub(crate) fn tree_blocks(&self) -> Result, DecodeError> { if let Some(blocks) = self.tree_blocks.get() { return Ok(blocks.clone()); @@ -154,6 +163,7 @@ impl<'r> FeatureBlockBindings<'r> { .collect(), tags: bound_tags, tree_blocks: std::sync::OnceLock::new(), + structures: None, air: [ get("minecraft:air")?, get("minecraft:cave_air")?, diff --git a/crates/horizon-world/src/worldgen/feature_graph.rs b/crates/horizon-world/src/worldgen/feature_graph.rs index 68408a30e..014ea3f42 100644 --- a/crates/horizon-world/src/worldgen/feature_graph.rs +++ b/crates/horizon-world/src/worldgen/feature_graph.rs @@ -86,6 +86,8 @@ pub enum FeatureDefinition { SteppedColumnCluster(Box), FallenTree(Box), NoOp, + Template(Box), + Fossil(Box), WeightedChoice(OptionalWeightedList), Sequence(Vec), Overlay(Vec), @@ -312,6 +314,16 @@ impl FeatureDefinition { )?)?; match kind.as_str() { "minecraft:no_op" => Ok(Self::NoOp), + "minecraft:template" => super::structure::features::TemplateFeature::decode( + json, + blocks.ok_or(DecodeError::Field("template bindings"))?, + ) + .map(|f| Self::Template(Box::new(f))), + "minecraft:fossil" => super::structure::features::FossilFeature::decode( + json, + blocks.ok_or(DecodeError::Field("fossil bindings"))?, + ) + .map(|f| Self::Fossil(Box::new(f))), "minecraft:freeze_top_layer" => super::snow_freeze::SnowAndFreezeFeature::new( blocks.ok_or(DecodeError::Field("snow and freeze bindings"))?, ) @@ -843,6 +855,12 @@ impl FeatureDefinition { .place(world, random, origin, run.blocks) .map_err(FeatureExecutionError::Basic), Self::NoOp => Ok(true), + Self::Template(feature) => feature + .place(world, random, origin) + .map_err(FeatureExecutionError::Query), + Self::Fossil(feature) => feature + .place(world, random, origin) + .map_err(FeatureExecutionError::Query), Self::SnowAndFreeze(feature) => feature .place(world, origin) .map_err(FeatureExecutionError::SnowAndFreeze), diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index e3fe337aa..2458cb705 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -170,6 +170,8 @@ pub struct GeneratorData { pub(super) block_tags: BTreeMap>, pub(super) biome_tags: BTreeMap>, pub(super) feature_resources: Option, + /// Templates, processor lists and per-state template transforms. + pub(super) structures: Option>, } type Bundle = BTreeMap; fn read_bundle(dir: &Path, name: &str) -> Result { @@ -393,7 +395,18 @@ impl GeneratorData { } _ => None, }; + let structures = match fs::read_to_string(dir.join("blocks/structure-blocks.json")) { + Ok(json) => Some(Arc::new(super::structure::StructureResources::new( + registry, + super::structure::StateTransforms::from_json(&json, registry.len())?, + &dir.join("structure"), + read_optional_bundle(dir, "processor_lists")?.unwrap_or_default(), + &block_tags, + ))), + Err(_) => None, + }; Ok(Arc::new(Self { + structures, registry, states: GenBlockStates(states.into()), integers, @@ -452,6 +465,9 @@ pub struct ProtoChunk { biomes: BiomeChunk, data: Arc, decorated: bool, + /// 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)>, } impl ProtoChunk { pub fn position(&self) -> ChunkPos { @@ -919,6 +935,7 @@ where biomes: center, data: data.clone(), decorated: false, + block_entities: Vec::new(), }) } } diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index fc3a65f97..047bd7053 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -125,6 +125,9 @@ impl Decoration { FeatureBlockBindings::with_tags(registry, data.integers().clone(), &data.block_tags)? .with_fluid_tags(&resources.fluid_tags)? .with_biomes(biomes.clone()); + if let Some(structures) = &data.structures { + bindings = bindings.with_structures(structures.clone()); + } if let Some(blocks) = &resources.blocks { bindings = bindings .with_block_properties(&blocks.properties)? @@ -268,7 +271,12 @@ impl Decoration { Err(e) => return Err(resource(e.to_string())), }; let mut next_boolean = next_boolean; + let mut block_entities = Vec::new(); + for chunk in region.iter_mut() { + block_entities.append(&mut chunk.block_entities); + } let mut world = World { + block_entities, next_boolean: &mut next_boolean, blocks: data .feature_resources @@ -309,6 +317,14 @@ impl Decoration { Ok(placed.unwrap_or(false)) }, ); + for (pos, nbt) in std::mem::take(&mut world.block_entities) { + let index = ((pos[2] >> 4).wrapping_sub(center.z) + 1) * 3 + + (pos[0] >> 4).wrapping_sub(center.x) + + 1; + if let Some(chunk) = usize::try_from(index).ok().and_then(|i| region.get_mut(i)) { + chunk.block_entities.push((pos, nbt)); + } + } for terrain in world.region.into_chunks() { let p = terrain.position(); let index = (p.z.wrapping_sub(center.z) + 1) * 3 + p.x.wrapping_sub(center.x) + 1; @@ -326,6 +342,7 @@ impl Decoration { /// WorldGenRegion-style view: reads anywhere in the 3×3 region, writes within /// the FEATURES step's write radius, biome lookups through the biome zoom. struct World<'a> { + block_entities: Vec<([i32; 3], crate::nbt::Compound)>, next_boolean: &'a mut dyn FnMut() -> bool, blocks: Option<&'a BlockBehavior>, region: TerrainRegion<'static, GenBlockStates>, @@ -370,6 +387,7 @@ impl FeatureWorld for World<'_> { return Ok(false); } self.region.set_block_worldgen(position, state)?; + self.block_entities.retain(|(p, _)| *p != position); Ok(true) } } @@ -497,6 +515,15 @@ impl PlacementContext for World<'_> { (0..ny).all(|y| (0..nz).all(|z| shape.is_full(x as i32, y as i32, z as i32))) })) } + fn set_block_entity( + &mut self, + position: [i32; 3], + nbt: crate::nbt::Compound, + ) -> Result<(), PlacementQueryError> { + self.block_entities.retain(|(p, _)| *p != position); + self.block_entities.push((position, nbt)); + Ok(()) + } fn world_seed(&mut self) -> Result { self.region.world_seed() } diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index d00bec6c4..f64dadf94 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -285,6 +285,15 @@ pub trait PlacementContext { fn layer_block(&mut self, _position: [i32; 3]) -> Result { Err(PlacementQueryError::Unavailable) } + /// Store block-entity data loaded at a just-placed block (structure + /// templates). Worlds without block-entity storage drop it. + fn set_block_entity( + &mut self, + _position: [i32; 3], + _nbt: crate::nbt::Compound, + ) -> Result<(), PlacementQueryError> { + Ok(()) + } fn generation(&self) -> WorldGenerationContext; /// Recreate the generation bounds for a block-predicate invocation. World /// adapters may perform fallible level/generator queries here; ordinary diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs new file mode 100644 index 000000000..ee12ef5ff --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -0,0 +1,340 @@ +//! Structure templates, processors and placement shared by template features +//! and structure pieces. +pub mod features; +pub mod processor; +pub mod template; + +use crate::{ + nbt::{self, Limits}, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::geometry::Direction; +use processor::ProcessorList; +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + io::Read, + path::{Path, PathBuf}, + sync::{Arc, RwLock}, +}; +pub use template::{BlockInfo, JigsawInfo, StructureTemplate}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Rotation { + None, + Clockwise90, + Clockwise180, + Counterclockwise90, +} +impl Rotation { + pub const ALL: [Self; 4] = [ + Self::None, + Self::Clockwise90, + Self::Clockwise180, + Self::Counterclockwise90, + ]; + pub fn from_name(name: &str) -> Option { + Some(match name { + "none" => Self::None, + "clockwise_90" => Self::Clockwise90, + "180" => Self::Clockwise180, + "counterclockwise_90" => Self::Counterclockwise90, + _ => return None, + }) + } + /// Rotation.getRandom: one bounded draw over the four values. + pub fn random(random: &mut impl horizon_core::random::RandomSource) -> Self { + Self::ALL[random.next_int_bound(4).unwrap_or(0) as usize] + } + pub fn rotate_direction(self, direction: Direction) -> Direction { + if matches!(direction, Direction::Up | Direction::Down) { + return direction; + } + let order = [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ]; + let index = order.iter().position(|d| *d == direction).unwrap(); + order[(index + self as usize) % 4] + } + pub fn get_rotated(self, other: Self) -> Self { + Self::ALL[(self as usize + other as usize) % 4] + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Mirror { + None, + LeftRight, + FrontBack, +} + +/// Inclusive integer box (vanilla BoundingBox). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct BoundingBox { + pub min: [i32; 3], + pub max: [i32; 3], +} +impl BoundingBox { + pub fn new(min: [i32; 3], max: [i32; 3]) -> Self { + Self { min, max } + } + pub fn from_corners(a: [i32; 3], b: [i32; 3]) -> Self { + Self { + min: std::array::from_fn(|i| a[i].min(b[i])), + max: std::array::from_fn(|i| a[i].max(b[i])), + } + } + pub fn moved(self, d: [i32; 3]) -> Self { + Self { + min: std::array::from_fn(|i| self.min[i] + d[i]), + max: std::array::from_fn(|i| self.max[i] + d[i]), + } + } + pub fn is_inside(&self, p: [i32; 3]) -> bool { + (0..3).all(|i| p[i] >= self.min[i] && p[i] <= self.max[i]) + } + pub fn intersects(&self, other: &Self) -> bool { + (0..3).all(|i| self.max[i] >= other.min[i] && self.min[i] <= other.max[i]) + } + pub fn encapsulate(&mut self, other: &Self) { + for i in 0..3 { + self.min[i] = self.min[i].min(other.min[i]); + self.max[i] = self.max[i].max(other.max[i]); + } + } + pub fn inflated(self, xz: i32, y: i32) -> Self { + Self { + min: [self.min[0] - xz, self.min[1] - y, self.min[2] - xz], + max: [self.max[0] + xz, self.max[1] + y, self.max[2] + xz], + } + } + pub fn span(&self) -> [i32; 3] { + std::array::from_fn(|i| self.max[i] - self.min[i] + 1) + } + pub fn center(&self) -> [i32; 3] { + std::array::from_fn(|i| self.min[i] + (self.max[i] - self.min[i] + 1) / 2) + } + pub fn corners(&self) -> [[i32; 3]; 8] { + let (a, b) = (self.min, self.max); + [ + [a[0], a[1], a[2]], + [a[0], a[1], b[2]], + [a[0], b[1], a[2]], + [a[0], b[1], b[2]], + [b[0], a[1], a[2]], + [b[0], a[1], b[2]], + [b[0], b[1], a[2]], + [b[0], b[1], b[2]], + ] + } +} + +/// Per-state BlockState.rotate/mirror results and template ordering flags, +/// exported from vanilla (`blocks/structure-blocks.json`). +#[derive(Debug, Default)] +pub struct StateTransforms { + rotate: Vec<[u32; 3]>, + mirror: Vec<[u32; 2]>, + full: Vec, + loot: BTreeSet, +} +impl StateTransforms { + pub fn from_json(json: &str, states: usize) -> Result { + let value: serde_json::Value = serde_json::from_str(json)?; + let arr = |key: &'static str| { + value[key] + .as_array() + .cloned() + .ok_or(super::DecodeError::Field(key)) + }; + let ids = |v: &serde_json::Value| -> Vec { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|x| x.as_u64()) + .map(|x| x as u32) + .collect() + }) + .unwrap_or_default() + }; + let rotate = arr("rotate")? + .iter() + .map(|v| { + let v = ids(v); + [v[0], v[1], v[2]] + }) + .collect::>(); + let mirror = arr("mirror")? + .iter() + .map(|v| { + let v = ids(v); + [v[0], v[1]] + }) + .collect::>(); + let full = arr("full_block")? + .iter() + .map(|v| v.as_bool().unwrap_or(false)) + .collect::>(); + if rotate.len() != states || mirror.len() != states || full.len() != states { + return Err(super::DecodeError::Field("structure block table size")); + } + let loot = ids(&value["loot_containers"]) + .into_iter() + .map(BlockStateId) + .collect(); + Ok(Self { + rotate, + mirror, + full, + loot, + }) + } + pub fn rotate(&self, state: BlockStateId, rotation: Rotation) -> BlockStateId { + match rotation { + Rotation::None => state, + r => self + .rotate + .get(state.0 as usize) + .map_or(state, |t| BlockStateId(t[r as usize - 1])), + } + } + pub fn mirror(&self, state: BlockStateId, mirror: Mirror) -> BlockStateId { + match mirror { + Mirror::None => state, + m => self + .mirror + .get(state.0 as usize) + .map_or(state, |t| BlockStateId(t[m as usize - 1])), + } + } + pub fn full_block(&self, state: BlockStateId) -> bool { + self.full.get(state.0 as usize).copied().unwrap_or(false) + } + pub fn loot_container(&self, state: BlockStateId) -> bool { + self.loot.contains(&state) + } +} + +/// Lazily loaded templates (`structure//.nbt`, gzip NBT) and +/// processor lists, shared by all generators of one resource bundle. +pub struct StructureResources { + pub registry: &'static BlockRegistry, + pub transforms: StateTransforms, + dir: PathBuf, + templates: RwLock>>>, + pub processor_lists: BTreeMap, + jigsaw_states: BTreeMap, + pub(crate) waterlogged: HashMap, + sources: BTreeSet, + /// Block names in each block tag, for processors matching tags by block. + pub block_tags: BTreeMap>, +} +impl std::fmt::Debug for StructureResources { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StructureResources") + } +} +impl StructureResources { + pub fn new( + registry: &'static BlockRegistry, + transforms: StateTransforms, + dir: &Path, + processor_lists: BTreeMap, + block_tags: &BTreeMap>, + ) -> Self { + let mut sources = BTreeSet::new(); + let fluids = crate::fluid::FluidStateTable::new(registry).ok(); + let mut jigsaw_states = BTreeMap::new(); + let mut waterlogged = HashMap::new(); + for id in 0..registry.len() { + let id = BlockStateId(id as u32); + let state = registry.state(id).unwrap(); + if state.name == "minecraft:jigsaw" { + let orientation = state + .properties + .get("orientation") + .cloned() + .unwrap_or_default(); + let front = orientation.split('_').next().unwrap_or(""); + jigsaw_states.insert(id, !matches!(front, "up" | "down")); + } + if fluids + .as_ref() + .and_then(|table| table.get(id)) + .is_some_and(|fluid| fluid.is_source()) + { + sources.insert(id); + } + if state.properties.get("waterlogged").map(String::as_str) == Some("false") { + let mut wet = state.clone(); + wet.properties.insert("waterlogged".into(), "true".into()); + if let Some(wet) = registry.id(&wet) { + waterlogged.insert(id, wet); + } + } + } + Self { + registry, + transforms, + dir: dir.to_owned(), + templates: RwLock::new(HashMap::new()), + processor_lists, + jigsaw_states, + waterlogged, + sources, + block_tags: block_tags + .iter() + .map(|(k, v)| (k.clone(), v.iter().cloned().collect())) + .collect(), + } + } + /// StructureTemplateManager.getOrCreate; missing templates are None. + pub fn template(&self, id: &str) -> Option> { + let id = if id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + }; + if let Some(found) = self.templates.read().unwrap().get(&id) { + return found.clone(); + } + let (namespace, path) = id.split_once(':').unwrap(); + let file = self.dir.join(namespace).join(format!("{path}.nbt")); + let loaded = std::fs::read(&file).ok().and_then(|bytes| { + let mut raw = Vec::new(); + flate2::read::GzDecoder::new(bytes.as_slice()) + .read_to_end(&mut raw) + .ok()?; + let limits = Limits { + max_bytes: 1 << 28, + ..Limits::default() + }; + let tag = nbt::read_named(&raw, limits).ok()?.0.tag; + Some(Arc::new(StructureTemplate::from_nbt( + &tag, + self.registry, + &self.transforms, + ))) + }); + self.templates.write().unwrap().insert(id, loaded.clone()); + loaded + } + /// Whether the state's fluid is a source (water/lava level 0, waterlogged). + pub fn source_fluid(&self, state: BlockStateId) -> bool { + self.sources.contains(&state) + } + pub fn jigsaw_horizontal(&self, state: BlockStateId) -> Option { + self.jigsaw_states.get(&state).copied() + } + pub fn processor_list( + &self, + json: &str, + bindings: &super::block_feature::FeatureBlockBindings<'_>, + ) -> Result { + ProcessorList::decode(json, self, bindings) + } + pub fn is_jigsaw(&self, state: BlockStateId) -> bool { + self.jigsaw_states.contains_key(&state) + } +} diff --git a/crates/horizon-world/src/worldgen/structure/features.rs b/crates/horizon-world/src/worldgen/structure/features.rs new file mode 100644 index 000000000..63e9a494a --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/features.rs @@ -0,0 +1,231 @@ +//! The `template` and `fossil` configured features. +use super::{ + BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate, + processor::{PlaceSettings, ProcessorList, place_in_world}, +}; +use crate::{ + heightmap::HeightmapType, + worldgen::{ + DecodeError, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + placement::{PlacementContext, PlacementQueryError}, + weighted::WeightedList, + }, +}; +use horizon_core::random::RandomSource; +use serde_json::{Value, value::RawValue}; +use std::sync::Arc; + +fn resources(bindings: &FeatureBlockBindings<'_>) -> Result, DecodeError> { + bindings + .structures + .clone() + .ok_or(DecodeError::Field("structure template bindings")) +} +fn template( + resources: &StructureResources, + id: &str, +) -> Result, DecodeError> { + resources + .template(id) + .ok_or_else(|| DecodeError::Registry(format!("missing structure template {id}"))) +} + +#[derive(Clone, Debug)] +pub struct TemplateFeature { + templates: WeightedList<(Arc, Vec)>, + processors: ProcessorList, + resources: Arc, +} +impl TemplateFeature { + pub fn decode(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + let resources = resources(bindings)?; + let value: Value = serde_json::from_str(json)?; + let raw: Box = serde_json::from_str(&value["templates"].to_string())?; + let templates = WeightedList::decode(&raw, |entry| { + let entry: Value = serde_json::from_str(entry.get())?; + let id = entry["id"] + .as_str() + .ok_or(DecodeError::Field("template id"))?; + let rotations = match entry.get("rotations").and_then(Value::as_array) { + Some(list) => list + .iter() + .map(|r| { + r.as_str() + .and_then(Rotation::from_name) + .ok_or(DecodeError::Field("rotation")) + }) + .collect::, _>>()?, + None => Rotation::ALL.to_vec(), + }; + Ok((template(&resources, id)?, rotations)) + })?; + let processors = match value.get("processors") { + Some(p) => ProcessorList::decode(&p.to_string(), &resources, bindings)?, + None => ProcessorList::default(), + }; + Ok(Self { + templates, + processors, + resources, + }) + } + pub fn place( + &self, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + ) -> Result { + let invalid = |_| PlacementQueryError::Failed("template weights".into()); + let (template, rotations) = self.templates.sample(random).map_err(invalid)?; + let rotation = rotations[random + .next_int_bound(rotations.len() as i32) + .map_err(invalid)? as usize]; + // rotation.rotate(axis.getNegative()) * (size along axis / 2), for X then Z. + let mut pos = origin; + for (axis, negative) in [ + (0, horizon_core::geometry::Direction::West), + (2, horizon_core::geometry::Direction::North), + ] { + let step = rotation.rotate_direction(negative).normal(); + let length = template.size[axis] / 2; + for i in 0..3 { + pos[i] += step[i] * length; + } + } + let mut settings = PlaceSettings::new(rotation).add(&self.processors); + settings.random = Some(random); + place_in_world( + world, + &self.resources, + template, + pos, + pos, + &mut settings, + None, + 3, + ) + } +} + +#[derive(Clone, Debug)] +pub struct FossilFeature { + fossils: Vec<(Arc, Arc)>, + fossil_processors: ProcessorList, + overlay_processors: ProcessorList, + max_empty_corners: i32, + resources: Arc, +} +impl FossilFeature { + pub fn decode(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + let resources = resources(bindings)?; + let value: Value = serde_json::from_str(json)?; + let list = |key: &'static str| -> Result>, DecodeError> { + value[key] + .as_array() + .ok_or(DecodeError::Field(key))? + .iter() + .map(|id| template(&resources, id.as_str().unwrap_or_default())) + .collect() + }; + let (base, overlay) = (list("fossil_structures")?, list("overlay_structures")?); + if base.is_empty() || base.len() != overlay.len() { + return Err(DecodeError::Field("fossil structure lists")); + } + Ok(Self { + fossils: base.into_iter().zip(overlay).collect(), + fossil_processors: ProcessorList::decode( + &value["fossil_processors"].to_string(), + &resources, + bindings, + )?, + overlay_processors: ProcessorList::decode( + &value["overlay_processors"].to_string(), + &resources, + bindings, + )?, + max_empty_corners: value["max_empty_corners_allowed"].as_i64().unwrap_or(0) as i32, + resources, + }) + } + pub fn place( + &self, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + ) -> Result { + let invalid = |_| PlacementQueryError::Failed("fossil bounds".into()); + let rotation = Rotation::random(random); + let index = random + .next_int_bound(self.fossils.len() as i32) + .map_err(invalid)? as usize; + let (base, overlay) = &self.fossils[index]; + let (cx, cz) = (origin[0] >> 4, origin[2] >> 4); + let bounds = BoundingBox::new( + [cx * 16 - 16, world.min_y()?, cz * 16 - 16], + [cx * 16 + 15 + 16, world.max_y()?, cz * 16 + 15 + 16], + ); + let size = base.size(rotation); + let low = [origin[0] - size[0] / 2, 0, origin[2] - size[2] / 2]; + let mut lowest = origin[1]; + for x in 0..size[0] { + for z in 0..size[2] { + lowest = lowest.min(world.height( + HeightmapType::OceanFloorWg, + low[0] + x, + low[2] + z, + )?); + } + } + let y = + (lowest - 15 - random.next_int_bound(10).map_err(invalid)?).max(world.min_y()? + 10); + let target = StructureTemplate::zero_position_with_transform( + [low[0], y, low[2]], + Mirror::None, + rotation, + base.size[0], + base.size[2], + ); + let mut empty = 0; + for corner in base + .bounding_box(target, rotation, [0; 3], Mirror::None) + .corners() + { + let state = world.block_state(corner)?; + let name = &self.resources.registry.state(state).unwrap().name; + if matches!( + name.as_str(), + "minecraft:air" + | "minecraft:cave_air" + | "minecraft:void_air" + | "minecraft:lava" + | "minecraft:water" + ) { + empty += 1; + } + } + if empty > self.max_empty_corners { + return Ok(false); + } + for (template, processors) in [ + (base, &self.fossil_processors), + (overlay, &self.overlay_processors), + ] { + let mut settings = PlaceSettings::new(rotation).add(processors); + settings.bounding_box = Some(bounds); + settings.random = Some(&mut *random); + place_in_world( + world, + &self.resources, + template, + target, + target, + &mut settings, + None, + 260, + )?; + } + Ok(true) + } +} diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs new file mode 100644 index 000000000..4e50654d6 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -0,0 +1,788 @@ +//! Structure processors (`worldgen/processor_list`) and template placement. +use super::{BlockInfo, BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate}; +use crate::{ + fluid::FluidKind, + heightmap::HeightmapType, + nbt::{Compound, JavaString, Tag}, + registry::BlockStateId, + worldgen::{ + DecodeError, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + placement::{PlacementContext, PlacementQueryError}, + rule_test::RuleTest, + value_provider::IntProvider, + }, +}; +use horizon_core::{ + position::BlockPos, + random::{LegacyRandom, PositionalRandom, RandomSource, position_seed}, +}; +use serde_json::Value; +use std::{collections::BTreeSet, sync::Arc}; + +/// The draws processors make from StructurePlaceSettings' random. +pub trait ProcessorRandom { + fn float(&mut self) -> f32; + fn int(&mut self, bound: i32) -> i32; + fn long(&mut self) -> i64; +} +impl ProcessorRandom for R { + fn float(&mut self) -> f32 { + self.next_float() + } + fn int(&mut self, bound: i32) -> i32 { + self.next_int_bound(bound).unwrap_or(0) + } + fn long(&mut self) -> i64 { + self.next_long() + } +} + +#[derive(Clone, Debug)] +enum PosRule { + Always, + Linear { + min_chance: f32, + max_chance: f32, + min_dist: i32, + max_dist: i32, + axis: Option, + }, +} +#[derive(Clone, Debug)] +enum Modifier { + Passthrough, + Clear, + AppendLoot(String), + AppendStatic(Compound), +} +#[derive(Clone, Debug)] +pub struct Rule { + input: RuleTest, + location: RuleTest, + position: PosRule, + output: BlockStateId, + modifier: Modifier, +} +#[derive(Clone, Debug)] +pub enum Processor { + Nop, + BlockIgnore(BTreeSet), + BlockRot { + rottable: Option>>, + integrity: f32, + }, + Gravity { + heightmap: HeightmapType, + offset: i32, + }, + Rule(Vec), + Protected(Arc>), + Capped { + delegate: Box, + limit: IntProvider, + }, + JigsawReplacement, + BlockAge(f32), + LavaSubmerged, +} +#[derive(Clone, Debug, Default)] +pub struct ProcessorList(pub Vec); + +fn holder_set( + value: &Value, + bindings: &FeatureBlockBindings<'_>, +) -> Result>, 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(), + _ => return Err(DecodeError::Field("block holder set")), + }; + let mut out = BTreeSet::new(); + for name in names { + if let Some(tag) = name.strip_prefix('#') { + let tag = super::super::tags::identifier(tag)?; + out.extend( + bindings + .tags + .get(&tag) + .map(|s| s.iter().copied()) + .into_iter() + .flatten(), + ); + } else { + let name = super::super::tags::identifier(name)?; + out.extend( + bindings + .blocks + .get(&name) + .ok_or_else(|| DecodeError::Registry(format!("unknown block {name}")))? + .iter() + .copied(), + ); + } + } + Ok(Arc::new(out)) +} +fn json_to_nbt(value: &Value) -> Tag { + match value { + Value::Bool(b) => Tag::Byte(i8::from(*b)), + Value::Number(n) => match n.as_i64() { + Some(i) if i32::try_from(i).is_ok() => Tag::Int(i as i32), + Some(i) => Tag::Long(i), + None => Tag::Double(n.as_f64().unwrap_or(0.).to_bits()), + }, + Value::String(s) => Tag::String(s.as_str().into()), + Value::Array(a) => Tag::List(a.iter().map(json_to_nbt).collect()), + Value::Object(o) => Tag::Compound( + o.iter() + .map(|(k, v)| (JavaString::from(k.as_str()), json_to_nbt(v))) + .collect(), + ), + Value::Null => Tag::End, + } +} +fn float(value: &Value, key: &'static str) -> Result { + value[key] + .as_f64() + .map(|v| v as f32) + .ok_or(DecodeError::Field(key)) +} +impl Processor { + fn decode( + value: &Value, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + ) -> Result { + let kind = value["processor_type"] + .as_str() + .ok_or(DecodeError::Field("processor_type"))?; + let state = |v: &Value| -> Result { + bindings + .codec + .decode(&v.to_string(), false) + .map_err(|e| DecodeError::Registry(e.to_string())) + }; + Ok(match super::super::tags::identifier(kind)?.as_str() { + "minecraft:nop" => Self::Nop, + "minecraft:block_ignore" => Self::BlockIgnore( + value["blocks"] + .as_array() + .ok_or(DecodeError::Field("block_ignore blocks"))? + .iter() + .map(|b| state(b).map(|id| resources.registry.state(id).unwrap().name.clone())) + .collect::>()?, + ), + "minecraft:block_rot" => Self::BlockRot { + rottable: match value.get("rottable_blocks") { + Some(v) => Some(holder_set(v, bindings)?), + None => None, + }, + integrity: float(value, "integrity")?, + }, + "minecraft:gravity" => Self::Gravity { + heightmap: match value.get("heightmap").and_then(Value::as_str) { + Some(name) => HeightmapType::ALL + .into_iter() + .find(|k| k.name() == name) + .ok_or(DecodeError::Field("gravity heightmap"))?, + None => HeightmapType::WorldSurfaceWg, + }, + offset: value.get("offset").and_then(Value::as_i64).unwrap_or(0) as i32, + }, + "minecraft:protected_blocks" => Self::Protected(holder_set(&value["value"], bindings)?), + "minecraft:jigsaw_replacement" => Self::JigsawReplacement, + "minecraft:block_age" => Self::BlockAge(float(value, "mossiness")?), + "minecraft:lava_submerged_block" => Self::LavaSubmerged, + "minecraft:capped" => Self::Capped { + delegate: Box::new(Self::decode(&value["delegate"], resources, bindings)?), + limit: IntProvider::from_json(&value["limit"].to_string())?, + }, + "minecraft:rule" => Self::Rule( + value["rules"] + .as_array() + .ok_or(DecodeError::Field("rules"))? + .iter() + .map(|rule| { + let test = |key| RuleTest::from_json(&rule[key].to_string(), bindings); + let position = match rule.get("position_predicate") { + Some(p) => match p["predicate_type"] + .as_str() + .unwrap_or("minecraft:always_true") + { + "minecraft:always_true" => PosRule::Always, + kind @ ("minecraft:linear_pos" + | "minecraft:axis_aligned_linear_pos") => PosRule::Linear { + min_chance: p + .get("min_chance") + .and_then(Value::as_f64) + .unwrap_or(0.) + as f32, + max_chance: p + .get("max_chance") + .and_then(Value::as_f64) + .unwrap_or(0.) + as f32, + min_dist: p.get("min_dist").and_then(Value::as_i64).unwrap_or(0) + as i32, + max_dist: p.get("max_dist").and_then(Value::as_i64).unwrap_or(0) + as i32, + axis: (kind == "minecraft:axis_aligned_linear_pos").then( + || match p.get("axis").and_then(Value::as_str) { + Some("x") => 0, + Some("z") => 2, + _ => 1, + }, + ), + }, + _ => return Err(DecodeError::Field("position predicate")), + }, + None => PosRule::Always, + }; + let modifier = match rule.get("block_entity_modifier") { + None => Modifier::Passthrough, + Some(m) => match m["type"].as_str().unwrap_or("") { + "minecraft:passthrough" => Modifier::Passthrough, + "minecraft:clear" => Modifier::Clear, + "minecraft:append_loot" => Modifier::AppendLoot( + m["loot_table"].as_str().unwrap_or_default().to_owned(), + ), + "minecraft:append_static" => match json_to_nbt(&m["data"]) { + Tag::Compound(c) => Modifier::AppendStatic(c), + _ => Modifier::AppendStatic(Compound::new()), + }, + _ => return Err(DecodeError::Field("block entity modifier")), + }, + }; + Ok(Rule { + input: test("input_predicate")?, + location: test("location_predicate")?, + position, + output: state(&rule["output_state"])?, + modifier, + }) + }) + .collect::>()?, + ), + _ => return Err(DecodeError::Field("structure processor type")), + }) + } + fn evaluates_entire_piece(&self) -> bool { + matches!(self, Self::Capped { .. }) + } +} +impl ProcessorList { + /// A processor list holder: a registry name, `{"processors": [...]}` or a list. + pub fn decode( + json: &str, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + ) -> Result { + let value: Value = serde_json::from_str(json)?; + let value = match &value { + Value::String(name) => { + let name = super::super::tags::identifier(name)?; + let raw = resources.processor_lists.get(&name).ok_or_else(|| { + DecodeError::Registry(format!("unknown processor list {name}")) + })?; + serde_json::from_str(raw)? + } + other => other.clone(), + }; + let list = match &value { + Value::Array(a) => a.clone(), + Value::Object(_) => value["processors"].as_array().cloned().unwrap_or_default(), + _ => return Err(DecodeError::Field("processor list")), + }; + Ok(Self( + list.iter() + .map(|p| Processor::decode(p, resources, bindings)) + .collect::>()?, + )) + } +} + +/// StructurePlaceSettings without entity options. +pub struct PlaceSettings<'a> { + pub mirror: Mirror, + pub rotation: Rotation, + pub pivot: [i32; 3], + pub bounding_box: Option, + pub processors: Vec<&'a Processor>, + pub waterlogging: bool, + pub random: Option<&'a mut dyn ProcessorRandom>, +} +impl<'a> PlaceSettings<'a> { + pub fn new(rotation: Rotation) -> Self { + Self { + mirror: Mirror::None, + rotation, + pivot: [0; 3], + bounding_box: None, + processors: Vec::new(), + waterlogging: true, + random: None, + } + } + pub fn add(mut self, list: &'a ProcessorList) -> Self { + self.processors.extend(list.0.iter()); + self + } + /// settings.getRandom(pos): the shared random, else a position-seeded one. + fn with_random( + &mut self, + pos: [i32; 3], + f: impl FnOnce(&mut dyn ProcessorRandom) -> T, + ) -> T { + match self.random.as_deref_mut() { + Some(random) => f(random), + None => f(&mut LegacyRandom::new(position_seed(BlockPos::new( + pos[0], pos[1], pos[2], + )))), + } + } +} + +type ProcessResult = Result, PlacementQueryError>; +#[allow(clippy::too_many_arguments)] +fn process_block( + processor: &Processor, + world: &mut W, + resources: &StructureResources, + reference: [i32; 3], + relative: [i32; 3], + info: BlockInfo, + settings: &mut PlaceSettings<'_>, +) -> ProcessResult { + let registry = resources.registry; + let name = |id: BlockStateId| registry.state(id).map(|s| s.name.as_str()).unwrap_or(""); + Ok(match processor { + Processor::Nop => Some(info), + Processor::BlockIgnore(blocks) => (!blocks.contains(name(info.state))).then_some(info), + Processor::BlockRot { + rottable, + integrity, + } => { + let candidate = rottable + .as_ref() + .is_none_or(|set| set.contains(&info.state)); + let keep = settings.with_random(info.pos, |r| !candidate || r.float() <= *integrity); + keep.then_some(info) + } + Processor::Gravity { heightmap, offset } => { + let height = world.height(*heightmap, info.pos[0], info.pos[2])? + offset; + Some(BlockInfo { + pos: [info.pos[0], height + relative[1], info.pos[2]], + ..info + }) + } + Processor::Protected(set) => (!set.contains(&world.block_state(info.pos)?)).then_some(info), + Processor::JigsawReplacement => { + if !resources.is_jigsaw(info.state) { + return Ok(Some(info)); + } + let Some(nbt) = &info.nbt else { + return Ok(Some(info)); + }; + let text = match nbt.get(&JavaString::from("final_state")) { + Some(Tag::String(s)) => s.to_string_lossy(), + _ => "minecraft:air".to_owned(), + }; + let Some(state) = super::template::parse_state_string(registry, &text) else { + return Ok(None); + }; + (name(state) != "minecraft:structure_void").then_some(BlockInfo { + pos: info.pos, + state, + nbt: None, + }) + } + Processor::LavaSubmerged => { + let lava = name(world.block_state(info.pos)?) == "minecraft:lava"; + if lava && !resources.transforms.full_block(info.state) { + Some(BlockInfo { + state: registry.default_state("minecraft:lava").unwrap(), + ..info + }) + } else { + Some(info) + } + } + Processor::BlockAge(mossiness) => block_age(*mossiness, info, settings, resources), + Processor::Rule(rules) => { + let mut random = LegacyRandom::new(position_seed(BlockPos::new( + info.pos[0], + info.pos[1], + info.pos[2], + ))); + for rule in rules { + if !rule.input.test(info.state, info.pos, &mut random) { + continue; + } + let located = world.block_state(info.pos)?; + if !rule.location.test(located, info.pos, &mut random) { + continue; + } + let position_ok = match &rule.position { + PosRule::Always => true, + PosRule::Linear { + min_chance, + max_chance, + min_dist, + max_dist, + axis, + } => { + let dist = match axis { + None => (0..3) + .map(|i| (info.pos[i] - reference[i]).abs()) + .sum::(), + Some(a) => { + let d: [f32; 3] = std::array::from_fn(|i| { + if i == *a { + ((info.pos[i] - reference[i]) as f32).abs() + } else { + 0. + } + }); + (d[0] + d[1] + d[2]) as i32 + } + }; + let roll = random.next_float(); + let t = (dist - min_dist) as f32 / (max_dist - min_dist) as f32; + let chance = if t < 0. { + *min_chance + } else if t > 1. { + *max_chance + } else { + min_chance + t * (max_chance - min_chance) + }; + roll <= chance + } + }; + if !position_ok { + continue; + } + let nbt = match &rule.modifier { + Modifier::Passthrough => info.nbt.clone(), + Modifier::Clear => Some(Compound::new()), + Modifier::AppendLoot(table) => { + let mut nbt = info.nbt.clone().unwrap_or_default(); + nbt.insert("LootTable".into(), Tag::String(table.as_str().into())); + nbt.insert("LootTableSeed".into(), Tag::Long(random.next_long())); + Some(nbt) + } + Modifier::AppendStatic(data) => { + let mut nbt = info.nbt.clone().unwrap_or_default(); + nbt.extend(data.clone()); + Some(nbt) + } + }; + return Ok(Some(BlockInfo { + pos: info.pos, + state: rule.output, + nbt, + })); + } + Some(info) + } + Processor::Capped { .. } => Some(info), + }) +} +fn block_age( + mossiness: f32, + info: BlockInfo, + settings: &mut PlaceSettings<'_>, + resources: &StructureResources, +) -> Option { + let registry = resources.registry; + let state = registry.state(info.state)?.clone(); + let default = |n: &str| registry.default_state(n).unwrap(); + let with_props = |n: &str| { + let mut target = registry.state(default(n)).unwrap().clone(); + for (k, v) in &state.properties { + if target.properties.contains_key(k) { + target.properties.insert(k.clone(), v.clone()); + } + } + registry.id(&target).unwrap_or(default(n)) + }; + let random_stairs = |r: &mut dyn ProcessorRandom, n: &str| { + let facing = ["north", "east", "south", "west"][r.int(4) as usize]; + let half = ["top", "bottom"][r.int(2) as usize]; + let mut target = registry.state(default(n)).unwrap().clone(); + target.properties.insert("facing".into(), facing.into()); + target.properties.insert("half".into(), half.into()); + registry.id(&target).unwrap() + }; + let name = state.name.as_str(); + let is_tag = |tag: &str| { + // Tags are matched by block name through the template resources' bindings. + resources + .block_tags + .get(tag) + .is_some_and(|set| set.contains(name)) + }; + let new_state = settings.with_random(info.pos, |r| -> Option { + let pick = |r: &mut dyn ProcessorRandom, non: &[BlockStateId], mossy: &[BlockStateId]| { + if r.float() < mossiness { + mossy[r.int(mossy.len() as i32) as usize] + } else { + non[r.int(non.len() as i32) as usize] + } + }; + if matches!( + name, + "minecraft:stone_bricks" | "minecraft:stone" | "minecraft:chiseled_stone_bricks" + ) { + if r.float() >= 0.5 { + return None; + } + let non = [ + default("minecraft:cracked_stone_bricks"), + random_stairs(r, "minecraft:stone_brick_stairs"), + ]; + let mossy = [ + default("minecraft:mossy_stone_bricks"), + random_stairs(r, "minecraft:mossy_stone_brick_stairs"), + ]; + Some(pick(r, &non, &mossy)) + } else if is_tag("minecraft:stairs") { + if r.float() >= 0.5 { + return None; + } + let non = [ + default("minecraft:stone_slab"), + default("minecraft:stone_brick_slab"), + ]; + let mossy = [ + with_props("minecraft:mossy_stone_brick_stairs"), + default("minecraft:mossy_stone_brick_slab"), + ]; + Some(pick(r, &non, &mossy)) + } else if is_tag("minecraft:slabs") { + (r.float() < mossiness).then(|| with_props("minecraft:mossy_stone_brick_slab")) + } else if is_tag("minecraft:walls") { + (r.float() < mossiness).then(|| with_props("minecraft:mossy_stone_brick_wall")) + } else if name == "minecraft:obsidian" { + (r.float() < 0.15).then(|| default("minecraft:crying_obsidian")) + } else { + None + } + }); + Some(match new_state { + Some(state) => BlockInfo { state, ..info }, + None => info, + }) +} + +/// StructureTemplate.processBlockInfos. +fn process_infos( + world: &mut W, + resources: &StructureResources, + template: &StructureTemplate, + palette: usize, + position: [i32; 3], + reference: [i32; 3], + settings: &mut PlaceSettings<'_>, +) -> Result, PlacementQueryError> { + let whole = settings + .processors + .iter() + .any(|p| p.evaluates_entire_piece()); + let mut original = Vec::new(); + let mut processed = Vec::new(); + for info in template.palettes()[palette].blocks() { + let relative = StructureTemplate::transform( + info.pos, + settings.mirror, + settings.rotation, + settings.pivot, + ); + let pos = std::array::from_fn(|i| relative[i] + position[i]); + if !whole && settings.bounding_box.is_some_and(|b| !b.is_inside(pos)) { + continue; + } + let mut current = Some(BlockInfo { + pos, + state: info.state, + nbt: info.nbt.clone(), + }); + let processors = settings.processors.clone(); + for processor in processors { + let Some(value) = current.take() else { break }; + current = process_block( + processor, world, resources, reference, info.pos, value, settings, + )?; + } + if let Some(value) = current { + processed.push(value); + original.push(info.clone()); + } + } + let processors = settings.processors.clone(); + for processor in processors { + let Processor::Capped { delegate, limit } = processor else { + continue; + }; + if limit.bounds()[1] == 0 || processed.is_empty() || original.len() != processed.len() { + continue; + } + let seed = world.world_seed()?; + let mut random = LegacyRandom::new(seed).fork_positional().at(BlockPos::new( + position[0], + position[1], + position[2], + )); + let max = limit + .sample(&mut random) + .unwrap_or(0) + .min(processed.len() as i32); + if max < 1 { + continue; + } + let mut indices: Vec = (0..processed.len()).collect(); + for i in (2..=indices.len()).rev() { + let swap = random.next_int_bound(i as i32).unwrap_or(0) as usize; + indices.swap(i - 1, swap); + } + let mut replaced = 0; + for index in indices { + if replaced >= max { + break; + } + let before = processed[index].clone(); + let altered = process_block( + delegate, + world, + resources, + reference, + original[index].pos, + before.clone(), + settings, + )?; + if let Some(altered) = altered { + if altered != before { + replaced += 1; + processed[index] = altered; + } + } + } + } + Ok(processed) +} + +/// StructureTemplate.placeInWorld without entities or neighbor shape updates. +/// Returns false for empty templates. +#[allow(clippy::too_many_arguments)] +pub fn place_in_world( + world: &mut W, + resources: &StructureResources, + template: &StructureTemplate, + position: [i32; 3], + reference: [i32; 3], + settings: &mut PlaceSettings<'_>, + mut loot_random: Option<&mut dyn ProcessorRandom>, + flags: i32, +) -> Result { + if template.palettes().is_empty() { + return Ok(false); + } + let palette = match settings.random.as_deref_mut() { + Some(r) => r.int(template.palettes().len() as i32) as usize, + None => 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, + }; + if template.palettes()[palette].blocks().is_empty() || template.size.iter().any(|s| *s < 1) { + return Ok(false); + } + let infos = process_infos( + world, resources, template, palette, position, reference, settings, + )?; + let barrier = resources + .registry + .default_state("minecraft:barrier") + .unwrap(); + let mut to_fill = Vec::new(); + let mut locked = Vec::new(); + let world_err = |_| PlacementQueryError::Failed("template write".into()); + for info in infos { + if settings + .bounding_box + .is_some_and(|b| !b.is_inside(info.pos)) + { + continue; + } + let previous = if settings.waterlogging { + Some(world.fluid_state(info.pos)?) + } else { + None + }; + let state = resources.transforms.rotate( + resources.transforms.mirror(info.state, settings.mirror), + settings.rotation, + ); + if info.nbt.is_some() { + world.set_block(info.pos, barrier, 820).map_err(world_err)?; + } + if !world.set_block(info.pos, state, flags).map_err(world_err)? { + continue; + } + if let Some(mut nbt) = info.nbt { + if resources.transforms.loot_container(state) { + let seed = match loot_random.as_deref_mut() { + Some(random) => random.long(), + None => settings.random.as_deref_mut().map_or(0, |r| r.long()), + }; + nbt.insert("LootTableSeed".into(), Tag::Long(seed)); + } + world.set_block_entity(info.pos, nbt)?; + } + if let Some(previous) = previous { + if resources.source_fluid(state) { + locked.push(info.pos); + } else if let Some(wet) = resources.waterlogged.get(&state) { + if previous.kind() == FluidKind::Water { + world.set_block(info.pos, *wet, 3).map_err(world_err)?; + world.schedule_fluid_tick(info.pos, previous.kind(), 5).ok(); + } else if !previous.is_source() { + to_fill.push(info.pos); + } + } + } + } + let mut filled = true; + while filled && !to_fill.is_empty() { + filled = false; + let mut remaining = Vec::new(); + for pos in std::mem::take(&mut to_fill) { + let mut fluid = world.fluid_state(pos)?; + for d in [[0, 1, 0], [0, 0, -1], [1, 0, 0], [0, 0, 1], [-1, 0, 0]] { + if fluid.is_source() { + break; + } + let n = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; + let neighbor = world.fluid_state(n)?; + if neighbor.is_source() && !locked.contains(&n) { + fluid = neighbor; + } + } + let state = world.block_state(pos)?; + match resources.waterlogged.get(&state) { + Some(wet) if fluid.is_source() && fluid.kind() == FluidKind::Water => { + world.set_block(pos, *wet, 3).map_err(world_err)?; + world.schedule_fluid_tick(pos, fluid.kind(), 5).ok(); + filled = true; + } + _ => remaining.push(pos), + } + } + to_fill = remaining; + } + Ok(true) +} diff --git a/crates/horizon-world/src/worldgen/structure/template.rs b/crates/horizon-world/src/worldgen/structure/template.rs new file mode 100644 index 000000000..8726d2b20 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/template.rs @@ -0,0 +1,302 @@ +//! StructureTemplate: NBT loading, palettes, transforms and bounding boxes. +use super::{BoundingBox, Mirror, Rotation, StateTransforms}; +use crate::{ + chunk::BlockState, + nbt::{Compound, Tag}, + registry::{BlockRegistry, BlockStateId}, +}; +use std::sync::OnceLock; + +#[derive(Clone, Debug, PartialEq)] +pub struct BlockInfo { + pub pos: [i32; 3], + pub state: BlockStateId, + pub nbt: Option, +} +#[derive(Clone, Debug)] +pub struct JigsawInfo { + pub info: BlockInfo, + pub rollable: bool, + pub name: String, + pub pool: String, + pub target: String, + pub placement_priority: i32, + pub selection_priority: i32, +} +#[derive(Debug)] +pub struct Palette { + blocks: Vec, + jigsaws: OnceLock>, +} +impl Palette { + pub fn blocks(&self) -> &[BlockInfo] { + &self.blocks + } +} +#[derive(Debug)] +pub struct StructureTemplate { + pub size: [i32; 3], + palettes: Vec, +} + +fn int_list(tag: Option<&Tag>) -> [i32; 3] { + let mut out = [0; 3]; + if let Some(Tag::List(values)) = tag { + for (slot, value) in out.iter_mut().zip(values) { + if let Tag::Int(v) = value { + *slot = *v; + } + } + } + out +} +fn string(tag: Option<&Tag>) -> Option { + match tag { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + } +} +fn get<'a>(compound: &'a Compound, key: &str) -> Option<&'a Tag> { + compound.get(&crate::nbt::JavaString::from(key)) +} +/// NbtUtils.readBlockState: unknown blocks read as air; missing or invalid +/// properties keep the block's defaults. +pub(super) fn read_state(registry: &BlockRegistry, tag: &Tag) -> BlockStateId { + let air = registry.default_state("minecraft:air").expect("air"); + let Tag::Compound(compound) = tag else { + return air; + }; + let Some(name) = string(get(compound, "Name")) else { + return air; + }; + let Some(default) = registry.default_state(&name) else { + return air; + }; + let mut state = registry.state(default).unwrap().clone(); + if let Some(Tag::Compound(properties)) = get(compound, "Properties") { + for (key, value) in properties { + let (Tag::String(value), key) = (value, key.to_string_lossy()) else { + continue; + }; + let value = value.to_string_lossy(); + if let Some(slot) = state.properties.get_mut(&key) { + let previous = std::mem::replace(slot, value); + if registry.id(&state).is_none() { + *state.properties.get_mut(&key).unwrap() = previous; + } + } + } + } + registry.id(&state).unwrap_or(default) +} +/// Parse `name[key=value,...]` (BlockStateParser without NBT); None if invalid. +pub(super) fn parse_state_string(registry: &BlockRegistry, text: &str) -> Option { + let text = text.split('{').next().unwrap_or(text).trim(); + let (name, properties) = match text.split_once('[') { + Some((name, rest)) => (name, rest.strip_suffix(']')?), + None => (text, ""), + }; + let name = if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }; + let mut descriptor = BlockState { + name, + properties: Default::default(), + }; + for pair in properties.split(',').filter(|p| !p.trim().is_empty()) { + let (k, v) = pair.split_once('=')?; + descriptor + .properties + .insert(k.trim().to_owned(), v.trim().to_owned()); + } + registry.resolve(&descriptor).ok() +} + +impl StructureTemplate { + /// StructureTemplate.load. Blocks are ordered as vanilla orders them: + /// full collision blocks, then other blocks, then block entities, each + /// sorted by Y, X, Z. + pub fn from_nbt(tag: &Tag, registry: &BlockRegistry, transforms: &StateTransforms) -> Self { + let empty = Compound::new(); + let root = match tag { + Tag::Compound(c) => c, + _ => &empty, + }; + let size = int_list(get(root, "size")); + let blocks = match get(root, "blocks") { + Some(Tag::List(list)) => list.as_slice(), + _ => &[], + }; + let mut palettes = Vec::new(); + let mut load = |palette: &[Tag]| { + let states: Vec = + palette.iter().map(|t| read_state(registry, t)).collect(); + let air = registry.default_state("minecraft:air").unwrap(); + let mut lists: [Vec; 3] = Default::default(); + for block in blocks { + let Tag::Compound(block) = block else { + continue; + }; + let index = match get(block, "state") { + Some(Tag::Int(i)) => *i, + _ => 0, + }; + let state = usize::try_from(index) + .ok() + .and_then(|i| states.get(i)) + .copied() + .unwrap_or(air); + let nbt = match get(block, "nbt") { + Some(Tag::Compound(c)) => Some(c.clone()), + _ => None, + }; + let class = if nbt.is_some() { + 2 + } else if transforms.full_block(state) { + 0 + } else { + 1 + }; + lists[class].push(BlockInfo { + pos: int_list(get(block, "pos")), + state, + nbt, + }); + } + let mut result = Vec::with_capacity(blocks.len()); + for mut list in lists { + list.sort_by_key(|b| (b.pos[1], b.pos[0], b.pos[2])); + result.extend(list); + } + palettes.push(Palette { + blocks: result, + jigsaws: OnceLock::new(), + }); + }; + match get(root, "palettes") { + Some(Tag::List(lists)) => { + for list in lists { + match list { + Tag::List(p) => load(p), + _ => load(&[]), + } + } + } + _ => match get(root, "palette") { + Some(Tag::List(p)) => load(p), + _ => load(&[]), + }, + } + Self { size, palettes } + } + pub fn palettes(&self) -> &[Palette] { + &self.palettes + } + pub fn size(&self, rotation: Rotation) -> [i32; 3] { + match rotation { + Rotation::Clockwise90 | Rotation::Counterclockwise90 => { + [self.size[2], self.size[1], self.size[0]] + } + _ => self.size, + } + } + pub fn transform( + pos: [i32; 3], + mirror: Mirror, + rotation: Rotation, + pivot: [i32; 3], + ) -> [i32; 3] { + let [mut x, y, mut z] = pos; + match mirror { + Mirror::LeftRight => z = z.wrapping_neg(), + Mirror::FrontBack => x = x.wrapping_neg(), + Mirror::None => {} + } + let (px, pz) = (pivot[0], pivot[2]); + match rotation { + Rotation::Counterclockwise90 => [px - pz + z, y, px + pz - x], + Rotation::Clockwise90 => [px + pz - z, y, pz - px + x], + Rotation::Clockwise180 => [px + px - x, y, pz + pz - z], + Rotation::None => [x, y, z], + } + } + pub fn zero_position_with_transform( + zero: [i32; 3], + mirror: Mirror, + rotation: Rotation, + size_x: i32, + size_z: i32, + ) -> [i32; 3] { + let (sx, sz) = (size_x - 1, size_z - 1); + let mx = if mirror == Mirror::FrontBack { sx } else { 0 }; + let mz = if mirror == Mirror::LeftRight { sz } else { 0 }; + let d = match rotation { + Rotation::Counterclockwise90 => [mz, 0, sx - mx], + Rotation::Clockwise90 => [sz - mz, 0, mx], + Rotation::Clockwise180 => [sx - mx, 0, sz - mz], + Rotation::None => [mx, 0, mz], + }; + [zero[0] + d[0], zero[1], zero[2] + d[2]] + } + pub fn bounding_box( + &self, + position: [i32; 3], + rotation: Rotation, + pivot: [i32; 3], + mirror: Mirror, + ) -> BoundingBox { + let delta = [self.size[0] - 1, self.size[1] - 1, self.size[2] - 1]; + let a = Self::transform([0; 3], mirror, rotation, pivot); + let b = Self::transform(delta, mirror, rotation, pivot); + BoundingBox::from_corners(a, b).moved(position) + } + /// The palette selected by StructurePlaceSettings.getRandomPalette. + pub fn palette_index(&self, random: &mut impl horizon_core::random::RandomSource) -> usize { + random + .next_int_bound(self.palettes.len().max(1) as i32) + .unwrap_or(0) as usize + } + /// Jigsaw blocks of a palette, parsed from their block-entity data. + pub fn jigsaws( + &self, + palette: usize, + jigsaw_states: &dyn Fn(BlockStateId) -> Option, + ) -> &[JigsawInfo] { + let Some(palette) = self.palettes.get(palette) else { + return &[]; + }; + palette.jigsaws.get_or_init(|| { + palette + .blocks + .iter() + .filter_map(|info| { + let horizontal = jigsaw_states(info.state)?; + let nbt = info.nbt.clone().unwrap_or_default(); + let joint = string(get(&nbt, "joint")); + let text = |key: &str, default: &str| { + string(get(&nbt, key)).unwrap_or_else(|| default.to_owned()) + }; + let int = |key: &str| match get(&nbt, key) { + Some(Tag::Int(v)) => *v, + _ => 0, + }; + Some(JigsawInfo { + rollable: match joint.as_deref() { + Some("rollable") => true, + Some("aligned") => false, + _ => !horizontal, + }, + name: text("name", "minecraft:empty"), + pool: text("pool", "minecraft:empty"), + target: text("target", "minecraft:empty"), + placement_priority: int("placement_priority"), + selection_priority: int("selection_priority"), + info: info.clone(), + }) + }) + .collect() + }) + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java new file mode 100644 index 000000000..0e37d5cda --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java @@ -0,0 +1,40 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.BlockPos; +import net.minecraft.server.Bootstrap; +import net.minecraft.world.RandomizableContainer; +import net.minecraft.world.level.EmptyBlockGetter; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.state.BlockState; + +/** + * Original exporter of per-state structure-template behavior: BlockState.rotate + * and BlockState.mirror results, StructureTemplate's full-block ordering class + * and whether the state's block entity is a RandomizableContainer. + */ +public final class VanillaStructureBlockExporter { + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion();Bootstrap.bootStrap(); + var rotate=new JsonArray();var mirror=new JsonArray();var full=new JsonArray();var loot=new JsonArray(); + Rotation[] rotations={Rotation.CLOCKWISE_90,Rotation.CLOCKWISE_180,Rotation.COUNTERCLOCKWISE_90}; + Mirror[] mirrors={Mirror.LEFT_RIGHT,Mirror.FRONT_BACK}; + for(BlockState state:Block.BLOCK_STATE_REGISTRY) { + var r=new JsonArray();for(var rotation:rotations)r.add(Block.getId(state.rotate(rotation)));rotate.add(r); + var m=new JsonArray();for(var value:mirrors)m.add(Block.getId(state.mirror(value)));mirror.add(m); + full.add(!state.getBlock().hasDynamicShape()&&state.isCollisionShapeFullBlock(EmptyBlockGetter.INSTANCE,BlockPos.ZERO)); + boolean container=false; + if(state.getBlock() instanceof EntityBlock entityBlock) { + try{container=entityBlock.newBlockEntity(BlockPos.ZERO,state) instanceof RandomizableContainer;}catch(Throwable ignored){} + } + if(container)loot.add(Block.getId(state)); + } + var result=new JsonObject(); + result.addProperty("states",Block.BLOCK_STATE_REGISTRY.size()); + result.add("rotate",rotate);result.add("mirror",mirror);result.add("full_block",full);result.add("loot_containers",loot); + Files.writeString(Path.of(args[0]),new Gson().toJson(result),StandardCharsets.UTF_8); + } +} diff --git a/tools/prepare_native_client.py b/tools/prepare_native_client.py index 0e2f881f0..280d53e24 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -21,13 +21,44 @@ WORLDGEN_BUNDLES = { 'biomes': 'worldgen/biome', 'world_presets': 'worldgen/world_preset', 'features': 'worldgen/feature', 'placed_features': 'worldgen/placed_feature', 'state_providers': 'worldgen/block_state_provider', 'biome_tags': 'tags/worldgen/biome', 'feature_tags': 'tags/worldgen/feature', 'block_tags': 'tags/block', - 'fluid_tags': 'tags/fluid'} + 'fluid_tags': 'tags/fluid', 'processor_lists': 'worldgen/processor_list', + 'template_pools': 'worldgen/template_pool', 'structures': 'worldgen/structure', + 'structure_sets': 'worldgen/structure_set'} -def prepare_worldgen(root, jars, local): +def export_structure_blocks(target, jars, libraries): + """Run the vanilla exporter of per-state rotate/mirror results and template flags.""" + lock = json.loads((lab.ROOT/'research-lock.json').read_text()) + source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java' + export = lab.LOCAL/'horizon-client-structures' + classes = export/'classes' + classes.mkdir(parents=True, exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + with (export/'export.log').open('w') as log: + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies, + '-d', str(classes), str(source)], check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) + subprocess.run(['java', '-Xmx1G', '-cp', str(classes)+os.pathsep+dependencies, + 'dev.horizonlab.parity.VanillaStructureBlockExporter', str(target)], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) + + +def prepare_worldgen(root, jars, local, libraries=None): """Write the chunk generator's resource bundle to root/worldgen (see GeneratorData::load).""" out = root / 'worldgen' out.mkdir(exist_ok=True) + # Structure templates: gzip NBT files under structure//.nbt. + with zipfile.ZipFile(jars['server']) as server: + prefix = 'data/minecraft/structure/' + for name in server.namelist(): + if name.startswith(prefix) and name.endswith('.nbt'): + relative = Path(name[len(prefix):]) + if relative.is_absolute() or '..' in relative.parts: + raise ValueError('Invalid structure path') + target = out/'structure'/'minecraft'/relative + data = server.read(name) + if not target.exists() or target.read_bytes() != data: + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) with zipfile.ZipFile(jars['server']) as server, zipfile.ZipFile(jars['client']) as client: for name, path in WORLDGEN_BUNDLES.items(): prefix = f'data/minecraft/{path}/' @@ -60,6 +91,9 @@ def prepare_worldgen(root, jars, local): blocks.mkdir(exist_ok=True) for name in names: (blocks/name).write_bytes((behavior/name).read_bytes()) + if libraries is not None: + blocks.mkdir(exist_ok=True) + export_structure_blocks(blocks/'structure-blocks.json', jars, libraries) else: print('Feature block behavior exports missing; run tools/test_simple_block_parity.py for full decoration') if presets is None: @@ -215,7 +249,7 @@ def main(): check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) (root/'render-definitions.json').write_bytes((export/'definitions.json').read_bytes()) (root/'occlusion.nbt').write_bytes((export/'occlusion.nbt').read_bytes()) - prepare_worldgen(root, jars, lab.LOCAL) + prepare_worldgen(root, jars, lab.LOCAL, libraries) count = 0 # The playable client needs every client asset (textures, models, fonts, GUI) # and every data-pack resource (worldgen, recipes, loot tables, tags). From f192d01eaa026802015e022033a9db0d096ae66d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 02:51:22 +0200 Subject: [PATCH 2/4] Generate jigsaw structure starts, references and terrain adaptation Port structure sets (random spread with frequency reducers and exclusion zones), vanilla start selection, JigsawPlacement (pool aliases, shuffled jigsaws by selection priority, placement-priority queue, free-space checks, expansion hack, rigid/terrain-matching junctions) and pool element placement. Proto generation computes per-chunk references within 8 chunks and feeds the beardifier into the noise fill; FEATURES places referenced starts per decoration step before that step's features. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../horizon-world/examples/chunkgen_bench.rs | 22 +- crates/horizon-world/src/worldgen.rs | 1 + .../horizon-world/src/worldgen/decoration.rs | 33 +- .../horizon-world/src/worldgen/generator.rs | 220 +++++ .../src/worldgen/generator_decoration.rs | 76 +- .../src/worldgen/generator_structures.rs | 152 ++++ .../horizon-world/src/worldgen/structure.rs | 2 + .../src/worldgen/structure/jigsaw.rs | 849 ++++++++++++++++++ .../src/worldgen/structure/start.rs | 620 +++++++++++++ 9 files changed, 1972 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-world/src/worldgen/generator_structures.rs create mode 100644 crates/horizon-world/src/worldgen/structure/jigsaw.rs create mode 100644 crates/horizon-world/src/worldgen/structure/start.rs 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(()) +} From c5fc4d7eb59258d5281168eb07e4572852fa0f80 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 03:19:08 +0200 Subject: [PATCH 3/4] Read 26.3 template block states and verify jigsaw starts against vanilla Templates store palette states as id/properties; reading only Name made every template block air. Add a vanilla oracle (structure placement, start selection and Structure.generate over a chunk rectangle), a bench mode dumping Rust starts in the same format, and a comparison script. For seed 0 over 97x97 chunks all 15 jigsaw starts (villages, trial chambers, trail ruins, abandoned camps) match vanilla piece for piece. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../horizon-world/examples/chunkgen_bench.rs | 77 +++++++++++++++ .../horizon-world/src/worldgen/generator.rs | 31 ++++++ .../src/worldgen/structure/jigsaw.rs | 18 +++- .../src/worldgen/structure/template.rs | 7 +- .../parity/VanillaStructureStartOracle.java | 95 +++++++++++++++++++ tools/compare_structure_starts.py | 55 +++++++++++ tools/structure_start_oracle.py | 35 +++++++ 7 files changed, 311 insertions(+), 7 deletions(-) create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java create mode 100644 tools/compare_structure_starts.py create mode 100644 tools/structure_start_oracle.py diff --git a/crates/horizon-world/examples/chunkgen_bench.rs b/crates/horizon-world/examples/chunkgen_bench.rs index e38b01392..f38de35df 100644 --- a/crates/horizon-world/examples/chunkgen_bench.rs +++ b/crates/horizon-world/examples/chunkgen_bench.rs @@ -146,6 +146,69 @@ fn verify(data: &std::sync::Arc, parity: &Path) -> Result<(), Err } } +/// Structure starts in the oracle's line format (VanillaStructureStartOracle). +fn dump_starts( + generator: &OverworldGenerator, + seed: i64, + [x0, z0, x1, z1]: [i32; 4], + out: &Path, +) -> Result<(), Error> { + use horizon_world::worldgen::structure::{Rotation, start::Piece}; + let _ = seed; + let mut worker = generator.worker(); + let mut lines = Vec::new(); + let start = Instant::now(); + for cx in x0..=x1 { + for cz in z0..=z1 { + for s in worker.structure_starts(ChunkPos::new(cx, cz)) { + let b = s.bounding_box; + lines.push(format!( + "start {cx} {cz} {} {} {} {} {} {} {} {}", + s.name, + b.min[0], + b.min[1], + b.min[2], + b.max[0], + b.max[1], + b.max[2], + s.pieces.len() + )); + for piece in &s.pieces { + let Piece::Pool(p) = piece; + let b = p.bounding_box; + let rotation = match p.rotation { + Rotation::None => "NONE", + Rotation::Clockwise90 => "CLOCKWISE_90", + Rotation::Clockwise180 => "CLOCKWISE_180", + Rotation::Counterclockwise90 => "COUNTERCLOCKWISE_90", + }; + lines.push(format!( + "piece minecraft:jigsaw {} {} {} {} {} {} {} {} {} {rotation} {} {}", + b.min[0], + b.min[1], + b.min[2], + b.max[0], + b.max[1], + b.max[2], + p.position[0], + p.position[1], + p.position[2], + p.ground_level_delta, + p.junctions.len() + )); + } + } + } + } + println!( + "structure starts for {} chunks in {:.2?}", + (x1 - x0 + 1) * (z1 - z0 + 1), + start.elapsed() + ); + fs::write(out, lines.join("\n") + "\n")?; + Ok(()) +} + /// Process CPU seconds (Linux), robust against other load on shared machines. fn cpu_seconds() -> f64 { fs::read_to_string("/proc/self/stat") @@ -198,6 +261,7 @@ fn main() -> Result<(), Error> { let (mut seed, mut size, mut threads, mut center) = (0i64, 16i32, 2usize, (0, 0)); let mut parity = None; let mut decorate = true; + let mut starts: Option<(i32, i32, i32, i32, PathBuf)> = None; while let Some(arg) = args.next() { let mut next = || args.next().expect("argument value"); match arg.as_str() { @@ -207,6 +271,15 @@ fn main() -> Result<(), Error> { "--center" => center = (next().parse()?, next().parse()?), "--verify" => parity = Some(PathBuf::from(next())), "--no-decorate" => decorate = false, + "--starts" => { + starts = Some(( + next().parse()?, + next().parse()?, + next().parse()?, + next().parse()?, + PathBuf::from(next()), + )) + } _ => return Err(format!("unknown argument {arg}").into()), } } @@ -220,6 +293,10 @@ fn main() -> Result<(), Error> { let start = Instant::now(); let generator = OverworldGenerator::new(data.clone(), seed)?; println!("seeded generator in {:.2?}", start.elapsed()); + if let Some((x0, z0, x1, z1, out)) = starts { + dump_starts(&generator, seed, [x0, z0, x1, z1], &out)?; + return Ok(()); + } let (x0, z0) = (center.0 - size / 2, center.1 - size / 2); let count = (size * size) as usize; let next = AtomicUsize::new(0); diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7a1708599..3a0b76529 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -1264,6 +1264,11 @@ trait SeededPipeline: Send + Sync { ) -> Result; fn data(&self) -> &Arc; fn sea_level(&self) -> i32; + fn structure_starts( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + ) -> Vec>; fn unsupported_features(&self) -> Vec<(String, String)>; } impl SeededPipeline for Pipeline @@ -1314,6 +1319,25 @@ where fn sea_level(&self) -> i32 { self.settings.sea_level } + fn structure_starts( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + ) -> Vec> { + match &self.structures { + Some(structures) => structures + .starts_at( + &mut StructureQueries { + pipeline: self, + worker, + valid: BTreeSet::new(), + }, + pos, + ) + .to_vec(), + None => Vec::new(), + } + } fn unsupported_features(&self) -> Vec<(String, String)> { self.decoration .as_ref() @@ -1452,6 +1476,13 @@ impl GeneratorWorker { self.state.timings.chunks += 1; result } + /// STRUCTURE_STARTS: the structure starts owned by a chunk (cached). + pub fn structure_starts( + &mut self, + pos: ChunkPos, + ) -> Vec> { + self.pipeline.structure_starts(&mut self.state, pos) + } pub fn stage_timings(&self) -> StageTimings { self.state.timings } diff --git a/crates/horizon-world/src/worldgen/structure/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs index 76035582e..005fab6d0 100644 --- a/crates/horizon-world/src/worldgen/structure/jigsaw.rs +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -345,9 +345,16 @@ impl Pools { 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()?, - ); + let element = + match PoolElement::decode(&entry["element"], resources, bindings, None) { + Ok(element) => Arc::new(element), + Err(error) => { + if std::env::var_os("HORIZON_JIGSAW_DEBUG").is_some() { + eprintln!("pool {name}: {error}"); + } + return None; + } + }; for _ in 0..entry["weight"].as_i64().unwrap_or(1) { templates.push(element.clone()); } @@ -687,12 +694,13 @@ impl Placer<'_, '_> { 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( + let jigsaws = source_element.shuffled_jigsaws( self.resources, source_position, source_rotation, random, - ) { + ); + 'jigsaws: for jigsaw in jigsaws { let direction = jigsaw.front; let s = step(direction); let target_pos: [i32; 3] = std::array::from_fn(|i| jigsaw.pos[i] + s[i]); diff --git a/crates/horizon-world/src/worldgen/structure/template.rs b/crates/horizon-world/src/worldgen/structure/template.rs index 8726d2b20..a95a68f46 100644 --- a/crates/horizon-world/src/worldgen/structure/template.rs +++ b/crates/horizon-world/src/worldgen/structure/template.rs @@ -66,14 +66,17 @@ pub(super) fn read_state(registry: &BlockRegistry, tag: &Tag) -> BlockStateId { let Tag::Compound(compound) = tag else { return air; }; - let Some(name) = string(get(compound, "Name")) else { + // 26.3 writes `id`/`properties`; older templates use `Name`/`Properties`. + let Some(name) = string(get(compound, "id")).or_else(|| string(get(compound, "Name"))) else { return air; }; let Some(default) = registry.default_state(&name) else { return air; }; let mut state = registry.state(default).unwrap().clone(); - if let Some(Tag::Compound(properties)) = get(compound, "Properties") { + if let Some(Tag::Compound(properties)) = + get(compound, "properties").or_else(|| get(compound, "Properties")) + { for (key, value) in properties { let (Tag::String(value), key) = (value, key.to_string_lossy()) else { continue; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java new file mode 100644 index 000000000..3b0818cc3 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java @@ -0,0 +1,95 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.TagLoader; +import net.minecraft.util.datafix.DataFixers; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelHeightAccessor; +import net.minecraft.world.level.biome.MultiNoiseBiomeSource; +import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterLists; +import net.minecraft.world.level.chunk.ChunkGeneratorStructureState; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.structure.*; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; +import net.minecraft.world.level.storage.LevelStorageSource; + +/** + * Original oracle: runs vanilla structure placement checks, start selection + * and Structure.generate (as ChunkGenerator.createStructures does for a fresh + * chunk) for a rectangle of overworld chunks and prints every valid start. + */ +public final class VanillaStructureStartOracle { + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion();Bootstrap.bootStrap(); + Path out=Path.of(args[0]);long seed=Long.parseLong(args[1]); + int x0=Integer.parseInt(args[2]),z0=Integer.parseInt(args[3]),x1=Integer.parseInt(args[4]),z1=Integer.parseInt(args[5]); + var repo=ServerPacksSource.createVanillaTrustedRepository();repo.reload();repo.setSelected(List.of("vanilla")); + var resources=new MultiPackResourceManager(PackType.SERVER_DATA,repo.openAllSelected()); + var layers=RegistryLayer.createRegistryAccess(); + var staticTags=TagLoader.loadTagsForExistingRegistries(resources,layers.getLayer(RegistryLayer.STATIC)); + var context=TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD),staticTags); + RegistryAccess.Frozen world=RegistryDataLoader.load(resources,context,RegistryDataLoader.WORLD_REGISTRIES,Runnable::run).join(); + staticTags.forEach(Registry.PendingTags::apply); + RegistryAccess access=layers.replaceFrom(RegistryLayer.WORLD,world).compositeAccess(); + var settings=world.lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow(NoiseGeneratorSettings.OVERWORLD); + var randomState=RandomState.create(world.lookupOrThrow(Registries.NOISE),seed,settings.value()); + var biomeSource=MultiNoiseBiomeSource.createFromPreset(world.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST).getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD)); + var generator=new NoiseBasedChunkGenerator(biomeSource,settings); + var state=ChunkGeneratorStructureState.createForNormal(randomState,seed,new ChunkPos(0,0),biomeSource,world.lookupOrThrow(Registries.STRUCTURE_SET)); + Path tmp=Files.createTempDirectory("horizon-structures"); + var storage=LevelStorageSource.createDefault(tmp).createAccess("oracle"); + var templates=new StructureTemplateManager(resources,storage,DataFixers.getDataFixer(),BuiltInRegistries.BLOCK); + LevelHeightAccessor height=LevelHeightAccessor.create(-64,384); + var climate=randomState.createClimateSampler(net.minecraft.world.level.levelgen.densityfunction.SamplerContext.builder().enableCaches().build()); + var structures=world.lookupOrThrow(Registries.STRUCTURE); + try(var w=new PrintWriter(Files.newBufferedWriter(out,StandardCharsets.UTF_8))) { + structures.listElements().forEach(h->w.println("registry "+h.key().identifier()+" "+h.value().step().ordinal())); + for(int cx=x0;cx<=x1;cx++)for(int cz=z0;cz<=z1;cz++) { + ChunkPos pos=new ChunkPos(cx,cz); + for(var set:state.possibleStructureSets()) { + var placement=set.value().placement();var entries=set.value().structures(); + if(!placement.isStructureChunk(state,cx,cz))continue; + var options=new ArrayList<>(entries); + WorldgenRandom random=new WorldgenRandom(new LegacyRandomSource(0L));random.setLargeFeatureSeed(seed,cx,cz); + int total=0;for(var o:options)total+=o.weight(); + while(!options.isEmpty()) { + StructureSet.StructureSelectionEntry selected;int index=0; + if(entries.size()==1){selected=options.get(0);} + else{int choice=random.nextInt(total);for(var o:options){choice-=o.weight();if(choice<0)break;index++;}selected=options.get(index);} + var structure=selected.structure(); + StructureStart start=structure.value().generate(structure,Level.OVERWORLD,access,generator,biomeSource,climate,randomState,templates,seed,pos,0,height,structure.value().biomes()::contains); + if(start.isValid()) { + var b=start.getBoundingBox(); + w.println("start "+cx+" "+cz+" "+structure.unwrapKey().get().identifier()+" "+b.minX()+" "+b.minY()+" "+b.minZ()+" "+b.maxX()+" "+b.maxY()+" "+b.maxZ()+" "+start.getPieces().size()); + for(var piece:start.getPieces()) { + var pb=piece.getBoundingBox(); + String extra=""; + if(piece instanceof PoolElementStructurePiece pool)extra=" "+pool.getPosition().getX()+" "+pool.getPosition().getY()+" "+pool.getPosition().getZ()+" "+pool.getRotation()+" "+pool.getGroundLevelDelta()+" "+pool.getJunctions().size()+" "+pool.getElement(); + w.println("piece "+BuiltInRegistries.STRUCTURE_PIECE.getKey(piece.getType())+" "+pb.minX()+" "+pb.minY()+" "+pb.minZ()+" "+pb.maxX()+" "+pb.maxY()+" "+pb.maxZ()+extra); + } + break; + } + if(entries.size()==1)break; + options.remove(index);total-=selected.weight(); + } + } + } + } + storage.close(); + System.exit(0); + } +} diff --git a/tools/compare_structure_starts.py b/tools/compare_structure_starts.py new file mode 100644 index 000000000..363e7b76f --- /dev/null +++ b/tools/compare_structure_starts.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Compare Rust structure starts (chunkgen_bench --starts) with the vanilla oracle. + +usage: compare_structure_starts.py VANILLA RUST [--all] +Pieces are compared by type, bounding box and (for jigsaw pieces) position, +rotation, ground level delta and junction count. Without --all, vanilla +starts of structure types Rust does not generate yet are only counted. +""" +import collections +import sys + + +def load(path): + starts = {} + current = None + for line in open(path): + t = line.split() + if not t: + continue + if t[0] == 'start': + current = (int(t[1]), int(t[2]), t[3]) + starts[current] = [' '.join(t[4:])] + elif t[0] == 'piece' and current: + starts[current].append(' '.join(t[1:14])) + return starts + + +def main(): + vanilla, rust = load(sys.argv[1]), load(sys.argv[2]) + generated = {k[2] for k in rust} + matched = 0 + missing = collections.Counter() + for key in sorted(vanilla): + if key not in rust: + missing[key[2]] += 1 + if key[2] in generated or '--all' in sys.argv: + print('missing', key) + continue + if vanilla[key] == rust[key]: + matched += 1 + continue + v, r = vanilla[key], rust[key] + print('DIFF', key, 'pieces', len(v) - 1, len(r) - 1) + for i, (a, b) in enumerate(zip(v, r)): + if a != b: + print(' first difference at line', i, '\n vanilla', a, '\n rust ', b) + break + for key in sorted(set(rust) - set(vanilla)): + print('extra', key) + print(f'{matched} of {len(vanilla)} vanilla starts match exactly; not generated by Rust:', dict(missing)) + return 0 if matched == len(rust) == sum(1 for k in vanilla if k[2] in generated) else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/structure_start_oracle.py b/tools/structure_start_oracle.py new file mode 100644 index 000000000..3382905a9 --- /dev/null +++ b/tools/structure_start_oracle.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Run the vanilla structure-start oracle for a seed and chunk rectangle. + +usage: structure_start_oracle.py OUT SEED X0 Z0 X1 Z1 +""" +import os +import subprocess +import sys +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def main(): + out, seed, x0, z0, x1, z1 = sys.argv[1:7] + lock, jars, libraries = base.verify_artifacts() + source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java' + build = lab.LOCAL/'structure-start-oracle' + classes = build/'classes' + classes.mkdir(parents=True, exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies, + '-d', str(classes), str(source)], check=True) + result = subprocess.run(['java', '-Xmx2G', '-cp', str(classes)+os.pathsep+dependencies, + 'dev.horizonlab.parity.VanillaStructureStartOracle', out, seed, x0, z0, x1, z1], + capture_output=True, text=True) + if result.returncode: + lines = [line for line in (result.stdout + result.stderr).splitlines() if 'Exception' in line or 'Caused' in line] + raise SystemExit('oracle failed: ' + ' | '.join(lines[:5])) + + +if __name__ == '__main__': + main() From 5732ba362c89255e8a42fecb9762bac7004d05c6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 03:39:16 +0200 Subject: [PATCH 4/4] Add piece-based structures: buried treasure, igloo, swamp hut, shipwreck, ocean ruin Port StructurePiece's orientation frame and block helpers, template pieces with data markers, chest/dispenser loot block entities and the five smaller legacy structures. Structure stubs use the chunk middle (block 8). For seed 0 over 97x97 chunks all 35 starts of implemented structure types match the vanilla oracle (pieces, boxes, positions). Co-Authored-By: Claude Opus 5.5 (1M context) --- .../horizon-world/examples/chunkgen_bench.rs | 15 +- .../horizon-world/src/worldgen/structure.rs | 3 + .../src/worldgen/structure/legacy.rs | 818 ++++++++++++++++++ .../src/worldgen/structure/ocean_ruin.rs | 353 ++++++++ .../src/worldgen/structure/simple.rs | 486 +++++++++++ .../src/worldgen/structure/start.rs | 159 +++- .../parity/VanillaStructureStartOracle.java | 16 + tools/structure_start_oracle.py | 6 +- 8 files changed, 1851 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-world/src/worldgen/structure/legacy.rs create mode 100644 crates/horizon-world/src/worldgen/structure/ocean_ruin.rs create mode 100644 crates/horizon-world/src/worldgen/structure/simple.rs diff --git a/crates/horizon-world/examples/chunkgen_bench.rs b/crates/horizon-world/examples/chunkgen_bench.rs index f38de35df..5c1c99400 100644 --- a/crates/horizon-world/examples/chunkgen_bench.rs +++ b/crates/horizon-world/examples/chunkgen_bench.rs @@ -174,7 +174,20 @@ fn dump_starts( s.pieces.len() )); for piece in &s.pieces { - let Piece::Pool(p) = piece; + let Piece::Pool(p) = piece else { + let b = piece.bounding_box(); + lines.push(format!( + "piece {} {} {} {} {} {} {}", + piece.type_name(), + b.min[0], + b.min[1], + b.min[2], + b.max[0], + b.max[1], + b.max[2] + )); + continue; + }; let b = p.bounding_box; let rotation = match p.rotation { Rotation::None => "NONE", diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index 5e10c7ec3..c5146d62a 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -2,7 +2,10 @@ //! and structure pieces. pub mod features; pub mod jigsaw; +pub mod legacy; +pub mod ocean_ruin; pub mod processor; +pub mod simple; pub mod start; pub mod template; diff --git a/crates/horizon-world/src/worldgen/structure/legacy.rs b/crates/horizon-world/src/worldgen/structure/legacy.rs new file mode 100644 index 000000000..d78b89b68 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/legacy.rs @@ -0,0 +1,818 @@ +//! Piece-based ("legacy") structure support: the StructurePiece helpers, +//! object-safe world/random access and template pieces. +use super::{ + BlockInfo, BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate, + processor::{PlaceSettings, Processor, ProcessorList, ProcessorRandom, place_in_world}, +}; +use crate::{ + chunk::BlockState, + fluid::FluidState, + heightmap::HeightmapType, + nbt::{Compound, JavaString, Tag}, + registry::BlockStateId, + worldgen::{ + feature::FeatureWorld, + placement::{PlacementContext, PlacementQueryError}, + }, +}; +use horizon_core::{ + geometry::Direction, + position::{BlockPos, ChunkPos}, + random::{LegacyRandom, RandomSource, position_seed}, +}; +use std::sync::{Arc, Mutex}; + +pub type Result = std::result::Result; + +/// The random draws legacy pieces make. +pub trait PieceRandom: ProcessorRandom { + fn boolean(&mut self) -> bool; + fn double(&mut self) -> f64; +} +impl PieceRandom for R { + fn boolean(&mut self) -> bool { + self.next_boolean() + } + fn double(&mut self) -> f64 { + self.next_double() + } +} + +/// Object-safe world access for piece post-processing. +pub trait PieceWorld { + fn block(&mut self, pos: [i32; 3]) -> Result; + fn set(&mut self, pos: [i32; 3], state: BlockStateId, flags: i32) -> Result; + fn fluid(&mut self, pos: [i32; 3]) -> Result; + fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result; + fn min_y(&mut self) -> Result; + fn max_y(&mut self) -> Result; + fn block_entity(&mut self, pos: [i32; 3], nbt: Compound) -> Result<()>; + fn post_process(&mut self, pos: [i32; 3]) -> Result<()>; + fn place_template( + &mut self, + resources: &StructureResources, + template: &StructureTemplate, + position: [i32; 3], + reference: [i32; 3], + settings: &mut PlaceSettings<'_>, + random: &mut dyn ProcessorRandom, + flags: i32, + ) -> Result; +} +impl PieceWorld for W { + fn block(&mut self, pos: [i32; 3]) -> Result { + self.block_state(pos) + } + fn set(&mut self, pos: [i32; 3], state: BlockStateId, flags: i32) -> Result { + self.set_block(pos, state, flags) + .map_err(|_| PlacementQueryError::Failed("piece write".into())) + } + fn fluid(&mut self, pos: [i32; 3]) -> Result { + self.fluid_state(pos) + } + fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result { + PlacementContext::height(self, kind, x, z) + } + fn min_y(&mut self) -> Result { + PlacementContext::min_y(self) + } + fn max_y(&mut self) -> Result { + PlacementContext::max_y(self) + } + fn block_entity(&mut self, pos: [i32; 3], nbt: Compound) -> Result<()> { + self.set_block_entity(pos, nbt) + } + fn post_process(&mut self, pos: [i32; 3]) -> Result<()> { + self.mark_postprocessing(pos) + } + fn place_template( + &mut self, + resources: &StructureResources, + template: &StructureTemplate, + position: [i32; 3], + reference: [i32; 3], + settings: &mut PlaceSettings<'_>, + random: &mut dyn ProcessorRandom, + flags: i32, + ) -> Result { + place_in_world( + self, + resources, + template, + position, + reference, + settings, + Some(random), + flags, + ) + } +} + +/// Everything a piece needs while post-processing one chunk. +pub struct PieceContext<'a> { + pub world: &'a mut dyn PieceWorld, + pub resources: &'a StructureResources, + pub random: &'a mut dyn PieceRandom, + pub chunk_box: BoundingBox, + pub chunk: ChunkPos, + pub reference: [i32; 3], +} +impl PieceContext<'_> { + pub fn state(&self, name: &str) -> BlockStateId { + state(self.resources, name, &[]) + } + pub fn state_with(&self, name: &str, properties: &[(&str, &str)]) -> BlockStateId { + state(self.resources, name, properties) + } + pub fn name(&self, state: BlockStateId) -> &str { + self.resources + .registry + .state(state) + .map(|s| s.name.as_str()) + .unwrap_or("") + } + pub fn is_block(&mut self, pos: [i32; 3], name: &str) -> Result { + let state = self.world.block(pos)?; + Ok(self.name(state) == name) + } + pub fn is_air(&self, state: BlockStateId) -> bool { + matches!( + self.name(state), + "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" + ) + } + /// BlockState.liquid(): water and lava blocks. + pub fn is_liquid(&self, state: BlockStateId) -> bool { + matches!(self.name(state), "minecraft:water" | "minecraft:lava") + } + pub fn property<'s>(&'s self, state: BlockStateId, key: &str) -> Option<&'s str> { + self.resources + .registry + .state(state) + .and_then(|s| s.properties.get(key)) + .map(String::as_str) + } + pub fn with_property(&self, state: BlockStateId, key: &str, value: &str) -> BlockStateId { + let Some(mut descriptor) = self.resources.registry.state(state).cloned() else { + return state; + }; + if let Some(slot) = descriptor.properties.get_mut(key) { + *slot = value.to_owned(); + } + self.resources.registry.id(&descriptor).unwrap_or(state) + } + /// Store a loot-table container's block entity (RandomizableContainer.setLootTable). + pub fn loot_table(&mut self, pos: [i32; 3], kind: &str, table: &str) -> Result<()> { + let seed = self.random.long(); + let mut nbt = Compound::new(); + nbt.insert("id".into(), Tag::String(kind.into())); + nbt.insert("LootTable".into(), Tag::String(table.into())); + nbt.insert("LootTableSeed".into(), Tag::Long(seed)); + self.world.block_entity(pos, nbt) + } +} +/// A state by block name and properties (missing properties keep defaults). +pub fn state( + resources: &StructureResources, + name: &str, + properties: &[(&str, &str)], +) -> BlockStateId { + let registry = resources.registry; + let mut descriptor = BlockState { + name: if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }, + properties: Default::default(), + }; + for (k, v) in properties { + descriptor + .properties + .insert((*k).to_owned(), (*v).to_owned()); + } + registry + .resolve(&descriptor) + .ok() + .or_else(|| registry.default_state(&descriptor.name)) + .unwrap_or_else(|| registry.default_state("minecraft:air").unwrap()) +} + +/// A placed structure piece. +pub trait LegacyPiece: std::fmt::Debug + Send + Sync { + fn bounding_box(&self) -> BoundingBox; + /// The vanilla StructurePieceType id, for diagnostics and comparisons. + fn type_name(&self) -> &'static str; + fn post_process(&self, context: &mut PieceContext<'_>) -> Result<()>; +} + +/// StructurePiece's orientation transform and block helpers. +#[derive(Clone, Copy, Debug)] +pub struct PieceFrame { + pub bounding_box: BoundingBox, + pub orientation: Option, + pub mirror: Mirror, + pub rotation: Rotation, +} +pub const HORIZONTAL: [Direction; 4] = [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, +]; +/// Direction.Plane.HORIZONTAL.getRandomDirection. +pub fn random_horizontal(random: &mut impl RandomSource) -> Direction { + HORIZONTAL[random.next_int_bound(4).unwrap_or(0) as usize] +} +pub fn make_bounding_box( + x: i32, + y: i32, + z: i32, + direction: Direction, + width: i32, + height: i32, + depth: i32, +) -> BoundingBox { + if matches!(direction, Direction::North | Direction::South) { + BoundingBox::new([x, y, z], [x + width - 1, y + height - 1, z + depth - 1]) + } else { + BoundingBox::new([x, y, z], [x + depth - 1, y + height - 1, z + width - 1]) + } +} +impl PieceFrame { + pub fn new(bounding_box: BoundingBox, orientation: Option) -> Self { + let (mirror, rotation) = match orientation { + Some(Direction::South) => (Mirror::LeftRight, Rotation::None), + Some(Direction::West) => (Mirror::LeftRight, Rotation::Clockwise90), + Some(Direction::East) => (Mirror::None, Rotation::Clockwise90), + _ => (Mirror::None, Rotation::None), + }; + Self { + bounding_box, + orientation, + mirror, + rotation, + } + } + pub fn world_x(&self, x: i32, z: i32) -> i32 { + match self.orientation { + Some(Direction::North | Direction::South) => self.bounding_box.min[0] + x, + Some(Direction::West) => self.bounding_box.max[0] - z, + Some(Direction::East) => self.bounding_box.min[0] + z, + _ => x, + } + } + pub fn world_y(&self, y: i32) -> i32 { + if self.orientation.is_none() { + y + } else { + y + self.bounding_box.min[1] + } + } + pub fn world_z(&self, x: i32, z: i32) -> i32 { + match self.orientation { + Some(Direction::North) => self.bounding_box.max[2] - z, + Some(Direction::South) => self.bounding_box.min[2] + z, + Some(Direction::West | Direction::East) => self.bounding_box.min[2] + x, + _ => z, + } + } + pub fn world_pos(&self, x: i32, y: i32, z: i32) -> [i32; 3] { + [self.world_x(x, z), self.world_y(y), self.world_z(x, z)] + } + /// StructurePiece.placeBlock (canBeReplaced is always true here). + pub fn place( + &self, + c: &mut PieceContext<'_>, + state: BlockStateId, + x: i32, + y: i32, + z: i32, + ) -> Result<()> { + let pos = self.world_pos(x, y, z); + if !c.chunk_box.is_inside(pos) { + return Ok(()); + } + let mut state = state; + if self.mirror != Mirror::None { + state = c.resources.transforms.mirror(state, self.mirror); + } + if self.rotation != Rotation::None { + state = c.resources.transforms.rotate(state, self.rotation); + } + c.world.set(pos, state, 2)?; + let fluid = c.world.fluid(pos)?; + if fluid.kind() != crate::fluid::FluidKind::Empty { + // scheduleTick(pos, fluid, 0) is a no-op for generation output. + } + if matches!( + c.name(state), + "minecraft:nether_brick_fence" + | "minecraft:torch" + | "minecraft:wall_torch" + | "minecraft:oak_fence" + | "minecraft:spruce_fence" + | "minecraft:dark_oak_fence" + | "minecraft:pale_oak_fence" + | "minecraft:acacia_fence" + | "minecraft:birch_fence" + | "minecraft:jungle_fence" + | "minecraft:ladder" + | "minecraft:iron_bars" + ) { + c.world.post_process(pos)?; + } + Ok(()) + } + pub fn get(&self, c: &mut PieceContext<'_>, x: i32, y: i32, z: i32) -> Result { + let pos = self.world_pos(x, y, z); + if c.chunk_box.is_inside(pos) { + c.world.block(pos) + } else { + Ok(c.state("air")) + } + } + pub fn is_interior(&self, c: &mut PieceContext<'_>, x: i32, y: i32, z: i32) -> Result { + let pos = self.world_pos(x, y + 1, z); + if !c.chunk_box.is_inside(pos) { + return Ok(false); + } + Ok(pos[1] + < c.world + .height(HeightmapType::OceanFloorWg, pos[0], pos[2])?) + } + #[allow(clippy::too_many_arguments)] + pub fn generate_box( + &self, + c: &mut PieceContext<'_>, + [x0, y0, z0]: [i32; 3], + [x1, y1, z1]: [i32; 3], + edge: BlockStateId, + fill: BlockStateId, + skip_air: bool, + ) -> Result<()> { + for y in y0..=y1 { + for x in x0..=x1 { + for z in z0..=z1 { + if skip_air { + let s = self.get(c, x, y, z)?; + if c.is_air(s) { + continue; + } + } + let interior = y != y0 && y != y1 && x != x0 && x != x1 && z != z0 && z != z1; + self.place(c, if interior { fill } else { edge }, x, y, z)?; + } + } + } + Ok(()) + } + /// generateBox with a block selector called as (random, x, y, z, edge). + pub fn generate_box_selector( + &self, + c: &mut PieceContext<'_>, + [x0, y0, z0]: [i32; 3], + [x1, y1, z1]: [i32; 3], + skip_air: bool, + selector: &mut dyn FnMut(&mut PieceContext<'_>, i32, i32, i32, bool) -> BlockStateId, + ) -> Result<()> { + for y in y0..=y1 { + for x in x0..=x1 { + for z in z0..=z1 { + if skip_air { + let s = self.get(c, x, y, z)?; + if c.is_air(s) { + continue; + } + } + let edge = y == y0 || y == y1 || x == x0 || x == x1 || z == z0 || z == z1; + let state = selector(c, x, y, z, edge); + self.place(c, state, x, y, z)?; + } + } + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + pub fn generate_maybe_box( + &self, + c: &mut PieceContext<'_>, + probability: f32, + [x0, y0, z0]: [i32; 3], + [x1, y1, z1]: [i32; 3], + edge: BlockStateId, + fill: BlockStateId, + skip_air: bool, + inside: bool, + ) -> Result<()> { + for y in y0..=y1 { + for x in x0..=x1 { + for z in z0..=z1 { + if c.random.float() > probability { + continue; + } + if skip_air { + let s = self.get(c, x, y, z)?; + if c.is_air(s) { + continue; + } + } + if inside && !self.is_interior(c, x, y, z)? { + continue; + } + let interior = y != y0 && y != y1 && x != x0 && x != x1 && z != z0 && z != z1; + self.place(c, if interior { fill } else { edge }, x, y, z)?; + } + } + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + pub fn maybe_block( + &self, + c: &mut PieceContext<'_>, + probability: f32, + x: i32, + y: i32, + z: i32, + state: BlockStateId, + ) -> Result<()> { + if c.random.float() < probability { + self.place(c, state, x, y, z)?; + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + pub fn upper_half_sphere( + &self, + c: &mut PieceContext<'_>, + [x0, y0, z0]: [i32; 3], + [x1, y1, z1]: [i32; 3], + fill: BlockStateId, + skip_air: bool, + ) -> Result<()> { + let dx = (x1 - x0 + 1) as f32; + let dy = (y1 - y0 + 1) as f32; + let dz = (z1 - z0 + 1) as f32; + let cx = x0 as f32 + dx / 2.; + let cz = z0 as f32 + dz / 2.; + for y in y0..=y1 { + let ny = (y - y0) as f32 / dy; + for x in x0..=x1 { + let nx = (x as f32 - cx) / (dx * 0.5); + for z in z0..=z1 { + let nz = (z as f32 - cz) / (dz * 0.5); + if skip_air { + let s = self.get(c, x, y, z)?; + if c.is_air(s) { + continue; + } + } + if nx * nx + ny * ny + nz * nz <= 1.05 { + self.place(c, fill, x, y, z)?; + } + } + } + } + Ok(()) + } + pub fn fill_column_down( + &self, + c: &mut PieceContext<'_>, + state: BlockStateId, + x: i32, + y: i32, + z: i32, + ) -> Result<()> { + let mut pos = self.world_pos(x, y, z); + if !c.chunk_box.is_inside(pos) { + return Ok(()); + } + let min = c.world.min_y()?; + loop { + let current = c.world.block(pos)?; + let replaceable = c.is_air(current) + || c.is_liquid(current) + || matches!( + c.name(current), + "minecraft:glow_lichen" | "minecraft:seagrass" | "minecraft:tall_seagrass" + ); + if !replaceable || pos[1] <= min + 1 { + break; + } + c.world.set(pos, state, 2)?; + pos[1] -= 1; + } + Ok(()) + } + /// StructurePiece.createChest at piece coordinates. + pub fn create_chest( + &self, + c: &mut PieceContext<'_>, + x: i32, + y: i32, + z: i32, + table: &str, + ) -> Result { + let pos = self.world_pos(x, y, z); + create_chest(c, pos, table, None) + } + #[allow(clippy::too_many_arguments)] + pub fn create_dispenser( + &self, + c: &mut PieceContext<'_>, + x: i32, + y: i32, + z: i32, + facing: Direction, + table: &str, + ) -> Result { + let pos = self.world_pos(x, y, z); + if !c.chunk_box.is_inside(pos) || c.is_block(pos, "minecraft:dispenser")? { + return Ok(false); + } + let state = c.state_with("dispenser", &[("facing", direction_name(facing))]); + self.place(c, state, x, y, z)?; + c.loot_table(pos, "minecraft:dispenser", table)?; + Ok(true) + } +} +pub fn direction_name(d: Direction) -> &'static str { + match d { + Direction::Down => "down", + Direction::Up => "up", + Direction::North => "north", + Direction::South => "south", + Direction::West => "west", + Direction::East => "east", + } +} +pub fn offset(pos: [i32; 3], d: Direction, n: i32) -> [i32; 3] { + let s = d.normal(); + [pos[0] + s[0] * n, pos[1] + s[1] * n, pos[2] + s[2] * n] +} +fn solid_render(c: &PieceContext<'_>, state: BlockStateId) -> bool { + c.resources.transforms.full_block(state) && !c.is_liquid(state) +} +/// StructurePiece.createChest with an absolute position. +pub fn create_chest( + c: &mut PieceContext<'_>, + pos: [i32; 3], + table: &str, + state: Option, +) -> Result { + if !c.chunk_box.is_inside(pos) || c.is_block(pos, "minecraft:chest")? { + return Ok(false); + } + let state = match state { + Some(s) => s, + None => reorient(c, pos, c.state("chest"))?, + }; + c.world.set(pos, state, 2)?; + c.loot_table(pos, "minecraft:chest", table)?; + Ok(true) +} +/// StructurePiece.reorient for chests (solid-render approximated by the +/// full collision cube of non-liquid blocks). +fn reorient(c: &mut PieceContext<'_>, pos: [i32; 3], state: BlockStateId) -> Result { + let mut solid: Option = None; + for d in HORIZONTAL { + let n = c.world.block(offset(pos, d, 1))?; + if c.name(n) == "minecraft:chest" { + return Ok(state); + } + if solid_render(c, n) { + if solid.is_some() { + solid = None; + break; + } + solid = Some(d); + } + } + if let Some(d) = solid { + return Ok(c.with_property(state, "facing", direction_name(opposite(d)))); + } + let mut facing = match c.property(state, "facing") { + Some("south") => Direction::South, + Some("east") => Direction::East, + Some("west") => Direction::West, + _ => Direction::North, + }; + let solid_at = |c: &mut PieceContext<'_>, d: Direction| -> Result { + let s = c.world.block(offset(pos, d, 1))?; + Ok(solid_render(c, s)) + }; + if solid_at(c, facing)? { + facing = opposite(facing); + } + if solid_at(c, facing)? { + facing = clockwise(facing); + } + if solid_at(c, facing)? { + facing = opposite(facing); + } + Ok(c.with_property(state, "facing", direction_name(facing))) +} +pub 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, + } +} +pub fn clockwise(d: Direction) -> Direction { + match d { + Direction::North => Direction::East, + Direction::East => Direction::South, + Direction::South => Direction::West, + Direction::West => Direction::North, + other => other, + } +} +pub fn counter_clockwise(d: Direction) -> Direction { + match d { + Direction::North => Direction::West, + Direction::West => Direction::South, + Direction::South => Direction::East, + Direction::East => Direction::North, + other => other, + } +} + +/// TemplateStructurePiece: one template with fixed settings; data markers +/// are handed to the owning structure. +#[derive(Debug)] +pub struct TemplatePiece { + pub type_name: &'static str, + pub template_name: String, + pub template: Arc, + pub position: [i32; 3], + pub rotation: Rotation, + pub mirror: Mirror, + pub pivot: [i32; 3], + pub processors: Arc, + pub waterlogging: bool, + /// Ignore structure blocks (and air, for ocean ruins) before processors. + pub ignore: Vec, + pub bounding_box: BoundingBox, + pub handler: TemplateHandler, + /// Per-piece state mutated by vanilla post-processing (e.g. ruined + /// portals record nothing; shipwrecks/igloos re-place at a height). + pub state: Mutex>, +} +#[derive(Clone, Copy, Debug)] +pub enum TemplateHandler { + Igloo, + Shipwreck { + beached: bool, + }, + OceanRuin { + warm: bool, + large: bool, + integrity: f32, + }, + Plain, +} +impl TemplatePiece { + #[allow(clippy::too_many_arguments)] + pub fn new( + type_name: &'static str, + template_name: &str, + template: Arc, + position: [i32; 3], + rotation: Rotation, + mirror: Mirror, + pivot: [i32; 3], + processors: Arc, + waterlogging: bool, + ignore: Vec, + handler: TemplateHandler, + ) -> Self { + Self { + bounding_box: template.bounding_box(position, rotation, pivot, mirror), + type_name, + template_name: template_name.to_owned(), + template, + position, + rotation, + mirror, + pivot, + processors, + waterlogging, + ignore, + handler, + state: Mutex::new(None), + } + } + pub fn settings(&self) -> PlaceSettings<'_> { + let mut s = PlaceSettings::new(self.rotation); + s.mirror = self.mirror; + s.pivot = self.pivot; + s.waterlogging = self.waterlogging; + s + } + /// TemplateStructurePiece.postProcess at a (possibly shifted) position; + /// returns the data markers (metadata, absolute position) on success. + pub fn place_at( + &self, + c: &mut PieceContext<'_>, + position: [i32; 3], + extra: &[Processor], + ) -> Result>> { + let ignore = Processor::BlockIgnore(self.ignore.iter().cloned().collect()); + let mut settings = self.settings(); + settings.bounding_box = Some(c.chunk_box); + settings.processors.push(&ignore); + settings.processors.extend(extra.iter()); + settings.processors.extend(self.processors.0.iter()); + let resources = c.resources; + let reference = c.reference; + if !c.world.place_template( + resources, + &self.template, + position, + reference, + &mut settings, + &mut *c.random, + 2, + )? { + return Ok(None); + } + let mut markers = Vec::new(); + let mut jigsaws = Vec::new(); + for info in filter_blocks(resources, &self.template, position, &settings) { + let name = c.name(info.state).to_owned(); + let Some(nbt) = &info.nbt else { continue }; + let text = |key: &str| match nbt.get(&JavaString::from(key)) { + Some(Tag::String(s)) => s.to_string_lossy(), + _ => String::new(), + }; + if name == "minecraft:structure_block" && text("mode").eq_ignore_ascii_case("data") { + markers.push((text("metadata"), info.pos)); + } else if name == "minecraft:jigsaw" { + let final_state = nbt + .get(&JavaString::from("final_state")) + .map(|_| text("final_state")) + .unwrap_or_else(|| "minecraft:air".into()); + jigsaws.push((info.pos, final_state)); + } + } + for (pos, final_state) in jigsaws { + let state = super::template::parse_state_string(resources.registry, &final_state) + .unwrap_or_else(|| c.state("air")); + c.world.set(pos, state, 3)?; + } + Ok(Some(markers)) + } +} +/// StructureTemplate.filterBlocks for structure and jigsaw blocks (palette +/// chosen by settings' random or a position seed), within the settings box. +fn filter_blocks( + resources: &StructureResources, + template: &StructureTemplate, + position: [i32; 3], + settings: &PlaceSettings<'_>, +) -> 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.palettes()[palette] + .blocks() + .iter() + .filter(|b| { + let name = resources + .registry + .state(b.state) + .map(|s| s.name.as_str()) + .unwrap_or(""); + name == "minecraft:structure_block" || name == "minecraft:jigsaw" + }) + .filter_map(|b| { + let relative = StructureTemplate::transform( + b.pos, + settings.mirror, + settings.rotation, + settings.pivot, + ); + let pos: [i32; 3] = std::array::from_fn(|i| relative[i] + position[i]); + settings + .bounding_box + .is_none_or(|bb| bb.is_inside(pos)) + .then(|| BlockInfo { + pos, + state: resources.transforms.rotate(b.state, settings.rotation), + nbt: b.nbt.clone(), + }) + }) + .collect() +} diff --git a/crates/horizon-world/src/worldgen/structure/ocean_ruin.rs b/crates/horizon-world/src/worldgen/structure/ocean_ruin.rs new file mode 100644 index 000000000..270c51633 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/ocean_ruin.rs @@ -0,0 +1,353 @@ +//! Ocean ruins (OceanRuinPieces). +use super::{ + BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate, + legacy::{PieceContext, Result, TemplateHandler, TemplatePiece}, + processor::ProcessorList, +}; +use crate::{ + fluid::FluidKind, + heightmap::HeightmapType, + worldgen::{DecodeError, block_feature::FeatureBlockBindings}, +}; +use horizon_core::random::RandomSource; +use std::sync::Arc; + +const WARM: [&str; 8] = [ + "warm_1", "warm_2", "warm_3", "warm_4", "warm_5", "warm_6", "warm_7", "warm_8", +]; +const BIG_WARM: [&str; 4] = ["big_warm_4", "big_warm_5", "big_warm_6", "big_warm_7"]; +const BRICK: [&str; 8] = [ + "brick_1", "brick_2", "brick_3", "brick_4", "brick_5", "brick_6", "brick_7", "brick_8", +]; +const CRACKED: [&str; 8] = [ + "cracked_1", + "cracked_2", + "cracked_3", + "cracked_4", + "cracked_5", + "cracked_6", + "cracked_7", + "cracked_8", +]; +const MOSSY: [&str; 8] = [ + "mossy_1", "mossy_2", "mossy_3", "mossy_4", "mossy_5", "mossy_6", "mossy_7", "mossy_8", +]; +const BIG_BRICK: [&str; 4] = ["big_brick_1", "big_brick_2", "big_brick_3", "big_brick_8"]; +const BIG_CRACKED: [&str; 4] = [ + "big_cracked_1", + "big_cracked_2", + "big_cracked_3", + "big_cracked_8", +]; +const BIG_MOSSY: [&str; 4] = ["big_mossy_1", "big_mossy_2", "big_mossy_3", "big_mossy_8"]; + +/// Mth.nextInt(random, min, max). +pub fn next_int(random: &mut impl RandomSource, min: i32, max: i32) -> i32 { + if min >= max { + min + } else { + random.next_int_bound(max - min + 1).unwrap_or(0) + min + } +} + +pub struct OceanRuinConfig { + pub warm: bool, + pub large_probability: f32, + pub cluster_probability: f32, +} +fn processors( + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + integrity: f32, + warm: bool, +) -> std::result::Result, DecodeError> { + let (candidate, replacement, table) = if warm { + ( + "minecraft:sand", + "minecraft:suspicious_sand", + "minecraft:archaeology/ocean_ruin_warm", + ) + } else { + ( + "minecraft:gravel", + "minecraft:suspicious_gravel", + "minecraft:archaeology/ocean_ruin_cold", + ) + }; + let json = serde_json::json!({"processors": [ + {"processor_type": "minecraft:block_rot", "integrity": integrity}, + {"processor_type": "minecraft:block_ignore", "blocks": [{"id": "minecraft:structure_block"}, {"id": "minecraft:air"}]}, + {"processor_type": "minecraft:capped", "limit": 5, "delegate": {"processor_type": "minecraft:rule", "rules": [{ + "input_predicate": {"predicate_type": "minecraft:block_match", "block": candidate}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": {"id": replacement}, + "block_entity_modifier": {"type": "minecraft:append_loot", "loot_table": table} + }]}} + ]}); + Ok(Arc::new(ProcessorList::decode( + &json.to_string(), + resources, + bindings, + )?)) +} +#[allow(clippy::too_many_arguments)] +fn piece( + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + name: &str, + position: [i32; 3], + rotation: Rotation, + integrity: f32, + warm: bool, + large: bool, +) -> Option { + let name = format!("minecraft:underwater_ruin/{name}"); + Some(TemplatePiece::new( + "minecraft:orp", + &name, + resources.template(&name)?, + position, + rotation, + Mirror::None, + [0; 3], + processors(resources, bindings, integrity, warm).ok()?, + true, + Vec::new(), + TemplateHandler::OceanRuin { + warm, + large, + integrity, + }, + )) +} +#[allow(clippy::too_many_arguments)] +fn add_piece( + out: &mut Vec, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + position: [i32; 3], + rotation: Rotation, + random: &mut impl RandomSource, + config: &OceanRuinConfig, + large: bool, + integrity: f32, +) -> Option<()> { + if config.warm { + let names: &[&str] = if large { &BIG_WARM } else { &WARM }; + let name = names[random.next_int_bound(names.len() as i32).ok()? as usize]; + out.push(piece( + resources, bindings, name, position, rotation, integrity, true, large, + )?); + } else { + let (bricks, cracked, mossy): (&[&str], &[&str], &[&str]) = if large { + (&BIG_BRICK, &BIG_CRACKED, &BIG_MOSSY) + } else { + (&BRICK, &CRACKED, &MOSSY) + }; + let idx = random.next_int_bound(bricks.len() as i32).ok()? as usize; + out.push(piece( + resources, + bindings, + bricks[idx], + position, + rotation, + integrity, + false, + large, + )?); + out.push(piece( + resources, + bindings, + cracked[idx], + position, + rotation, + 0.7, + false, + large, + )?); + out.push(piece( + resources, bindings, mossy[idx], position, rotation, 0.5, false, large, + )?); + } + Some(()) +} +/// OceanRuinPieces.addPieces. +pub fn pieces( + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + position: [i32; 3], + rotation: Rotation, + random: &mut impl RandomSource, + config: &OceanRuinConfig, +) -> Option> { + let mut out = Vec::new(); + let large = random.next_float() <= config.large_probability; + let integrity = if large { 0.9 } else { 0.8 }; + add_piece( + &mut out, resources, bindings, position, rotation, random, config, large, integrity, + )?; + if large && random.next_float() <= config.cluster_probability { + let parent = [position[0], 90, position[2]]; + let corner = StructureTemplate::transform([15, 0, 15], Mirror::None, rotation, [0; 3]); + let corner = [ + corner[0] + parent[0], + corner[1] + parent[1], + corner[2] + parent[2], + ]; + let parent_box = BoundingBox::from_corners(parent, corner); + let origin = [ + parent[0].min(corner[0]), + parent[1], + parent[2].min(corner[2]), + ]; + let mut all = vec![ + [ + origin[0] - 16 + next_int(random, 1, 8), + origin[1], + origin[2] + 16 + next_int(random, 1, 7), + ], + [ + origin[0] - 16 + next_int(random, 1, 8), + origin[1], + origin[2] + next_int(random, 1, 7), + ], + [ + origin[0] - 16 + next_int(random, 1, 8), + origin[1], + origin[2] - 16 + next_int(random, 4, 8), + ], + [ + origin[0] + next_int(random, 1, 7), + origin[1], + origin[2] + 16 + next_int(random, 1, 7), + ], + [ + origin[0] + next_int(random, 1, 7), + origin[1], + origin[2] - 16 + next_int(random, 4, 6), + ], + [ + origin[0] + 16 + next_int(random, 1, 7), + origin[1], + origin[2] + 16 + next_int(random, 3, 8), + ], + [ + origin[0] + 16 + next_int(random, 1, 7), + origin[1], + origin[2] + next_int(random, 1, 7), + ], + [ + origin[0] + 16 + next_int(random, 1, 7), + origin[1], + origin[2] - 16 + next_int(random, 4, 8), + ], + ]; + let ruins = next_int(random, 4, 8); + for _ in 0..ruins { + if all.is_empty() { + continue; + } + let idx = random.next_int_bound(all.len() as i32).ok()? as usize; + let pos = all.remove(idx); + let next_rotation = Rotation::random(random); + let c = StructureTemplate::transform([5, 0, 6], Mirror::None, next_rotation, [0; 3]); + let next_box = + BoundingBox::from_corners(pos, [c[0] + pos[0], c[1] + pos[1], c[2] + pos[2]]); + if !next_box.intersects(&parent_box) { + add_piece( + &mut out, + resources, + bindings, + pos, + next_rotation, + random, + config, + false, + 0.8, + )?; + } + } + } + Some(out) +} + +fn is_water(c: &mut PieceContext<'_>, pos: [i32; 3]) -> Result { + Ok(matches!( + c.world.fluid(pos)?.kind(), + FluidKind::Water | FluidKind::FlowingWater + )) +} +/// OceanRuinPiece.postProcess. +pub fn post_process(piece: &TemplatePiece, c: &mut PieceContext<'_>) -> Result<()> { + let TemplateHandler::OceanRuin { large, .. } = piece.handler else { + return Ok(()); + }; + let [x, _, z] = piece.position; + let mut position = [x, c.world.height(HeightmapType::OceanFloorWg, x, z)?, z]; + let size = piece.template.size; + let r = StructureTemplate::transform( + [size[0] - 1, 0, size[2] - 1], + Mirror::None, + piece.rotation, + [0; 3], + ); + let corner = [r[0] + position[0], r[1] + position[1], r[2] + position[2]]; + // getHeight over the footprint. + let mut new_y = position[1]; + let mut min_y = 512; + let top_y = new_y - 1; + let mut area = 0; + let min_world = c.world.min_y()?; + for px in position[0].min(corner[0])..=position[0].max(corner[0]) { + for pz in position[2].min(corner[2])..=position[2].max(corner[2]) { + let mut floor = position[1] - 1; + loop { + let state = c.world.block([px, floor, pz])?; + let ice = c + .resources + .block_tags + .get("minecraft:ice") + .is_some_and(|t| t.contains(c.name(state))); + let open = c.is_air(state) || is_water(c, [px, floor, pz])? || ice; + if !(open && floor > min_world + 1) { + break; + } + floor -= 1; + } + min_y = min_y.min(floor); + if floor < top_y - 2 { + area += 1; + } + } + } + let width = (position[0] - corner[0]).abs(); + if top_y - min_y > 2 && area > width - 2 { + new_y = min_y + 1; + } + position[1] = new_y; + if let Some(markers) = piece.place_at(c, position, &[])? { + for (marker, pos) in markers { + if marker == "chest" { + let water = if is_water(c, pos)? { "true" } else { "false" }; + let chest = c.state_with("chest", &[("waterlogged", water)]); + c.world.set(pos, chest, 2)?; + let table = if large { + "minecraft:chests/underwater_ruin_big" + } else { + "minecraft:chests/underwater_ruin_small" + }; + c.loot_table(pos, "minecraft:chest", table)?; + } else if marker == "drowned" { + // The drowned entity is not created; its marker block is cleared. + let sea = 63; + let state = if pos[1] > sea { + c.state("air") + } else { + c.state("water") + }; + c.world.set(pos, state, 2)?; + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/src/worldgen/structure/simple.rs b/crates/horizon-world/src/worldgen/structure/simple.rs new file mode 100644 index 000000000..31794f9e3 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/simple.rs @@ -0,0 +1,486 @@ +//! Small piece-based structures: buried treasure, igloo, swamp hut, shipwreck. +use super::{ + BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate, + legacy::{ + LegacyPiece, PieceContext, PieceFrame, Result, TemplateHandler, TemplatePiece, + create_chest, make_bounding_box, offset, random_horizontal, + }, + processor::ProcessorList, +}; +use crate::heightmap::HeightmapType; +use horizon_core::{geometry::Direction, random::RandomSource}; +use std::sync::{Arc, Mutex}; + +fn empty_processors() -> Arc { + Arc::new(ProcessorList::default()) +} + +#[derive(Debug)] +pub struct BuriedTreasurePiece { + pub position: [i32; 3], +} +impl LegacyPiece for BuriedTreasurePiece { + fn bounding_box(&self) -> BoundingBox { + BoundingBox::new(self.position, self.position) + } + fn type_name(&self) -> &'static str { + "minecraft:btp" + } + fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> { + let [x, _, z] = self.position; + let mut pos = [x, c.world.height(HeightmapType::OceanFloorWg, x, z)?, z]; + let min = c.world.min_y()?; + while pos[1] > min { + let current = c.world.block(pos)?; + let below = c.world.block(offset(pos, Direction::Down, 1))?; + if matches!( + c.name(below), + "minecraft:sandstone" + | "minecraft:stone" + | "minecraft:andesite" + | "minecraft:granite" + | "minecraft:diorite" + ) { + let soft = if !c.is_air(current) && !c.is_liquid(current) { + current + } else { + c.state("sand") + }; + for d in Direction::ALL { + let relative = offset(pos, d, 1); + let state = c.world.block(relative)?; + if c.is_air(state) || c.is_liquid(state) { + let under = c.world.block(offset(relative, Direction::Down, 1))?; + if (c.is_air(under) || c.is_liquid(under)) && d != Direction::Up { + c.world.set(relative, below, 3)?; + } else { + c.world.set(relative, soft, 3)?; + } + } + } + create_chest(c, pos, "minecraft:chests/buried_treasure", None)?; + return Ok(()); + } + pos[1] -= 1; + } + Ok(()) + } +} + +pub const IGLOO_TOP: &str = "minecraft:igloo/top"; +const IGLOO_MIDDLE: &str = "minecraft:igloo/middle"; +const IGLOO_BOTTOM: &str = "minecraft:igloo/bottom"; +fn igloo_pivot(name: &str) -> [i32; 3] { + match name { + IGLOO_TOP => [3, 5, 5], + IGLOO_MIDDLE => [1, 3, 1], + _ => [3, 6, 7], + } +} +fn igloo_offset(name: &str) -> [i32; 3] { + match name { + IGLOO_TOP => [0, 0, 0], + IGLOO_MIDDLE => [2, -3, 4], + _ => [0, -3, -2], + } +} +/// IglooPieces.addPieces. +pub fn igloo_pieces( + resources: &StructureResources, + position: [i32; 3], + rotation: Rotation, + random: &mut impl RandomSource, +) -> Option> { + let piece = |name: &str, depth: i32| -> Option { + let o = igloo_offset(name); + Some(TemplatePiece::new( + "minecraft:iglu", + name, + resources.template(name)?, + [ + position[0] + o[0], + position[1] + o[1] - depth, + position[2] + o[2], + ], + rotation, + Mirror::None, + igloo_pivot(name), + empty_processors(), + false, + vec!["minecraft:structure_block".into()], + TemplateHandler::Igloo, + )) + }; + let mut pieces = Vec::new(); + if random.next_double() < 0.5 { + let depth = random.next_int_bound(8).unwrap_or(0) + 4; + pieces.push(piece(IGLOO_BOTTOM, depth * 3)?); + for i in 0..depth - 1 { + pieces.push(piece(IGLOO_MIDDLE, i * 3)?); + } + } + pieces.push(piece(IGLOO_TOP, 0)?); + Some(pieces) +} + +const SHIPWRECK_BEACHED: [&str; 11] = [ + "with_mast", + "sideways_full", + "sideways_fronthalf", + "sideways_backhalf", + "rightsideup_full", + "rightsideup_fronthalf", + "rightsideup_backhalf", + "with_mast_degraded", + "rightsideup_full_degraded", + "rightsideup_fronthalf_degraded", + "rightsideup_backhalf_degraded", +]; +const SHIPWRECK_OCEAN: [&str; 20] = [ + "with_mast", + "upsidedown_full", + "upsidedown_fronthalf", + "upsidedown_backhalf", + "sideways_full", + "sideways_fronthalf", + "sideways_backhalf", + "rightsideup_full", + "rightsideup_fronthalf", + "rightsideup_backhalf", + "with_mast_degraded", + "upsidedown_full_degraded", + "upsidedown_fronthalf_degraded", + "upsidedown_backhalf_degraded", + "sideways_full_degraded", + "sideways_fronthalf_degraded", + "sideways_backhalf_degraded", + "rightsideup_full_degraded", + "rightsideup_fronthalf_degraded", + "rightsideup_backhalf_degraded", +]; +/// ShipwreckPieces.addRandomPiece. +pub fn shipwreck_piece( + resources: &StructureResources, + position: [i32; 3], + rotation: Rotation, + random: &mut impl RandomSource, + beached: bool, +) -> Option { + let names: &[&str] = if beached { + &SHIPWRECK_BEACHED + } else { + &SHIPWRECK_OCEAN + }; + let name = format!( + "minecraft:shipwreck/{}", + names[random.next_int_bound(names.len() as i32).ok()? as usize] + ); + Some(TemplatePiece::new( + "minecraft:shipwreck", + &name, + resources.template(&name)?, + position, + rotation, + Mirror::None, + [4, 0, 15], + empty_processors(), + true, + vec!["minecraft:structure_block".into(), "minecraft:air".into()], + TemplateHandler::Shipwreck { beached }, + )) +} +pub fn shipwreck_too_big(template: &StructureTemplate) -> bool { + template.size[0] > 32 || template.size[1] > 32 +} + +impl LegacyPiece for TemplatePiece { + fn bounding_box(&self) -> BoundingBox { + self.bounding_box + } + fn type_name(&self) -> &'static str { + self.type_name + } + fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> { + match self.handler { + TemplateHandler::Plain => { + self.place_at(c, self.position, &[])?; + } + TemplateHandler::Igloo => { + let o = igloo_offset(&self.template_name); + let entrance_relative = StructureTemplate::transform( + [3 - o[0], 0, -o[2]], + Mirror::None, + self.rotation, + self.pivot, + ); + let entrance = [ + self.position[0] + entrance_relative[0], + 0, + self.position[2] + entrance_relative[2], + ]; + let height = + c.world + .height(HeightmapType::WorldSurfaceWg, entrance[0], entrance[2])?; + let position = [ + self.position[0], + self.position[1] + height - 90 - 1, + self.position[2], + ]; + if let Some(markers) = self.place_at(c, position, &[])? { + for (marker, pos) in markers { + if marker == "chest" { + c.world.set(pos, c.state("air"), 3)?; + let below = offset(pos, Direction::Down, 1); + if c.is_block(below, "minecraft:chest")? { + c.loot_table( + below, + "minecraft:chest", + "minecraft:chests/igloo_chest", + )?; + } + } + } + } + if self.template_name == IGLOO_TOP { + let r = StructureTemplate::transform( + [3, 0, 5], + Mirror::None, + self.rotation, + self.pivot, + ); + let trapdoor = [position[0] + r[0], position[1] + r[1], position[2] + r[2]]; + let below = c.world.block(offset(trapdoor, Direction::Down, 1))?; + if !c.is_air(below) && c.name(below) != "minecraft:ladder" { + c.world.set(trapdoor, c.state("snow_block"), 3)?; + } + } + } + TemplateHandler::Shipwreck { beached } => { + let adjusted = *self.state.lock().unwrap(); + let y = match adjusted { + Some(y) => y, + None if shipwreck_too_big(&self.template) => self.position[1], + None => { + let kind = if beached { + HeightmapType::WorldSurfaceWg + } else { + HeightmapType::OceanFloorWg + }; + let size = self.template.size; + let mut min = c.world.max_y()? + 1; + let mut mean = 0; + let base = size[0] * size[2]; + if base == 0 { + mean = c.world.height(kind, self.position[0], self.position[2])?; + } else { + for x in self.position[0]..self.position[0] + size[0] { + for z in self.position[2]..self.position[2] + size[2] { + let h = c.world.height(kind, x, z)?; + mean += h; + min = min.min(h); + } + } + mean /= base; + } + let y = if beached { + min - size[1] / 2 - c.random.int(3) + } else { + mean + }; + *self.state.lock().unwrap() = Some(y); + y + } + }; + let position = [self.position[0], y, self.position[2]]; + if let Some(markers) = self.place_at(c, position, &[])? { + for (marker, pos) in markers { + let table = match marker.as_str() { + "map_chest" => "minecraft:chests/shipwreck_map", + "treasure_chest" => "minecraft:chests/shipwreck_treasure", + "supply_chest" => "minecraft:chests/shipwreck_supply", + _ => continue, + }; + let below = offset(pos, Direction::Down, 1); + let state = c.world.block(below)?; + if c.resources.transforms.loot_container(state) { + let kind = c.name(state).to_owned(); + c.loot_table(below, &kind, table)?; + } + } + } + } + TemplateHandler::OceanRuin { .. } => { + super::ocean_ruin::post_process(self, c)?; + } + } + Ok(()) + } +} + +/// ScatteredFeaturePiece: an oriented box whose height is fixed on first use. +#[derive(Debug)] +pub struct Scattered { + pub frame: Mutex, + pub width: i32, + pub height: i32, + pub depth: i32, + pub height_position: Mutex, +} +impl Scattered { + pub fn new( + west: i32, + floor: i32, + north: i32, + width: i32, + height: i32, + depth: i32, + direction: Direction, + ) -> Self { + Self { + frame: Mutex::new(PieceFrame::new( + make_bounding_box(west, floor, north, direction, width, height, depth), + Some(direction), + )), + width, + height, + depth, + height_position: Mutex::new(-1), + } + } + pub fn frame(&self) -> PieceFrame { + *self.frame.lock().unwrap() + } + /// updateAverageGroundHeight over the part of the box inside the chunk. + pub fn average_ground(&self, c: &mut PieceContext<'_>, offset: i32) -> Result { + if *self.height_position.lock().unwrap() >= 0 { + return Ok(true); + } + let b = self.frame().bounding_box; + let (mut total, mut count) = (0, 0); + for z in b.min[2]..=b.max[2] { + for x in b.min[0]..=b.max[0] { + if c.chunk_box.is_inside([x, 64, z]) { + total += c + .world + .height(HeightmapType::MotionBlockingNoLeaves, x, z)?; + count += 1; + } + } + } + if count == 0 { + return Ok(false); + } + let h = total / count; + *self.height_position.lock().unwrap() = h; + let mut frame = self.frame.lock().unwrap(); + frame.bounding_box = + frame + .bounding_box + .moved([0, h - frame.bounding_box.min[1] + offset, 0]); + Ok(true) + } + /// updateHeightPositionToLowestGroundHeight over the whole box. + pub fn lowest_ground(&self, c: &mut PieceContext<'_>, offset: i32) -> Result { + if *self.height_position.lock().unwrap() >= 0 { + return Ok(true); + } + let b = self.frame().bounding_box; + let mut lowest = c.world.max_y()? + 1; + for z in b.min[2]..=b.max[2] { + for x in b.min[0]..=b.max[0] { + lowest = lowest.min( + c.world + .height(HeightmapType::MotionBlockingNoLeaves, x, z)?, + ); + } + } + *self.height_position.lock().unwrap() = lowest; + let mut frame = self.frame.lock().unwrap(); + frame.bounding_box = + frame + .bounding_box + .moved([0, lowest - frame.bounding_box.min[1] + offset, 0]); + Ok(true) + } +} + +#[derive(Debug)] +pub struct SwampHutPiece { + pub base: Scattered, +} +impl SwampHutPiece { + pub fn new(random: &mut impl RandomSource, west: i32, north: i32) -> Self { + let direction = random_horizontal(random); + Self { + base: Scattered::new(west, 64, north, 7, 7, 9, direction), + } + } +} +impl LegacyPiece for SwampHutPiece { + fn bounding_box(&self) -> BoundingBox { + self.base.frame().bounding_box + } + fn type_name(&self) -> &'static str { + "minecraft:tesh" + } + fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> { + if !self.base.average_ground(c, 0)? { + return Ok(()); + } + let f = self.base.frame(); + let planks = c.state("spruce_planks"); + let log = c.state("oak_log"); + for (a, b) in [ + ([1, 1, 1], [5, 1, 7]), + ([1, 4, 2], [5, 4, 7]), + ([2, 1, 0], [4, 1, 0]), + ([2, 2, 2], [3, 3, 2]), + ([1, 2, 3], [1, 3, 6]), + ([5, 2, 3], [5, 3, 6]), + ([2, 2, 7], [4, 3, 7]), + ] { + f.generate_box(c, a, b, planks, planks, false)?; + } + for (a, b) in [ + ([1, 0, 2], [1, 3, 2]), + ([5, 0, 2], [5, 3, 2]), + ([1, 0, 7], [1, 3, 7]), + ([5, 0, 7], [5, 3, 7]), + ] { + f.generate_box(c, a, b, log, log, false)?; + } + let fence = c.state("oak_fence"); + let air = c.state("air"); + f.place(c, fence, 2, 3, 2)?; + f.place(c, fence, 3, 3, 7)?; + f.place(c, air, 1, 3, 4)?; + f.place(c, air, 5, 3, 4)?; + f.place(c, air, 5, 3, 5)?; + f.place(c, c.state("potted_red_mushroom"), 1, 3, 5)?; + f.place(c, c.state("crafting_table"), 3, 2, 6)?; + f.place(c, c.state("cauldron"), 4, 2, 6)?; + f.place(c, fence, 1, 2, 1)?; + f.place(c, fence, 5, 2, 1)?; + let stairs = |c: &PieceContext<'_>, facing: &str, shape: &str| { + c.state_with("spruce_stairs", &[("facing", facing), ("shape", shape)]) + }; + let north = stairs(c, "north", "straight"); + let east = stairs(c, "east", "straight"); + let west = stairs(c, "west", "straight"); + let south = stairs(c, "south", "straight"); + f.generate_box(c, [0, 4, 1], [6, 4, 1], north, north, false)?; + f.generate_box(c, [0, 4, 2], [0, 4, 7], east, east, false)?; + f.generate_box(c, [6, 4, 2], [6, 4, 7], west, west, false)?; + f.generate_box(c, [0, 4, 8], [6, 4, 8], south, south, false)?; + f.place(c, stairs(c, "north", "outer_right"), 0, 4, 1)?; + f.place(c, stairs(c, "north", "outer_left"), 6, 4, 1)?; + f.place(c, stairs(c, "south", "outer_left"), 0, 4, 8)?; + f.place(c, stairs(c, "south", "outer_right"), 6, 4, 8)?; + for z in [2, 7] { + for x in [1, 5] { + f.fill_column_down(c, log, x, -1, z)?; + } + } + Ok(()) + } +} diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index b7c693c51..32c838a54 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -3,6 +3,7 @@ use super::{ BoundingBox, StructureResources, jigsaw::{JigsawConfig, JigsawContext, PoolPiece, Pools, Projection, assemble}, + legacy::{LegacyPiece, PieceContext}, }; use crate::{ heightmap::HeightmapType, @@ -58,6 +59,17 @@ pub struct JigsawDef { #[derive(Debug)] pub enum StructureKind { Jigsaw(JigsawDef), + BuriedTreasure, + Igloo, + SwampHut, + Shipwreck { + beached: bool, + }, + OceanRuin { + warm: bool, + large: f32, + cluster: f32, + }, /// A structure type whose generator is not implemented yet. Unsupported(String), } @@ -160,6 +172,17 @@ impl StructureRegistry { padding: pair(v.get("dimension_padding"), "bottom", "top", 0), waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"), }), + "minecraft:buried_treasure" => StructureKind::BuriedTreasure, + "minecraft:igloo" => StructureKind::Igloo, + "minecraft:swamp_hut" => StructureKind::SwampHut, + "minecraft:shipwreck" => StructureKind::Shipwreck { + beached: v["is_beached"].as_bool().unwrap_or(false), + }, + "minecraft:ocean_ruin" => StructureKind::OceanRuin { + warm: v["biome_temp"].as_str() == Some("warm"), + large: v["large_probability"].as_f64().unwrap_or(0.) as f32, + cluster: v["cluster_probability"].as_f64().unwrap_or(0.) as f32, + }, other => StructureKind::Unsupported(other.to_owned()), }; defs.push(StructureDef { @@ -312,13 +335,52 @@ fn reduce(method: Reduction, seed: i64, salt: i32, x: i32, z: i32, probability: #[derive(Debug)] pub enum Piece { Pool(PoolPiece), + Legacy(Box), } impl Piece { pub fn bounding_box(&self) -> BoundingBox { match self { Self::Pool(p) => p.bounding_box, + Self::Legacy(p) => p.bounding_box(), } } + pub fn type_name(&self) -> &'static str { + match self { + Self::Pool(_) => "minecraft:jigsaw", + Self::Legacy(p) => p.type_name(), + } + } +} +fn legacy(pieces: Vec) -> Vec { + pieces + .into_iter() + .map(|p| Piece::Legacy(Box::new(p))) + .collect() +} +/// Structure.onTopOfChunkCenter: the start position, or None when no valid +/// biome can exist in the chunk-center column. +fn top_of_chunk_center( + context: &mut impl StartContext, + chunk: ChunkPos, + kind: HeightmapType, +) -> Option<[i32; 3]> { + let (x, z) = (chunk.x * 16 + 8, chunk.z * 16 + 8); + let (min, max) = (context.min_y(), context.max_y()); + if !context.column_has_valid_biome(x, z, min - 1, max) { + return None; + } + Some([x, context.base_height(x, z, kind) - 1, z]) +} +fn first_occupied(context: &mut impl StartContext, x: i32, z: i32) -> i32 { + context.base_height(x, z, HeightmapType::WorldSurfaceWg) - 1 +} +fn corner_heights(context: &mut impl StartContext, x: i32, sx: i32, z: i32, sz: i32) -> [i32; 4] { + [ + first_occupied(context, x, z), + first_occupied(context, x, z + sz), + first_occupied(context, x + sx, z), + first_occupied(context, x + sx, z + sz), + ] } #[derive(Debug)] pub struct StructureStart { @@ -445,6 +507,80 @@ fn try_generate( pieces.into_iter().map(Piece::Pool).collect::>(), ) } + StructureKind::BuriedTreasure => { + let stub = top_of_chunk_center(context, chunk, HeightmapType::OceanFloorWg)?; + let piece = super::simple::BuriedTreasurePiece { + position: [chunk.x * 16 + 9, 90, chunk.z * 16 + 9], + }; + (stub, legacy(vec![piece])) + } + StructureKind::Igloo => { + let stub = top_of_chunk_center(context, chunk, HeightmapType::WorldSurfaceWg)?; + let rotation = super::Rotation::random(&mut random); + let pieces = super::simple::igloo_pieces( + resources, + [chunk.x * 16, 90, chunk.z * 16], + rotation, + &mut random, + )?; + (stub, legacy(pieces)) + } + StructureKind::SwampHut => { + let stub = top_of_chunk_center(context, chunk, HeightmapType::WorldSurfaceWg)?; + let piece = super::simple::SwampHutPiece::new(&mut random, chunk.x * 16, chunk.z * 16); + (stub, legacy(vec![piece])) + } + StructureKind::Shipwreck { beached } => { + let kind = if *beached { + HeightmapType::WorldSurfaceWg + } else { + HeightmapType::OceanFloorWg + }; + let stub = top_of_chunk_center(context, chunk, kind)?; + let rotation = super::Rotation::random(&mut random); + let piece = super::simple::shipwreck_piece( + resources, + [chunk.x * 16, 90, chunk.z * 16], + rotation, + &mut random, + *beached, + )?; + if super::simple::shipwreck_too_big(&piece.template) { + let b = piece.bounding_box; + let [sx, _, sz] = b.span(); + let heights = corner_heights(context, b.min[0], sx, b.min[2], sz); + let height = if *beached { + let min = heights.into_iter().min().unwrap_or(0); + min - piece.template.size[1] / 2 - random.next_int_bound(3).unwrap_or(0) + } else { + heights.iter().sum::() / 4 + }; + *piece.state.lock().unwrap() = Some(height); + } + (stub, legacy(vec![piece])) + } + StructureKind::OceanRuin { + warm, + large, + cluster, + } => { + let stub = top_of_chunk_center(context, chunk, HeightmapType::OceanFloorWg)?; + let rotation = super::Rotation::random(&mut random); + let config = super::ocean_ruin::OceanRuinConfig { + warm: *warm, + large_probability: *large, + cluster_probability: *cluster, + }; + let pieces = super::ocean_ruin::pieces( + resources, + bindings, + [chunk.x * 16, 90, chunk.z * 16], + rotation, + &mut random, + &config, + )?; + (stub, legacy(pieces)) + } StructureKind::Unsupported(_) => return None, }; let quart = position.map(|v| v >> 2); @@ -544,7 +680,15 @@ pub fn beardifier( if !near { continue; } - let Piece::Pool(pool) = piece; + let Piece::Pool(pool) = piece else { + rigids.push(RigidPiece { + bounds: StructureBounds::new(b.min, b.max)?, + adjustment, + ground_level_delta: 0, + }); + include(b, &mut any); + continue; + }; if pool.element.projection() == Projection::Rigid { rigids.push(RigidPiece { bounds: StructureBounds::new(b.min, b.max)?, @@ -581,7 +725,7 @@ pub fn beardifier( /// StructureStart.placeInChunk for pieces intersecting the chunk's writable box. #[allow(clippy::too_many_arguments)] -pub fn place_in_chunk( +pub fn place_in_chunk( start: &StructureStart, world: &mut W, resources: &StructureResources, @@ -613,6 +757,17 @@ pub fn place_in_chunk( place_feature, )?; } + Piece::Legacy(p) => { + let mut context = PieceContext { + world, + resources, + random, + chunk_box, + chunk: ChunkPos::new(chunk_box.min[0] >> 4, chunk_box.min[2] >> 4), + reference, + }; + p.post_process(&mut context)?; + } } } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java index 3b0818cc3..c2a226a3c 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java @@ -58,11 +58,20 @@ public final class VanillaStructureStartOracle { var structures=world.lookupOrThrow(Registries.STRUCTURE); try(var w=new PrintWriter(Files.newBufferedWriter(out,StandardCharsets.UTF_8))) { structures.listElements().forEach(h->w.println("registry "+h.key().identifier()+" "+h.value().step().ordinal())); + if(System.getenv("HORIZON_HEIGHTS")!=null)for(String p:System.getenv("HORIZON_HEIGHTS").split(";")){ + String[] xz=p.split(",");int x=Integer.parseInt(xz[0]),z=Integer.parseInt(xz[1]); + int floor=generator.getBaseHeight(x,z,Heightmap.Types.OCEAN_FLOOR_WG,height,randomState),surface=generator.getBaseHeight(x,z,Heightmap.Types.WORLD_SURFACE_WG,height,randomState); + var resolver=biomeSource.createResolver(climate); + StringBuilder biomes=new StringBuilder(); + for(int qy=(floor-12)>>2;qy<=(floor+8)>>2;qy++)biomes.append(" "+qy+":"+resolver.getNoiseBiome(x>>2,qy,z>>2).unwrapKey().get().identifier().getPath()); + w.println("height "+x+" "+z+" "+floor+" "+surface+biomes); + } for(int cx=x0;cx<=x1;cx++)for(int cz=z0;cz<=z1;cz++) { ChunkPos pos=new ChunkPos(cx,cz); for(var set:state.possibleStructureSets()) { var placement=set.value().placement();var entries=set.value().structures(); if(!placement.isStructureChunk(state,cx,cz))continue; + if(System.getenv("HORIZON_PLACED")!=null)w.println("placed "+cx+" "+cz+" "+set.unwrapKey().get().identifier()); var options=new ArrayList<>(entries); WorldgenRandom random=new WorldgenRandom(new LegacyRandomSource(0L));random.setLargeFeatureSeed(seed,cx,cz); int total=0;for(var o:options)total+=o.weight(); @@ -72,6 +81,13 @@ public final class VanillaStructureStartOracle { else{int choice=random.nextInt(total);for(var o:options){choice-=o.weight();if(choice<0)break;index++;}selected=options.get(index);} var structure=selected.structure(); StructureStart start=structure.value().generate(structure,Level.OVERWORLD,access,generator,biomeSource,climate,randomState,templates,seed,pos,0,height,structure.value().biomes()::contains); + if(System.getenv("HORIZON_PLACED")!=null){ + w.println("generate "+structure.unwrapKey().get().identifier()+" "+start.isValid()); + var ctx=new Structure.GenerationContext(access,generator,biomeSource,climate,randomState,templates,seed,pos,height,structure.value().biomes()::contains); + try{var m=Structure.class.getDeclaredMethod("findGenerationPoint",Structure.GenerationContext.class);m.setAccessible(true); + var stub=(java.util.Optional)m.invoke(structure.value(),ctx); + stub.ifPresent(st->{var sp=((Structure.GenerationStub)st).position();w.println("stub "+sp+" "+ctx.biomeResolver().getNoiseBiome(sp.getX()>>2,sp.getY()>>2,sp.getZ()>>2).unwrapKey().get().identifier());});}catch(Exception e){w.println("err "+e);} + } if(start.isValid()) { var b=start.getBoundingBox(); w.println("start "+cx+" "+cz+" "+structure.unwrapKey().get().identifier()+" "+b.minX()+" "+b.minY()+" "+b.minZ()+" "+b.maxX()+" "+b.maxY()+" "+b.maxZ()+" "+start.getPieces().size()); diff --git a/tools/structure_start_oracle.py b/tools/structure_start_oracle.py index 3382905a9..61ab19c61 100644 --- a/tools/structure_start_oracle.py +++ b/tools/structure_start_oracle.py @@ -21,8 +21,10 @@ def main(): classes = build/'classes' classes.mkdir(parents=True, exist_ok=True) dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies, - '-d', str(classes), str(source)], check=True) + compiled = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies, + '-d', str(classes), str(source)], capture_output=True, text=True) + if compiled.returncode: + raise SystemExit('javac failed:\n' + compiled.stderr[-3000:]) result = subprocess.run(['java', '-Xmx2G', '-cp', str(classes)+os.pathsep+dependencies, 'dev.horizonlab.parity.VanillaStructureStartOracle', out, seed, x0, z0, x1, z1], capture_output=True, text=True)