WIP: chunk parity structure fixes

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 03:47:54 +02:00
parent 90023be7c2
commit 1d6b7b5a0c
7 changed files with 167 additions and 2 deletions
@@ -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,
+1
View File
@@ -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;
@@ -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<usize, Vec<usize>> = 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<i64> = 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(
@@ -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<usize> {
let mut n = array_size(16);
let mut table: Vec<Option<usize>> = 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<Option<usize>> = 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::<usize>::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<i64> = (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::<Vec<_>>());
}
}
@@ -152,6 +152,8 @@ pub struct StateTransforms {
mirror: Vec<[u32; 2]>,
full: Vec<bool>,
loot: BTreeSet<BlockStateId>,
/// Block entity type of every state that has one (`BlockState.hasBlockEntity`).
entity_types: HashMap<BlockStateId, Arc<str>>,
}
impl StateTransforms {
pub fn from_json(json: &str, states: usize) -> Result<Self, super::DecodeError> {
@@ -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<str> = 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<str>> {
self.entity_types.get(&state)
}
pub fn rotate(&self, state: BlockStateId, rotation: Rotation) -> BlockStateId {
match rotation {
Rotation::None => state,
@@ -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<Integer, List<String>>();
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());
}
}
@@ -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);
}
}