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) <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-07 19:14:23 +02:00
parent 082cbb4077
commit 497cb8e0e3
5 changed files with 1626 additions and 1 deletions
@@ -0,0 +1,370 @@
//! 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())
}
}
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 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
);
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 !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(())
}
+2
View File
@@ -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;
File diff suppressed because it is too large Load Diff
@@ -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<GeneratorData>,
_source: &ResolvedBiomeSource,
) -> Result<Option<Self>, GeneratorError> {
Ok(None)
}
pub(super) fn decorate(
&self,
_data: &Arc<GeneratorData>,
_seed: i64,
_generation: WorldGenerationContext,
_worker: &mut WorkerState,
_region: &mut [ProtoChunk; 9],
) -> Result<DecorateStats, GeneratorError> {
Ok(DecorateStats::default())
}
}
+42 -1
View File
@@ -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'))