From 497cb8e0e36cc7be7f8308730f245600756e2fed Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 19:14:23 +0200 Subject: [PATCH] Add production noise-chunk generator, worldgen resource bundle and bench GeneratorData loads a worldgen bundle (written by prepare_native_client.py to the client resource dir) once; OverworldGenerator binds a seed and shares compiled samplers across threads; GeneratorWorker generates vanilla BIOMES..TERRAIN proto chunks (noise fill with aquifers, material surface, carvers) that match the material-stage parity dumps. Decoration is stubbed. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../horizon-world/examples/chunkgen_bench.rs | 370 +++++ crates/horizon-world/src/worldgen.rs | 2 + .../horizon-world/src/worldgen/generator.rs | 1185 +++++++++++++++++ .../src/worldgen/generator_decoration.rs | 27 + tools/prepare_native_client.py | 43 +- 5 files changed, 1626 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-world/examples/chunkgen_bench.rs create mode 100644 crates/horizon-world/src/worldgen/generator.rs create mode 100644 crates/horizon-world/src/worldgen/generator_decoration.rs diff --git a/crates/horizon-world/examples/chunkgen_bench.rs b/crates/horizon-world/examples/chunkgen_bench.rs new file mode 100644 index 000000000..484237780 --- /dev/null +++ b/crates/horizon-world/examples/chunkgen_bench.rs @@ -0,0 +1,370 @@ +//! Chunk generation throughput and sanity map. +//! +//! chunkgen_bench [--seed S] [--size N] [--threads T] +//! [--center CX CZ] [--verify ] [--no-decorate] +use horizon_core::position::ChunkPos; +use horizon_world::{ + DATA_VERSION, + heightmap::HeightmapType, + nbt::Tag, + registry::BlockRegistry, + worldgen::generator::{ + DecorateStats, GeneratorData, GeneratorWorker, OverworldGenerator, ProtoChunk, StageTimings, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{BufRead, BufReader}, + path::{Path, PathBuf}, + sync::{ + Mutex, + atomic::{AtomicUsize, Ordering}, + }, + time::Instant, +}; + +type Error = Box; + +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(o) => { + Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { + let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + facts["states"] + .as_array() + .unwrap() + .iter() + .map(|v| tag(&v[4])) + .collect(), + ), + ), + ("defaults", tag(&facts["defaults"])), + ]))?; + Ok(Box::leak(Box::new(registry))) +} + +/// The material-stage fixture's chunk dump format. +fn dump(chunk: &ProtoChunk) -> Vec { + let terrain = &chunk.terrain; + let mut out = Vec::new(); + for section in 0..terrain.height() as usize / 16 { + out.push(format!("section {section}")); + let data = terrain.section(section).unwrap(); + for y in 0..16 { + for z in 0..16 { + let mut line = String::from("blocks"); + for x in 0..16 { + line += &format!(" {}", data.get((y << 8) | (z << 4) | x).unwrap().0); + } + out.push(line); + } + } + } + for kind in [HeightmapType::WorldSurfaceWg, HeightmapType::OceanFloorWg] { + out.push(format!("heightmap {}", kind.name())); + for word in terrain.heightmap(kind).unwrap().raw_data() { + out.push(format!("{word:x}")); + } + } + for (section, offsets) in terrain.postprocessing().iter().enumerate() { + out.push(format!("post {section} {}", offsets.len())); + out.extend(offsets.iter().map(u16::to_string)); + } + out +} + +/// Compare generated chunks with vanilla's post-carver dumps in server.txt. +fn verify(data: &std::sync::Arc, parity: &Path) -> Result<(), Error> { + let cases = [ + (-1i64, -2, 3), + (0x0123_4567_89ab_cdef, 1_875_000, -1_875_000), + ]; + let mut expected = Vec::new(); + for (seed, x, z) in cases { + let generator = OverworldGenerator::new(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")?; + } + expected.push((seed, lines)); + } + let mut matched = vec![false; expected.len()]; + let mut lines = BufReader::new(fs::File::open(parity.join("server.txt"))?).lines(); + let mut candidates = 0; + while let Some(line) = lines.next() { + if line? != "generatedcarving ok" { + continue; + } + candidates += 1; + // Each candidate dump is followed by other output; compare per case. + let mut active = (0..expected.len()).collect::>(); + let length = expected.iter().map(|(_, e)| e.len()).max().unwrap_or(0); + for i in 0..length { + let Some(line) = lines.next() else { break }; + let line = line?; + active.retain(|&c| { + let expected = &expected[c].1; + if i == expected.len() { + matched[c] = true; + } + i < expected.len() && expected[i] == line + }); + if active.is_empty() { + break; + } + } + for c in active { + matched[c] = true; + } + } + for ((seed, _), ok) in expected.iter().zip(&matched) { + println!( + "verify seed {seed}: {}", + if *ok { "MATCH" } else { "MISMATCH" } + ); + } + println!("({candidates} vanilla generated-terrain dumps scanned)"); + if matched.iter().all(|m| *m) { + Ok(()) + } else { + Err("generated chunks differ from vanilla".into()) + } +} + +fn glyph(name: &str) -> char { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + match name { + "water" => '~', + "lava" => '!', + "grass_block" => '"', + "sand" | "suspicious_sand" => '.', + "red_sand" => ',', + "sandstone" | "red_sandstone" => '=', + "stone" | "deepslate" | "andesite" | "diorite" | "granite" | "tuff" => '#', + "gravel" => ':', + "dirt" | "coarse_dirt" | "rooted_dirt" => 'd', + "podzol" => 'p', + "mycelium" => 'm', + "mud" => 'u', + "snow" | "snow_block" | "powder_snow" => 's', + "ice" | "packed_ice" | "blue_ice" => 'i', + "clay" => 'c', + "calcite" => 'C', + _ if name.ends_with("terracotta") => 't', + _ if name.ends_with("leaves") => '*', + _ if name.ends_with("log") || name.ends_with("wood") => '|', + _ if name.contains("grass") || name.contains("fern") || name.contains("flower") => '\'', + _ => '?', + } +} + +fn main() -> Result<(), Error> { + let mut args = std::env::args().skip(1); + let resources = PathBuf::from(args.next().expect("client resource directory")); + let (mut seed, mut size, mut threads, mut center) = (0i64, 16i32, 2usize, (0, 0)); + let mut parity = None; + let mut decorate = true; + while let Some(arg) = args.next() { + let mut next = || args.next().expect("argument value"); + match arg.as_str() { + "--seed" => seed = next().parse()?, + "--size" => size = next().parse()?, + "--threads" => threads = next().parse()?, + "--center" => center = (next().parse()?, next().parse()?), + "--verify" => parity = Some(PathBuf::from(next())), + "--no-decorate" => decorate = false, + _ => return Err(format!("unknown argument {arg}").into()), + } + } + let start = Instant::now(); + let registry = registry(&resources)?; + let data = GeneratorData::load(&resources.join("worldgen"), registry)?; + println!("loaded resources in {:.2?}", start.elapsed()); + if let Some(parity) = parity { + verify(&data, &parity)?; + } + let start = Instant::now(); + let generator = OverworldGenerator::new(data.clone(), seed)?; + println!("seeded generator in {:.2?}", start.elapsed()); + let (x0, z0) = (center.0 - size / 2, center.1 - size / 2); + let count = (size * size) as usize; + let next = AtomicUsize::new(0); + let slots: Vec>> = (0..count).map(|_| Mutex::new(None)).collect(); + let timings = Mutex::new(Vec::new()); + let start = Instant::now(); + std::thread::scope(|scope| -> Result<(), Error> { + let handles = (0..threads) + .map(|_| { + scope.spawn(|| -> Result<(), Error> { + let mut worker = generator.worker(); + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= count { + timings.lock().unwrap().push(worker.stage_timings()); + return Ok(()); + } + let pos = ChunkPos::new(x0 + (i as i32 % size), z0 + (i as i32 / size)); + *slots[i].lock().unwrap() = Some(worker.generate_proto(pos)?); + } + }) + }) + .collect::>(); + handles.into_iter().try_for_each(|h| h.join().unwrap()) + })?; + let elapsed = start.elapsed(); + println!( + "generated {count} proto chunks with {threads} threads in {elapsed:.2?}: {:.1} chunks/s ({:.1} ms/chunk/thread)", + count as f64 / elapsed.as_secs_f64(), + elapsed.as_secs_f64() * 1000. * threads as f64 / count as f64 + ); + let timings = timings.into_inner().unwrap(); + let per_chunk = |f: fn(&StageTimings) -> std::time::Duration| { + timings + .iter() + .map(f) + .sum::() + .as_secs_f64() + * 1000. + / count as f64 + }; + println!( + " per chunk: biomes {:.2} ms, noise {:.2} ms, surface {:.2} ms, carvers {:.2} ms", + per_chunk(|t| t.biomes), + per_chunk(|t| t.noise), + per_chunk(|t| t.surface), + per_chunk(|t| t.carvers) + ); + let mut chunks: Vec> = slots + .into_iter() + .map(|slot| slot.into_inner().unwrap()) + .collect(); + if decorate && size >= 3 { + let totals = Mutex::new(DecorateStats::default()); + let start = Instant::now(); + let mut decorated = 0; + // Disjoint 3×3 regions per phase can be decorated concurrently. + for phase in 0..9 { + let mut regions = Vec::new(); + for z in 1..size - 1 { + for x in 1..size - 1 { + if (x % 3) * 3 + z % 3 != phase { + continue; + } + let mut region = Vec::with_capacity(9); + for dz in -1..=1 { + for dx in -1..=1 { + region + .push(chunks[((z + dz) * size + x + dx) as usize].take().unwrap()); + } + } + regions.push(((x, z), region)); + } + } + decorated += regions.len(); + let queue = Mutex::new(regions); + let done = Mutex::new(Vec::new()); + std::thread::scope(|scope| -> Result<(), Error> { + let handles = (0..threads) + .map(|_| { + scope.spawn(|| -> Result<(), Error> { + let mut worker: GeneratorWorker = generator.worker(); + loop { + let Some((at, region)) = queue.lock().unwrap().pop() else { + return Ok(()); + }; + let mut region: [ProtoChunk; 9] = + region.try_into().map_err(|_| "region size")?; + let stats = worker.decorate(&mut region)?; + let mut totals = totals.lock().unwrap(); + totals.placed += stats.placed; + totals.unsupported += stats.unsupported; + totals.failed += stats.failed; + totals.skipped.extend(stats.skipped); + drop(totals); + done.lock().unwrap().push((at, region)); + } + }) + }) + .collect::>(); + handles.into_iter().try_for_each(|h| h.join().unwrap()) + })?; + for ((x, z), region) in done.into_inner().unwrap() { + for (i, chunk) in region.into_iter().enumerate() { + let (dx, dz) = (i as i32 % 3 - 1, i as i32 / 3 - 1); + chunks[((z + dz) * size + x + dx) as usize] = Some(chunk); + } + } + } + let elapsed = start.elapsed(); + let totals = totals.into_inner().unwrap(); + println!( + "decorated {decorated} chunks in {elapsed:.2?}: {:.1} chunks/s; feature roots placed {}, unsupported {}, failed {}", + decorated as f64 / elapsed.as_secs_f64(), + totals.placed, + totals.unsupported, + totals.failed + ); + if !totals.skipped.is_empty() { + println!( + "skipped roots: {}", + totals.skipped.into_iter().collect::>().join(" ") + ); + } + } + let mut legend = BTreeMap::>::new(); + let step = (size * 16 / 96).max(1); + for bz in (0..size * 16).step_by(step as usize) { + let mut row = String::new(); + for bx in (0..size * 16).step_by(step as usize) { + let chunk = chunks[((bz / 16) * size + bx / 16) as usize] + .as_ref() + .unwrap(); + let (x, z) = ( + chunk.position().x * 16 + bx % 16, + chunk.position().z * 16 + bz % 16, + ); + let y = chunk.surface_height(x, z) - 1; + let name = chunk.block_name(x, y, z).to_owned(); + let c = glyph(&name); + *legend.entry(c).or_default().entry(name).or_default() += 1; + row.push(c); + } + println!("{row}"); + } + for (c, names) in legend { + let mut names = names.into_iter().collect::>(); + names.sort_by_key(|(_, n)| std::cmp::Reverse(*n)); + let names = names + .into_iter() + .take(4) + .map(|(n, _)| n) + .collect::>(); + println!(" {c} {}", names.join(" ")); + } + let middle = chunks[(size / 2 * size + size / 2) as usize] + .as_ref() + .unwrap(); + let p = middle.position(); + println!( + "biome at center ({}, 64, {}): {}", + p.x * 16, + p.z * 16, + middle.biome_at(p.x * 16, 64, p.z * 16) + ); + Ok(()) +} diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index ed126b40e..a9828cc18 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -33,6 +33,8 @@ pub mod feature_graph; pub mod feature_region; pub mod feature_sort; pub mod fluid_predicate; +pub mod generator; +mod generator_decoration; pub mod height_provider; pub mod material_condition; pub mod material_extensions; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs new file mode 100644 index 000000000..876f1dbb9 --- /dev/null +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -0,0 +1,1185 @@ +//! Production noise-chunk generation for one dimension of a world preset. +//! +//! `GeneratorData` holds seed-independent resources parsed once from a bundle +//! directory (see `GeneratorData::load`). `OverworldGenerator` binds a world seed +//! and is shared across threads; each thread owns a `GeneratorWorker`. +//! `generate_proto` runs vanilla's BIOMES and TERRAIN statuses (noise fill with +//! aquifers, material surface, carvers) and primes the post-terrain heightmaps. +//! `decorate` runs the FEATURES status for the center of a 3×3 neighborhood with +//! whatever feature algorithms are implemented; structures are not generated. +use super::{ + DecodeError, + anchor::WorldGenerationContext, + aquifer::{ + AquiferConfig, AquiferField, AquiferSamplers, DisabledAquifer, GlobalFluidPicker, + NoiseBasedAquifer, RegistryAquiferBlockStates, + }, + biome::BiomeId, + biome_chunk::{BiomeChunk, BiomeRegion}, + biome_source::{BiomeSourceCatalog, ResolvedBiomeSource}, + biome_temperature::{BiomeTemperature, BiomeTemperatureSettings}, + carver::{CarverCatalog, WorldCarver, generate_carving_mask}, + carving::{CarvingBlocks, apply_carving_mask}, + climate::{ClimateSampler, quantize}, + decode_noise, + density::DensityRegistry, + material_condition::{ + MaterialConditionRegistry, MaterialRule, MaterialRuleError, MaterialRuleLibrary, + MaterialSurfaceQueries, + }, + material_extensions::{ExtensionBlocks, ExtensionNoises, MaterialExtensions}, + material_stage::{SurfaceInputs, TopMaterialInputs, build_surface}, + material_surface::{ClayBandBlocks, MaterialSurface}, + router::{NoiseRouter, RouterField, RouterSamplers}, + tags::TagDefinitions, + terrain::{PreLightChunkStage, TerrainAquifer, TerrainBlockStates, TerrainChunk, fill_noise}, +}; +use crate::{ + heightmap::{HeightmapState, HeightmapType}, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::{ + biome::{BiomeZoom, obfuscate_seed}, + density::{DensitySampler, SamplerContext}, + noise::{DensityVolume, Noise}, + position::{BlockPos, ChunkPos}, + random::{LegacyRandom, PositionalRandom, RandomSource, XoroshiroRandom}, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + fs, io, + path::Path, + sync::{Arc, Mutex}, +}; + +#[derive(Debug)] +pub enum GeneratorError { + Io(io::Error), + Decode(DecodeError), + /// A resource is missing or inconsistent with the block registry. + Resource(String), + /// A generation stage failed; the chunk is incomplete. + Stage(&'static str, String), +} +impl std::fmt::Display for GeneratorError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Io(e) => e.fmt(f), + Self::Decode(e) => e.fmt(f), + Self::Resource(e) => write!(f, "invalid generator resources: {e}"), + Self::Stage(stage, e) => write!(f, "{stage} failed: {e}"), + } + } +} +impl std::error::Error for GeneratorError {} +impl From for GeneratorError { + fn from(e: io::Error) -> Self { + Self::Io(e) + } +} +impl From for GeneratorError { + fn from(e: DecodeError) -> Self { + Self::Decode(e) + } +} +impl From for GeneratorError { + fn from(e: serde_json::Error) -> Self { + Self::Decode(e.into()) + } +} +fn stage(name: &'static str) -> impl FnOnce(E) -> GeneratorError { + move |e| GeneratorError::Stage(name, e.to_string()) +} +fn resource(message: impl Into) -> GeneratorError { + GeneratorError::Resource(message.into()) +} + +/// Heightmap-relevant block behavior, one entry per registry state. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct GenBlockState { + pub air: bool, + pub air_block: bool, + pub fluid: bool, + pub motion: bool, + pub no_leaves: bool, +} +impl HeightmapState for GenBlockState { + fn is_air(self) -> bool { + self.air + } + fn is_air_block(self) -> bool { + self.air_block + } + fn has_fluid(self) -> bool { + self.fluid + } + fn blocks_motion_in_heightmap(self) -> bool { + self.motion + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.no_leaves + } +} +/// Shared, cheaply cloned state table bound into every generated chunk. +#[derive(Clone, Debug)] +pub struct GenBlockStates(Arc<[GenBlockState]>); +impl GenBlockStates { + pub fn get(&self, id: BlockStateId) -> GenBlockState { + self.0.get(id.0 as usize).copied().unwrap_or_default() + } +} +impl TerrainBlockStates for GenBlockStates { + type State = GenBlockState; + fn heightmap_state(&self, id: BlockStateId) -> GenBlockState { + self.get(id) + } +} + +/// Feature resources for the FEATURES status, keyed by resource identifier. +pub(super) struct FeatureResources { + pub(super) features: BTreeMap, + pub(super) placed: BTreeMap, + pub(super) feature_tags: BTreeMap, + pub(super) fluid_tags: BTreeMap>, +} + +/// Seed-independent generation resources, loaded once and shared by every +/// generator. Biome identities are indices into the sorted biome registry. +pub struct GeneratorData { + registry: &'static BlockRegistry, + states: GenBlockStates, + integers: BTreeSet<(String, String)>, + noises: BTreeMap, + densities: BTreeMap, + rules: BTreeMap, + settings: BTreeMap, + presets: BTreeMap, + world_presets: BTreeMap, + conditions: MaterialConditionRegistry, + source_catalog: BiomeSourceCatalog, + biome_names: Vec>, + biome_ids: BTreeMap, + biome_json: Vec, + temperatures: Vec, + biome_carvers: Vec>>, + carving_blocks: CarvingBlocks, + pub(super) block_tags: BTreeMap>, + pub(super) biome_tags: BTreeMap>, + pub(super) feature_resources: Option, +} +type Bundle = BTreeMap; +fn read_bundle(dir: &Path, name: &str) -> Result { + let path = dir.join(format!("{name}.json")); + let text = + fs::read_to_string(&path).map_err(|e| resource(format!("{}: {e}", path.display())))?; + Ok(serde_json::from_str(&text)?) +} +fn read_optional_bundle(dir: &Path, name: &str) -> Result, GeneratorError> { + if dir.join(format!("{name}.json")).exists() { + read_bundle(dir, name).map(Some) + } else { + Ok(None) + } +} +fn build_tags( + raw: &Bundle, + known: impl Fn(&str) -> bool, +) -> Result>, GeneratorError> { + let mut definitions = TagDefinitions::default(); + for (name, json) in raw { + definitions.apply_json(name, "vanilla", json)?; + } + let built = definitions + .build(|id, _| known(id).then(|| id.to_owned())) + .map_err(|e| resource(format!("tags: {e:?}")))?; + if !built.missing.is_empty() { + return Err(resource(format!( + "unresolved tag entries in {:?}", + built.missing.keys().collect::>() + ))); + } + Ok(built.tags) +} +/// Convert a data-generator `biome_parameters` report into the quantized +/// preset table format, using vanilla's float `quantizeCoord`. +fn quantize_parameter_report(json: &str) -> Result { + let report: Value = serde_json::from_str(json)?; + let float = |v: &Value| -> Result { + let text = v.to_string(); + text.parse::() + .map(quantize) + .map_err(|_| resource("biome parameter value")) + }; + let mut entries = Vec::new(); + for entry in report["biomes"] + .as_array() + .ok_or_else(|| resource("biome parameter report"))? + { + let parameters = &entry["parameters"]; + let mut coordinates = Vec::new(); + for key in [ + "temperature", + "humidity", + "continentalness", + "erosion", + "depth", + "weirdness", + ] { + let value = ¶meters[key]; + coordinates.push(match value.as_array() { + Some(range) if range.len() == 2 => { + serde_json::json!([float(&range[0])?, float(&range[1])?]) + } + None if value.is_number() => { + let v = float(value)?; + serde_json::json!([v, v]) + } + _ => return Err(resource("biome parameter interval")), + }); + } + entries.push(serde_json::json!({ + "coordinates": coordinates, + "offset": float(¶meters["offset"])?, + "biome": entry["biome"], + })); + } + Ok(Value::Array(entries).to_string()) +} +impl GeneratorData { + /// Load a worldgen bundle directory. Required files are JSON objects mapping + /// resource identifiers to the resource's JSON text: `noises`, `densities`, + /// `rules` (material rules), `conditions` (material conditions), `settings` + /// (noise settings), `carvers`, `biomes`, `biome_tags`, `block_tags`, + /// `world_presets`; `block_flags.json` is an array of `[is_air, has_fluid]` + /// per registry state. Multi-noise tables come from `presets.json` + /// (quantized) or `biome_parameters/.json` data-generator reports. + /// Optional decoration inputs: `features`, `placed_features`, + /// `feature_tags`, `fluid_tags`. Integer block properties are derived from + /// the registry: properties whose every value is a decimal integer. + pub fn load(dir: &Path, registry: &'static BlockRegistry) -> Result, GeneratorError> { + let flags: Vec<(bool, bool)> = + serde_json::from_str(&fs::read_to_string(dir.join("block_flags.json"))?)?; + if flags.len() != registry.len() { + return Err(resource("block_flags.json does not match the registry")); + } + let block_tags = build_tags(&read_bundle(dir, "block_tags")?, |id| { + registry.default_state(id).is_some() + })?; + let tag_set = |name: &str| -> Result, GeneratorError> { + Ok(block_tags + .get(name) + .ok_or_else(|| resource(format!("missing block tag {name}")))? + .iter() + .map(String::as_str) + .collect()) + }; + let motion = tag_set("minecraft:blocks_motion_in_heightmap")?; + let no_leaves = tag_set("minecraft:blocks_motion_in_heightmap_no_leaves")?; + let mut values = BTreeMap::<(String, String), bool>::new(); + let states = (0..registry.len()) + .map(|i| { + let state = registry.state(BlockStateId(i as u32)).unwrap(); + for (key, value) in &state.properties { + let integer = !value.is_empty() + && value + .trim_start_matches('-') + .bytes() + .all(|b| b.is_ascii_digit()); + *values + .entry((state.name.clone(), key.clone())) + .or_insert(true) &= integer; + } + GenBlockState { + air: flags[i].0, + air_block: state.name == "minecraft:air", + fluid: flags[i].1, + motion: motion.contains(state.name.as_str()), + no_leaves: no_leaves.contains(state.name.as_str()), + } + }) + .collect::>(); + let integers = values + .into_iter() + .filter_map(|(key, integer)| integer.then_some(key)) + .collect(); + let biomes = read_bundle(dir, "biomes")?; + let biome_tags = build_tags(&read_bundle(dir, "biome_tags")?, |id| { + biomes.contains_key(id) + })?; + let biome_set = biomes.keys().cloned().collect::>(); + let conditions = MaterialConditionRegistry::from_json_with_biome_tags( + &read_bundle(dir, "conditions")?, + &biome_set, + &biome_tags, + )?; + let mut presets = read_optional_bundle(dir, "presets")?.unwrap_or_default(); + let reports = dir.join("biome_parameters"); + if reports.is_dir() { + for entry in fs::read_dir(&reports)? { + let path = entry?.path(); + let Some(stem) = path + .file_stem() + .and_then(|s| s.to_str()) + .filter(|_| path.extension().is_some_and(|e| e == "json")) + else { + continue; + }; + presets + .entry(format!("minecraft:{stem}")) + .or_insert(quantize_parameter_report(&fs::read_to_string(&path)?)?); + } + } + let source_catalog = + BiomeSourceCatalog::new(&biome_set, &biome_tags, &presets.keys().cloned().collect())?; + let carvers = CarverCatalog::from_json(&read_bundle(dir, "carvers")?)?; + let mut biome_names = Vec::new(); + let mut biome_ids = BTreeMap::new(); + let mut biome_json = Vec::new(); + let mut temperatures = Vec::new(); + let mut biome_carvers = Vec::new(); + for (name, json) in &biomes { + biome_ids.insert(name.clone(), BiomeId(biome_names.len() as u32)); + biome_names.push(Arc::::from(name.as_str())); + temperatures.push(BiomeTemperatureSettings::from_json(json)?); + let value: Value = serde_json::from_str(json)?; + biome_carvers.push(carvers.decode_set(&value["carvers"].to_string())?); + biome_json.push(json.clone()); + } + let carving_blocks = CarvingBlocks::from_registry( + registry, + &tag_set("minecraft:uncarvable")? + .into_iter() + .map(str::to_owned) + .collect(), + ) + .map_err(|e| resource(format!("carving blocks: {e}")))?; + let feature_resources = match ( + read_optional_bundle(dir, "features")?, + read_optional_bundle(dir, "placed_features")?, + ) { + (Some(features), Some(placed)) => { + let fluid_tags = match read_optional_bundle(dir, "fluid_tags")? { + Some(raw) => build_tags(&raw, |id| { + matches!( + id, + "minecraft:water" + | "minecraft:flowing_water" + | "minecraft:lava" + | "minecraft:flowing_lava" + | "minecraft:empty" + ) + })?, + None => BTreeMap::new(), + }; + Some(FeatureResources { + features, + placed, + feature_tags: read_optional_bundle(dir, "feature_tags")?.unwrap_or_default(), + fluid_tags, + }) + } + _ => None, + }; + Ok(Arc::new(Self { + registry, + states: GenBlockStates(states.into()), + integers, + noises: read_bundle(dir, "noises")?, + densities: read_bundle(dir, "densities")?, + rules: read_bundle(dir, "rules")?, + settings: read_bundle(dir, "settings")?, + world_presets: read_bundle(dir, "world_presets")?, + presets, + conditions, + source_catalog, + biome_names, + biome_ids, + biome_json, + temperatures, + biome_carvers, + carving_blocks, + block_tags, + biome_tags, + feature_resources, + })) + } + pub fn registry(&self) -> &'static BlockRegistry { + self.registry + } + pub fn block_states(&self) -> &GenBlockStates { + &self.states + } + /// Biome identifiers in registry (identifier-sorted) order. + pub fn biome_names(&self) -> &[Arc] { + &self.biome_names + } + pub fn biome_name(&self, id: BiomeId) -> &str { + &self.biome_names[id.0 as usize] + } + pub fn biome_id(&self, name: &str) -> Option { + self.biome_ids.get(name).copied() + } + /// The biome's resource JSON (climate, effects such as water/sky/foliage + /// colors, attributes, carvers and features). + pub fn biome_json(&self, id: BiomeId) -> &str { + &self.biome_json[id.0 as usize] + } + pub(super) fn integers(&self) -> &BTreeSet<(String, String)> { + &self.integers + } +} + +/// A generated chunk with its quart biomes. Blocks and heightmaps live in +/// `terrain`; after `generate_proto` it is at the TERRAIN status with the +/// WORLD_SURFACE(_WG), OCEAN_FLOOR(_WG) and MOTION_BLOCKING(_NO_LEAVES) +/// heightmaps primed. Fluid positions scheduled for postprocessing are kept in +/// `terrain.postprocessing()`. +pub struct ProtoChunk { + pub terrain: TerrainChunk<'static, GenBlockStates>, + biomes: BiomeChunk, + data: Arc, + decorated: bool, +} +impl ProtoChunk { + pub fn position(&self) -> ChunkPos { + self.terrain.position() + } + pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId { + self.terrain.block(x, y, z) + } + pub fn block_name(&self, x: i32, y: i32, z: i32) -> &str { + &self + .data + .registry + .state(self.block(x, y, z)) + .expect("registered state") + .name + } + /// Stored quart biome (4×4×4 cell) containing this block, without the + /// client's biome zoom. X/Z wrap to this chunk; Y clamps to its range. + pub fn biome_id_at(&self, x: i32, y: i32, z: i32) -> BiomeId { + *self.biomes.noise_biome([x >> 2, y >> 2, z >> 2]) + } + pub fn biome_at(&self, x: i32, y: i32, z: i32) -> &str { + self.data.biome_name(self.biome_id_at(x, y, z)) + } + pub fn biomes(&self) -> &BiomeChunk { + &self.biomes + } + pub fn data(&self) -> &Arc { + &self.data + } + pub fn is_decorated(&self) -> bool { + self.decorated + } + /// Highest non-air block + 1 in the column (WORLD_SURFACE). + pub fn surface_height(&self, x: i32, z: i32) -> i32 { + self.terrain + .heightmap(HeightmapType::WorldSurface) + .and_then(|map| map.first_available(x & 15, z & 15).ok()) + .unwrap_or(self.terrain.min_y()) + } +} + +/// Per-noise-settings values resolved from the dimension's generator JSON. +struct Settings { + min_y: i32, + height: i32, + sea_level: i32, + default_block: BlockStateId, + default_fluid: BlockStateId, + legacy: bool, +} + +/// The seed-bound pipeline for one random-source kind. +struct Pipeline { + data: Arc, + seed: i64, + settings: Settings, + root: R::Positional, + router: RouterSamplers, + climate: ClimateSampler, + aquifer: Option<[Arc; 6]>, + rule: MaterialRule, + preliminary: Arc, + source: ResolvedBiomeSource, + surface: MaterialSurface, + noises: BTreeMap>, + extensions: MaterialExtensions, + picker: GlobalFluidPicker, + zoom: BiomeZoom, + biome_cache: Mutex>>>, + carver_cache: Mutex>, + pub(super) decoration: Option, +} +const CACHE_LIMIT: usize = 16384; + +fn state(registry: &BlockRegistry, raw: &Value) -> Result { + let name = raw + .get("Name") + .and_then(Value::as_str) + .or_else(|| raw.as_str()) + .ok_or_else(|| resource("block state"))?; + let properties = raw.get("Properties").and_then(Value::as_object); + match properties { + Some(properties) if !properties.is_empty() => { + let descriptor = crate::chunk::BlockState { + name: super::tags::identifier(name)?, + properties: properties + .iter() + .map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_owned())) + .collect(), + }; + registry + .resolve(&descriptor) + .map_err(|e| resource(format!("block state {name}: {e}"))) + } + _ => registry + .default_state(&super::tags::identifier(name)?) + .ok_or_else(|| resource(format!("unknown block {name}"))), + } +} + +impl Pipeline +where + R::Positional: Clone + Send + Sync, +{ + fn new( + data: Arc, + seed: i64, + mut random: R, + generator: &Value, + settings_json: &Value, + ) -> Result { + let registry = data.registry; + let noise = &settings_json["noise"]; + let settings = Settings { + min_y: noise["min_y"] + .as_i64() + .ok_or_else(|| resource("noise min_y"))? as i32, + height: noise["height"] + .as_i64() + .ok_or_else(|| resource("noise height"))? as i32, + sea_level: settings_json["sea_level"] + .as_i64() + .ok_or_else(|| resource("sea_level"))? as i32, + default_block: state(registry, &settings_json["default_block"])?, + default_fluid: state(registry, &settings_json["default_fluid"])?, + legacy: settings_json["legacy_random_source"] + .as_bool() + .unwrap_or(false), + }; + let root = random.fork_positional(); + let codec = crate::registry::BlockStateJsonCodec::new(registry, data.integers.clone()) + .map_err(|e| resource(e.to_string()))?; + let mut densities = DensityRegistry::from_json(&data.noises, &data.densities)?; + let router = + NoiseRouter::from_json(&settings_json["noise_router"].to_string(), &mut densities)?; + let aquifers = settings_json + .get("aquifers") + .filter(|v| !v.is_null()) + .map(|v| AquiferConfig::from_json(&v.to_string(), &mut densities)) + .transpose()?; + let mut library = MaterialRuleLibrary::from_json( + &data.rules, + &data.conditions, + &codec, + densities, + seed, + settings.legacy, + )?; + let router = library.compile_router(router)?; + let aquifer = aquifers + .map(|config| library.compile_aquifer(config)) + .transpose()? + .map(|samplers| AquiferField::ALL.map(|field| samplers.get(field).clone())); + let rule_name = settings_json["material_rule"] + .as_str() + .ok_or_else(|| resource("material_rule"))?; + let rule = library.rule(rule_name)?; + let preliminary = router.get(RouterField::ChunkSurfaceLevel).clone(); + let source = data + .source_catalog + .decode(&generator["biome_source"].to_string())? + .resolve(&data.presets) + .map_err(|e| resource(format!("biome source: {e}")))?; + let climate = router.climate_sampler(); + let mut noises = BTreeMap::new(); + for (name, json) in &data.noises { + let noise: Arc = Arc::new( + decode_noise(json)? + .create(&mut root.from_hash_of(name)) + .map_err(DecodeError::from)?, + ); + noises.insert(name.clone(), noise); + } + let noise = |name: &str| -> Result, GeneratorError> { + noises + .get(name) + .cloned() + .ok_or_else(|| resource(format!("missing noise {name}"))) + }; + let surface = MaterialSurface::new( + root.clone(), + ClayBandBlocks::from_registry(registry).ok_or_else(|| resource("clay bands"))?, + noise("minecraft:clay_bands_offset")?, + noise("minecraft:surface")?, + noise("minecraft:surface_secondary")?, + ); + let default = |name: &str| { + registry + .default_state(name) + .ok_or_else(|| resource(format!("missing block {name}"))) + }; + let extensions = MaterialExtensions::new( + root.clone(), + ExtensionBlocks { + default: settings.default_block, + water: default("minecraft:water")?, + packed_ice: default("minecraft:packed_ice")?, + snow: default("minecraft:snow_block")?, + }, + ExtensionNoises { + badlands_surface: noise("minecraft:badlands_surface")?, + badlands_pillar: noise("minecraft:badlands_pillar")?, + badlands_roof: noise("minecraft:badlands_pillar_roof")?, + iceberg_surface: noise("minecraft:iceberg_surface")?, + iceberg_pillar: noise("minecraft:iceberg_pillar")?, + iceberg_roof: noise("minecraft:iceberg_pillar_roof")?, + }, + settings.sea_level, + ); + let picker = GlobalFluidPicker::new( + settings.sea_level, + settings.default_fluid, + default("minecraft:lava")?, + default("minecraft:air")?, + ); + let mut pipeline = Self { + zoom: BiomeZoom::new(obfuscate_seed(seed)), + data, + seed, + settings, + root, + router, + climate, + aquifer, + rule, + preliminary, + source, + surface, + noises, + extensions, + picker, + biome_cache: Mutex::new(HashMap::new()), + carver_cache: Mutex::new(HashMap::new()), + decoration: None, + }; + pipeline.decoration = + super::generator_decoration::Decoration::new(&pipeline.data, &pipeline.source)?; + Ok(pipeline) + } + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new( + self.settings.min_y, + self.settings.height, + self.settings.sea_level, + ) + } + fn biome_chunk( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + ) -> Result>, GeneratorError> { + if let Some(chunk) = self.biome_cache.lock().unwrap().get(&(pos.x, pos.z)) { + return Ok(chunk.clone()); + } + let (min, height) = (self.settings.min_y, self.settings.height); + let mut chunk = BiomeChunk::new(pos, min, height, BiomeId(0)).map_err(stage("biomes"))?; + let mut resolver = self.source.resolver( + &self.climate, + self.router.get(RouterField::Erosion).as_ref(), + ); + let context = &mut worker.biome_context; + let volume = resolver + .prepare_volume( + context, + [ + pos.x.wrapping_shl(4) >> 2, + min >> 2, + pos.z.wrapping_shl(4) >> 2, + ], + [4, height >> 2, 4], + ) + .map_err(stage("biomes"))?; + let ids = &self.data.biome_ids; + chunk + .fill(min, min + height - 1, |quart| { + resolver + .sample_prepared(context, volume.as_ref(), quart) + .map_err(|e| e.to_string()) + .and_then(|name| ids.get(name).copied().ok_or_else(|| name.to_owned())) + }) + .map_err(stage("biomes"))?; + let chunk = Arc::new(chunk); + let mut cache = self.biome_cache.lock().unwrap(); + if cache.len() >= CACHE_LIMIT { + cache.clear(); + } + cache.insert((pos.x, pos.z), chunk.clone()); + Ok(chunk) + } + fn carver_biome(&self, worker: &mut WorkerState, origin: ChunkPos) -> Result { + if let Some(id) = self.carver_cache.lock().unwrap().get(&(origin.x, origin.z)) { + return Ok(*id); + } + let mut resolver = self.source.resolver( + &self.climate, + self.router.get(RouterField::Erosion).as_ref(), + ); + let quart = [ + origin.x.wrapping_shl(4) >> 2, + 0, + origin.z.wrapping_shl(4) >> 2, + ]; + let name = resolver + .sample(&mut worker.carver_context, quart) + .map_err(|e| e.to_string())?; + let id = self.data.biome_id(name).ok_or_else(|| name.to_owned())?; + let mut cache = self.carver_cache.lock().unwrap(); + if cache.len() >= CACHE_LIMIT * 4 { + cache.clear(); + } + cache.insert((origin.x, origin.z), id); + Ok(id) + } + fn generate( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + ) -> Result { + let data = &self.data; + let (min, height, sea) = ( + self.settings.min_y, + self.settings.height, + self.settings.sea_level, + ); + let mut clock = std::time::Instant::now(); + let mut neighbors = Vec::with_capacity(9); + let mut possible = BTreeSet::new(); + for dz in -1..=1 { + for dx in -1..=1 { + let chunk = self.biome_chunk( + worker, + ChunkPos::new(pos.x.wrapping_add(dx), pos.z.wrapping_add(dz)), + )?; + for section in 0..(height / 16) as usize { + possible.extend(chunk.section(section).unwrap().iter().copied()); + } + neighbors.push((*chunk).clone()); + } + } + let center = neighbors[4].clone(); + let biomes = + BiomeRegion::new(neighbors, obfuscate_seed(self.seed)).map_err(stage("biomes"))?; + let possible = possible + .into_iter() + .map(|id| data.biome_name(id).to_owned()) + .collect(); + worker.timings.biomes += lap(&mut clock); + let mut chunk = TerrainChunk::new(pos, min, height, data.registry, data.states.clone()) + .map_err(stage("noise"))?; + chunk.set_generation_stage(PreLightChunkStage::Biomes); + let mut context = SamplerContext::cached(); + let volume = DensityVolume::new( + [16, height, 16], + [pos.x.wrapping_shl(4), min, pos.z.wrapping_shl(4)], + [1; 3], + ) + .map_err(stage("noise"))?; + worker.timings.noise += lap(&mut clock); + let mut aquifer: Box = match &self.aquifer { + Some(samplers) => Box::new( + NoiseBasedAquifer::new( + AquiferSamplers::new(samplers.clone()), + self.picker, + self.root + .from_hash_of("minecraft:aquifer") + .fork_positional(), + RegistryAquiferBlockStates::new(data.registry).map_err(stage("aquifer"))?, + volume, + &mut context, + ) + .map_err(stage("aquifer"))?, + ), + None => Box::new(DisabledAquifer::new( + self.picker, + data.registry.default_state("minecraft:air").unwrap(), + )), + }; + worker.timings.noise += lap(&mut clock); + fill_noise( + &mut chunk, + volume, + self.router.get(RouterField::FinalDensity).as_ref(), + &mut context, + aquifer.as_mut(), + self.settings.default_block, + ) + .map_err(stage("noise"))?; + let generation = self.generation(); + worker.timings.noise += lap(&mut clock); + build_surface( + &mut chunk, + self.rule.clone(), + SurfaceInputs:: { + generation, + noise_volume: volume, + root: self.root.clone(), + surface: SurfaceQueries { + pipeline: self, + temperatures: &mut worker.temperatures, + biome: Biomes::Region(&biomes), + possible: Some(possible), + }, + preliminary_surface: self.preliminary.clone(), + density_context: &mut context, + write_min_y: min, + write_max_y: min + height - 1, + }, + &self.extensions, + ) + .map_err(stage("surface"))?; + worker.timings.surface += lap(&mut clock); + let carvers = &data.biome_carvers; + let mask = generate_carving_mask(self.seed, pos, generation, false, |origin| { + self.carver_biome(worker, origin) + .map(|id| carvers[id.0 as usize].as_slice()) + }) + .map_err(stage("carvers"))?; + worker.timings.carvers += lap(&mut clock); + if !mask.is_empty() { + let mut resolver = self.source.resolver( + &self.climate, + self.router.get(RouterField::Erosion).as_ref(), + ); + let mut biome_context = SamplerContext::default(); + apply_carving_mask( + &mut chunk, + &mask, + self.rule.clone(), + TopMaterialInputs:: { + generation, + root: self.root.clone(), + surface: SurfaceQueries { + pipeline: self, + temperatures: &mut worker.temperatures, + biome: Biomes::Resolver(&mut resolver, &mut biome_context), + possible: None, + }, + preliminary_surface: self.preliminary.clone(), + density_context: &mut context, + }, + aquifer.as_mut(), + &data.carving_blocks, + |_| true, + ) + .map_err(stage("carvers"))?; + } + worker.timings.carvers += lap(&mut clock); + chunk + .prime_heightmaps(&[ + HeightmapType::MotionBlocking, + HeightmapType::MotionBlockingNoLeaves, + HeightmapType::OceanFloor, + HeightmapType::WorldSurface, + ]) + .map_err(stage("heightmaps"))?; + chunk.set_generation_stage(PreLightChunkStage::Terrain); + let _ = sea; + Ok(ProtoChunk { + terrain: chunk, + biomes: center, + data: data.clone(), + decorated: false, + }) + } +} + +enum Biomes<'a, 'b> { + Region(&'a BiomeRegion), + Resolver( + &'a mut super::biome_source::BiomeSourceResolver<'b>, + &'a mut SamplerContext, + ), +} +/// Material-rule world queries for one chunk: shared seed-bound noises, the +/// worker's temperature caches and either stored or raw-resolver biomes. +struct SurfaceQueries<'a, 'b, R: RandomSource> { + pipeline: &'a Pipeline, + temperatures: &'a mut [BiomeTemperature], + biome: Biomes<'a, 'b>, + possible: Option>, +} +impl SurfaceQueries<'_, '_, R> { + fn temperature(&mut self, name: &str) -> Result<&mut BiomeTemperature, MaterialRuleError> { + let id = self + .pipeline + .data + .biome_id(name) + .ok_or(MaterialRuleError::MissingBiome)?; + Ok(&mut self.temperatures[id.0 as usize]) + } +} +impl MaterialSurfaceQueries for SurfaceQueries<'_, '_, R> { + fn surface_depth(&mut self, x: i32, z: i32) -> i32 { + self.pipeline.surface.surface_depth(x, z) + } + fn surface_secondary(&mut self, x: i32, z: i32) -> f64 { + self.pipeline.surface.surface_secondary(x, z) + } + fn band(&mut self, p: BlockPos) -> Result { + self.pipeline + .surface + .band([p.x, p.y, p.z]) + .ok_or(MaterialRuleError::InvalidBandIndex) + } + fn bind_noise(&mut self, name: &str) -> Result, DecodeError> { + self.pipeline + .noises + .get(&super::tags::identifier(name)?) + .cloned() + .ok_or(DecodeError::Field("unknown material noise")) + } + fn possible_biomes(&self) -> Option> { + self.possible.clone() + } + fn biome(&mut self, p: BlockPos) -> Result>, MaterialRuleError> { + let data = &self.pipeline.data; + let id = match &mut self.biome { + Biomes::Region(region) => *region + .biome(p) + .map_err(|_| MaterialRuleError::MissingBiome)?, + Biomes::Resolver(resolver, context) => { + let name = resolver + .sample(context, self.pipeline.zoom.quart_at_block(p)) + .map_err(|_| MaterialRuleError::BiomeQueryFailed)?; + data.biome_id(name).ok_or(MaterialRuleError::MissingBiome)? + } + }; + Ok(Some(data.biome_names[id.0 as usize].clone())) + } + fn cold_enough_to_snow( + &mut self, + name: &str, + p: BlockPos, + sea: i32, + ) -> Result { + Ok(self.temperature(name)?.cold_enough_to_snow(p, sea)) + } + fn melts_frozen_ocean( + &mut self, + name: &str, + p: BlockPos, + sea: i32, + ) -> Result { + Ok(self + .temperature(name)? + .should_melt_frozen_ocean_iceberg_slightly(p, sea)) + } +} + +fn lap(clock: &mut std::time::Instant) -> std::time::Duration { + let now = std::time::Instant::now(); + let elapsed = now - *clock; + *clock = now; + elapsed +} +/// Cumulative wall time spent by one worker in each proto-chunk stage. +#[derive(Clone, Copy, Debug, Default)] +pub struct StageTimings { + pub chunks: u64, + pub biomes: std::time::Duration, + /// Noise fill including aquifer setup. + pub noise: std::time::Duration, + pub surface: std::time::Duration, + /// Carving mask generation/application and final heightmap priming. + pub carvers: std::time::Duration, +} +/// Worker-owned mutable caches. Biome temperature caches mirror vanilla's +/// thread-local caches and never change results. +pub(super) struct WorkerState { + pub(super) temperatures: Vec, + biome_context: SamplerContext, + carver_context: SamplerContext, + timings: StageTimings, +} + +trait SeededPipeline: Send + Sync { + fn generate( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + ) -> Result; + fn decorate( + &self, + worker: &mut WorkerState, + region: &mut [ProtoChunk; 9], + ) -> Result; + fn data(&self) -> &Arc; + fn sea_level(&self) -> i32; +} +impl SeededPipeline for Pipeline +where + R::Positional: Clone + Send + Sync, +{ + fn generate( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + ) -> Result { + Pipeline::generate(self, worker, pos) + } + fn decorate( + &self, + worker: &mut WorkerState, + region: &mut [ProtoChunk; 9], + ) -> Result { + match &self.decoration { + Some(decoration) => { + decoration.decorate(&self.data, self.seed, self.generation(), worker, region) + } + None => Err(resource("decoration resources were not loaded")), + } + } + fn data(&self) -> &Arc { + &self.data + } + fn sea_level(&self) -> i32 { + self.settings.sea_level + } +} + +/// Counters from one FEATURES pass. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DecorateStats { + /// Placed-feature roots executed (including those that placed nothing). + pub placed: usize, + /// Roots skipped because their algorithm or bindings are not implemented. + pub unsupported: usize, + /// Roots that started but failed on an unavailable world query or error. + /// Their partial writes are kept, as each root reseeds its own random. + pub failed: usize, + /// Identifiers of skipped or failed roots, for diagnostics. + pub skipped: BTreeSet, +} + +/// A seed-bound generator for one dimension, shareable across worker threads. +#[derive(Clone)] +pub struct OverworldGenerator { + pipeline: Arc, +} +impl OverworldGenerator { + /// The `minecraft:overworld` dimension of the `minecraft:normal` world preset. + pub fn new(data: Arc, seed: i64) -> Result { + Self::for_dimension(data, seed, "minecraft:normal", "minecraft:overworld") + } + /// Any noise-generator dimension of a bundled world preset. + pub fn for_dimension( + data: Arc, + seed: i64, + preset: &str, + dimension: &str, + ) -> Result { + let preset_json: Value = serde_json::from_str( + data.world_presets + .get(preset) + .ok_or_else(|| resource(format!("missing world preset {preset}")))?, + )?; + let generator = preset_json["dimensions"][dimension]["generator"].clone(); + if generator["type"].as_str() != Some("minecraft:noise") { + return Err(resource(format!("{dimension} is not a noise generator"))); + } + let settings_json: Value = match &generator["settings"] { + Value::String(name) => serde_json::from_str( + data.settings + .get(name) + .ok_or_else(|| resource(format!("missing noise settings {name}")))?, + )?, + inline => inline.clone(), + }; + let pipeline: Arc = if settings_json["legacy_random_source"] + .as_bool() + .unwrap_or(false) + { + Arc::new(Pipeline::new( + data, + seed, + LegacyRandom::new(seed), + &generator, + &settings_json, + )?) + } else { + Arc::new(Pipeline::new( + data, + seed, + XoroshiroRandom::new(seed), + &generator, + &settings_json, + )?) + }; + Ok(Self { pipeline }) + } + pub fn data(&self) -> &Arc { + self.pipeline.data() + } + pub fn sea_level(&self) -> i32 { + self.pipeline.sea_level() + } + /// Create per-thread state. Workers are cheap; keep one per thread. + pub fn worker(&self) -> GeneratorWorker { + let data = self.pipeline.data(); + GeneratorWorker { + pipeline: self.pipeline.clone(), + state: WorkerState { + temperatures: data + .temperatures + .iter() + .map(|s| BiomeTemperature::new(*s)) + .collect(), + biome_context: SamplerContext::cached(), + carver_context: SamplerContext::default(), + timings: StageTimings::default(), + }, + } + } +} + +/// Per-thread generation state. +pub struct GeneratorWorker { + pipeline: Arc, + state: WorkerState, +} +impl GeneratorWorker { + /// Biomes, noise fill and aquifers, material surface and carvers: the + /// vanilla statuses up to TERRAIN. Independent of neighbor chunks' state. + pub fn generate_proto(&mut self, pos: ChunkPos) -> Result { + let result = self.pipeline.generate(&mut self.state, pos); + self.state.timings.chunks += 1; + result + } + pub fn stage_timings(&self) -> StageTimings { + self.state.timings + } + /// FEATURES status for `region[4]`. The region is a 3×3 neighborhood in + /// row-major order: index `(dz + 1) * 3 + (dx + 1)` around the center. + /// Writes may reach the neighbors, as in vanilla. Unsupported features are + /// skipped and counted. On error, chunks keep partial writes. + pub fn decorate( + &mut self, + region: &mut [ProtoChunk; 9], + ) -> Result { + self.pipeline.decorate(&mut self.state, region) + } +} diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs new file mode 100644 index 000000000..eaf78f14e --- /dev/null +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -0,0 +1,27 @@ +//! FEATURES status over a 3×3 neighborhood of generated chunks. +use super::{ + anchor::WorldGenerationContext, + biome_source::ResolvedBiomeSource, + generator::{DecorateStats, GeneratorData, GeneratorError, ProtoChunk, WorkerState}, +}; +use std::sync::Arc; + +pub(super) struct Decoration; +impl Decoration { + pub(super) fn new( + _data: &Arc, + _source: &ResolvedBiomeSource, + ) -> Result, GeneratorError> { + Ok(None) + } + pub(super) fn decorate( + &self, + _data: &Arc, + _seed: i64, + _generation: WorldGenerationContext, + _worker: &mut WorkerState, + _region: &mut [ProtoChunk; 9], + ) -> Result { + Ok(DecorateStats::default()) + } +} diff --git a/tools/prepare_native_client.py b/tools/prepare_native_client.py index bfbac9c45..6d96390e8 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -15,6 +15,46 @@ except ImportError: import test_model_baking_parity as baking +WORLDGEN_BUNDLES = { + 'noises': 'worldgen/noise', 'densities': 'worldgen/density_function', 'rules': 'worldgen/material_rule', + 'conditions': 'worldgen/material_condition', 'settings': 'worldgen/noise_settings', 'carvers': 'worldgen/carver', + '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'} + + +def prepare_worldgen(root, jars, local): + """Write the chunk generator's resource bundle to root/worldgen (see GeneratorData::load).""" + out = root / 'worldgen' + out.mkdir(exist_ok=True) + 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}/' + def extract(archive): + return {'minecraft:'+n[len(prefix):-5]: archive.read(n).decode('utf-8') + for n in sorted(archive.namelist()) if n.startswith(prefix) and n.endswith('.json')} + resources = extract(server) + if not resources or resources != extract(client): + raise ValueError('Reference worldgen resources disagree: '+path) + (out/(name+'.json')).write_text(json.dumps(resources, separators=(',', ':')), encoding='utf-8') + facts = json.loads((root/'facts.json').read_text()) + (out/'block_flags.json').write_text(json.dumps([[s[1], s[2]] for s in facts['states']], separators=(',', ':'))) + reports = out/'biome_parameters' + reports.mkdir(exist_ok=True) + for source in [root/'biome-parameters', local/'datagen/out/reports/biome_parameters/minecraft']: + if (source/'overworld.json').exists(): + for report in sorted(source.glob('*.json')): + (reports/report.name).write_bytes(report.read_bytes()) + break + else: + # Fall back to the Java-exported quantized tables from the material-stage parity run. + presets = local/'rust-material-stage-parity/presets.json' + if not presets.exists(): + raise FileNotFoundError('No multi-noise biome parameter tables; run the data generator reports') + (out/'presets.json').write_bytes(presets.read_bytes()) + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--prepare', action='store_true', help='Fetch pinned reference artifacts first') @@ -160,8 +200,9 @@ 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) count = 0 - prefixes = ('assets/minecraft/blockstates/', 'assets/minecraft/models/block/', + prefixes =('assets/minecraft/blockstates/', 'assets/minecraft/models/block/', 'assets/minecraft/textures/block/') with zipfile.ZipFile(jars['client']) as archive: version = json.loads(archive.read('version.json'))