Merge vanilla overworld generator with decoration

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-07 23:44:19 +02:00
9 changed files with 2538 additions and 17 deletions
@@ -0,0 +1,394 @@
//! Chunk generation throughput and sanity map.
//!
//! chunkgen_bench <client resource dir> [--seed S] [--size N] [--threads T]
//! [--center CX CZ] [--verify <material-stage parity dir>] [--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<dyn std::error::Error + Send + Sync>;
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<String> {
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<GeneratorData>, 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::<Vec<_>>();
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())
}
}
/// Process CPU seconds (Linux), robust against other load on shared machines.
fn cpu_seconds() -> f64 {
fs::read_to_string("/proc/self/stat")
.ok()
.and_then(|stat| {
let fields = stat
.rsplit_once(')')?
.1
.split_whitespace()
.collect::<Vec<_>>();
Some((fields[11].parse::<f64>().ok()? + fields[12].parse::<f64>().ok()?) / 100.)
})
.unwrap_or(0.)
}
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<Mutex<Option<ProtoChunk>>> = (0..count).map(|_| Mutex::new(None)).collect();
let timings = Mutex::new(Vec::new());
let cpu = cpu_seconds();
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::<Vec<_>>();
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
);
println!(
" cpu time {:.1} ms/chunk",
(cpu_seconds() - cpu) * 1000. / count as f64
);
let timings = timings.into_inner().unwrap();
let per_chunk = |f: fn(&StageTimings) -> std::time::Duration| {
timings
.iter()
.map(f)
.sum::<std::time::Duration>()
.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<Option<ProtoChunk>> = 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::<Vec<_>>();
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 std::env::var_os("HORIZON_FEATURE_ERRORS").is_some() {
for (name, error) in generator.unsupported_features() {
println!("unsupported {name}: {error}");
}
}
if !totals.skipped.is_empty() {
println!(
"skipped roots: {}",
totals.skipped.into_iter().collect::<Vec<_>>().join(" ")
);
}
}
let mut legend = BTreeMap::<char, BTreeMap<String, usize>>::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::<Vec<_>>();
names.sort_by_key(|(_, n)| std::cmp::Reverse(*n));
let names = names
.into_iter()
.take(4)
.map(|(n, _)| n)
.collect::<Vec<_>>();
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(())
}
+27 -3
View File
@@ -357,9 +357,33 @@ impl ChunkData {
/// Resident section: 4,096 blocks stored as numeric palette entries. Uniform
/// sections have no word array; property strings live in the shared registry.
/// Multiplicative hash for dense state IDs; section palettes are hashed on
/// every block write, where SipHash dominated generation profiles.
#[derive(Default)]
struct StateIdHasher(u64);
impl std::hash::Hasher for StateIdHasher {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for &b in bytes {
self.0 = (self.0.rotate_left(8) ^ u64::from(b)).wrapping_mul(0x9e37_79b9_7f4a_7c15);
}
}
fn write_u32(&mut self, value: u32) {
self.0 = (self.0 ^ u64::from(value)).wrapping_mul(0x9e37_79b9_7f4a_7c15);
}
}
type LocalIds =
std::collections::HashMap<BlockStateId, u32, std::hash::BuildHasherDefault<StateIdHasher>>;
fn local_ids(state: BlockStateId) -> LocalIds {
let mut ids = LocalIds::default();
ids.insert(state, 0);
ids
}
pub struct BlockSection<'r> {
palette: Vec<BlockStateId>,
local_ids: std::collections::HashMap<BlockStateId, u32>,
local_ids: LocalIds,
counts: Vec<u16>,
free: Vec<u32>,
storage: Option<PackedStorage>,
@@ -376,7 +400,7 @@ impl<'r> BlockSection<'r> {
}
Ok(Self {
palette: vec![state],
local_ids: [(state, 0)].into(),
local_ids: local_ids(state),
counts: vec![4096],
free: Vec::new(),
storage: None,
@@ -474,7 +498,7 @@ impl<'r> BlockSection<'r> {
}
if self.counts[id as usize] == 4096 {
self.palette = vec![state];
self.local_ids = [(state, 0)].into();
self.local_ids = local_ids(state);
self.counts = vec![4096];
self.free.clear();
self.storage = None;
+3
View File
@@ -33,6 +33,9 @@ pub mod feature_graph;
pub mod feature_region;
pub mod feature_sort;
pub mod fluid_predicate;
pub mod generator;
mod generator_blocks;
mod generator_decoration;
pub mod height_provider;
pub mod material_condition;
pub mod material_extensions;
@@ -177,6 +177,10 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> {
self.sea_level = sea_level;
self
}
/// Release the resident chunks, ordered by X then Z; match them by position.
pub fn into_chunks(self) -> Vec<TerrainChunk<'r, B>> {
self.chunks.into_values().collect()
}
pub fn chunks(&self) -> impl Iterator<Item = &TerrainChunk<'r, B>> {
self.chunks.values()
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,163 @@
//! Optional block-behavior registries used by feature placement: physical
//! properties, face support, collision and survival rules. Loaded from the
//! bundle's `blocks/` directory (Java-exported, see prepare_native_client.py).
use super::generator::GeneratorError;
use crate::{
block_collision::BlockCollisionRegistry,
block_properties::BlockPropertiesRegistry,
block_support::BlockSupportRegistry,
block_survival::{BlockSurvivalRegistry, SurvivalDefinitions, SurvivalRule},
collision::CachedCollisionRegistry,
nbt::{self, Limits, Tag},
registry::BlockRegistry,
};
use serde_json::Value;
use std::{
collections::{BTreeMap, BTreeSet},
fs,
path::Path,
sync::Arc,
};
pub(super) struct BlockBehavior {
pub(super) properties: BlockPropertiesRegistry<'static>,
pub(super) support: Arc<BlockSupportRegistry<'static>>,
pub(super) collision: Arc<BlockCollisionRegistry<'static>>,
pub(super) survival: BlockSurvivalRegistry<'static>,
pub(super) double_plants: BTreeSet<String>,
pub(super) mossy_carpets: BTreeSet<String>,
}
fn resource(message: impl Into<String>) -> GeneratorError {
GeneratorError::Resource(message.into())
}
fn rule(name: &str) -> Option<SurvivalRule> {
use SurvivalRule::*;
if let Some(tag) = name.strip_prefix("TagBelow:") {
return Some(TagBelow(tag.to_owned()));
}
Some(match name {
"CactusFlower" => CactusFlower,
"Seagrass" => Seagrass,
"BubbleColumn" => BubbleColumn,
"RedstoneWire" => RedstoneWire,
"DoublePlant" => DoublePlant,
"Door" => Door,
"BigDripleaf" => BigDripleaf,
"BigDripleafStem" => BigDripleafStem,
"Farmland" => Farmland,
"Cocoa" => Cocoa,
"Crop" => Crop,
"GrowingPlant" => GrowingPlant,
"MangrovePropagule" => MangrovePropagule,
"Speleothem" => Speleothem,
"Scaffolding" => Scaffolding,
"PistonHead" => PistonHead,
"ChorusPlant" => ChorusPlant,
"ChorusFlower" => ChorusFlower,
"PitcherCrop" => PitcherCrop,
"Multiface" => Multiface,
"Vine" => Vine,
"HangingMoss" => HangingMoss,
"SnowLayer" => SnowLayer,
"SeaPickle" => SeaPickle,
"Fire" => Fire,
"Cactus" => Cactus,
"Path" => Path,
"Mushroom" => Mushroom,
"Bell" => Bell,
"SugarCane" => SugarCane,
"LilyPad" => LilyPad,
"Frogspawn" => Frogspawn,
"SporeBlossom" => SporeBlossom,
"SmallDripleaf" => SmallDripleaf,
"TallSeagrass" => TallSeagrass,
"Always" => Always,
"SolidBelow" => SolidBelow,
"SolidBehind" => SolidBehind,
"NonAirBelow" => NonAirBelow,
"MossCarpet" => MossCarpet,
"CenterBelow" => CenterBelow,
"Lantern" => Lantern,
"FullAbove" => FullAbove,
"FullBehind" => FullBehind,
"RigidOrCenterBelow" => RigidOrCenterBelow,
"RigidBelow" => RigidBelow,
"FullBelow" => FullBelow,
"CenterAbove" => CenterAbove,
"FaceAttached" => FaceAttached,
"SupportsBamboo" => SupportsBamboo,
_ => return None,
})
}
impl BlockBehavior {
/// Files: `block-properties.nbt`, `cached-collision.nbt`,
/// `cached-support.nbt`, `survival-rules.json`,
/// `survival-extra-definitions.json` and `placement-definitions.json`.
pub(super) fn load(
dir: &Path,
registry: &'static BlockRegistry,
tags: &BTreeMap<String, Vec<String>>,
fluid_tags: &BTreeMap<String, Vec<String>>,
) -> Result<Option<Self>, GeneratorError> {
if !dir.join("block-properties.nbt").exists() {
return Ok(None);
}
let read = |name: &str| -> Result<Tag, GeneratorError> {
let limits = Limits {
max_bytes: 1 << 28,
..Limits::default()
};
Ok(nbt::read_named(&fs::read(dir.join(name))?, limits)
.map_err(|e| resource(format!("{name}: {e:?}")))?
.0
.tag)
};
let json = |name: &str| -> Result<Value, GeneratorError> {
Ok(serde_json::from_str(&fs::read_to_string(dir.join(name))?)?)
};
let collisions =
CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, registry)?;
let properties =
BlockPropertiesRegistry::from_nbt(&read("block-properties.nbt")?, &collisions)?;
let support = Arc::new(BlockSupportRegistry::from_nbt(
&read("cached-support.nbt")?,
registry,
)?);
let collision = Arc::new(BlockCollisionRegistry::new(Arc::new(collisions))?);
let rules = json("survival-rules.json")?
.as_object()
.ok_or_else(|| resource("survival rules"))?
.iter()
.map(|(name, value)| {
let text = value.as_str().unwrap_or_default();
rule(text)
.map(|rule| (name.clone(), rule))
.ok_or_else(|| resource(format!("unknown survival rule {text}")))
})
.collect::<Result<_, _>>()?;
let extra = json("survival-extra-definitions.json")?;
let definitions = SurvivalDefinitions {
rules,
ignition_odds: serde_json::from_value(extra["ignition_odds"].clone())?,
fence_gates: serde_json::from_value(extra["fence_gates"].clone())?,
};
let survival = BlockSurvivalRegistry::new(
registry,
&properties,
support.clone(),
collision.clone(),
&definitions,
tags,
fluid_tags,
)?;
let placement = json("placement-definitions.json")?;
Ok(Some(Self {
double_plants: serde_json::from_value(placement["double_plants"].clone())?,
mossy_carpets: serde_json::from_value(placement["mossy_carpets"].clone())?,
properties,
support,
collision,
survival,
}))
}
}
@@ -0,0 +1,616 @@
//! FEATURES status over a 3×3 neighborhood of generated chunks.
//!
//! Placed features are resolved by name from the bundled feature registries.
//! 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::{
anchor::WorldGenerationContext,
biome::BiomeId,
biome_chunk::BiomeRegion,
biome_predicate::BiomePredicateBindings,
biome_source::ResolvedBiomeSource,
biome_temperature::BiomeTemperature,
biome_weather::BiomeWeatherBindings,
block_feature::FeatureBlockBindings,
decoration::{DecorationWorld, FeatureDecorationPlan},
feature::{FeatureBlocks, FeatureWorld},
feature_catalog::FeatureCatalog,
feature_graph::PlacedFeatureDefinition,
feature_region::{RegionError, TerrainRegion},
feature_sort::FeatureIdentity,
generator::{
DecorateStats, GenBlockStates, GeneratorData, GeneratorError, ProtoChunk, WorkerState,
},
placement::{LayerBlock, PlacementContext, PlacementQueryError},
tags::TagDefinitions,
terrain::PreLightChunkStage,
write_zone::GenerationWriteZone,
};
use super::{
generator_blocks::BlockBehavior,
state_provider::{StateProviderBindings, StateProviderCatalog},
};
use crate::{
block_collision::{DynamicCollisionWorld, ShulkerCollisionState},
block_placement::BlockPlacementBindings,
block_support::SupportType,
block_survival::SurvivalWorld,
dynamic_support::DynamicSupportWorld,
fluid::{FluidKind, FluidState},
heightmap::{HeightmapState, HeightmapType},
registry::BlockStateId,
};
use horizon_core::{
biome::obfuscate_seed,
geometry::{Direction, VoxelShape},
position::{BlockPos, ChunkPos},
};
use serde_json::Value;
use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
};
pub(super) struct Decoration {
plan: FeatureDecorationPlan,
names: Vec<String>,
/// Executable roots by identity, or why the root cannot be executed.
features: Vec<Result<PlacedFeatureDefinition, String>>,
/// Placed features of each biome's generation settings, by BiomeId.
biome_features: Vec<BTreeSet<FeatureIdentity>>,
bindings: FeatureBlockBindings<'static>,
weather: Option<BiomeWeatherBindings>,
blocks: FeatureBlocks,
}
fn resource(message: impl Into<String>) -> GeneratorError {
GeneratorError::Resource(message.into())
}
/// Biomes in vanilla's possible-biome encounter order for this source.
fn possible_biomes(source: &ResolvedBiomeSource) -> Vec<String> {
let mut seen = BTreeSet::new();
let ordered: Vec<String> = match source {
ResolvedBiomeSource::MultiNoise(source) => source
.parameters()
.entries()
.iter()
.map(|(_, name)| name.clone())
.collect(),
ResolvedBiomeSource::End(source) => [
&source.center,
&source.highlands,
&source.midlands,
&source.islands,
&source.barrens,
]
.into_iter()
.cloned()
.collect(),
other => other
.possible_biomes()
.into_iter()
.map(str::to_owned)
.collect(),
};
ordered
.into_iter()
.filter(|name| seen.insert(name.clone()))
.collect()
}
impl Decoration {
pub(super) fn new(
data: &Arc<GeneratorData>,
source: &ResolvedBiomeSource,
) -> Result<Option<Self>, GeneratorError> {
let Some(resources) = &data.feature_resources else {
return Ok(None);
};
let registry = data.registry();
let mut feature_tags = TagDefinitions::default();
for (name, json) in &resources.feature_tags {
feature_tags.apply_json(name, "vanilla", json)?;
}
let catalog =
FeatureCatalog::from_resources(&resources.features, &resources.placed, &feature_tags)?;
let biomes = Arc::new(BiomePredicateBindings::new(
&data
.biome_names()
.iter()
.enumerate()
.map(|(i, name)| (name.to_string(), BiomeId(i as u32)))
.collect(),
&data.biome_tags,
)?);
let mut bindings =
FeatureBlockBindings::with_tags(registry, data.integers().clone(), &data.block_tags)?
.with_fluid_tags(&resources.fluid_tags)?
.with_biomes(biomes.clone());
if let Some(blocks) = &resources.blocks {
bindings = bindings
.with_block_properties(&blocks.properties)?
.with_state_providers(
StateProviderBindings::new(
registry,
data.integers().clone(),
&data.block_tags,
)?
.with_block_properties(&blocks.properties)?
.with_fluid_tags(&resources.fluid_tags)?
.with_biomes(biomes),
StateProviderCatalog::from_resources(&resources.state_providers)?,
BlockPlacementBindings::new(
registry,
&blocks.properties,
&blocks.double_plants,
&blocks.mossy_carpets,
)?,
)?;
}
let tags = feature_tags
.build(|name, _| resources.placed.contains_key(name).then(|| name.to_owned()))
.map_err(|e| resource(format!("feature tags: {e:?}")))?
.tags;
let mut ids = BTreeMap::<String, FeatureIdentity>::new();
let mut names = Vec::new();
let mut features = Vec::new();
let mut identity = |name: &str| -> FeatureIdentity {
*ids.entry(name.to_owned()).or_insert_with(|| {
let id = FeatureIdentity(names.len() as u32);
names.push(name.to_owned());
features.push(
catalog
.placed_feature_with_blocks(&Value::from(name).to_string(), &bindings)
.map_err(|e| e.to_string()),
);
id
})
};
let mut biome_features = vec![BTreeSet::new(); data.biome_names().len()];
let mut plan = Vec::new();
for name in possible_biomes(source) {
let id = data
.biome_id(&name)
.ok_or_else(|| resource(format!("unknown biome {name}")))?;
let json: Value = serde_json::from_str(data.biome_json(id))?;
let mut steps = Vec::new();
for step in json["features"].as_array().into_iter().flatten() {
let mut list = Vec::new();
let entries = match step {
Value::String(tag) if tag.starts_with('#') => tags
.get(&super::tags::identifier(&tag[1..])?)
.cloned()
.ok_or_else(|| resource(format!("unknown feature tag {tag}")))?,
Value::String(name) => vec![name.clone()],
Value::Array(values) => values
.iter()
.map(|v| {
v.as_str()
.map(str::to_owned)
.ok_or_else(|| resource("inline placed feature in biome"))
})
.collect::<Result<_, _>>()?,
_ => return Err(resource("biome feature step")),
};
for entry in entries {
let feature = identity(&super::tags::identifier(&entry)?);
list.push(feature);
biome_features[id.0 as usize].insert(feature);
}
steps.push(list);
}
plan.push((id, steps));
}
let plan = FeatureDecorationPlan::new(plan).map_err(|e| resource(e.to_string()))?;
let weather = BiomeWeatherBindings::new(&bindings).ok();
Ok(Some(Self {
plan,
names,
features,
biome_features,
weather,
blocks: FeatureBlocks::from_registry(registry)?,
bindings,
}))
}
/// Placed-feature roots that cannot run, with their decode errors.
pub(super) fn unsupported(&self) -> Vec<(String, String)> {
self.names
.iter()
.zip(&self.features)
.filter_map(|(name, feature)| feature.as_ref().err().map(|e| (name.clone(), e.clone())))
.collect()
}
pub(super) fn decorate(
&self,
data: &Arc<GeneratorData>,
seed: i64,
generation: WorldGenerationContext,
worker: &mut WorkerState,
region: &mut [ProtoChunk; 9],
next_boolean: impl FnMut() -> bool,
) -> Result<DecorateStats, GeneratorError> {
let center = region[4].position();
for (i, chunk) in region.iter().enumerate() {
let expected = ChunkPos::new(
center.x.wrapping_add(i as i32 % 3 - 1),
center.z.wrapping_add(i as i32 / 3 - 1),
);
if chunk.position() != expected {
return Err(resource("decoration region is not a 3×3 neighborhood"));
}
if (chunk.terrain.generation_stage() as u8) < PreLightChunkStage::Terrain as u8 {
return Err(resource("decoration requires terrain-stage chunks"));
}
}
if region[4].is_decorated() {
return Ok(DecorateStats::default());
}
let mut chunks = Vec::with_capacity(9);
let mut biomes = Vec::with_capacity(9);
let (min_y, height) = (region[4].terrain.min_y(), region[4].terrain.height());
for chunk in region.iter_mut() {
let empty = super::terrain::TerrainChunk::new(
chunk.position(),
min_y,
height,
data.registry(),
data.block_states().clone(),
)
.map_err(|e| resource(e.to_string()))?;
chunks.push(std::mem::replace(&mut chunk.terrain, empty));
biomes.push(chunk.biomes().clone());
}
let terrain = TerrainRegion::new(chunks, generation)
.and_then(|region| region.with_block_bindings(&self.bindings));
let terrain = match terrain {
Ok(terrain) => terrain,
Err(e) => return Err(resource(e.to_string())),
};
let mut next_boolean = next_boolean;
let mut world = World {
next_boolean: &mut next_boolean,
blocks: data
.feature_resources
.as_ref()
.and_then(|r| r.blocks.as_ref()),
region: terrain,
biomes: BiomeRegion::new(biomes, obfuscate_seed(seed))
.map_err(|e| resource(e.to_string()))?,
zone: GenerationWriteZone::new(center, 1),
decoration: self,
temperatures: &mut worker.temperatures,
};
let mut stats = DecorateStats::default();
let blocks = self.blocks;
let result = self.plan.decorate_features(
&mut world,
center,
seed,
|world, placer, random, id, origin| {
let Ok(feature) = &self.features[id.0 as usize] else {
stats.unsupported += 1;
stats.skipped.insert(self.names[id.0 as usize].clone());
return Ok(false);
};
stats.placed += 1;
let placed = placer.place_with_biome_check(
&feature.placement,
world,
random,
origin,
id,
|world, random, p| feature.feature.place(world, random, p, blocks),
);
if placed.is_err() {
stats.failed += 1;
stats.skipped.insert(self.names[id.0 as usize].clone());
}
Ok(placed.unwrap_or(false))
},
);
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;
region[index as usize].terrain = terrain;
}
result.map_err(|e| GeneratorError::Stage("features", e.to_string()))?;
region[4]
.terrain
.set_generation_stage(PreLightChunkStage::Features);
region[4].set_decorated();
Ok(stats)
}
}
/// 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> {
next_boolean: &'a mut dyn FnMut() -> bool,
blocks: Option<&'a BlockBehavior>,
region: TerrainRegion<'static, GenBlockStates>,
biomes: BiomeRegion<BiomeId>,
zone: GenerationWriteZone,
decoration: &'a Decoration,
temperatures: &'a mut [BiomeTemperature],
}
impl DecorationWorld for World<'_> {
type Error = RegionError;
fn min_section_y(&mut self) -> Result<i32, RegionError> {
Ok(self
.region
.min_y()
.map_err(|_| RegionError::InvalidChunks)?
>> 4)
}
fn chunk_biomes(&mut self, chunk: ChunkPos) -> Result<Vec<BiomeId>, RegionError> {
self.biomes
.present_in_chunk(chunk)
.map_err(RegionError::Biome)
}
fn set_currently_generating(&mut self, _: Option<FeatureIdentity>) -> Result<(), RegionError> {
Ok(())
}
}
impl FeatureWorld for World<'_> {
type Error = RegionError;
fn block(&mut self, position: [i32; 3]) -> Result<BlockStateId, RegionError> {
self.region.block(position)
}
fn set_block(
&mut self,
position: [i32; 3],
state: BlockStateId,
_flags: i32,
) -> Result<bool, RegionError> {
if !self
.zone
.contains_block(BlockPos::new(position[0], position[1], position[2]))
{
return Ok(false);
}
self.region.set_block_worldgen(position, state)?;
Ok(true)
}
}
fn query(e: impl std::fmt::Display) -> PlacementQueryError {
PlacementQueryError::Failed(e.to_string())
}
impl<'a> World<'a> {
fn blocks(&self) -> Result<&'a BlockBehavior, PlacementQueryError> {
self.blocks.ok_or(PlacementQueryError::Unavailable)
}
}
/// Proto chunks hold no block entities, so dynamic shapes resolve to absent.
impl DynamicSupportWorld for World<'_> {
type Error = PlacementQueryError;
fn shulker_is_closed(&mut self, _: [i32; 3]) -> Result<Option<bool>, PlacementQueryError> {
Ok(None)
}
fn moving_piston_shape(
&mut self,
_: [i32; 3],
) -> Result<Option<VoxelShape>, PlacementQueryError> {
Ok(None)
}
}
impl DynamicCollisionWorld for World<'_> {
fn shulker_collision_state(
&mut self,
_: [i32; 3],
) -> Result<Option<ShulkerCollisionState>, PlacementQueryError> {
Ok(None)
}
}
impl SurvivalWorld for World<'_> {
fn fluid_state(&mut self, position: [i32; 3]) -> Result<FluidState, PlacementQueryError> {
self.region.fluid_state(position)
}
/// Unlit generation chunks report no sky or block light.
fn raw_brightness(&mut self, _: [i32; 3], _: i32) -> Result<i32, PlacementQueryError> {
Ok(0)
}
fn block_state(&mut self, position: [i32; 3]) -> Result<BlockStateId, PlacementQueryError> {
self.region.block_state(position)
}
}
impl PlacementContext for World<'_> {
fn state_collision_empty(
&mut self,
state: BlockStateId,
position: [i32; 3],
) -> Result<bool, PlacementQueryError> {
let collision = self.blocks()?.collision.clone();
collision
.collision_shape(self, state, position)
.map(|shape| shape.is_empty())
.map_err(query)
}
/// Block entities are not stored in proto chunks; loot tables are no-ops.
fn set_block_entity_loot_table(
&mut self,
_: [i32; 3],
_: &str,
_: &mut impl horizon_core::random::RandomSource,
) -> Result<(), PlacementQueryError> {
Ok(())
}
fn attachment_at(
&mut self,
position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
let blocks = self.blocks()?;
blocks
.survival
.can_attach_to(self, position, direction)
.map_err(query)
}
fn next_world_boolean(&mut self) -> Result<bool, PlacementQueryError> {
Ok((self.next_boolean)())
}
fn block_survives(
&mut self,
state: BlockStateId,
position: [i32; 3],
) -> Result<bool, PlacementQueryError> {
let blocks = self.blocks()?;
blocks
.survival
.can_survive(self, state, position)
.map_err(query)
}
fn face_sturdy(
&mut self,
position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
let state = self.region.block_state(position)?;
self.state_face_sturdy(state, position, direction)
}
fn state_face_sturdy(
&mut self,
state: BlockStateId,
position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
let support = self.blocks()?.support.clone();
support
.is_face_sturdy(self, state, position, direction, SupportType::Full)
.map_err(query)
}
/// Generation regions contain no entities.
fn unobstructed_block(&mut self, _: [i32; 3]) -> Result<bool, PlacementQueryError> {
Ok(true)
}
fn destroy_block_without_entity(
&mut self,
position: [i32; 3],
_drop_resources: bool,
) -> Result<bool, PlacementQueryError> {
let chunk = self.region.chunk(position[0] >> 4, position[2] >> 4)?;
let state = chunk.block(position[0], position[1], position[2]);
if chunk.block_properties(state).is_air() {
return Ok(false);
}
let air = self
.decoration
.bindings
.registry()
.default_state("minecraft:air")
.ok_or(PlacementQueryError::Unavailable)?;
self.set_block(position, air, 3).map_err(query)
}
fn biome_should_freeze(
&mut self,
biome: BiomeId,
position: [i32; 3],
require_edge: bool,
) -> Result<bool, PlacementQueryError> {
let weather = self
.decoration
.weather
.clone()
.ok_or(PlacementQueryError::Unavailable)?;
let settings = self.temperatures[biome.0 as usize].settings();
let mut temperature = std::mem::replace(
&mut self.temperatures[biome.0 as usize],
BiomeTemperature::new(settings),
);
let result = weather.should_freeze(self, &mut temperature, position, require_edge);
self.temperatures[biome.0 as usize] = temperature;
result
}
fn biome_should_snow(
&mut self,
biome: BiomeId,
position: [i32; 3],
) -> Result<bool, PlacementQueryError> {
let weather = self
.decoration
.weather
.clone()
.ok_or(PlacementQueryError::Unavailable)?;
let settings = self.temperatures[biome.0 as usize].settings();
let mut temperature = std::mem::replace(
&mut self.temperatures[biome.0 as usize],
BiomeTemperature::new(settings),
);
let result = weather.should_snow(self, &mut temperature, position);
self.temperatures[biome.0 as usize] = temperature;
result
}
/// Lighting has not run during FEATURES; block light reads zero.
fn block_brightness(&mut self, _: [i32; 3]) -> Result<i32, PlacementQueryError> {
Ok(0)
}
fn fluid_state(&mut self, position: [i32; 3]) -> Result<FluidState, PlacementQueryError> {
self.region.fluid_state(position)
}
fn sea_level(&mut self) -> Result<i32, PlacementQueryError> {
self.region.sea_level()
}
fn schedule_fluid_tick(
&mut self,
position: [i32; 3],
fluid: FluidKind,
delay: i32,
) -> Result<(), PlacementQueryError> {
self.region.schedule_fluid_tick(position, fluid, delay)
}
fn mark_postprocessing(&mut self, position: [i32; 3]) -> Result<(), PlacementQueryError> {
self.region.mark_postprocessing(position)
}
fn water_at(&mut self, position: [i32; 3]) -> Result<bool, PlacementQueryError> {
self.region.water_at(position)
}
fn schedule_block_tick(
&mut self,
position: [i32; 3],
block: BlockStateId,
delay: i32,
) -> Result<(), PlacementQueryError> {
self.region.schedule_block_tick(position, block, delay)
}
fn biome_identity(&mut self, position: [i32; 3]) -> Result<BiomeId, PlacementQueryError> {
self.region
.biome_at(
&self.biomes,
BlockPos::new(position[0], position[1], position[2]),
)
.copied()
.map_err(Into::into)
}
fn biome_allows_feature(
&mut self,
position: [i32; 3],
feature: FeatureIdentity,
) -> Result<bool, PlacementQueryError> {
let biome = self.biome_identity(position)?;
Ok(self.decoration.biome_features[biome.0 as usize].contains(&feature))
}
fn block_state(&mut self, position: [i32; 3]) -> Result<BlockStateId, PlacementQueryError> {
self.region.block_state(position)
}
fn block_matches_tag(
&mut self,
position: [i32; 3],
tag: &str,
) -> Result<bool, PlacementQueryError> {
self.region.block_matches_tag(position, tag)
}
fn max_y(&mut self) -> Result<i32, PlacementQueryError> {
self.region.max_y()
}
fn layer_block(&mut self, position: [i32; 3]) -> Result<LayerBlock, PlacementQueryError> {
self.region.layer_block(position)
}
fn generation(&self) -> WorldGenerationContext {
self.region.generation()
}
fn min_y(&mut self) -> Result<i32, PlacementQueryError> {
self.region.min_y()
}
fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result<i32, PlacementQueryError> {
self.region.height(kind, x, z)
}
}
+21 -14
View File
@@ -482,10 +482,20 @@ pub fn fill_noise<B: TerrainBlockStates>(
chunk.ensure_heightmap(HeightmapType::WorldSurfaceWg);
let mut density = vec![0.; volume.size()];
final_density.sample_volume(context, &mut density, volume)?;
const MAPS: [HeightmapType; 2] = [HeightmapType::OceanFloorWg, HeightmapType::WorldSurfaceWg];
for z in 0..sz {
let world_z = bz.wrapping_add(z as i32);
for x in 0..sx {
let world_x = bx.wrapping_add(x as i32);
// Heightmap updates at or below first-available - 2 are no-ops; the
// bound only changes through an update, so skip those calls.
let mut settled = MAPS.map(|kind| {
chunk.heightmaps[kind as usize]
.as_ref()
.expect("ensured heightmap")
.first_available(x as i32, z as i32)
.map(|first| first.wrapping_sub(2))
});
for y in (0..sy).rev() {
let world_y = by.wrapping_add(y as i32);
let value = density[volume.index([x, y, z]).expect("valid density coordinates")];
@@ -496,20 +506,17 @@ pub fn fill_noise<B: TerrainBlockStates>(
continue;
}
chunk.set_block_raw(x as i32, world_y, z as i32, state)?;
chunk.update_heightmap(
HeightmapType::OceanFloorWg,
x as i32,
world_y,
z as i32,
state,
)?;
chunk.update_heightmap(
HeightmapType::WorldSurfaceWg,
x as i32,
world_y,
z as i32,
state,
)?;
for (kind, settled) in MAPS.into_iter().zip(&mut settled) {
if matches!(settled, Ok(bound) if world_y <= *bound) {
continue;
}
chunk.update_heightmap(kind, x as i32, world_y, z as i32, state)?;
*settled = chunk.heightmaps[kind as usize]
.as_ref()
.expect("ensured heightmap")
.first_available(x as i32, z as i32)
.map(|first| first.wrapping_sub(2));
}
if aquifer.should_schedule_fluid_update()
&& chunk.blocks.properties.heightmap_state(state).has_fluid()
{
+56
View File
@@ -15,6 +15,61 @@ 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)
presets = reports
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:
presets = None
# Block behavior used by feature placement checks (survival, support, collision).
# These come from the Java exporters of the simple-block parity run.
behavior = local/'rust-simple-block-parity'
blocks = out/'blocks'
names = ['block-properties.nbt', 'cached-collision.nbt', 'cached-support.nbt', 'survival-rules.json',
'survival-extra-definitions.json', 'placement-definitions.json']
if all((behavior/name).exists() for name in names):
blocks.mkdir(exist_ok=True)
for name in names:
(blocks/name).write_bytes((behavior/name).read_bytes())
else:
print('Feature block behavior exports missing; run tools/test_simple_block_parity.py for full decoration')
if presets is None:
# 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,6 +215,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)
count = 0
# The playable client needs every client asset (textures, models, fonts, GUI)
# and every data-pack resource (worldgen, recipes, loot tables, tags).