Add level block-behaviour module: setBlock, neighbour/shape updates, fluids, redstone, ticks

Behaviours loads per-block class chains, instance configuration and per-state
support/signal/fluid facts exported by VanillaBlockBehaviourExporter, and ports
Level.setBlock with the CollectingNeighborUpdater, updateShape for every
overriding class, canSurvive, FlowingFluid spreading with lava/water
interactions, gravity blocks, rails, tripwires, redstone wire/torches/diodes,
scheduled ticks and random ticks.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 01:22:03 +02:00
parent 8d87f6c45f
commit f11931e1d3
14 changed files with 2521 additions and 15 deletions
+2 -2
View File
@@ -8,7 +8,7 @@
macro_rules! classes {
($($name:ident = $java:literal,)*) => {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(u8)]
#[repr(u16)]
pub enum Class { $($name,)* }
impl Class {
pub const ALL: &'static [Class] = &[$(Class::$name,)*];
@@ -327,7 +327,7 @@ impl Interface {
/// Set of recognised classes in one block's chain.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ClassSet([u64; 4]);
pub struct ClassSet([u64; 5]);
impl ClassSet {
pub fn insert(&mut self, class: Class) {
let i = class as usize;
+31
View File
@@ -41,6 +41,7 @@ pub mod state_flags {
pub const FULL_COLLISION: u32 = 1 << 14;
pub const SKYLIGHT_DOWN: u32 = 1 << 15;
pub const REQUIRES_TOOL: u32 = 1 << 16;
pub const SHAPE_OCCLUSION: u32 = 1 << 17;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -551,6 +552,7 @@ props! {
crafting = "crafting",
side_chain = "side_chain",
copper_golem_pose = "copper_golem_pose",
sculk_sensor_phase = "sculk_sensor_phase",
}
fn fail(message: &str) -> io::Error {
@@ -584,6 +586,33 @@ fn set_type(value: &Value, cache: &mut HashMap<String, Arc<str>>) -> Option<SetT
})
}
/// Build the block-state registry from the resources' `facts.json` (the
/// same source the native client uses).
pub fn load_registry(root: &Path) -> io::Result<BlockRegistry> {
use crate::{DATA_VERSION, nbt::Tag};
fn tag(value: &Value) -> io::Result<Tag> {
Ok(match value {
Value::String(value) => Tag::String(value.as_str().into()),
Value::Number(value) => Tag::Int(value.as_i64().and_then(|v| i32::try_from(v).ok()).ok_or_else(|| fail("invalid registry number"))?),
Value::Array(values) => Tag::List(values.iter().map(tag).collect::<io::Result<_>>()?),
Value::Object(values) => Tag::Compound(
values
.iter()
.map(|(name, value)| Ok((name.as_str().into(), tag(value)?)))
.collect::<io::Result<_>>()?,
),
_ => return Err(fail("unsupported registry value")),
})
}
let facts = read_json(&root.join("facts.json"))?;
let states = facts["states"].as_array().ok_or_else(|| fail("missing registry state facts"))?;
BlockRegistry::from_nbt(&Tag::compound([
("DataVersion", Tag::Int(DATA_VERSION)),
("states", Tag::List(states.iter().map(|state| tag(&state[4])).collect::<io::Result<_>>()?)),
("defaults", tag(&facts["defaults"])?),
]))
}
pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviours> {
let mut table = StateTable::new(registry)?;
let props = Props::resolve(&mut table);
@@ -711,6 +740,7 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviou
("full_collision", state_flags::FULL_COLLISION),
("skylight_down", state_flags::SKYLIGHT_DOWN),
("requires_tool", state_flags::REQUIRES_TOOL),
("shape_occlusion", state_flags::SHAPE_OCCLUSION),
] {
if gb(key) {
flags |= bit;
@@ -794,6 +824,7 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviou
"base",
"candleBlock",
"requiredBlock",
"baseBlock",
]
.into_iter()
.find_map(block_field);
+106
View File
@@ -0,0 +1,106 @@
//! Gravity blocks: `FallingBlock.tick`, `FallingBlockEntity.fall` and the
//! landing branch of `FallingBlockEntity.tick`. The falling entity itself
//! (motion, collision, entity damage) is simulated by the caller.
use super::{Behaviours, LevelAccess, LevelEvent, Sim, Ticks, classes::Class, update::below};
use crate::registry::BlockStateId;
use horizon_core::{geometry::Direction, position::BlockPos};
/// Outcome of [`Behaviours::falling_block_landed`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Landing {
/// The block was placed at the position (concrete powder may have
/// solidified); discard the entity.
Placed(BlockStateId),
/// The block could not be placed: discard the entity and, if the entity
/// drops items, spawn the block's item (vanilla `spawnAtLocation`).
Broken,
/// The landing position holds a moving piston: keep falling.
Continue,
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
/// `FallingBlockEntity.fall`.
pub(crate) fn falling_block_fall(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
let carried = b.table.with_bool(state, b.props.waterlogged, false).unwrap_or(state);
let legacy = b.legacy_block(b.fluid(state));
self.set_block_and_update(pos, legacy);
self.emit(LevelEvent::FallingBlock { pos, state: carried });
}
/// `FallingBlock.tick` (and `SpeleothemBlock`'s falling stalactites).
pub(crate) fn falling_block_tick(&mut self, pos: BlockPos, state: BlockStateId) {
if self.is_free(self.below_state(pos)) && pos.y >= self.level.min_y() {
self.falling_block_fall(pos, state);
}
}
/// `SpeleothemBlock.spawnFallingStalactite`.
pub(crate) fn spawn_falling_stalactite(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
let p = b.props;
let is_stalactite = |s: BlockStateId| {
b.tag("minecraft:speleothems").is_some_and(|tag| b.in_set(s, tag)) && b.table.dir(s, p.vertical_direction) == Some(Direction::Down)
};
let mut fall_pos = pos;
let mut fall_state = state;
while is_stalactite(fall_state) {
self.falling_block_fall(fall_pos, fall_state);
let thickness = b.table.text(fall_state, p.thickness);
if thickness == "tip" || thickness == "tip_merge" {
break;
}
fall_pos = below(fall_pos);
fall_state = self.state(fall_pos);
}
}
}
impl Behaviours {
/// The landing branch of `FallingBlockEntity.tick`, called by the caller's
/// falling-block entity once it is on the ground (or stuck in water as
/// concrete powder). `state` is the carried block state.
pub fn falling_block_landed<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
state: BlockStateId,
stuck_in_water: bool,
) -> Landing {
let mut sim = self.sim(level, ticks);
let current = sim.state(pos);
if self.is_block(current, self.named.moving_piston) {
return Landing::Continue;
}
let concrete = self.instance_of(state, Class::ConcretePowder);
let may_replace = self.is_replaceable(current);
let would_continue = sim.is_free(sim.below_state(pos)) && (!concrete || !stuck_in_water);
let would_survive = sim.can_survive(state, pos) && !would_continue;
if !(may_replace && would_survive) {
if self.instance_of(state, Class::Anvil) {
sim.level_event(1029, pos, 0);
}
return Landing::Broken;
}
let mut placed = state;
if self.table.has(placed, self.props.waterlogged) && self.is_water_fluid(sim.fluid_at(pos).kind()) {
placed = self.table.set_bool(placed, self.props.waterlogged, true);
}
if !sim.set_block_and_update(pos, placed) {
if self.instance_of(state, Class::Anvil) {
sim.level_event(1029, pos, 0);
}
return Landing::Broken;
}
// Fallable.onLand
if concrete {
if self.is_water_fluid(self.fluid(current).kind()) || sim.concrete_touches_liquid(pos) {
if let Some(solid) = self.data(state).link {
sim.set_block_and_update(pos, self.default_of(solid));
}
}
} else if self.instance_of(state, Class::Anvil) {
sim.level_event(1031, pos, 0);
}
Landing::Placed(sim.state(pos))
}
}
+56 -6
View File
@@ -78,7 +78,9 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
self.rail_update_state(pos, state, moved);
}
}
Class::Brushable => self.schedule_tick(pos, block, 2),
Class::Brushable => {
self.schedule_tick(pos, block, 2);
}
Class::Composter => {
if b.table.int(state, b.props.level) == 7 {
self.schedule_tick(pos, block, 20);
@@ -131,7 +133,9 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
self.wire_update_neighbors_of_neighboring_wires(pos);
}
}
Class::Scaffolding => self.schedule_tick(pos, block, 1),
Class::Scaffolding => {
self.schedule_tick(pos, block, 1);
}
Class::SculkSensor => {
if !same && b.table.int(state, b.props.power) > 0 && !self.ticks.has_block_tick(pos, block) {
self.set_block(pos, b.table.set_int(state, b.props.power, 0), 18);
@@ -289,6 +293,52 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
}
}
/// `ServerPlayerGameMode.destroyBlock`: `playerWillDestroy` then
/// `removeBlock`. Drops are the caller's (tool-dependent loot).
pub(crate) fn player_destroy(&mut self, pos: BlockPos, creative: bool) -> bool {
let b = self.b;
let p = b.props;
let state = self.state(pos);
if b.is_air(state) {
return false;
}
let data = b.data(state);
if creative && (data.is(Class::DoublePlant) || data.is(Class::Door)) && b.table.text(state, p.half) == "upper" {
let bottom = below(pos);
let bottom_state = self.state(bottom);
if b.is_block(bottom_state, b.block(state)) && b.table.text(bottom_state, p.half) == "lower" {
let replacement = if b.is_water_fluid(b.fluid(bottom_state).kind()) { b.default_of(b.named.water) } else { b.air() };
self.set_block(bottom, replacement, 35);
self.level_event(2001, bottom, bottom_state.0 as i32);
}
}
if creative && data.is(Class::AbstractBed) && b.table.text(state, p.part) == "foot" {
let head_pos = rel(pos, b.facing(state));
let head = self.state(head_pos);
if b.is_block(head, b.block(state)) && b.table.text(head, p.part) == "head" {
self.set_block(head_pos, b.air(), 35);
self.level_event(2001, head_pos, head.0 as i32);
}
}
self.level_event(2001, pos, state.0 as i32);
self.game_event(pos, "minecraft:block_destroy");
self.remove_block(pos, false)
}
/// `entityInside` for entity-sensing blocks.
pub(crate) fn entity_inside(&mut self, pos: BlockPos) {
let b = self.b;
let state = self.state(pos);
let data = b.data(state);
if data.is(Class::BasePressurePlate) {
let signal = self.plate_signal_for_state(state);
if signal == 0 {
self.plate_check_pressed(pos, state, signal);
}
} else if data.is(Class::TripWire) && !b.table.bool(state, b.props.powered) && !self.ticks.has_block_tick(pos, b.block(state)) {
self.tripwire_check_pressed(pos);
}
}
// ---- misc helpers ----
/// `BaseFireBlock.onPlace` (portal ignition is not modelled).
@@ -387,16 +437,16 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
}
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" {
let next = b.table.set_text(state, b.props.tilt, "none");
self.set_block(pos, next, 2);
let pitch = self.random().next_float() * 0.4 + 0.8;
self.emit(super::LevelEvent::Sound {
pos,
sound: "minecraft:block.big_dripleaf.tilt_up".into(),
volume: 1.0,
pitch: 1.0,
pitch,
});
self.ticks.blocks.clear_area(horizon_core::ticks::TickArea::new(pos, pos));
}
}
pub(crate) fn horizontal_neighbours(pos: BlockPos) -> [BlockPos; 4] {
@@ -0,0 +1,12 @@
//! `useWithoutItem` interactions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InteractionResult {
Success,
Consume,
Pass,
}
#[derive(Clone, Copy, Debug)]
pub struct PlayerContext {
pub yaw: f32,
pub may_build: bool,
}
+62 -2
View File
@@ -52,12 +52,13 @@ pub mod data;
pub mod states;
pub mod ticks;
mod connect;
mod falling;
mod fluids;
mod hooks;
mod interact;
mod place;
mod plants;
mod query;
mod rails;
mod redstone;
mod shapes;
mod survive;
@@ -68,6 +69,7 @@ mod update;
mod tests;
pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags};
pub use falling::Landing;
pub use place::{PlaceContext, PlaceOutcome};
pub use interact::{InteractionResult, PlayerContext};
pub use states::{BlockId, PropKey, StateTable};
@@ -173,6 +175,14 @@ pub enum LevelEvent {
},
/// `TntBlock.prime`: the TNT block is removed; spawn primed TNT.
PrimeTnt { pos: BlockPos },
/// 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).
BlockEvent {
pos: BlockPos,
state: BlockStateId,
kind: &'static str,
},
/// `Level.gameEvent` (vibration system), by vanilla identifier.
GameEvent { pos: BlockPos, event: &'static str },
}
@@ -354,6 +364,56 @@ impl Behaviours {
}
}
/// Level mutation entry points (all keep vanilla update semantics).
impl Behaviours {
/// `Level.setBlock(pos, state, flags)` with vanilla's update limit (512).
/// Returns false when nothing was written (unloaded, out of bounds, or
/// the state was already present).
pub fn set_block<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, state: BlockStateId, flags: i32) -> bool {
self.sim(level, ticks).set_block(pos, state, flags)
}
/// `Level.removeBlock(pos, movedByPiston)`: replace with the fluid's block.
pub fn remove_block<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, moved_by_piston: bool) -> bool {
self.sim(level, ticks).remove_block(pos, moved_by_piston)
}
/// `Level.destroyBlock(pos, dropResources)`: destroy particles (2001),
/// optional drops, and replacement by the block's fluid.
pub fn destroy_block<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, drop: bool) -> bool {
self.sim(level, ticks).destroy_block(pos, drop, flags::UPDATE_LIMIT)
}
/// A player breaking a block (`playerWillDestroy` + `Level.destroyBlock`
/// without drops; the caller handles the player's loot/tool). Double
/// blocks (doors, tall plants, beds) remove their other half as vanilla.
pub fn player_destroy_block<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, creative: bool) -> bool {
self.sim(level, ticks).player_destroy(pos, creative)
}
/// `BlockState.canSurvive(level, pos)`.
pub fn can_survive<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, state: BlockStateId) -> bool {
self.sim(level, ticks).can_survive(state, pos)
}
/// `Block.updateFromNeighbourShapes`: a state adjusted to its neighbours.
pub fn update_from_neighbour_shapes<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, state: BlockStateId) -> BlockStateId {
self.sim(level, ticks).update_from_neighbour_shapes(state, pos)
}
/// `Level.updateNeighborsAt(pos, block)`: notify the six neighbours.
pub fn update_neighbors_at<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, block: BlockId) {
self.sim(level, ticks).update_neighbors_at(pos, block);
}
/// Entity collision with a block (`entityInside`) for the entity-sensing
/// blocks: pressure plates, tripwires and buttons hit by arrows are
/// re-evaluated through [`LevelAccess::count_entities`].
pub fn entity_inside<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos) {
self.sim(level, ticks).entity_inside(pos);
}
/// Redstone signal queries (`SignalGetter`).
pub fn has_neighbor_signal<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos) -> bool {
self.sim(level, ticks).has_neighbor_signal(pos)
}
pub fn best_neighbor_signal<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos) -> i32 {
self.sim(level, ticks).best_neighbor_signal(pos)
}
}
/// One mutable view used by the ported behaviour code.
pub(crate) struct Sim<'a, L: LevelAccess + ?Sized> {
pub b: &'a Behaviours,
+25
View File
@@ -0,0 +1,25 @@
//! Block placement (`BlockItem.place`, `BlockPlaceContext`, `getStateForPlacement`).
use crate::registry::BlockStateId;
use horizon_core::{
geometry::{Direction, Vec3},
position::BlockPos,
};
/// `BlockPlaceContext` inputs from the player's use-item-on-block action.
#[derive(Clone, Debug)]
pub struct PlaceContext {
pub clicked_pos: BlockPos,
pub face: Direction,
pub hit: Vec3,
pub inside: bool,
pub yaw: f32,
pub pitch: f32,
pub sneaking: bool,
pub item: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlaceOutcome {
Placed { pos: BlockPos, state: BlockStateId },
Failed,
}
+598
View File
@@ -0,0 +1,598 @@
//! Rails (`BaseRailBlock`, `RailState`, powered/activator rails) and
//! tripwires (`TripWireBlock`, `TripWireHookBlock`).
use super::{
LevelAccess, LevelEvent, Sim,
classes::Class,
states::BlockId,
update::{above, below, rel},
};
use crate::registry::BlockStateId;
use horizon_core::{
geometry::{Aabb, Direction, Vec3},
position::BlockPos,
random::RandomSource,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RailShape {
NorthSouth,
EastWest,
AscendingEast,
AscendingWest,
AscendingNorth,
AscendingSouth,
SouthEast,
SouthWest,
NorthWest,
NorthEast,
}
impl RailShape {
fn parse(text: &str) -> Self {
match text {
"east_west" => Self::EastWest,
"ascending_east" => Self::AscendingEast,
"ascending_west" => Self::AscendingWest,
"ascending_north" => Self::AscendingNorth,
"ascending_south" => Self::AscendingSouth,
"south_east" => Self::SouthEast,
"south_west" => Self::SouthWest,
"north_west" => Self::NorthWest,
"north_east" => Self::NorthEast,
_ => Self::NorthSouth,
}
}
fn name(self) -> &'static str {
match self {
Self::NorthSouth => "north_south",
Self::EastWest => "east_west",
Self::AscendingEast => "ascending_east",
Self::AscendingWest => "ascending_west",
Self::AscendingNorth => "ascending_north",
Self::AscendingSouth => "ascending_south",
Self::SouthEast => "south_east",
Self::SouthWest => "south_west",
Self::NorthWest => "north_west",
Self::NorthEast => "north_east",
}
}
fn is_slope(self) -> bool {
matches!(self, Self::AscendingEast | Self::AscendingWest | Self::AscendingNorth | Self::AscendingSouth)
}
}
/// `RailState`.
struct Rail {
pos: BlockPos,
state: BlockStateId,
straight: bool,
connections: Vec<BlockPos>,
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
pub(crate) fn rail_shape(&self, state: BlockStateId) -> &str {
self.b.table.text(state, self.b.props.shape)
}
fn is_rail(&self, state: BlockStateId) -> bool {
self.b.in_set(state, &self.b.tags.rails) && self.b.instance_of(state, Class::BaseRail)
}
fn is_rail_at(&self, pos: BlockPos) -> bool {
self.is_rail(self.state(pos))
}
fn rail_connections(pos: BlockPos, shape: RailShape) -> Vec<BlockPos> {
let (n, s, w, e) = (rel(pos, Direction::North), rel(pos, Direction::South), rel(pos, Direction::West), rel(pos, Direction::East));
match shape {
RailShape::NorthSouth => vec![n, s],
RailShape::EastWest => vec![w, e],
RailShape::AscendingEast => vec![w, above(e)],
RailShape::AscendingWest => vec![above(w), e],
RailShape::AscendingNorth => vec![above(n), s],
RailShape::AscendingSouth => vec![n, above(s)],
RailShape::SouthEast => vec![e, s],
RailShape::SouthWest => vec![w, s],
RailShape::NorthWest => vec![w, n],
RailShape::NorthEast => vec![e, n],
}
}
fn rail_new(&self, pos: BlockPos, state: BlockStateId) -> Rail {
let shape = RailShape::parse(self.rail_shape(state));
Rail {
pos,
state,
straight: !self.b.data(state).is(Class::Rail),
connections: Self::rail_connections(pos, shape),
}
}
fn rail_get(&self, pos: BlockPos) -> Option<Rail> {
for test in [pos, above(pos), below(pos)] {
let state = self.state(test);
if self.is_rail(state) {
return Some(self.rail_new(test, state));
}
}
None
}
fn rail_has_connection(rail: &Rail, pos: BlockPos) -> bool {
rail.connections.iter().any(|c| c.x == pos.x && c.z == pos.z)
}
fn rail_remove_soft_connections(&self, rail: &mut Rail) {
let mut i = 0;
while i < rail.connections.len() {
match self.rail_get(rail.connections[i]) {
Some(other) if Self::rail_has_connection(&other, rail.pos) => {
rail.connections[i] = other.pos;
i += 1;
}
_ => {
rail.connections.remove(i);
}
}
}
}
fn rail_can_connect_to(rail: &Rail, other: &Rail) -> bool {
Self::rail_has_connection(rail, other.pos) || rail.connections.len() != 2
}
fn rail_has_neighbor_rail(&self, rail: &Rail, pos: BlockPos) -> bool {
match self.rail_get(pos) {
Some(mut neighbour) => {
self.rail_remove_soft_connections(&mut neighbour);
Self::rail_can_connect_to(&neighbour, rail)
}
None => false,
}
}
fn rail_count_potential_connections(&self, pos: BlockPos) -> i32 {
super::update::HORIZONTAL
.into_iter()
.filter(|d| {
let p = rel(pos, *d);
self.is_rail_at(p) || self.is_rail_at(above(p)) || self.is_rail_at(below(p))
})
.count() as i32
}
fn rail_slopes(&self, pos: BlockPos, shape: Option<RailShape>) -> Option<RailShape> {
let (n, s, w, e) = (rel(pos, Direction::North), rel(pos, Direction::South), rel(pos, Direction::West), rel(pos, Direction::East));
let mut shape = shape;
if shape == Some(RailShape::NorthSouth) {
if self.is_rail_at(above(n)) {
shape = Some(RailShape::AscendingNorth);
}
if self.is_rail_at(above(s)) {
shape = Some(RailShape::AscendingSouth);
}
}
if shape == Some(RailShape::EastWest) {
if self.is_rail_at(above(e)) {
shape = Some(RailShape::AscendingEast);
}
if self.is_rail_at(above(w)) {
shape = Some(RailShape::AscendingWest);
}
}
shape
}
fn rail_set_shape(&self, state: BlockStateId, shape: RailShape) -> BlockStateId {
self.b.table.set_text(state, self.b.props.shape, shape.name())
}
fn rail_connect_to(&mut self, rail: &mut Rail, other_pos: BlockPos) {
rail.connections.push(other_pos);
let pos = rail.pos;
let n = Self::rail_has_connection(rail, rel(pos, Direction::North));
let s = Self::rail_has_connection(rail, rel(pos, Direction::South));
let w = Self::rail_has_connection(rail, rel(pos, Direction::West));
let e = Self::rail_has_connection(rail, rel(pos, Direction::East));
let mut shape = None;
if n || s {
shape = Some(RailShape::NorthSouth);
}
if w || e {
shape = Some(RailShape::EastWest);
}
if !rail.straight {
if s && e && !n && !w {
shape = Some(RailShape::SouthEast);
}
if s && w && !n && !e {
shape = Some(RailShape::SouthWest);
}
if n && w && !s && !e {
shape = Some(RailShape::NorthWest);
}
if n && e && !s && !w {
shape = Some(RailShape::NorthEast);
}
}
let shape = self.rail_slopes(pos, shape).unwrap_or(RailShape::NorthSouth);
rail.state = self.rail_set_shape(rail.state, shape);
self.set_block_and_update(pos, rail.state);
}
/// `RailState.place`; returns the resulting state.
fn rail_place(&mut self, pos: BlockPos, state: BlockStateId, has_signal: bool, first: bool, default: RailShape) -> BlockStateId {
let mut rail = self.rail_new(pos, state);
let n = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::North));
let s = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::South));
let w = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::West));
let e = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::East));
let mut shape = None;
let ns = n || s;
let we = w || e;
if ns && !we {
shape = Some(RailShape::NorthSouth);
}
if we && !ns {
shape = Some(RailShape::EastWest);
}
let (se, sw, ne, nw) = (s && e, s && w, n && e, n && w);
if !rail.straight {
if se && !n && !w {
shape = Some(RailShape::SouthEast);
}
if sw && !n && !e {
shape = Some(RailShape::SouthWest);
}
if nw && !s && !e {
shape = Some(RailShape::NorthWest);
}
if ne && !s && !w {
shape = Some(RailShape::NorthEast);
}
}
if shape.is_none() {
if ns && we {
shape = Some(default);
} else if ns {
shape = Some(RailShape::NorthSouth);
} else if we {
shape = Some(RailShape::EastWest);
}
if !rail.straight {
if has_signal {
for (cond, s) in [
(se, RailShape::SouthEast),
(sw, RailShape::SouthWest),
(ne, RailShape::NorthEast),
(nw, RailShape::NorthWest),
] {
if cond {
shape = Some(s);
}
}
} else {
for (cond, s) in [
(nw, RailShape::NorthWest),
(ne, RailShape::NorthEast),
(sw, RailShape::SouthWest),
(se, RailShape::SouthEast),
] {
if cond {
shape = Some(s);
}
}
}
}
}
let shape = self.rail_slopes(pos, shape).unwrap_or(default);
rail.connections = Self::rail_connections(pos, shape);
rail.state = self.rail_set_shape(rail.state, shape);
if first || self.state(pos) != rail.state {
self.set_block_and_update(pos, rail.state);
for i in 0..rail.connections.len() {
if let Some(mut neighbour) = self.rail_get(rail.connections[i]) {
self.rail_remove_soft_connections(&mut neighbour);
if Self::rail_can_connect_to(&neighbour, &rail) {
self.rail_connect_to(&mut neighbour, rail.pos);
}
}
}
}
rail.state
}
fn rail_update_dir(&mut self, pos: BlockPos, state: BlockStateId, first: bool) -> BlockStateId {
let current = RailShape::parse(self.rail_shape(state));
let signal = self.has_neighbor_signal(pos);
self.rail_place(pos, state, signal, first, current)
}
/// `BaseRailBlock.updateState(state, level, pos, movedByPiston)`.
pub(crate) fn rail_update_state(&mut self, pos: BlockPos, state: BlockStateId, moved: bool) -> BlockStateId {
let state = self.rail_update_dir(pos, state, true);
if !self.b.data(state).is(Class::Rail) {
let block = self.b.block(state);
self.neighbor_changed_full(state, pos, block, moved);
}
state
}
pub(crate) fn rail_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId, changed: BlockId, moved: bool) {
let b = self.b;
if !b.is_block(self.state(pos), b.block(state)) {
return;
}
let shape = RailShape::parse(self.rail_shape(state));
let support = |sim: &Self, p: BlockPos| sim.can_support_rigid_block(p);
let remove = !support(self, below(pos))
|| match shape {
RailShape::AscendingEast => !support(self, rel(pos, Direction::East)),
RailShape::AscendingWest => !support(self, rel(pos, Direction::West)),
RailShape::AscendingNorth => !support(self, rel(pos, Direction::North)),
RailShape::AscendingSouth => !support(self, rel(pos, Direction::South)),
_ => false,
};
if remove {
self.drop_resources(state, pos);
self.remove_block(pos, moved);
return;
}
let data = b.data(state);
if data.is(Class::PoweredRail) {
self.powered_rail_update(pos, state);
} else if data.is(Class::Rail) {
let changed_default = b.default_of(changed);
if self.is_signal_source_default(changed_default) && self.rail_count_potential_connections(pos) == 3 {
self.rail_update_dir(pos, state, false);
}
}
}
fn is_signal_source_default(&self, state: BlockStateId) -> bool {
self.b.has_flag(state, super::data::state_flags::SIGNAL_SOURCE)
}
fn powered_rail_update(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
let powered = b.table.bool(state, b.props.powered);
let should = self.has_neighbor_signal(pos) || self.powered_rail_find(pos, state, true, 0) || self.powered_rail_find(pos, state, false, 0);
if should != powered {
self.set_block_and_update(pos, b.table.set_bool(state, b.props.powered, should));
let block = b.block(state);
self.update_neighbors_at(below(pos), block);
if RailShape::parse(self.rail_shape(state)).is_slope() {
self.update_neighbors_at(above(pos), block);
}
}
}
fn powered_rail_find(&self, pos: BlockPos, state: BlockStateId, forward: bool, depth: i32) -> bool {
if depth >= 8 {
return false;
}
let (mut x, mut y, mut z) = (pos.x, pos.y, pos.z);
let mut check_below = true;
let mut shape = RailShape::parse(self.rail_shape(state));
match shape {
RailShape::NorthSouth => z += if forward { 1 } else { -1 },
RailShape::EastWest => x += if forward { -1 } else { 1 },
RailShape::AscendingEast => {
if forward {
x -= 1;
} else {
x += 1;
y += 1;
check_below = false;
}
shape = RailShape::EastWest;
}
RailShape::AscendingWest => {
if forward {
x -= 1;
y += 1;
check_below = false;
} else {
x += 1;
}
shape = RailShape::EastWest;
}
RailShape::AscendingNorth => {
if forward {
z += 1;
} else {
z -= 1;
y += 1;
check_below = false;
}
shape = RailShape::NorthSouth;
}
RailShape::AscendingSouth => {
if forward {
z += 1;
y += 1;
check_below = false;
} else {
z -= 1;
}
shape = RailShape::NorthSouth;
}
_ => {}
}
let block = self.b.block(state);
self.powered_rail_same_with_power(BlockPos::new(x, y, z), block, forward, depth, shape)
|| (check_below && self.powered_rail_same_with_power(BlockPos::new(x, y - 1, z), block, forward, depth, shape))
}
fn powered_rail_same_with_power(&self, pos: BlockPos, block: BlockId, forward: bool, depth: i32, dir: RailShape) -> bool {
let b = self.b;
let state = self.state(pos);
if !b.is_block(state, block) {
return false;
}
let mine = RailShape::parse(self.rail_shape(state));
if dir == RailShape::EastWest && matches!(mine, RailShape::NorthSouth | RailShape::AscendingNorth | RailShape::AscendingSouth) {
return false;
}
if dir == RailShape::NorthSouth && matches!(mine, RailShape::EastWest | RailShape::AscendingEast | RailShape::AscendingWest) {
return false;
}
if !b.table.bool(state, b.props.powered) {
return false;
}
self.has_neighbor_signal(pos) || self.powered_rail_find(pos, state, forward, depth + 1)
}
// ---- tripwire ----
/// `TripWireBlock.updateSource`.
pub(crate) fn tripwire_update_source(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
for direction in [Direction::South, Direction::West] {
for i in 1..42 {
let [dx, dy, dz] = direction.normal();
let test = pos.offset(dx * i, dy * i, dz * i);
let block = self.state(test);
if b.is_block(block, b.named.tripwire_hook) {
if b.facing(block) == direction.opposite() {
self.tripwire_hook_calculate(test, block, false, true, i, Some(state));
}
break;
}
if !b.is_block(block, b.named.tripwire) {
break;
}
}
}
}
pub(crate) fn tripwire_tick(&mut self, pos: BlockPos) {
let b = self.b;
let state = self.state(pos);
if b.table.bool(state, b.props.powered) {
self.tripwire_check_pressed(pos);
}
}
/// `TripWireBlock.checkPressed` with the entities currently inside.
pub(crate) fn tripwire_check_pressed(&mut self, pos: BlockPos) {
let b = self.b;
let state = self.state(pos);
let was = b.table.bool(state, b.props.powered);
let top = if b.table.bool(state, b.props.attached) { 2.5 / 16.0 } else { 8.0 / 16.0 };
let area = Aabb::new(
Vec3::new(f64::from(pos.x), f64::from(pos.y) + 1.0 / 16.0, f64::from(pos.z)),
Vec3::new(f64::from(pos.x) + 1.0, f64::from(pos.y) + top, f64::from(pos.z) + 1.0),
);
let pressed = self.level.count_entities(area, super::EntityQuery::Everything) > 0;
let block = b.block(state);
if pressed != was {
let next = b.table.set_bool(state, b.props.powered, pressed);
self.set_block_and_update(pos, next);
self.tripwire_update_source(pos, next);
}
if pressed {
self.schedule_tick(pos, block, 10);
} else if was {
self.schedule_tick(pos, block, 1);
}
}
fn tripwire_hook_notify(&mut self, block: BlockId, pos: BlockPos, direction: Direction) {
let front = direction.opposite();
self.update_neighbors_at(pos, block);
self.update_neighbors_at(rel(pos, front), block);
}
fn tripwire_emit(&mut self, pos: BlockPos, attached: bool, powered: bool, was_attached: bool, was_powered: bool) {
let (sound, volume, pitch, event) = if powered && !was_powered {
("minecraft:block.tripwire.click_on", 0.4, 0.6, "minecraft:block_activate")
} else if !powered && was_powered {
("minecraft:block.tripwire.click_off", 0.4, 0.5, "minecraft:block_deactivate")
} else if attached && !was_attached {
("minecraft:block.tripwire.attach", 0.4, 0.7, "minecraft:block_attach")
} else if !attached && was_attached {
let pitch = 1.2 / (self.random().next_float() * 0.2 + 0.9);
("minecraft:block.tripwire.detach", 0.4, pitch, "minecraft:block_detach")
} else {
return;
};
self.emit(LevelEvent::Sound {
pos,
sound: sound.into(),
volume,
pitch,
});
self.game_event(pos, event);
}
/// `TripWireHookBlock.calculateState`.
pub(crate) fn tripwire_hook_calculate(
&mut self,
pos: BlockPos,
state: BlockStateId,
destroyed: bool,
can_update: bool,
wire_source: i32,
wire_source_state: Option<BlockStateId>,
) {
let b = self.b;
let p = b.props;
let Some(direction) = b.table.dir(state, p.facing) else {
return;
};
let was_attached = b.table.bool(state, p.attached);
let was_powered = b.table.bool(state, p.powered);
let block = b.block(state);
let mut attached = !destroyed;
let mut powered = false;
let mut receiver = 0;
let mut wires: Vec<Option<BlockStateId>> = vec![None; 42];
let [dx, dy, dz] = direction.normal();
for i in 1..42 {
let test = pos.offset(dx * i, dy * i, dz * i);
let mut wire = self.state(test);
if b.is_block(wire, b.named.tripwire_hook) {
if b.facing(wire) == direction.opposite() {
receiver = i;
}
break;
}
if !b.is_block(wire, b.named.tripwire) && i != wire_source {
wires[i as usize] = None;
attached = false;
} else {
if i == wire_source {
wire = wire_source_state.unwrap_or(wire);
}
let armed = !b.table.bool(wire, p.disarmed);
let wire_powered = b.table.bool(wire, p.powered);
powered |= armed && wire_powered;
wires[i as usize] = Some(wire);
if i == wire_source {
self.schedule_tick(pos, block, 10);
attached &= armed;
}
}
}
attached &= receiver > 1;
powered &= attached;
let new_state = b.table.set_bool(b.table.set_bool(b.default_of(block), p.attached, attached), p.powered, powered);
if receiver > 0 {
let test = pos.offset(dx * receiver, dy * receiver, dz * receiver);
let opposite = direction.opposite();
self.set_block_and_update(test, b.table.set_dir(new_state, p.facing, opposite));
self.tripwire_hook_notify(block, test, opposite);
if !b.is_block(self.state(pos), b.named.tripwire_hook) {
self.tripwire_hook_removed(pos, new_state);
return;
}
self.tripwire_emit(test, attached, powered, was_attached, was_powered);
}
self.tripwire_emit(pos, attached, powered, was_attached, was_powered);
if !destroyed {
self.set_block_and_update(pos, b.table.set_dir(new_state, p.facing, direction));
if can_update {
self.tripwire_hook_notify(block, pos, direction);
}
}
if was_attached != attached {
for i in 1..receiver {
let test = pos.offset(dx * i, dy * i, dz * i);
if let Some(wire) = wires[i as usize] {
let current = self.state(test);
if b.is_block(current, b.named.tripwire) || b.is_block(current, b.named.tripwire_hook) {
let next = b.table.with_bool(wire, p.attached, attached).unwrap_or(wire);
self.set_block_and_update(test, next);
}
}
}
}
}
/// `TripWireHookBlock.onRemoved`.
pub(crate) fn tripwire_hook_removed(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
let attached = b.table.bool(state, b.props.attached);
let powered = b.table.bool(state, b.props.powered);
if attached || powered {
self.tripwire_hook_calculate(pos, state, true, false, -1, None);
}
if powered {
let facing = b.facing(state);
self.tripwire_hook_notify(b.block(state), pos, facing);
}
}
}
+1 -1
View File
@@ -567,7 +567,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
Class::LavaCauldron => 3,
Class::RespawnAnchor => {
let charges = b.table.int(state, p.charges);
((charges - 0) as f32 / 4.0 * 15.0).floor() as i32
(charges as f32 / 4.0 * 15.0).floor() as i32
}
Class::CopperGolemStatue => {
let pose = b.table.text(state, p.copper_golem_pose);
+436
View File
@@ -0,0 +1,436 @@
//! Behaviour tests over an in-memory level. They need the prepared client
//! resources (`HORIZON_RESOURCES`, or `.local/horizon-client/26.3` at the
//! repository root) and are skipped when those are absent.
use super::*;
use crate::chunk::BlockState;
use std::{
collections::{BTreeMap, HashMap},
path::PathBuf,
sync::OnceLock,
};
struct Fixture {
registry: BlockRegistry,
behaviours: Behaviours,
}
fn fixture() -> Option<&'static Fixture> {
static FIXTURE: OnceLock<Option<Fixture>> = OnceLock::new();
FIXTURE
.get_or_init(|| {
let root = std::env::var_os("HORIZON_RESOURCES").map(PathBuf::from).unwrap_or_else(|| {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3")
});
if !root.join("block-behaviours.json").exists() {
eprintln!("skipping level tests: no resources at {}", root.display());
return None;
}
let registry = data::load_registry(&root).expect("registry");
let behaviours = Behaviours::load(&registry, &root).expect("behaviours");
Some(Fixture { registry, behaviours })
})
.as_ref()
}
pub(crate) struct TestLevel {
blocks: HashMap<BlockPos, BlockStateId>,
air: BlockStateId,
random: LegacyRandom,
pub time: i64,
pub events: Vec<LevelEvent>,
pub block_light: HashMap<BlockPos, i32>,
}
impl TestLevel {
fn new(b: &Behaviours) -> Self {
Self {
blocks: HashMap::new(),
air: b.air(),
random: LegacyRandom::new(42),
time: 0,
events: Vec::new(),
block_light: HashMap::new(),
}
}
}
impl LevelAccess for TestLevel {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.blocks.get(&pos).copied().unwrap_or(self.air)
}
fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option<BlockStateId> {
Some(self.blocks.insert(pos, state).unwrap_or(self.air))
}
fn is_loaded(&self, _pos: BlockPos) -> bool {
true
}
fn random(&mut self) -> &mut LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
self.time
}
fn block_light(&self, pos: BlockPos) -> i32 {
self.block_light.get(&pos).copied().unwrap_or(0)
}
fn emit(&mut self, event: LevelEvent) {
self.events.push(event);
}
}
struct World<'f> {
f: &'f Fixture,
level: TestLevel,
ticks: Ticks,
}
impl<'f> World<'f> {
fn new(f: &'f Fixture) -> Self {
let mut ticks = Ticks::new(0);
for x in -4..4 {
for z in -4..4 {
ticks.add_empty_chunk(ChunkPos::new(x, z)).unwrap();
}
}
Self {
level: TestLevel::new(&f.behaviours),
f,
ticks,
}
}
fn b(&self) -> &'f Behaviours {
&self.f.behaviours
}
fn id(&self, name: &str, props: &[(&str, &str)]) -> BlockStateId {
let state = BlockState {
name: format!("minecraft:{name}"),
properties: props.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<BTreeMap<_, _>>(),
};
self.f.registry.resolve(&state).unwrap_or_else(|_| panic!("unknown state {name} {props:?}"))
}
fn set(&mut self, pos: BlockPos, state: BlockStateId) -> bool {
self.f.behaviours.set_block(&mut self.level, &mut self.ticks, pos, state, flags::UPDATE_ALL)
}
/// Raw storage write without updates (world generation).
fn put(&mut self, pos: BlockPos, state: BlockStateId) {
self.level.blocks.insert(pos, state);
}
fn get(&self, pos: BlockPos) -> BlockStateId {
self.level.block_state(pos)
}
fn name(&self, pos: BlockPos) -> String {
let state = self.f.registry.state(self.get(pos)).unwrap();
let props: Vec<String> = state.properties.iter().map(|(k, v)| format!("{k}={v}")).collect();
format!("{}[{}]", state.name.trim_start_matches("minecraft:"), props.join(","))
}
fn prop(&self, pos: BlockPos, key: &str) -> String {
self.f.registry.state(self.get(pos)).unwrap().properties.get(key).cloned().unwrap_or_default()
}
fn tick(&mut self) {
self.level.time += 1;
self.f.behaviours.tick_scheduled(&mut self.level, &mut self.ticks);
}
fn floor(&mut self, y: i32, radius: i32, block: &str) {
let state = self.id(block, &[]);
for x in -radius..=radius {
for z in -radius..=radius {
self.put(BlockPos::new(x, y, z), state);
}
}
}
}
macro_rules! world {
() => {{
let Some(f) = fixture() else {
return;
};
World::new(f)
}};
}
#[test]
fn state_table_matches_registry() {
let Some(f) = fixture() else {
return;
};
let t = &f.behaviours.table;
assert_eq!(t.state_count(), f.registry.len());
let stairs = f.registry.default_state("minecraft:oak_stairs").unwrap();
let key = f.behaviours.props.facing;
let east = t.with_text(stairs, key, "east").unwrap();
assert_eq!(f.registry.state(east).unwrap().properties["facing"], "east");
assert_eq!(t.text(east, f.behaviours.props.half), "bottom");
assert!(classes::Class::ALL.len() <= 320);
}
#[test]
fn fences_connect_and_disconnect() {
let mut w = world!();
let fence = w.id("oak_fence", &[]);
let a = BlockPos::new(0, 1, 0);
let c = BlockPos::new(1, 1, 0);
w.set(a, fence);
w.set(c, fence);
assert_eq!(w.prop(a, "east"), "true");
assert_eq!(w.prop(c, "west"), "true");
let stone = w.id("stone", &[]);
w.set(BlockPos::new(0, 1, -1), stone);
assert_eq!(w.prop(a, "north"), "true", "fences connect to sturdy faces");
let air = w.b().air();
w.set(c, air);
assert_eq!(w.prop(a, "east"), "false");
}
#[test]
fn walls_and_panes_connect() {
let mut w = world!();
let wall = w.id("cobblestone_wall", &[]);
let pane = w.id("glass_pane", &[]);
w.set(BlockPos::new(0, 1, 0), wall);
w.set(BlockPos::new(0, 1, 1), wall);
w.set(BlockPos::new(0, 1, 2), wall);
assert_eq!(w.prop(BlockPos::new(0, 1, 1), "north"), "low");
assert_eq!(w.prop(BlockPos::new(0, 1, 1), "south"), "low");
assert_eq!(w.prop(BlockPos::new(0, 1, 1), "up"), "false", "straight wall drops its post");
let stone = w.id("stone", &[]);
w.set(BlockPos::new(0, 2, 1), stone);
assert_eq!(w.prop(BlockPos::new(0, 1, 1), "north"), "tall");
w.set(BlockPos::new(5, 1, 0), pane);
w.set(BlockPos::new(6, 1, 0), pane);
assert_eq!(w.prop(BlockPos::new(5, 1, 0), "east"), "true");
}
#[test]
fn stairs_form_corners() {
let mut w = world!();
let north = w.id("oak_stairs", &[("facing", "north")]);
let east = w.id("oak_stairs", &[("facing", "east")]);
w.set(BlockPos::new(0, 1, 0), north);
w.set(BlockPos::new(0, 1, -1), east);
// The north-facing stair has an east-facing stair behind it.
assert_eq!(w.prop(BlockPos::new(0, 1, 0), "shape"), "outer_right");
}
#[test]
fn torch_and_door_halves_break_with_support() {
let mut w = world!();
w.floor(0, 3, "stone");
let torch = w.id("torch", &[]);
w.set(BlockPos::new(1, 1, 1), torch);
let door = w.id("oak_door", &[("half", "lower")]);
let upper = w.id("oak_door", &[("half", "upper")]);
w.set(BlockPos::new(0, 1, 0), door);
w.set(BlockPos::new(0, 2, 0), upper);
let air = w.b().air();
w.set(BlockPos::new(1, 0, 1), air);
assert_eq!(w.get(BlockPos::new(1, 1, 1)), air, "torch pops without support");
assert!(w.level.events.iter().any(|e| matches!(e, LevelEvent::DropResources { .. })));
w.set(BlockPos::new(0, 1, 0), air);
assert_eq!(w.get(BlockPos::new(0, 2, 0)), air, "upper door half goes with the lower");
}
#[test]
fn snowy_grass_and_chests_pair() {
let mut w = world!();
let grass = w.id("grass_block", &[]);
w.set(BlockPos::new(0, 0, 0), grass);
let snow = w.id("snow", &[]);
w.set(BlockPos::new(0, 1, 0), snow);
assert_eq!(w.prop(BlockPos::new(0, 0, 0), "snowy"), "true");
// A left chest's partner sits clockwise of its facing; removing the
// partner makes it single again.
let left = w.id("chest", &[("facing", "north"), ("type", "left")]);
let right = w.id("chest", &[("facing", "north"), ("type", "right")]);
w.set(BlockPos::new(3, 1, 0), left);
w.set(BlockPos::new(4, 1, 0), right);
let air = w.b().air();
w.set(BlockPos::new(4, 1, 0), air);
assert_eq!(w.prop(BlockPos::new(3, 1, 0), "type"), "single");
}
#[test]
fn sand_falls_and_concrete_solidifies() {
let mut w = world!();
let sand = w.id("sand", &[]);
w.set(BlockPos::new(0, 5, 0), sand);
w.tick();
w.tick();
assert_eq!(w.get(BlockPos::new(0, 5, 0)), w.b().air());
assert!(w.level.events.iter().any(|e| matches!(e, LevelEvent::FallingBlock { state, .. } if *state == sand)));
w.floor(0, 2, "stone");
let water = w.id("water", &[]);
w.put(BlockPos::new(1, 1, 0), water);
let powder = w.id("white_concrete_powder", &[]);
let landing = w.b().falling_block_landed(&mut w.level, &mut w.ticks, BlockPos::new(0, 1, 0), powder, false);
assert_eq!(landing, falling::Landing::Placed(w.id("white_concrete", &[])));
}
#[test]
fn water_spreads_on_a_floor() {
let mut w = world!();
w.floor(0, 10, "stone");
let water = w.id("water", &[]);
w.set(BlockPos::new(0, 1, 0), water);
for _ in 0..60 {
w.tick();
}
for d in 1..=7 {
let pos = BlockPos::new(d, 1, 0);
assert_eq!(w.prop(pos, "level"), d.to_string(), "flow at distance {d}: {}", w.name(pos));
}
assert_eq!(w.get(BlockPos::new(8, 1, 0)), w.b().air());
// Diagonals follow Manhattan distance.
assert_eq!(w.prop(BlockPos::new(2, 1, 2), "level"), "4");
}
#[test]
fn water_falls_and_makes_sources() {
let mut w = world!();
w.floor(0, 4, "stone");
let water = w.id("water", &[]);
w.set(BlockPos::new(0, 4, 0), water);
for _ in 0..30 {
w.tick();
}
assert_eq!(w.prop(BlockPos::new(0, 3, 0), "level"), "8", "falling water");
assert_eq!(w.prop(BlockPos::new(0, 1, 0), "level"), "8");
// Two sources make a third (no holes within slope distance, so the
// sources spread in every direction).
let mut w = world!();
w.floor(0, 12, "stone");
w.set(BlockPos::new(0, 1, 0), water);
w.set(BlockPos::new(2, 1, 0), water);
for _ in 0..20 {
w.tick();
}
assert_eq!(w.get(BlockPos::new(1, 1, 0)), water);
// On a small platform the water instead seeks the nearest edges.
let mut w = world!();
w.floor(0, 4, "stone");
w.set(BlockPos::new(0, 1, 0), water);
w.set(BlockPos::new(2, 1, 0), water);
for _ in 0..20 {
w.tick();
}
assert_eq!(w.get(BlockPos::new(1, 1, 0)), w.b().air());
assert_eq!(w.prop(BlockPos::new(-1, 1, 0), "level"), "1");
}
#[test]
fn lava_meets_water() {
let mut w = world!();
w.floor(0, 4, "stone");
let lava = w.id("lava", &[]);
let water = w.id("water", &[]);
w.set(BlockPos::new(0, 1, 0), lava);
w.set(BlockPos::new(1, 1, 0), water);
assert_eq!(w.get(BlockPos::new(0, 1, 0)), w.id("obsidian", &[]));
let mut w = world!();
w.floor(0, 4, "stone");
w.set(BlockPos::new(0, 1, 0), lava);
for _ in 0..40 {
w.tick();
}
w.set(BlockPos::new(1, 2, 0), water);
for _ in 0..40 {
w.tick();
}
assert_eq!(w.get(BlockPos::new(1, 1, 0)), w.id("cobblestone", &[]), "{}", w.name(BlockPos::new(1, 1, 0)));
}
#[test]
fn waterlogged_blocks_schedule_water() {
let mut w = world!();
w.floor(0, 4, "stone");
let slab = w.id("oak_slab", &[("waterlogged", "true")]);
w.set(BlockPos::new(0, 1, 0), slab);
// A neighbour shape update schedules the slab's water tick.
let stone = w.id("stone", &[]);
w.set(BlockPos::new(0, 1, 1), stone);
for _ in 0..20 {
w.tick();
}
assert_eq!(w.prop(BlockPos::new(1, 1, 0), "level"), "1");
}
#[test]
fn redstone_lever_wire_and_lamp() {
let mut w = world!();
w.floor(0, 20, "stone");
let wire = w.id("redstone_wire", &[]);
let lamp = w.id("redstone_lamp", &[]);
let lever = w.id("lever", &[("face", "floor"), ("facing", "north")]);
for x in 1..=5 {
w.set(BlockPos::new(x, 1, 0), wire);
}
w.set(BlockPos::new(6, 1, 0), lamp);
w.set(BlockPos::new(0, 1, 0), lever);
let lever_on = w.b().table.set_bool(w.get(BlockPos::new(0, 1, 0)), w.b().props.powered, true);
w.set(BlockPos::new(0, 1, 0), lever_on);
assert_eq!(w.prop(BlockPos::new(1, 1, 0), "power"), "15");
assert_eq!(w.prop(BlockPos::new(5, 1, 0), "power"), "11");
assert_eq!(w.prop(BlockPos::new(6, 1, 0), "lit"), "true");
let lever_off = w.b().table.set_bool(lever_on, w.b().props.powered, false);
w.set(BlockPos::new(0, 1, 0), lever_off);
assert_eq!(w.prop(BlockPos::new(3, 1, 0), "power"), "0");
for _ in 0..5 {
w.tick();
}
assert_eq!(w.prop(BlockPos::new(6, 1, 0), "lit"), "false");
}
#[test]
fn repeater_delays_and_torch_inverts() {
let mut w = world!();
w.floor(0, 10, "stone");
let block = w.id("redstone_block", &[]);
// A repeater takes its input from the side it faces.
let repeater = w.id("repeater", &[("facing", "west")]);
w.set(BlockPos::new(1, 1, 0), repeater);
w.set(BlockPos::new(0, 1, 0), block);
assert_eq!(w.prop(BlockPos::new(1, 1, 0), "powered"), "false");
w.tick();
w.tick();
assert_eq!(w.prop(BlockPos::new(1, 1, 0), "powered"), "true");
let torch = w.id("redstone_torch", &[]);
let stone = w.id("stone", &[]);
w.set(BlockPos::new(5, 1, 0), stone);
w.set(BlockPos::new(5, 2, 0), torch);
// A redstone block only weakly powers the stone: the torch stays lit.
w.set(BlockPos::new(6, 1, 0), block);
w.tick();
w.tick();
assert_eq!(w.prop(BlockPos::new(5, 2, 0), "lit"), "true");
// A lever on the stone strongly powers it.
let air = w.b().air();
w.set(BlockPos::new(6, 1, 0), air);
let lever = w.id("lever", &[("face", "wall"), ("facing", "east"), ("powered", "true")]);
w.set(BlockPos::new(6, 1, 0), lever);
// LeverBlock.pull notifies the attached block's neighbours.
let lever_block = w.b().block(lever);
w.b().update_neighbors_at(&mut w.level, &mut w.ticks, BlockPos::new(5, 1, 0), lever_block);
w.tick();
w.tick();
assert_eq!(w.prop(BlockPos::new(5, 2, 0), "lit"), "false");
}
#[test]
fn crops_grow_and_leaves_decay() {
let mut w = world!();
let farmland = w.id("farmland", &[("moisture", "7")]);
let wheat = w.id("wheat", &[]);
w.put(BlockPos::new(0, 0, 0), farmland);
w.put(BlockPos::new(0, 1, 0), wheat);
for _ in 0..400 {
w.b().random_tick(&mut w.level, &mut w.ticks, BlockPos::new(0, 1, 0));
}
assert_eq!(w.prop(BlockPos::new(0, 1, 0), "age"), "7");
let leaves = w.id("oak_leaves", &[("distance", "7")]);
w.put(BlockPos::new(5, 5, 5), leaves);
w.b().random_tick(&mut w.level, &mut w.ticks, BlockPos::new(5, 5, 5));
assert_eq!(w.get(BlockPos::new(5, 5, 5)), w.b().air());
let log = w.id("oak_log", &[]);
let leaf = w.id("oak_leaves", &[]);
w.set(BlockPos::new(9, 5, 5), leaf);
w.set(BlockPos::new(8, 5, 5), log);
w.tick();
assert_eq!(w.prop(BlockPos::new(9, 5, 5), "distance"), "1");
}
File diff suppressed because it is too large Load Diff
+1 -4
View File
@@ -393,10 +393,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
while let Some(update) = updater.added.pop() {
updater.stack.push(update);
}
loop {
let Some(top) = self.ticks.updater.stack.last_mut() else {
break;
};
while let Some(top) = self.ticks.updater.stack.last_mut() {
let (step, more) = top.next();
self.execute(step);
if !more {
+1
View File
@@ -72,6 +72,7 @@ pub mod item_use_catalog;
pub mod item_use_lifecycle;
pub mod item_use_start;
pub mod java_hash_map;
pub mod level;
pub mod liquid_collision;
pub mod live_attribute_updates;
pub mod living_air;
+17
View File
@@ -192,6 +192,22 @@ def main():
subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies,
'dev.horizonlab.parity.VanillaGameplayFactsExporter', str(gameplay)],
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
# Block classes, instance configuration and per-state support/signal/fluid
# facts for horizon-world's level behaviour (level::Behaviours::load).
behaviours = root / 'block-behaviours.json'
behaviour_oracle = oracle.with_name('VanillaBlockBehaviourExporter.java')
behaviour_sources = base.source_hashes([behaviour_oracle])
if not (previous.get('behaviour_exporters_sha256') == behaviour_sources and behaviours.exists()
and previous.get('server_sha256') == origin['server_sha256']):
classes = lab.LOCAL / 'block-behaviours' / 'classes'; classes.mkdir(parents=True, exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
with (root / 'behaviour-export.log').open('w') as log:
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none',
'-cp', dependencies, '-d', str(classes), str(behaviour_oracle)],
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies,
'dev.horizonlab.parity.VanillaBlockBehaviourExporter', str(behaviours)],
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
items = root / 'items.json'
if not items.exists() or previous.get('server_sha256') != origin['server_sha256']:
# Vanilla's own data generator reports every item's default components.
@@ -218,6 +234,7 @@ def main():
'render_files_sha256': {name: lab.digest(root/name, 'sha256') for name in render_files},
'model_state_exporters_sha256': binding_sources,
'gameplay_exporters_sha256': gameplay_sources,
'behaviour_exporters_sha256': behaviour_sources,
'model_states_sha256': lab.digest(model_states, 'sha256'), 'data_version': version['world_version'],
'facts_sha256': lab.digest(facts, 'sha256'),
'block_tags_sha256': lab.digest(root / 'block-tags.json', 'sha256'), 'resource_files': count})