From 1d6b7b5a0cb27165be5ad33d7e3f392b22aae258 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:47:54 +0200 Subject: [PATCH] WIP: chunk parity structure fixes Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-world/examples/chunk_dump.rs | 15 ++++ crates/horizon-world/src/worldgen.rs | 1 + .../src/worldgen/generator_structures.rs | 21 +++++ crates/horizon-world/src/worldgen/long_set.rs | 83 +++++++++++++++++++ .../horizon-world/src/worldgen/structure.rs | 16 ++++ .../parity/VanillaChunkGenerationOracle.java | 20 +++++ .../parity/VanillaStructureBlockExporter.java | 13 ++- 7 files changed, 167 insertions(+), 2 deletions(-) create mode 100644 crates/horizon-world/src/worldgen/long_set.rs diff --git a/crates/horizon-world/examples/chunk_dump.rs b/crates/horizon-world/examples/chunk_dump.rs index e7e440252..199f7e26f 100644 --- a/crates/horizon-world/examples/chunk_dump.rs +++ b/crates/horizon-world/examples/chunk_dump.rs @@ -128,6 +128,21 @@ fn main() -> Result<(), Error> { for z in z0..=z1 { for s in worker.structure_starts(ChunkPos::new(x, z)) { if s.chunk == ChunkPos::new(x, z) { + if std::env::var_os("HORIZON_PIECES").is_some() { + for piece in &s.pieces { + let b = piece.bounding_box(); + println!( + "piece {x} {z} {} {} {} {} {} {} {}", + piece.type_name(), + b.min[0], + b.min[1], + b.min[2], + b.max[0], + b.max[1], + b.max[2] + ); + } + } println!( "start {} {x} {z} {} {} {} {} {} {}", s.name, diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index 36fb43fb3..4c9295af7 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -44,6 +44,7 @@ mod generator_structures; pub mod height_provider; pub mod iceberg; pub mod live; +mod long_set; pub mod material_condition; pub mod material_extensions; pub mod material_stage; diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index 136c85264..ce584eaa4 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -10,6 +10,7 @@ use super::{ }; use horizon_core::{density::Beardifier, position::ChunkPos}; use serde_json::Value; +use std::collections::BTreeMap; use std::{ collections::{BTreeSet, HashMap}, sync::{Arc, Mutex, OnceLock}, @@ -252,6 +253,26 @@ impl StructureState { } } } + // Vanilla keeps each structure's references in a LongOpenHashSet and + // places the starts in its iteration order; reorder each structure's + // starts within the slots they already occupy. + let mut slots: BTreeMap> = BTreeMap::new(); + for (i, start) in out.iter().enumerate() { + slots.entry(start.structure).or_default().push(i); + } + let original = out.clone(); + for slots in slots.values().filter(|s| s.len() > 1) { + let keys: Vec = slots + .iter() + .map(|&i| { + let c = original[i].chunk; + i64::from(c.x as u32) | (i64::from(c.z as u32) << 32) + }) + .collect(); + for (&slot, &from) in slots.iter().zip(&super::long_set::iteration_order(&keys)) { + out[slot] = original[slots[from]].clone(); + } + } out } pub(super) fn beardifier( diff --git a/crates/horizon-world/src/worldgen/long_set.rs b/crates/horizon-world/src/worldgen/long_set.rs new file mode 100644 index 000000000..cfb79899e --- /dev/null +++ b/crates/horizon-world/src/worldgen/long_set.rs @@ -0,0 +1,83 @@ +//! Iteration order of fastutil's `LongOpenHashSet`, which vanilla uses for +//! structure references. Placing a structure's pieces consumes one shared +//! random stream, so starts must be visited in the set's order. + +const PHI: i64 = 0x9E37_79B9_7F4A_7C15_u64 as i64; +const LOAD_FACTOR: f64 = 0.75; + +fn mix(key: i64) -> usize { + let mut h = key.wrapping_mul(PHI); + h ^= ((h as u64) >> 32) as i64; + (h ^ (((h as u64) >> 16) as i64)) as i32 as u32 as usize +} + +fn array_size(expected: usize) -> usize { + ((expected as f64 / LOAD_FACTOR).ceil() as usize) + .next_power_of_two() + .max(2) +} + +fn max_fill(n: usize) -> usize { + ((n as f64 * LOAD_FACTOR).ceil() as usize).min(n - 1) +} + +/// Indices of `keys` (distinct, in insertion order) in the order a default +/// `LongOpenHashSet` holding them iterates: the zero key first, then the table +/// from its last slot down to its first. +pub fn iteration_order(keys: &[i64]) -> Vec { + let mut n = array_size(16); + let mut table: Vec> = vec![None; n]; + let mut contains_zero = None; + let mut size = 0; + for (index, &key) in keys.iter().enumerate() { + if key == 0 { + contains_zero = Some(index); + } else { + let mask = n - 1; + let mut pos = mix(key) & mask; + while table[pos].is_some() { + pos = (pos + 1) & mask; + } + table[pos] = Some(index); + } + size += 1; + if size - 1 >= max_fill(n) { + let new_n = array_size(size + 1); + let mut grown: Vec> = vec![None; new_n]; + for slot in table.iter().rev().flatten() { + let mask = new_n - 1; + let mut pos = mix(keys[*slot]) & mask; + while grown[pos].is_some() { + pos = (pos + 1) & mask; + } + grown[pos] = Some(*slot); + } + table = grown; + n = new_n; + } + } + contains_zero + .into_iter() + .chain(table.iter().rev().flatten().copied()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_and_zero_keys() { + assert_eq!(iteration_order(&[]), Vec::::new()); + assert_eq!(iteration_order(&[5]), vec![0]); + assert_eq!(iteration_order(&[7, 0]), vec![1, 0]); + } + + #[test] + fn every_key_is_visited_once_after_growth() { + let keys: Vec = (0..100).map(|i| i * 4_294_967_297 + 3).collect(); + let mut order = iteration_order(&keys); + order.sort_unstable(); + assert_eq!(order, (0..100).collect::>()); + } +} diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index 9f4108377..4b4c1cdbb 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -152,6 +152,8 @@ pub struct StateTransforms { mirror: Vec<[u32; 2]>, full: Vec, loot: BTreeSet, + /// Block entity type of every state that has one (`BlockState.hasBlockEntity`). + entity_types: HashMap>, } impl StateTransforms { pub fn from_json(json: &str, states: usize) -> Result { @@ -197,13 +199,27 @@ impl StateTransforms { .into_iter() .map(BlockStateId) .collect(); + let mut entity_types = HashMap::new(); + if let Some(types) = value["block_entities"].as_object() { + for (name, states) in types { + let name: Arc = Arc::from(name.as_str()); + for id in ids(states) { + entity_types.insert(BlockStateId(id), name.clone()); + } + } + } Ok(Self { rotate, mirror, full, loot, + entity_types, }) } + /// The block entity type a state carries, when it has one. + pub fn entity_type(&self, state: BlockStateId) -> Option<&Arc> { + self.entity_types.get(&state) + } pub fn rotate(&self, state: BlockStateId, rotation: Rotation) -> BlockStateId { match rotation { Rotation::None => state, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java index b381298ae..dad85d820 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java @@ -282,6 +282,22 @@ public final class VanillaChunkGenerationOracle { }; Runnable noop = () -> {}; try (var w = new PrintWriter(Files.newBufferedWriter(out, StandardCharsets.UTF_8))) { + if (mode.equals("random")) { + // diagnostics: first floats after setFeatureSeed for chunk X0,Z0 (args 4..) index step + int cx = Integer.parseInt(args[4]), cz = Integer.parseInt(args[5]), idx = Integer.parseInt(args[6]), step = Integer.parseInt(args[7]); + WorldgenRandom r = new WorldgenRandom(new XoroshiroRandomSource(0L)); + long ds = r.setDecorationSeed(seed, cx << 4, cz << 4); + r.setFeatureSeed(ds, idx, step); + w.println("random " + ds + " " + r.nextFloat() + " " + r.nextFloat() + " " + r.nextFloat()); + return; + } + if (mode.equals("order")) { + var byStep = new TreeMap>(); + var registry = access.lookupOrThrow(Registries.STRUCTURE); + registry.stream().forEach(st -> byStep.computeIfAbsent(st.step().ordinal(), k -> new ArrayList<>()).add(registry.getKey(st).toString())); + byStep.forEach((step, names) -> { for (int i = 0; i < names.size(); i++) w.println("order " + step + " " + i + " " + names.get(i)); }); + return; + } if (mode.equals("scan")) { int x0 = Integer.parseInt(args[4]), z0 = Integer.parseInt(args[5]), x1 = Integer.parseInt(args[6]), z1 = Integer.parseInt(args[7]); for (int x = x0; x <= x1; x++) for (int z = z0; z <= z1; z++) { @@ -291,6 +307,10 @@ public final class VanillaChunkGenerationOracle { if (!start.isValid()) continue; var box = start.getBoundingBox(); var id = access.lookupOrThrow(Registries.STRUCTURE).getKey(start.getStructure()); + if (System.getenv("HORIZON_PIECES") != null) for (var piece : start.getPieces()) { + var pb = piece.getBoundingBox(); + w.println("piece " + x + " " + z + " " + net.minecraft.core.registries.BuiltInRegistries.STRUCTURE_PIECE.getKey(piece.getType()) + " " + pb.minX() + " " + pb.minY() + " " + pb.minZ() + " " + pb.maxX() + " " + pb.maxY() + " " + pb.maxZ()); + } w.println("start " + id + " " + x + " " + z + " " + box.minX() + " " + box.minY() + " " + box.minZ() + " " + box.maxX() + " " + box.maxY() + " " + box.maxZ()); } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java index 0e37d5cda..de6d02f99 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java @@ -14,11 +14,13 @@ import net.minecraft.world.level.block.state.BlockState; /** * Original exporter of per-state structure-template behavior: BlockState.rotate * and BlockState.mirror results, StructureTemplate's full-block ordering class - * and whether the state's block entity is a RandomizableContainer. + * whether the state's block entity is a RandomizableContainer, and the block + * entity type of every state that has one. */ public final class VanillaStructureBlockExporter { public static void main(String[] args) throws Exception { SharedConstants.tryDetectVersion();Bootstrap.bootStrap(); + var entityTypes=new JsonObject(); var rotate=new JsonArray();var mirror=new JsonArray();var full=new JsonArray();var loot=new JsonArray(); Rotation[] rotations={Rotation.CLOCKWISE_90,Rotation.CLOCKWISE_180,Rotation.COUNTERCLOCKWISE_90}; Mirror[] mirrors={Mirror.LEFT_RIGHT,Mirror.FRONT_BACK}; @@ -31,10 +33,17 @@ public final class VanillaStructureBlockExporter { try{container=entityBlock.newBlockEntity(BlockPos.ZERO,state) instanceof RandomizableContainer;}catch(Throwable ignored){} } if(container)loot.add(Block.getId(state)); + if(state.hasBlockEntity()&&state.getBlock() instanceof EntityBlock entityBlock) { + try { + var type=net.minecraft.core.registries.BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(entityBlock.newBlockEntity(BlockPos.ZERO,state).getType()).toString(); + if(!entityTypes.has(type))entityTypes.add(type,new JsonArray()); + entityTypes.getAsJsonArray(type).add(Block.getId(state)); + }catch(Throwable ignored){} + } } var result=new JsonObject(); result.addProperty("states",Block.BLOCK_STATE_REGISTRY.size()); - result.add("rotate",rotate);result.add("mirror",mirror);result.add("full_block",full);result.add("loot_containers",loot); + result.add("rotate",rotate);result.add("mirror",mirror);result.add("full_block",full);result.add("loot_containers",loot);result.add("block_entities",entityTypes); Files.writeString(Path.of(args[0]),new Gson().toJson(result),StandardCharsets.UTF_8); } }