From cf570c9fba1b1f5f86e6da31524bc6be85da4fab Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 18:27:39 +0200 Subject: [PATCH] Match vanilla block updates on every harness case The block update oracle crashed on 625 cases because its constructor-less level had no sound seed generator, attribute system or chunk source; it now supplies them, keeps cave and void air apart from air, and creates block entities on demand as a real level does. With those cases compared, Horizon now primes TNT with the level random, sound and prime_fuse event at the moment of priming, links powered wooden shelves into side chains, breaks nether portals whose frame is no longer complete, reacts to power at command blocks through a new block entity hook, rings bells with their block event, uses the straw bed's own destroy particles and gives big dripleaf tilt changes their vibration. Empty dispensers also emit block_activate in the client. Block updates match on 40,000 of 40,000 cases and redstone on 3,999 of 4,000. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 2 +- crates/horizon-client/src/game/machines.rs | 3 + crates/horizon-client/src/game/tnt.rs | 34 +-- .../examples/block_update_fixture.rs | 23 ++ crates/horizon-world/src/level/data.rs | 1 + crates/horizon-world/src/level/hooks.rs | 28 ++- crates/horizon-world/src/level/interact.rs | 8 +- crates/horizon-world/src/level/mod.rs | 14 +- crates/horizon-world/src/level/portal.rs | 109 ++++++++++ crates/horizon-world/src/level/redstone.rs | 22 +- crates/horizon-world/src/level/shapes.rs | 16 +- crates/horizon-world/src/level/shelf.rs | 203 ++++++++++++++++++ crates/horizon-world/src/level/tick.rs | 42 +--- crates/horizon-world/src/level/update.rs | 20 +- .../parity/VanillaBlockUpdateOracle.java | 45 +++- 15 files changed, 490 insertions(+), 80 deletions(-) create mode 100644 crates/horizon-world/src/level/portal.rs create mode 100644 crates/horizon-world/src/level/shelf.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e7cb4b302..4f187952b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1514,7 +1514,7 @@ impl Game<'_> { } PlayerEffect::InteractLoot(_) | PlayerEffect::RespawnAnchor => {} }, - LevelEvent::PrimeTnt { pos } => self.spawn_primed_tnt(pos, false), + LevelEvent::PrimeTnt { pos, rot } => self.add_primed_tnt(pos, rot, 80), LevelEvent::BlockEvent { pos, state, diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 418d0eafc..ef66e1d96 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -604,6 +604,9 @@ impl Game<'_> { } let Some(slot) = slot else { self.dispenser_event(1001, key, 0); + if !dropper { + self.post_block_game_event("minecraft:block_activate", [pos.x, pos.y, pos.z], None, Some(state)); + } return Ok(()); }; let Some(facing) = self diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 3297fe96e..d8435da21 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -42,30 +42,34 @@ impl Game<'_> { self.post_block_game_event("minecraft:prime_fuse", [pos.x, pos.y, pos.z], who, None); let r = &mut self.world.random; let rot = r.next_double() * f64::from(std::f32::consts::TAU); + let fuse = if short { + // PrimedTnt.getRandomShortFuse + r.next_int_bound(20).unwrap_or(0) + 10 + } else { + self.audio.play( + "minecraft:entity.tnt.primed", + Some([f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5]), + 1.0, + 1.0, + ); + 80 + }; + self.add_primed_tnt(pos, rot, fuse); + } + /// Adds primed TNT at the block's bottom centre, pushed along `rot`. + pub(super) fn add_primed_tnt(&mut self, pos: BlockPos, rot: f64, fuse: i32) { let position = Vec3::new( f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5, ); - let mut tnt = PrimedTnt { + self.tnts.push(PrimedTnt { position, previous: position, velocity: Vec3::new(-rot.sin() * 0.02, f64::from(0.2f32), -rot.cos() * 0.02), - fuse: 80, + fuse, on_ground: false, - }; - if short { - // PrimedTnt.getRandomShortFuse - tnt.fuse = r.next_int_bound((tnt.fuse / 4).max(1)).unwrap_or(0) + tnt.fuse / 8; - } else { - self.audio.play( - "minecraft:entity.tnt.primed", - Some([position.x, position.y, position.z]), - 1.0, - 1.0, - ); - } - self.tnts.push(tnt); + }); } /// `PrimedTnt.tick` for every primed TNT, in order; an expired fuse /// explodes immediately (later TNT in the list feel its knockback this diff --git a/crates/horizon-world/examples/block_update_fixture.rs b/crates/horizon-world/examples/block_update_fixture.rs index b108d4ef8..42fdd1380 100644 --- a/crates/horizon-world/examples/block_update_fixture.rs +++ b/crates/horizon-world/examples/block_update_fixture.rs @@ -32,6 +32,7 @@ struct Cells { raining: bool, thundering: bool, events: Vec, + command_blocks: HashMap, } impl LevelAccess for Cells { fn block_state(&self, pos: BlockPos) -> BlockStateId { @@ -49,6 +50,10 @@ impl LevelAccess for Cells { fn is_loaded(&self, _pos: BlockPos) -> bool { true } + /// 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)) + } fn random(&mut self) -> &mut LegacyRandom { &mut self.random } @@ -161,6 +166,7 @@ fn main() -> Result<(), Box> { .and_then(|v| v.as_bool()) .unwrap_or(false), events: Vec::new(), + command_blocks: HashMap::new(), }; let mut ticks = Ticks::new(0); for x in -3..=3 { @@ -290,6 +296,23 @@ fn main() -> Result<(), Box> { LevelEvent::GameEvent { pos, event, .. } => { let _ = writeln!(result, "G {} {}", p(*pos), event); } + // Dispensing from the fixture's empty block entities, as the + // client does: the fail event, plus `block_activate` for a + // dispenser; a crafter without a recipe only fails. + LevelEvent::BlockEvent { kind: "dispense", pos, state } => { + match behaviours.table.name(*state) { + "minecraft:crafter" => { + let _ = writeln!(result, "L 1050 {} 0", p(*pos)); + } + "minecraft:dispenser" => { + let _ = writeln!(result, "L 1001 {} 0", p(*pos)); + let _ = writeln!(result, "G {} minecraft:block_activate", p(*pos)); + } + _ => { + let _ = writeln!(result, "L 1001 {} 0", p(*pos)); + } + } + } 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 b97ade119..1c347d136 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -376,6 +376,7 @@ named_blocks! { mangrove_roots = "mangrove_roots", big_dripleaf_fallback = "big_dripleaf", nether_portal = "nether_portal", + chain_command_block = "chain_command_block", frogspawn = "frogspawn", turtle_egg = "turtle_egg", sniffer_egg = "sniffer_egg", diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index 579c497bf..849a14ae4 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -1,7 +1,7 @@ //! `neighborChanged`, `onPlace`, `affectNeighborsAfterRemoval` and //! `updateIndirectNeighbourShapes` for the overriding vanilla classes. use super::{ - LevelAccess, LevelEvent, Sim, + LevelAccess, Sim, classes::Class, states::BlockId, update::{below, rel}, @@ -31,6 +31,18 @@ impl Sim<'_, L> { self.big_dripleaf_reset_tilt(pos, state); } } + Class::Command => { + // CommandBlock.setPoweredAndUpdate + let signal = self.has_neighbor_signal(pos); + if let Some((was_powered, automatic)) = self.level.set_command_block_powered(pos, signal) + && signal + && !was_powered + && !automatic + && !b.is_block(state, b.named.chain_command_block) + { + self.schedule_tick(pos, block, 1); + } + } Class::CopperBulb => self.copper_bulb_check(pos, state), Class::Crafter => self.crafter_neighbor_changed(pos, state), Class::Diode => self.diode_neighbor_changed(pos, state), @@ -64,6 +76,7 @@ impl Sim<'_, L> { self.remove_block(pos, false); } } + Class::Shelf => self.shelf_neighbor_changed(pos, state), Class::Sponge => self.sponge_try_absorb(pos), Class::Tnt => self.tnt_check(pos), Class::TrapDoor => self.trapdoor_neighbor_changed(pos, state), @@ -174,6 +187,7 @@ impl Sim<'_, L> { Class::Scaffolding => { self.schedule_tick(pos, block, 1); } + Class::Shelf => self.shelf_on_place(pos, state, old), Class::SnifferEgg => { let boosted = b.is_block(self.below_state(pos), b.named.moss_block); if boosted { @@ -263,7 +277,10 @@ impl Sim<'_, L> { | Class::Jukebox | Class::ShulkerBox | Class::CopperGolemStatue => self.update_neighbour_for_output_signal(pos, block), - Class::Shelf => self.update_neighbour_for_output_signal(pos, block), + Class::Shelf => { + self.update_neighbour_for_output_signal(pos, block); + self.shelf_after_powering_down(pos, state); + } Class::BasePressurePlate => { if !moved && self.plate_signal_for_state(state) > 0 { self.plate_update_neighbours(pos, block); @@ -403,7 +420,7 @@ impl Sim<'_, L> { } // TntBlock.playerWillDestroy: unstable TNT primes unless instabuild. if !creative && data.is(Class::Tnt) && b.table.bool(state, p.unstable) { - self.emit(LevelEvent::PrimeTnt { pos }); + self.prime_tnt(pos); } self.level_event(2001, pos, state.0 as i32); self.game_event(pos, "minecraft:block_destroy"); @@ -535,11 +552,14 @@ impl Sim<'_, L> { self.neighbor_changed_at(pos, b.named.water); } } - fn big_dripleaf_reset_tilt(&mut self, pos: BlockPos, state: BlockStateId) { + /// `BigDripleafBlock.resetTilt`. + pub(crate) fn big_dripleaf_reset_tilt(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; let next = b.table.set_text(state, b.props.tilt, "none"); self.set_block(pos, next, 2); if b.table.text(state, b.props.tilt) != "none" { + // setTilt: NONE causes a vibration when the tilt changes. + self.game_event(pos, "minecraft:block_change"); let pitch = self.random().next_float() * 0.4 + 0.8; self.emit(super::LevelEvent::Sound { pos, diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 0c888bb77..227615366 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -349,13 +349,7 @@ impl Sim<'_, L> { } }; if proper { - self.emit(LevelEvent::Sound { - pos, - sound: "minecraft:block.bell.use".into(), - volume: 2.0, - pitch: 1.0, - }); - self.game_event(pos, "minecraft:block_change"); + self.bell_ring(pos, state, face); Success } else { Pass diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 4f8b7f69a..c53500f5c 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -111,11 +111,13 @@ mod hooks; mod interact; pub mod pistons; mod place; +mod portal; mod query; mod rails; mod redstone; pub mod sculk; mod shapes; +mod shelf; mod signals; mod speleothem; mod survive; @@ -239,8 +241,10 @@ pub enum LevelEvent { state: BlockStateId, feature: Arc, }, - /// `TntBlock.prime`: the TNT block is removed; spawn primed TNT. - PrimeTnt { pos: BlockPos }, + /// `TntBlock.prime`: spawn primed TNT pushed along `rot` (radians, drawn + /// from the level random by `new PrimedTnt`). The primed sound and game + /// event follow as their own events; the caller removes the block. + 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). @@ -331,6 +335,12 @@ pub trait LevelAccess { ) -> i32 { 0 } + /// `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. + fn set_command_block_powered(&mut self, _pos: BlockPos, _powered: bool) -> Option<(bool, bool)> { + None + } /// Weak/strong signal of a block-entity-driven source (trapped chest /// openers); other sources are evaluated by the library. fn block_entity_signal( diff --git a/crates/horizon-world/src/level/portal.rs b/crates/horizon-world/src/level/portal.rs new file mode 100644 index 000000000..81a6a0562 --- /dev/null +++ b/crates/horizon-world/src/level/portal.rs @@ -0,0 +1,109 @@ +//! `PortalShape`: the obsidian frame search used by nether portal blocks. +use super::{LevelAccess, Sim, update::rel}; +use crate::registry::BlockStateId; +use horizon_core::{geometry::Direction, position::BlockPos}; + +const MIN_WIDTH: i32 = 2; +const MAX_WIDTH: i32 = 21; +const MIN_HEIGHT: i32 = 3; +const MAX_HEIGHT: i32 = 21; + +/// The result of `PortalShape.findAnyShape`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PortalShape { + pub x_axis: bool, + pub right: Direction, + pub bottom_left: BlockPos, + pub width: i32, + pub height: i32, + pub portal_blocks: i32, +} + +impl PortalShape { + pub const fn is_valid(&self) -> bool { + self.width >= MIN_WIDTH && self.width <= MAX_WIDTH && self.height >= MIN_HEIGHT && self.height <= MAX_HEIGHT + } + pub const fn is_complete(&self) -> bool { + self.is_valid() && self.portal_blocks == self.width * self.height + } +} + +fn step(pos: BlockPos, dir: Direction, n: i32) -> BlockPos { + let [dx, dy, dz] = dir.normal(); + pos.offset(dx * n, dy * n, dz * n) +} + +impl Sim<'_, L> { + fn portal_frame(&self, state: BlockStateId) -> bool { + let b = self.b; + b.tag("minecraft:nether_portal_frame").is_some_and(|tag| b.in_set(state, tag)) + } + /// `PortalShape.isEmpty`: air, fire or a portal block. + fn portal_empty(&self, state: BlockStateId) -> bool { + let b = self.b; + b.is_air(state) + || b.tag("minecraft:fire").is_some_and(|tag| b.in_set(state, tag)) + || b.is_block(state, b.named.nether_portal) + } + fn portal_distance_until_edge_above_frame(&self, pos: BlockPos, dir: Direction) -> i32 { + for width in 0..=MAX_WIDTH { + let at = step(pos, dir, width); + let state = self.state(at); + if !self.portal_empty(state) { + return if self.portal_frame(state) { width } else { 0 }; + } + if !self.portal_frame(self.state(rel(at, Direction::Down))) { + break; + } + } + 0 + } + /// `PortalShape.findAnyShape`. + pub fn find_portal_shape(&self, pos: BlockPos, x_axis: bool) -> PortalShape { + let right = if x_axis { Direction::West } else { Direction::South }; + let mut shape = PortalShape { x_axis, right, bottom_left: pos, width: 0, height: 0, portal_blocks: 0 }; + // calculateBottomLeft + let min_y = self.level.min_y().max(pos.y - MAX_HEIGHT); + let mut start = pos; + while start.y > min_y && self.portal_empty(self.state(rel(start, Direction::Down))) { + start = rel(start, Direction::Down); + } + let left = right.opposite(); + let edge = self.portal_distance_until_edge_above_frame(start, left) - 1; + if edge < 0 { + return shape; + } + shape.bottom_left = step(start, left, edge); + // calculateWidth + let width = self.portal_distance_until_edge_above_frame(shape.bottom_left, right); + if !(MIN_WIDTH..=MAX_WIDTH).contains(&width) { + return shape; + } + shape.width = width; + // calculateHeight: getDistanceUntilTop counts portal blocks as it goes. + let mut height = MAX_HEIGHT; + 'rows: for h in 0..MAX_HEIGHT { + let row = step(shape.bottom_left, Direction::Up, h); + if !self.portal_frame(self.state(step(row, right, -1))) + || !self.portal_frame(self.state(step(row, right, width))) + { + height = h; + break; + } + for i in 0..width { + let state = self.state(step(row, right, i)); + if !self.portal_empty(state) { + height = h; + break 'rows; + } + if self.b.is_block(state, self.b.named.nether_portal) { + shape.portal_blocks += 1; + } + } + } + let top = step(shape.bottom_left, Direction::Up, height); + let has_top = (0..width).all(|i| self.portal_frame(self.state(step(top, right, i)))); + shape.height = if (MIN_HEIGHT..=MAX_HEIGHT).contains(&height) && has_top { height } else { 0 }; + shape + } +} diff --git a/crates/horizon-world/src/level/redstone.rs b/crates/horizon-world/src/level/redstone.rs index 02d62b929..6e4722844 100644 --- a/crates/horizon-world/src/level/redstone.rs +++ b/crates/horizon-world/src/level/redstone.rs @@ -1120,7 +1120,7 @@ impl Sim<'_, L> { /// `TntBlock.prime` then `removeBlock`. pub(crate) fn tnt_check(&mut self, pos: BlockPos) { if self.has_neighbor_signal(pos) { - self.emit(LevelEvent::PrimeTnt { pos }); + self.prime_tnt(pos); self.remove_block(pos, false); } } @@ -1154,17 +1154,23 @@ impl Sim<'_, L> { let signal = self.has_neighbor_signal(pos); if signal != b.table.bool(state, b.props.powered) { if signal { - self.emit(LevelEvent::Sound { - pos, - sound: "minecraft:block.bell.use".into(), - volume: 2.0, - pitch: 1.0, - }); - self.game_event(pos, "minecraft:block_change"); + self.bell_ring(pos, state, b.facing(state)); } self.set_block_and_update(pos, b.table.set_bool(state, b.props.powered, signal)); } } + /// `BellBlock.attemptToRing`: `BellBlockEntity.onHit` queues block event 1 + /// with the struck direction, then the sound and game event. + pub(crate) fn bell_ring(&mut self, pos: BlockPos, state: BlockStateId, direction: Direction) { + self.block_event(pos, self.b.block(state), 1, direction as i32); + self.emit(LevelEvent::Sound { + pos, + sound: "minecraft:block.bell.use".into(), + volume: 2.0, + pitch: 1.0, + }); + self.game_event(pos, "minecraft:block_change"); + } pub(crate) fn crafter_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; let trigger = self.has_neighbor_signal(pos); diff --git a/crates/horizon-world/src/level/shapes.rs b/crates/horizon-world/src/level/shapes.rs index 6b9399346..242be2713 100644 --- a/crates/horizon-world/src/level/shapes.rs +++ b/crates/horizon-world/src/level/shapes.rs @@ -11,7 +11,7 @@ use super::{ update::{above, below, rel}, }; use crate::{fluid::FluidKind, registry::BlockStateId}; -use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; +use horizon_core::{geometry::{Axis, Direction}, position::BlockPos, random::RandomSource}; impl Sim<'_, L> { /// `BlockState.updateShape(level, ticks, pos, direction, neighbourPos, neighbourState, random)`. @@ -791,7 +791,19 @@ impl Sim<'_, L> { survive_or_air!(axis_of(dir) == axis_of(clockwise(b.facing(state)))) } Class::PotentSulfur => self.potent_sulfur_state(state, pos), - Class::NetherPortal => sup!(), + Class::NetherPortal => { + let x_axis = table.text(state, p.axis) == "x"; + let update_axis = axis_of(dir); + let wrong_axis = update_axis != if x_axis { Axis::X } else { Axis::Z } && update_axis != Axis::Y; + if !wrong_axis + && !b.is_block(nstate, block) + && !self.find_portal_shape(pos, x_axis).is_complete() + { + air + } else { + sup!() + } + } _ => return None, }) } diff --git a/crates/horizon-world/src/level/shelf.rs b/crates/horizon-world/src/level/shelf.rs new file mode 100644 index 000000000..44a011190 --- /dev/null +++ b/crates/horizon-world/src/level/shelf.rs @@ -0,0 +1,203 @@ +//! `ShelfBlock` power changes and its `SideChainPartBlock` linking: up to +//! three powered wooden shelves facing the same way join into one chain. +use super::{ + LevelAccess, Sim, + query::{clockwise, counter_clockwise}, + update::rel, +}; +use crate::registry::BlockStateId; +use horizon_core::{geometry::Direction, position::BlockPos}; +use std::collections::HashMap; + +/// `SideChainPart`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Part { + Unconnected, + Right, + Center, + Left, +} + +impl Part { + fn parse(text: &str) -> Self { + match text { + "right" => Self::Right, + "center" => Self::Center, + "left" => Self::Left, + _ => Self::Unconnected, + } + } + const fn name(self) -> &'static str { + match self { + Self::Unconnected => "unconnected", + Self::Right => "right", + Self::Center => "center", + Self::Left => "left", + } + } + const fn is_connection_towards(self, end: Self) -> bool { + matches!(self, Self::Center) || self as u8 == end as u8 + } + const fn is_chain_end(self) -> bool { + !matches!(self, Self::Center) + } + const fn connected_to_the_right(self) -> Self { + match self { + Self::Unconnected | Self::Left => Self::Left, + Self::Right | Self::Center => Self::Center, + } + } + const fn connected_to_the_left(self) -> Self { + match self { + Self::Unconnected | Self::Right => Self::Right, + Self::Center | Self::Left => Self::Center, + } + } + const fn disconnected_from_the_right(self) -> Self { + match self { + Self::Unconnected | Self::Left => Self::Unconnected, + Self::Right | Self::Center => Self::Right, + } + } + const fn disconnected_from_the_left(self) -> Self { + match self { + Self::Unconnected | Self::Right => Self::Unconnected, + Self::Center | Self::Left => Self::Left, + } + } +} + +/// `SideChainPartBlock.Neighbors`: neighbours along the chain are read once +/// (the part is captured when first seen, as vanilla's cache does). +struct Neighbors { + facing: Direction, + center: BlockPos, + cache: HashMap>, +} + +const MAX_CHAIN_LENGTH: usize = 3; + +impl Sim<'_, L> { + fn shelf_part(&self, state: BlockStateId) -> Part { + Part::parse(self.b.table.text(state, self.b.props.side_chain)) + } + /// `ShelfBlock.isConnectable`. + fn shelf_connectable(&self, state: BlockStateId) -> bool { + let b = self.b; + b.tag("minecraft:wooden_shelves").is_some_and(|tag| b.in_set(state, tag)) + && b.table.has(state, b.props.powered) + && b.table.bool(state, b.props.powered) + } + fn chain_neighbor(&mut self, n: &mut Neighbors, left: bool, steps: i32) -> (BlockPos, Option) { + let dir = if left { clockwise(n.facing) } else { counter_clockwise(n.facing) }; + let mut pos = n.center; + for _ in 0..steps { + pos = rel(pos, dir); + } + let part = *n.cache.entry(pos).or_insert_with(|| { + let state = self.state(pos); + (self.shelf_connectable(state) && self.b.facing(state) == n.facing) + .then(|| self.shelf_part(state)) + }); + (pos, part) + } + /// `SideChainPartBlock.setPart`. + fn shelf_set_part(&mut self, pos: BlockPos, part: Part) { + let state = self.state(pos); + if self.shelf_part(state) != part { + let next = self.b.table.set_text(state, self.b.props.side_chain, part.name()); + self.set_block_and_update(pos, next); + } + } + /// `SideChainPartBlock.getAllBlocksConnectedTo(...).size()`. + fn shelf_chain_size(&mut self, pos: BlockPos) -> usize { + let state = self.state(pos); + if !self.shelf_connectable(state) { + return 0; + } + let mut n = Neighbors { facing: self.b.facing(state), center: pos, cache: HashMap::new() }; + let mut size = 1; + for (left, end) in [(true, Part::Left), (false, Part::Right)] { + for steps in 1..MAX_CHAIN_LENGTH as i32 { + let (_, part) = self.chain_neighbor(&mut n, left, steps); + if part.is_some_and(|p| p.is_connection_towards(end)) { + size += 1; + } + if part.is_none_or(Part::is_chain_end) { + break; + } + } + } + size + } + /// `SideChainPartBlock.updateNeighborsAfterPoweringDown`. + pub(crate) fn shelf_after_powering_down(&mut self, pos: BlockPos, state: BlockStateId) { + let mut n = Neighbors { facing: self.b.facing(state), center: pos, cache: HashMap::new() }; + if let (at, Some(part)) = self.chain_neighbor(&mut n, true, 1) { + self.shelf_set_part(at, part.disconnected_from_the_right()); + } + if let (at, Some(part)) = self.chain_neighbor(&mut n, false, 1) { + self.shelf_set_part(at, part.disconnected_from_the_left()); + } + } + /// `SideChainPartBlock.updateSelfAndNeighborsOnPoweringUp`. + fn shelf_on_powering_up(&mut self, pos: BlockPos, state: BlockStateId, old: BlockStateId) { + if !self.shelf_connectable(state) { + return; + } + let updated_by_neighbor = self.shelf_part(state) != Part::Unconnected + || self.shelf_connectable(old) && self.shelf_part(old) != Part::Unconnected; + if updated_by_neighbor { + return; + } + let mut n = Neighbors { facing: self.b.facing(state), center: pos, cache: HashMap::new() }; + let (left_pos, left) = self.chain_neighbor(&mut n, true, 1); + let (right_pos, right) = self.chain_neighbor(&mut n, false, 1); + let on_left = if left.is_some() { self.shelf_chain_size(left_pos) } else { 0 }; + let on_right = if right.is_some() { self.shelf_chain_size(right_pos) } else { 0 }; + let mut own = Part::Unconnected; + let mut length = 1; + if on_left > 0 && length + on_left <= MAX_CHAIN_LENGTH { + own = own.connected_to_the_left(); + if let Some(part) = left { + self.shelf_set_part(left_pos, part.connected_to_the_right()); + } + length += on_left; + } + if on_right > 0 && length + on_right <= MAX_CHAIN_LENGTH { + own = own.connected_to_the_right(); + if let Some(part) = right { + self.shelf_set_part(right_pos, part.connected_to_the_left()); + } + } + self.shelf_set_part(pos, own); + } + /// `ShelfBlock.onPlace`. + pub(crate) fn shelf_on_place(&mut self, pos: BlockPos, state: BlockStateId, old: BlockStateId) { + if self.b.table.bool(state, self.b.props.powered) { + self.shelf_on_powering_up(pos, state, old); + } else { + self.shelf_after_powering_down(pos, state); + } + } + /// `ShelfBlock.neighborChanged`. + pub(crate) fn shelf_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let signal = self.has_neighbor_signal(pos); + if b.table.bool(state, b.props.powered) == signal { + return; + } + let mut next = b.table.set_bool(state, b.props.powered, signal); + if !signal { + next = b.table.set_text(next, b.props.side_chain, Part::Unconnected.name()); + } + self.set_block_and_update(pos, next); + let (sound, event) = if signal { + ("minecraft:block.shelf.activate", "minecraft:block_activate") + } else { + ("minecraft:block.shelf.deactivate", "minecraft:block_deactivate") + }; + self.sound(pos, &sound.into(), 1.0, 1.0); + self.game_event_state(pos, event, next); + } +} diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 09aaa4539..9d7ad93f0 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -434,46 +434,24 @@ impl Sim<'_, L> { } fn big_dripleaf_tick(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; - if self.has_neighbor_signal(pos) { - let next = b.table.set_text(state, b.props.tilt, "none"); - self.set_block(pos, next, 2); - if b.table.text(state, b.props.tilt) != "none" { - let pitch = self.random().next_float() * 0.4 + 0.8; - self.emit(LevelEvent::Sound { - pos, - sound: "minecraft:block.big_dripleaf.tilt_up".into(), - volume: 1.0, - pitch, - }); - } - return; - } let (next, delay) = match b.table.text(state, b.props.tilt) { - "unstable" => ("partial", Some(10)), - "partial" => ("full", Some(100)), - "full" => ("none", None), + _ if self.has_neighbor_signal(pos) => return self.big_dripleaf_reset_tilt(pos, state), + "unstable" => ("partial", 10), + "partial" => ("full", 100), + "full" => return self.big_dripleaf_reset_tilt(pos, state), _ => return, }; - let next_state = b.table.set_text(state, b.props.tilt, next); - self.set_block(pos, next_state, 2); - if next != "none" { - self.game_event(pos, "minecraft:block_change"); - } + // setTiltAndScheduleTick: PARTIAL and FULL cause vibrations. + self.set_block(pos, b.table.set_text(state, b.props.tilt, next), 2); + self.game_event(pos, "minecraft:block_change"); let pitch = self.random().next_float() * 0.4 + 0.8; - let sound = if next == "none" { - "minecraft:block.big_dripleaf.tilt_up" - } else { - "minecraft:block.big_dripleaf.tilt_down" - }; self.emit(LevelEvent::Sound { pos, - sound: sound.into(), + sound: "minecraft:block.big_dripleaf.tilt_down".into(), volume: 1.0, pitch, }); - if let Some(delay) = delay { - self.schedule_tick(pos, b.block(state), delay); - } + self.schedule_tick(pos, b.block(state), delay); } fn scaffolding_tick(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; @@ -619,7 +597,7 @@ impl Sim<'_, L> { self.remove_block(pos, false); } if b.instance_of(old, Class::Tnt) { - self.emit(LevelEvent::PrimeTnt { pos }); + self.prime_tnt(pos); } } } diff --git a/crates/horizon-world/src/level/update.rs b/crates/horizon-world/src/level/update.rs index 5ce173648..1fd90c33e 100644 --- a/crates/horizon-world/src/level/update.rs +++ b/crates/horizon-world/src/level/update.rs @@ -5,7 +5,7 @@ use crate::{fluid::FluidState, registry::BlockStateId}; use horizon_core::{ geometry::Direction, position::BlockPos, - random::LegacyRandom, + random::{LegacyRandom, RandomSource}, ticks::{ScheduleResult, TickPriority}, }; @@ -183,6 +183,14 @@ impl Sim<'_, L> { pub fn emit(&mut self, event: LevelEvent) { self.level.emit(event); } + /// `TntBlock.prime` without a source: `new PrimedTnt` draws its push angle + /// from the level random, then the primed sound and `prime_fuse` event. + pub fn prime_tnt(&mut self, pos: BlockPos) { + let rot = self.random().next_double() * f64::from(std::f32::consts::TAU); + self.emit(LevelEvent::PrimeTnt { pos, rot }); + self.sound(pos, &std::sync::Arc::from("minecraft:entity.tnt.primed"), 1.0, 1.0); + self.game_event(pos, "minecraft:prime_fuse"); + } pub fn level_event(&mut self, id: i32, pos: BlockPos, data: i32) { self.level.emit(LevelEvent::LevelEvent { id, pos, data }); } @@ -338,11 +346,11 @@ impl Sim<'_, L> { if self.b.is_air(state) { return false; } - let is_fire = { - let data = self.b.data(state); - data.is(Class::BaseFire) || data.is(Class::Fire) || data.is(Class::SoulFire) - }; - if !is_fire { + // Block.spawnDestroyParticles: fire spawns none, straw beds their own. + let data = self.b.data(state); + if data.is(Class::StrawBed) { + self.level_event(2014, pos, state.0 as i32); + } else if !(data.is(Class::BaseFire) || data.is(Class::Fire) || data.is(Class::SoulFire)) { self.level_event(2001, pos, state.0 as i32); } if drop { 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 8b7e198e6..e0f79864e 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -71,7 +71,7 @@ public final class VanillaBlockUpdateOracle { if (old == state) { return null; } - if (state.isAir()) { + if (state == AIR) { world.cells.remove(pos); } else { world.cells.put(pos.immutable(), state); @@ -123,7 +123,26 @@ public final class VanillaBlockUpdateOracle { } @Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, AIR); } @Override public FluidState getFluidState(BlockPos p) { return getBlockState(p).getFluidState(); } - @Override public BlockEntity getBlockEntity(BlockPos p) { return null; } + // A real level always holds the block entity of an entity block; this + // one creates it on first use and replaces it when the block changes. + Map blockEntities; + @Override public BlockEntity getBlockEntity(BlockPos p) { + BlockState state = getBlockState(p); + if (!(state.getBlock() instanceof net.minecraft.world.level.block.EntityBlock entityBlock)) { + return null; + } + if (blockEntities == null) blockEntities = new HashMap<>(); + BlockEntity be = blockEntities.get(p); + if (be == null || !be.getType().isValid(state)) { + be = entityBlock.newBlockEntity(p.immutable(), state); + if (be == null) return null; + be.setLevel(this); + blockEntities.put(p.immutable(), be); + } else { + be.setBlockState(state); + } + return be; + } @Override public LevelChunk getChunkAt(BlockPos p) { return chunk; } @Override public LevelChunk getChunk(int x, int z) { return chunk; } @Override public boolean isLoaded(BlockPos p) { return true; } @@ -179,6 +198,26 @@ 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; } + // 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 + // compared. + int nextEntityId; + net.minecraft.world.attribute.EnvironmentAttributeSystem attributes; + @Override public int getNextEntityId() { return ++nextEntityId; } + @Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { + if (attributes == null) attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build(); + return attributes; + } + @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); + } + @Override public void playSound(Entity except, double x, double y, double z, net.minecraft.core.Holder sound, SoundSource source, float volume, float pitch) { + playSeededSound(except, x, y, z, sound, source, volume, pitch, 0L); + } + @Override public void playSound(Entity except, Entity src, SoundEvent sound, SoundSource source, float volume, float pitch) { + playSeededSound(except, src, BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), source, volume, pitch, 0L); + } } static final class Loot extends net.minecraft.server.ReloadableServerRegistries.Holder { @@ -292,7 +331,7 @@ public final class VanillaBlockUpdateOracle { for (var cell : f.getAsJsonArray("cells")) { var c = cell.getAsJsonArray(); BlockState s = Block.stateById(c.get(3).getAsInt()); - if (!s.isAir()) w.cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), s); + if (s != AIR) w.cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), s); } w.rng = new LegacyRandomSource(f.get("seed").getAsLong()); w.time = f.has("time") ? f.get("time").getAsLong() : 0;