From 11b8a98ff5e4cdf5eeac29fdf75e5705be83e780 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 18:51:18 +0200 Subject: [PATCH] Match vanilla random ticks on every comparable case The random tick oracle now stands on a real overworld: the data pack's dimension type (for fire's infiniburn tag), its attributes and day timeline on a clock at the fixture's day time, level data for difficulty, and block scans that walk positions in BlockScanUtils' section order, since 26.3 reads chunk sections the map-backed level does not have. Horizon now rolls the nether portal's zombified piglin spawn with the level random (the client spawns it near a player), rechecks chest and ender chest openers through a new block entity hook and broadcasts the lid event, gives melting ice and placed sniffer eggs their game events, and reads the weather age of copper golem statues, which name the field weatheringState. The fixture prints empty dispensers, crafters, ghastling spawns and fresh shriekers as vanilla resolves them. Random ticks match on 39,998 of 39,998 compared cases (two propagules cannot grow trees in the oracle), block updates on 40,000 of 40,000 and redstone on 3,999 of 4,000. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 5 + crates/horizon-client/src/game/chat.rs | 2 + crates/horizon-client/src/game/creatures.rs | 32 +++++ .../examples/block_update_fixture.rs | 12 ++ crates/horizon-world/src/level/data.rs | 4 +- crates/horizon-world/src/level/hooks.rs | 8 +- crates/horizon-world/src/level/mod.rs | 15 ++- crates/horizon-world/src/level/tick.rs | 37 +++++- .../parity/VanillaBlockUpdateOracle.java | 120 +++++++++++++++++- 9 files changed, 227 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 4f187952b..00e025094 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1552,6 +1552,11 @@ impl Game<'_> { kind: "hatch_sniffer", .. } => self.hatch_sniffer([pos.x, pos.y, pos.z]), + LevelEvent::BlockEvent { + pos, + kind: "portal_spawn", + .. + } => self.portal_spawn([pos.x, pos.y, pos.z]), LevelEvent::BlockEvent { pos, state, diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 1e25d770e..812ac6118 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -547,6 +547,8 @@ impl Game<'_> { block_drops: r.bool("block_drops"), mob_griefing: r.bool("mob_griefing"), max_snow_accumulation_height: r.int("max_snow_accumulation_height"), + spawn_mobs: r.bool("spawn_mobs"), + spawn_monsters: r.bool("spawn_monsters"), } } /// Apply rules mirrored in other state (natural regeneration, difficulty). diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index b007ac2dd..033f1d812 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2672,3 +2672,35 @@ fn push_apart(mobs: &mut [Mob]) { } } } + +impl Game<'_> { + /// The rest of `NetherPortalBlock.randomTick` after a won roll: with a + /// player close enough for spawning, a zombified piglin spawns on the block + /// under the portal column when it is a valid spawn. + pub(super) fn portal_spawn(&mut self, pos: [i32; 3]) { + // ChunkMap.anyPlayerCloseEnoughForSpawning: a non-spectator within 128 + // blocks of the chunk centre. + let centre = [f64::from((pos[0] >> 4) * 16 + 8), f64::from((pos[2] >> 4) * 16 + 8)]; + let spectator = self.spectator(); + let Some(close) = self.player.as_ref().filter(|_| !spectator).map(|p| { + let (dx, dz) = (p.position.x - centre[0], p.position.z - centre[1]); + dx * dx + dz * dz < 16384.0 + }) else { + return; + }; + if !close { + return; + } + let mut y = pos[1]; + while &*self.res.facts.get(self.world.block(pos[0], y, pos[2])).name == "minecraft:nether_portal" { + y -= 1; + } + // isValidSpawn: a sturdy top face (portal frames emit no light). + let below = self.res.facts.get(self.world.block(pos[0], y, pos[2])); + if below.sturdy_full & (1 << 1) == 0 { + return; + } + let at = [f64::from(pos[0]) + 0.5, f64::from(y + 1), f64::from(pos[2]) + 0.5]; + let _ = self.spawn_mob("minecraft:zombified_piglin", at, false); + } +} diff --git a/crates/horizon-world/examples/block_update_fixture.rs b/crates/horizon-world/examples/block_update_fixture.rs index 42fdd1380..816af34f5 100644 --- a/crates/horizon-world/examples/block_update_fixture.rs +++ b/crates/horizon-world/examples/block_update_fixture.rs @@ -50,6 +50,10 @@ impl LevelAccess for Cells { fn is_loaded(&self, _pos: BlockPos) -> bool { true } + /// A chest's fresh block entity: nobody has it open. + fn recheck_container_openers(&mut self, _pos: BlockPos) -> Option<(i32, i32)> { + Some((0, 0)) + } /// A fresh command block entity: unpowered and not automatic. fn set_command_block_powered(&mut self, pos: BlockPos, powered: bool) -> Option<(bool, bool)> { Some((self.command_blocks.insert(pos, powered).unwrap_or(false), false)) @@ -313,6 +317,14 @@ fn main() -> Result<(), Box> { } } } + // DriedGhastBlock.spawnGhastling, as the client does it. + LevelEvent::BlockEvent { kind: "spawn_ghastling", .. } => { + let _ = writeln!(result, "E minecraft:happy_ghast"); + let _ = writeln!(result, "S entity minecraft:entity.ghastling.spawn"); + } + // A fresh shrieker has warning level 0 and so never responds, + // and no player is near enough for a portal to spawn a piglin. + LevelEvent::BlockEvent { kind: "shrieker_respond" | "portal_spawn", .. } => {} LevelEvent::BlockEvent { kind, .. } => { let _ = writeln!(result, "X {kind}"); } diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 1c347d136..a3736fb20 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -993,7 +993,9 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result 1, Some("WEATHERED") => 2, Some("OXIDIZED") => 3, diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index 849a14ae4..d91198035 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -193,6 +193,7 @@ impl Sim<'_, L> { if boosted { self.level_event(3009, pos, 0); } + self.game_event_state(pos, "minecraft:block_place", state); let delay = if boosted { 12000 } else { 24000 } / 3; let jitter = self.random().next_int_bound(300).unwrap_or(0); self.schedule_tick(pos, block, delay + jitter); @@ -538,11 +539,11 @@ impl Sim<'_, L> { true } /// `FrostedIceBlock.melt` → `IceBlock.melt`. - pub(crate) fn frosted_ice_melt(&mut self, pos: BlockPos, _state: BlockStateId) { - self.ice_melt(pos); + pub(crate) fn frosted_ice_melt(&mut self, pos: BlockPos, state: BlockStateId) { + self.ice_melt(pos, state); } /// `IceBlock.melt`. - pub(crate) fn ice_melt(&mut self, pos: BlockPos) { + pub(crate) fn ice_melt(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; if self.level.dimension() == super::Dimension::Nether { self.remove_block(pos, false); @@ -550,6 +551,7 @@ impl Sim<'_, L> { let water = b.default_of(b.named.water); self.set_block_and_update(pos, water); self.neighbor_changed_at(pos, b.named.water); + self.game_event_state(pos, "minecraft:block_destroy", state); } } /// `BigDripleafBlock.resetTilt`. diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index c53500f5c..4f240ae6b 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -177,6 +177,8 @@ pub struct GameRules { pub block_drops: bool, pub mob_griefing: bool, pub max_snow_accumulation_height: i32, + pub spawn_mobs: bool, + pub spawn_monsters: bool, } impl Default for GameRules { fn default() -> Self { @@ -187,6 +189,8 @@ impl Default for GameRules { block_drops: true, mob_griefing: true, max_snow_accumulation_height: 1, + spawn_mobs: true, + spawn_monsters: true, } } } @@ -247,7 +251,9 @@ pub enum LevelEvent { PrimeTnt { pos: BlockPos, rot: f64 }, /// Block-entity or entity side effects the caller implements: `"dispense"` /// (dispenser/dropper/crafter scheduled tick), `"hatch"` (frogspawn - /// hatched into tadpoles; the block is already destroyed). + /// hatched into tadpoles; the block is already destroyed), `"portal_spawn"` + /// (a nether portal won its zombified piglin roll; the caller checks + /// `anyPlayerCloseEnoughForSpawning` and spawns below the portal). BlockEvent { pos: BlockPos, state: BlockStateId, @@ -335,6 +341,13 @@ pub trait LevelAccess { ) -> i32 { 0 } + /// `ContainerOpenersCounter.recheckOpenCount` for the chest or ender chest + /// block entity at `pos`: recounts its openers and returns the previous + /// and new counts (the caller plays open/close effects when they change), + /// or None when there is no such block entity. + fn recheck_container_openers(&mut self, _pos: BlockPos) -> Option<(i32, i32)> { + None + } /// `CommandBlockEntity.setPowered` for the command block entity at `pos`: /// stores `powered` and returns the previous flag and `isAutomatic`, or /// None when there is no command block entity. diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 9d7ad93f0..f801f95ba 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -95,6 +95,21 @@ impl Sim<'_, L> { } } } + Class::Chest | Class::EnderChest => { + // recheckOpen: openerCountChanged broadcasts the lid, a + // trapped chest also updates its neighbours on a change, + // and the recheck repeats while anyone has it open. + if let Some((previous, count)) = self.level.recheck_container_openers(pos) { + self.block_event(pos, block, 1, count); + if previous != count && b.data(state).is(Class::TrappedChest) { + self.update_neighbors_at(pos, block); + self.update_neighbors_at(below(pos), block); + } + if count > 0 { + self.schedule_tick(pos, block, 5); + } + } + } Class::Dispenser | Class::Crafter => { self.emit(LevelEvent::BlockEvent { pos, @@ -243,6 +258,24 @@ impl Sim<'_, L> { } } Class::Farmland => self.farmland_random_tick(state, pos), + Class::NetherPortal => { + // NetherPortalBlock.randomTick: only the overworld sets + // NETHER_PORTAL_SPAWNS_PIGLINS. + let rules = self.level.game_rules(); + let difficulty = self.level.difficulty(); + if rules.spawn_mobs + && rules.spawn_monsters + && difficulty != 0 + && self.level.dimension() == super::Dimension::Overworld + && self.rand_int(2000) < difficulty + { + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "portal_spawn", + }); + } + } Class::GrowingPlantHead => { if b.table.int(state, p.age) < 25 && self.random().next_double() < data.grow_probability @@ -256,7 +289,7 @@ impl Sim<'_, L> { } Class::Ice => { if self.level.block_light(pos) > 11 - i32::from(b.facts(state).dampening) { - self.ice_melt(pos); + self.ice_melt(pos, state); } } Class::Leaves => { @@ -655,7 +688,7 @@ impl Sim<'_, L> { self.set_block(pos, b.table.set_int(state, b.props.age, age + 1), 2); false } else { - self.ice_melt(pos); + self.ice_melt(pos, state); true } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java index e0f79864e..85c76065d 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -198,6 +198,42 @@ public final class VanillaBlockUpdateOracle { @Override public boolean isPositionEntityTicking(BlockPos p) { return true; } @Override public boolean shouldTickBlocksAt(BlockPos p) { return true; } @Override public boolean shouldTickBlocksAt(long p) { return true; } + @Override public boolean canSpreadFireAround(BlockPos p) { return true; } + @Override public net.minecraft.world.Difficulty getDifficulty() { return net.minecraft.world.Difficulty.NORMAL; } + // 26.3 block scans read chunk sections; this level has none, so scan + // the same positions in the same order through getBlockState. + @Override public net.minecraft.world.level.blockscan.BlockMatcher findBlocksIn(BlockPos from, BlockPos to) { + return new Scan(this, boxOrder(from, to)); + } + @Override public net.minecraft.world.level.blockscan.OrderedBlockMatcher findBlocksIn(Iterable positions) { + return new Scan(this, positions); + } + /** BlockScanUtils.sectionBasedScan's order: sections by x, z, y, then y, z, x inside; then below and above the world. */ + List boxOrder(BlockPos from, BlockPos to) { + int minX = Math.min(from.getX(), to.getX()), minY = Math.min(from.getY(), to.getY()), minZ = Math.min(from.getZ(), to.getZ()); + int maxX = Math.max(from.getX(), to.getX()), maxY = Math.max(from.getY(), to.getY()), maxZ = Math.max(from.getZ(), to.getZ()); + List out = new ArrayList<>(); + for (int sx = minX >> 4; sx <= maxX >> 4; sx++) { + for (int sz = minZ >> 4; sz <= maxZ >> 4; sz++) { + for (int sy = Math.max(getMinSectionY(), minY >> 4); sy <= Math.min(getMaxSectionY(), maxY >> 4); sy++) { + for (int y = Math.max(sy << 4, minY); y <= Math.min((sy << 4) + 15, maxY); y++) { + for (int z = Math.max(sz << 4, minZ); z <= Math.min((sz << 4) + 15, maxZ); z++) { + for (int x = Math.max(sx << 4, minX); x <= Math.min((sx << 4) + 15, maxX); x++) { + out.add(new BlockPos(x, y, z)); + } + } + } + } + } + } + if (minY < getMinY()) { + for (BlockPos q : BlockPos.betweenClosed(minX, minY, minZ, maxX, getMinY() - 1, maxZ)) out.add(q.immutable()); + } + if (maxY > getMaxY()) { + for (BlockPos q : BlockPos.betweenClosed(minX, getMaxY() + 1, minZ, maxX, maxY, maxZ)) out.add(q.immutable()); + } + return out; + } // Allocated without a constructor, so the sound seed generator, attribute // system and chunk source are missing. Sound seeds never touch the level // RNG, the overworld keeps every attribute default and entity ids are not @@ -205,10 +241,19 @@ public final class VanillaBlockUpdateOracle { int nextEntityId; net.minecraft.world.attribute.EnvironmentAttributeSystem attributes; @Override public int getNextEntityId() { return ++nextEntityId; } + // The overworld's dimension attributes and timelines on a clock at the + // fixture's day time (6000); biome and weather layers are not modelled. @Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { - if (attributes == null) attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build(); + if (attributes == null) { + var builder = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addConstantLayer(OVERWORLD_TYPE.attributes()); + OVERWORLD_TYPE.timelines().forEach(timeline -> builder.addTimelineLayer(timeline, clock -> DAY)); + attributes = builder.build(); + } return attributes; } + @Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return OVERWORLD_TYPE; } + @Override public net.minecraft.world.level.storage.ServerLevelData getLevelData() { return LEVEL_DATA; } + @Override public boolean anyPlayerCloseEnoughForSpawning(BlockPos p) { return false; } @Override public void playSound(Entity except, double x, double y, double z, SoundEvent sound, SoundSource source, float volume, float pitch) { playSeededSound(except, x, y, z, BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), source, volume, pitch, 0L); } @@ -220,6 +265,78 @@ public final class VanillaBlockUpdateOracle { } } + /** A block matcher over explicit positions; outside the build height every block reads as air. */ + static final class Scan extends net.minecraft.world.level.blockscan.OrderedBlockMatcher { + final World world; + Iterable positions; + Scan(World world, Iterable positions) { + super(world, positions); + this.world = world; + this.positions = positions; + } + @Override public Scan filterPos(java.util.function.Predicate predicate) { + positions = com.google.common.collect.Iterables.filter(positions, predicate::test); + return this; + } + @Override public Scan filterState(java.util.function.Predicate predicate) { + super.filterState(predicate); + return this; + } + boolean scan(java.util.function.Predicate predicate, net.minecraft.world.level.blockscan.BlockStateConsumer consumer) { + for (BlockPos p : positions) { + BlockState s = p.getY() >= world.getMinY() && p.getY() <= world.getMaxY() ? world.getBlockState(p) : AIR; + if (predicate.test(s) && consumer.apply(p, s).shouldAbort()) return true; + } + return false; + } + @Override public boolean atLeastMatched(int n) { + int[] count = {0}; + return scan(statePredicate, (p, s) -> net.minecraft.util.Continuation.abortIf(++count[0] >= n)); + } + @Override protected boolean anyMatched(java.util.function.Predicate predicate) { + return scan(predicate, (p, s) -> net.minecraft.util.Continuation.ABORT); + } + @Override public void forEach(java.util.function.BiConsumer consumer) { + scan(statePredicate, (p, s) -> { consumer.accept(p, s); return net.minecraft.util.Continuation.CONTINUE; }); + } + @Override public boolean forEachUntil(net.minecraft.world.level.blockscan.BlockStateConsumer consumer) { + return scan(statePredicate, consumer); + } + } + + static net.minecraft.world.level.dimension.DimensionType OVERWORLD_TYPE; + static final net.minecraft.world.clock.ClockInstance DAY = new net.minecraft.world.clock.ClockInstance() { + @Override public long totalTicks() { return 6000L; } + @Override public float partialTick() { return 0f; } + @Override public float rate() { return 1f; } + @Override public boolean isPaused() { return false; } + }; + static final net.minecraft.world.level.storage.ServerLevelData LEVEL_DATA = (net.minecraft.world.level.storage.ServerLevelData) java.lang.reflect.Proxy.newProxyInstance( + VanillaBlockUpdateOracle.class.getClassLoader(), new Class[] {net.minecraft.world.level.storage.ServerLevelData.class}, (proxy, method, values) -> { + Class type = method.getReturnType(); + if (type == long.class) return 0L; + if (type == int.class) return 0; + if (type == boolean.class) return false; + if (type == float.class) return 0f; + if (type == double.class) return 0d; + if (type == net.minecraft.world.Difficulty.class) return net.minecraft.world.Difficulty.NORMAL; + return null; + }); + + /** The overworld dimension type from the vanilla data pack (its infiniburn tag, attributes and timelines). */ + static net.minecraft.world.level.dimension.DimensionType loadOverworld() { + var repo = net.minecraft.server.packs.repository.ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new net.minecraft.server.packs.resources.MultiPackResourceManager(net.minecraft.server.packs.PackType.SERVER_DATA, repo.openAllSelected()); + var layers = net.minecraft.server.RegistryLayer.createRegistryAccess(); + var staticTags = net.minecraft.tags.TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(net.minecraft.server.RegistryLayer.STATIC)); + var context = net.minecraft.tags.TagLoader.buildUpdatedLookups(layers.getAccessForLoading(net.minecraft.server.RegistryLayer.WORLD), staticTags); + var world = net.minecraft.resources.RegistryDataLoader.load(resources, context, net.minecraft.resources.RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + staticTags.forEach(net.minecraft.core.Registry.PendingTags::apply); + return world.lookupOrThrow(net.minecraft.core.registries.Registries.DIMENSION_TYPE).getOrThrow(net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD).value(); + } + static final class Loot extends net.minecraft.server.ReloadableServerRegistries.Holder { World world; Loot() { @@ -296,6 +413,7 @@ public final class VanillaBlockUpdateOracle { Path resources = Path.of(args[0]); VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(resources.resolve("block-tags.json"))).getAsJsonObject()); VanillaLevelShapeOracle.bindFluidTags(resources.resolve("data/minecraft/tags/fluid")); + OVERWORLD_TYPE = loadOverworld(); var allocator = Class.forName("sun.misc.Unsafe"); var field = allocator.getDeclaredField("theUnsafe"); field.setAccessible(true);