Merge vanilla block behaviours (level module)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 03:30:01 +02:00
30 changed files with 15284 additions and 84 deletions
@@ -0,0 +1,107 @@
//! Rust side of `tools/test_level_place_parity.py`: evaluates
//! `Behaviours::placement_state` for generated neighbourhoods.
use horizon_core::{
geometry::{Direction, Vec3},
position::{BlockPos, ChunkPos},
random::LegacyRandom,
};
use horizon_world::{
level::{Behaviours, LevelAccess, PlaceContext, Ticks, data::load_registry},
registry::BlockStateId,
};
use serde_json::Value;
use std::{
collections::HashMap,
io::{BufRead, Write},
path::Path,
};
struct Cells {
cells: HashMap<BlockPos, BlockStateId>,
air: BlockStateId,
random: LegacyRandom,
}
impl LevelAccess for Cells {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.cells.get(&pos).copied().unwrap_or(self.air)
}
fn set_raw(&mut self, _pos: BlockPos, _state: BlockStateId) -> Option<BlockStateId> {
None
}
fn is_loaded(&self, _pos: BlockPos) -> bool {
true
}
fn random(&mut self) -> &mut LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
0
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let resources = args.next().expect("resource directory");
let cases = args.next().expect("case file");
let output = args.next().expect("output file");
let resources = Path::new(&resources);
let registry = load_registry(resources)?;
let behaviours = Behaviours::load(&registry, resources)?;
let air = registry.default_state("minecraft:air").unwrap();
let mut out = std::io::BufWriter::new(std::fs::File::create(output)?);
for line in std::io::BufReader::new(std::fs::File::open(cases)?).lines() {
let case: Value = serde_json::from_str(&line?)?;
let mut cells = HashMap::new();
for cell in case["cells"].as_array().unwrap() {
let c: Vec<i64> = cell
.as_array()
.unwrap()
.iter()
.map(|v| v.as_i64().unwrap())
.collect();
cells.insert(
BlockPos::new(c[0] as i32, c[1] as i32, c[2] as i32),
BlockStateId(c[3] as u32),
);
}
let mut level = Cells {
cells,
air,
random: LegacyRandom::new(case["seed"].as_i64().unwrap()),
};
let mut ticks = Ticks::new(0);
for x in -2..=2 {
for z in -2..=2 {
ticks.add_empty_chunk(ChunkPos::new(x, z))?;
}
}
let p: Vec<i32> = case["pos"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_i64().unwrap() as i32)
.collect();
let h: Vec<f64> = case["hit"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_f64().unwrap())
.collect();
let ctx = PlaceContext {
clicked_pos: BlockPos::new(p[0], p[1], p[2]),
face: Direction::ALL[case["face"].as_u64().unwrap() as usize],
hit: Vec3::new(h[0], h[1], h[2]),
inside: false,
yaw: case["yaw"].as_f64().unwrap() as f32,
pitch: case["pitch"].as_f64().unwrap() as f32,
sneaking: case["sneak"].as_bool().unwrap(),
item: case["item"].as_str().unwrap().to_owned(),
can_use_game_master_blocks: false,
};
match behaviours.placement_state(&mut level, &mut ticks, &ctx) {
Some((pos, state)) => writeln!(out, "place {},{},{} {}", pos.x, pos.y, pos.z, state.0)?,
None => writeln!(out, "place none")?,
}
}
Ok(())
}
@@ -0,0 +1,147 @@
//! Rust side of `tools/test_level_shape_parity.py`: evaluates
//! `Behaviours::update_shape` and `can_survive` for generated neighbourhoods.
use horizon_core::{
geometry::Direction,
position::{BlockPos, ChunkPos},
random::LegacyRandom,
};
use horizon_world::{
level::{Behaviours, LevelAccess, Ticks, data::load_registry},
registry::BlockStateId,
};
use serde_json::Value;
use std::{
collections::{BTreeSet, HashMap},
io::{BufRead, Write},
path::Path,
};
struct Cells {
cells: HashMap<BlockPos, BlockStateId>,
air: BlockStateId,
random: LegacyRandom,
light: i32,
}
impl LevelAccess for Cells {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.cells.get(&pos).copied().unwrap_or(self.air)
}
fn set_raw(&mut self, _pos: BlockPos, _state: BlockStateId) -> Option<BlockStateId> {
None
}
fn is_loaded(&self, _pos: BlockPos) -> bool {
true
}
fn random(&mut self) -> &mut LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
0
}
fn sky_light(&self, _pos: BlockPos) -> i32 {
self.light
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let resources = args.next().expect("resource directory");
let cases = args.next().expect("case file");
let output = args.next().expect("output file");
let resources = Path::new(&resources);
let registry = load_registry(resources)?;
let behaviours = Behaviours::load(&registry, resources)?;
let air = registry.default_state("minecraft:air").unwrap();
let mut out = std::io::BufWriter::new(std::fs::File::create(output)?);
for line in std::io::BufReader::new(std::fs::File::open(cases)?).lines() {
let case: Value = serde_json::from_str(&line?)?;
let mut cells = HashMap::new();
for cell in case["cells"].as_array().unwrap() {
let c: Vec<i64> = cell
.as_array()
.unwrap()
.iter()
.map(|v| v.as_i64().unwrap())
.collect();
cells.insert(
BlockPos::new(c[0] as i32, c[1] as i32, c[2] as i32),
BlockStateId(c[3] as u32),
);
}
let mut level = Cells {
cells,
air,
random: LegacyRandom::new(case["seed"].as_i64().unwrap()),
light: case["light"].as_i64().unwrap() as i32,
};
let mut ticks = Ticks::new(0);
for x in -2..=2 {
for z in -2..=2 {
ticks.add_empty_chunk(ChunkPos::new(x, z))?;
}
}
let p: Vec<i32> = case["pos"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_i64().unwrap() as i32)
.collect();
let pos = BlockPos::new(p[0], p[1], p[2]);
let direction = Direction::ALL[case["dir"].as_u64().unwrap() as usize];
let [dx, dy, dz] = direction.normal();
let neighbour_pos = pos.offset(dx, dy, dz);
let state = level.block_state(pos);
let neighbour = level.block_state(neighbour_pos);
let shape = behaviours.update_shape(
&mut level,
&mut ticks,
state,
pos,
direction,
neighbour_pos,
neighbour,
);
let mut scheduled = BTreeSet::new();
for x in -2..=2 {
for z in -2..=2 {
let chunk = ChunkPos::new(x, z);
for tick in ticks
.blocks
.chunk(chunk)
.map(|c| c.queued())
.unwrap_or_default()
{
let name = &behaviours
.table
.info(horizon_world::level::BlockId(tick.kind.0 as u16))
.name;
scheduled.insert(format!(
"{name}@{},{},{}+{}p{}",
tick.pos.x, tick.pos.y, tick.pos.z, tick.trigger_tick, tick.priority as i32
));
}
for tick in ticks
.fluids
.chunk(chunk)
.map(|c| c.queued())
.unwrap_or_default()
{
let name = horizon_world::fluid::FluidKind::ALL[tick.kind.0 as usize].name();
scheduled.insert(format!(
"{name}@{},{},{}+{}p{}",
tick.pos.x, tick.pos.y, tick.pos.z, tick.trigger_tick, tick.priority as i32
));
}
}
}
let survive = behaviours.can_survive(&mut level, &mut ticks, pos, state);
let scheduled: Vec<String> = scheduled.into_iter().collect();
writeln!(
out,
"shape {} ticks {} survive {survive}",
shape.0,
scheduled.join(" ")
)?;
}
Ok(())
}
+11
View File
@@ -127,6 +127,17 @@ impl FluidState {
}
serde_json::to_string(&value).map_err(|e| invalid(e.to_string()))
}
/// A fluid state from its parts; the empty fluid ignores amount and falling.
pub const fn new(kind: FluidKind, amount: u8, falling: bool) -> Self {
if matches!(kind, FluidKind::Empty) {
return Self::EMPTY;
}
Self {
kind,
amount,
falling,
}
}
pub const EMPTY: Self = Self {
kind: FluidKind::Empty,
amount: 0,
+341
View File
@@ -0,0 +1,341 @@
//! Vanilla block classes recognised by Horizon's behaviour port.
//!
//! Each block's exported class chain (most derived first) is matched against
//! this list: `class` is the most derived recognised class (it selects the
//! ported overrides), and `instance_of` answers Java `instanceof` checks such
//! as `state.getBlock() instanceof LeavesBlock` for any recognised ancestor.
macro_rules! classes {
($($name:ident = $java:literal,)*) => {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(u16)]
pub enum Class { $($name,)* }
impl Class {
pub const ALL: &'static [Class] = &[$(Class::$name,)*];
pub fn from_java(name: &str) -> Option<Self> {
match name { $($java => Some(Class::$name),)* _ => None }
}
pub const fn java_name(self) -> &'static str {
match self { $(Class::$name => $java,)* }
}
}
};
}
classes! {
Block = "Block",
Air = "AirBlock",
AmethystCluster = "AmethystClusterBlock",
Anvil = "AnvilBlock",
AttachedStem = "AttachedStemBlock",
Azalea = "AzaleaBlock",
BambooSapling = "BambooSaplingBlock",
BambooStalk = "BambooStalkBlock",
AbstractBanner = "AbstractBannerBlock",
Banner = "BannerBlock",
WallBanner = "WallBannerBlock",
Barrel = "BarrelBlock",
BaseCoralPlantType = "BaseCoralPlantTypeBlock",
BaseCoralPlant = "BaseCoralPlantBlock",
BaseCoralFan = "BaseCoralFanBlock",
BaseCoralWallFan = "BaseCoralWallFanBlock",
CoralPlant = "CoralPlantBlock",
CoralFan = "CoralFanBlock",
CoralWallFan = "CoralWallFanBlock",
Coral = "CoralBlock",
BaseEntity = "BaseEntityBlock",
BaseFire = "BaseFireBlock",
Fire = "FireBlock",
SoulFire = "SoulFireBlock",
BasePressurePlate = "BasePressurePlateBlock",
PressurePlate = "PressurePlateBlock",
WeightedPressurePlate = "WeightedPressurePlateBlock",
BaseRail = "BaseRailBlock",
Rail = "RailBlock",
PoweredRail = "PoweredRailBlock",
DetectorRail = "DetectorRailBlock",
BaseTorch = "BaseTorchBlock",
Torch = "TorchBlock",
WallTorch = "WallTorchBlock",
RedstoneTorch = "RedstoneTorchBlock",
RedstoneWallTorch = "RedstoneWallTorchBlock",
AbstractBed = "AbstractBedBlock",
Bed = "BedBlock",
StrawBed = "StrawBedBlock",
Beehive = "BeehiveBlock",
Beetroot = "BeetrootBlock",
Bell = "BellBlock",
BigDripleaf = "BigDripleafBlock",
BigDripleafStem = "BigDripleafStemBlock",
BonemealableFeaturePlacer = "BonemealableFeaturePlacerBlock",
BubbleColumn = "BubbleColumnBlock",
BuddingAmethyst = "BuddingAmethystBlock",
Bush = "BushBlock",
Button = "ButtonBlock",
Cactus = "CactusBlock",
CactusFlower = "CactusFlowerBlock",
Cake = "CakeBlock",
Campfire = "CampfireBlock",
AbstractCandle = "AbstractCandleBlock",
Candle = "CandleBlock",
CandleCake = "CandleCakeBlock",
Carpet = "CarpetBlock",
WoolCarpet = "WoolCarpetBlock",
MossyCarpet = "MossyCarpetBlock",
Carrot = "CarrotBlock",
CarvedPumpkin = "CarvedPumpkinBlock",
AbstractCauldron = "AbstractCauldronBlock",
Cauldron = "CauldronBlock",
LavaCauldron = "LavaCauldronBlock",
LayeredCauldron = "LayeredCauldronBlock",
GrowingPlant = "GrowingPlantBlock",
GrowingPlantHead = "GrowingPlantHeadBlock",
GrowingPlantBody = "GrowingPlantBodyBlock",
CaveVines = "CaveVinesBlock",
CaveVinesPlant = "CaveVinesPlantBlock",
Kelp = "KelpBlock",
KelpPlant = "KelpPlantBlock",
TwistingVines = "TwistingVinesBlock",
TwistingVinesPlant = "TwistingVinesPlantBlock",
WeepingVines = "WeepingVinesBlock",
WeepingVinesPlant = "WeepingVinesPlantBlock",
Sign = "SignBlock",
StandingSign = "StandingSignBlock",
WallSign = "WallSignBlock",
CeilingHangingSign = "CeilingHangingSignBlock",
WallHangingSign = "WallHangingSignBlock",
RotatedPillar = "RotatedPillarBlock",
Chain = "ChainBlock",
AbstractChest = "AbstractChestBlock",
Chest = "ChestBlock",
TrappedChest = "TrappedChestBlock",
CopperChest = "CopperChestBlock",
EnderChest = "EnderChestBlock",
ChiseledBookShelf = "ChiseledBookShelfBlock",
ChorusFlower = "ChorusFlowerBlock",
ChorusPlant = "ChorusPlantBlock",
Pipe = "PipeBlock",
Cocoa = "CocoaBlock",
FallingBlock = "FallingBlock",
ColoredFalling = "ColoredFallingBlock",
Sand = "SandBlock",
ConcretePowder = "ConcretePowderBlock",
DragonEgg = "DragonEggBlock",
Comparator = "ComparatorBlock",
Repeater = "RepeaterBlock",
Diode = "DiodeBlock",
Composter = "ComposterBlock",
CopperBulb = "CopperBulbBlock",
Crafter = "CrafterBlock",
CraftingTable = "CraftingTableBlock",
CreakingHeart = "CreakingHeartBlock",
Crop = "CropBlock",
CrossCollision = "CrossCollisionBlock",
DaylightDetector = "DaylightDetectorBlock",
DecoratedPot = "DecoratedPotBlock",
Directional = "DirectionalBlock",
Dispenser = "DispenserBlock",
Dropper = "DropperBlock",
Door = "DoorBlock",
DoublePlant = "DoublePlantBlock",
DriedGhast = "DriedGhastBlock",
DropExperience = "DropExperienceBlock",
DryVegetation = "DryVegetationBlock",
ShortDryGrass = "ShortDryGrassBlock",
TallDryGrass = "TallDryGrassBlock",
EndPortalFrame = "EndPortalFrameBlock",
Rod = "RodBlock",
EndRod = "EndRodBlock",
LightningRod = "LightningRodBlock",
Flower = "FlowerBlock",
Eyeblossom = "EyeblossomBlock",
WitherRose = "WitherRoseBlock",
FaceAttachedHorizontalDirectional = "FaceAttachedHorizontalDirectionalBlock",
Farmland = "FarmlandBlock",
Fence = "FenceBlock",
FenceGate = "FenceGateBlock",
FireflyBush = "FireflyBushBlock",
FlowerBed = "FlowerBedBlock",
FlowerPot = "FlowerPotBlock",
Frogspawn = "FrogspawnBlock",
Ice = "IceBlock",
FrostedIce = "FrostedIceBlock",
AbstractFurnace = "AbstractFurnaceBlock",
GlazedTerracotta = "GlazedTerracottaBlock",
Multiface = "MultifaceBlock",
MultifaceSpreadeable = "MultifaceSpreadeableBlock",
GlowLichen = "GlowLichenBlock",
SculkVein = "SculkVeinBlock",
Snowy = "SnowyBlock",
SpreadingSnowy = "SpreadingSnowyBlock",
Grass = "GrassBlock",
Mycelium = "MyceliumBlock",
Grindstone = "GrindstoneBlock",
HalfTransparent = "HalfTransparentBlock",
HangingMoss = "HangingMossBlock",
HangingRoots = "HangingRootsBlock",
Hay = "HayBlock",
Hopper = "HopperBlock",
HorizontalDirectional = "HorizontalDirectionalBlock",
HugeMushroom = "HugeMushroomBlock",
Infested = "InfestedBlock",
InfestedRotatedPillar = "InfestedRotatedPillarBlock",
IronBars = "IronBarsBlock",
StainedGlassPane = "StainedGlassPaneBlock",
Jukebox = "JukeboxBlock",
Ladder = "LadderBlock",
Lantern = "LanternBlock",
LeafLitter = "LeafLitterBlock",
Leaves = "LeavesBlock",
MangroveLeaves = "MangroveLeavesBlock",
Lectern = "LecternBlock",
Lever = "LeverBlock",
Light = "LightBlock",
LilyPad = "LilyPadBlock",
Liquid = "LiquidBlock",
Loom = "LoomBlock",
Magma = "MagmaBlock",
MangrovePropagule = "MangrovePropaguleBlock",
MangroveRoots = "MangroveRootsBlock",
MovingPiston = "MovingPistonBlock",
Mud = "MudBlock",
Mushroom = "MushroomBlock",
NetherFungus = "NetherFungusBlock",
NetherPortal = "NetherPortalBlock",
NetherRoots = "NetherRootsBlock",
NetherSprouts = "NetherSproutsBlock",
NetherWart = "NetherWartBlock",
Note = "NoteBlock",
Nylium = "NyliumBlock",
Observer = "ObserverBlock",
Path = "PathBlock",
AbstractSkull = "AbstractSkullBlock",
Skull = "SkullBlock",
WallSkull = "WallSkullBlock",
PistonBase = "PistonBaseBlock",
PistonHead = "PistonHeadBlock",
PitcherCrop = "PitcherCropBlock",
Speleothem = "SpeleothemBlock",
PointedDripstone = "PointedDripstoneBlock",
SulfurSpike = "SulfurSpikeBlock",
Potato = "PotatoBlock",
PowderSnow = "PowderSnowBlock",
Powered = "PoweredBlock",
Pumpkin = "PumpkinBlock",
RedStoneOre = "RedStoneOreBlock",
RedstoneLamp = "RedstoneLampBlock",
RedstoneWire = "RedstoneWireBlock",
RespawnAnchor = "RespawnAnchorBlock",
RootedDirt = "RootedDirtBlock",
Sapling = "SaplingBlock",
Scaffolding = "ScaffoldingBlock",
SculkSensor = "SculkSensorBlock",
CalibratedSculkSensor = "CalibratedSculkSensorBlock",
SculkShrieker = "SculkShriekerBlock",
SeaPickle = "SeaPickleBlock",
Seagrass = "SeagrassBlock",
Shelf = "ShelfBlock",
ShelfMushroom = "ShelfMushroomBlock",
ShulkerBox = "ShulkerBoxBlock",
Slab = "SlabBlock",
SmallDripleaf = "SmallDripleafBlock",
SnifferEgg = "SnifferEggBlock",
SnowLayer = "SnowLayerBlock",
SoulSand = "SoulSandBlock",
Sponge = "SpongeBlock",
WetSponge = "WetSpongeBlock",
SporeBlossom = "SporeBlossomBlock",
Stair = "StairBlock",
Stem = "StemBlock",
Stonecutter = "StonecutterBlock",
SugarCane = "SugarCaneBlock",
SweetBerryBush = "SweetBerryBushBlock",
TallFlower = "TallFlowerBlock",
TallGrass = "TallGrassBlock",
TallSeagrass = "TallSeagrassBlock",
Target = "TargetBlock",
Tnt = "TntBlock",
TorchflowerCrop = "TorchflowerCropBlock",
TrapDoor = "TrapDoorBlock",
TripWire = "TripWireBlock",
TripWireHook = "TripWireHookBlock",
TurtleEgg = "TurtleEggBlock",
Vegetation = "VegetationBlock",
Vine = "VineBlock",
Wall = "WallBlock",
WaterloggedTransparent = "WaterloggedTransparentBlock",
WeatheringCopperFull = "WeatheringCopperFullBlock",
Web = "WebBlock",
CopperGolemStatue = "CopperGolemStatueBlock",
Beacon = "BeaconBlock",
BrewingStand = "BrewingStandBlock",
Brushable = "BrushableBlock",
Conduit = "ConduitBlock",
EnchantingTable = "EnchantingTableBlock",
EndGateway = "EndGatewayBlock",
EndPortal = "EndPortalBlock",
Spawner = "SpawnerBlock",
TrialSpawner = "TrialSpawnerBlock",
Vault = "VaultBlock",
Barrier = "BarrierBlock",
StructureVoid = "StructureVoidBlock",
Command = "CommandBlock",
Structure = "StructureBlock",
Jigsaw = "JigsawBlock",
SmithingTable = "SmithingTableBlock",
CartographyTable = "CartographyTableBlock",
Netherrack = "NetherrackBlock",
Sculk = "SculkBlock",
SculkCatalyst = "SculkCatalystBlock",
PotentSulfur = "PotentSulfurBlock",
Honey = "HoneyBlock",
Slime = "SlimeBlock",
HeavyCore = "HeavyCoreBlock",
CryingObsidian = "CryingObsidianBlock",
}
/// Java interfaces Horizon's port consults through `instanceof`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Interface {
SimpleWaterlogged,
LiquidBlockContainer,
BucketPickup,
Bonemealable,
Fallable,
Entity,
WeatheringCopper,
CaveVines,
}
impl Interface {
pub fn from_java(name: &str) -> Option<Self> {
Some(match name {
"SimpleWaterloggedBlock" => Self::SimpleWaterlogged,
"LiquidBlockContainer" => Self::LiquidBlockContainer,
"BucketPickup" => Self::BucketPickup,
"BonemealableBlock" => Self::Bonemealable,
"Fallable" => Self::Fallable,
"EntityBlock" => Self::Entity,
"WeatheringCopper" => Self::WeatheringCopper,
"CaveVines" => Self::CaveVines,
_ => return None,
})
}
pub const fn mask(self) -> u16 {
1 << self as u8
}
}
/// Set of recognised classes in one block's chain.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ClassSet([u64; 5]);
impl ClassSet {
pub fn insert(&mut self, class: Class) {
let i = class as usize;
self.0[i / 64] |= 1 << (i % 64);
}
pub fn contains(self, class: Class) -> bool {
let i = class as usize;
self.0[i / 64] & (1 << (i % 64)) != 0
}
}
File diff suppressed because it is too large Load Diff
+133
View File
@@ -0,0 +1,133 @@
//! 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);
// DirectionalPlaceContext(level, pos, DOWN, ItemStack.EMPTY, UP).
let ctx = super::place::Ctx {
pos,
hit_pos: pos,
face: Direction::Up,
hit: horizon_core::geometry::Vec3::new(
f64::from(pos.x) + 0.5,
f64::from(pos.y),
f64::from(pos.z) + 0.5,
),
inside: false,
yaw: 0.0,
pitch: 90.0,
sneaking: false,
item: String::new(),
replace_clicked: true,
};
let may_replace = sim.can_be_replaced(current, &ctx);
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))
}
}
+745
View File
@@ -0,0 +1,745 @@
//! `FlowingFluid` (water and lava) ticking and spreading, `LiquidBlock`
//! interactions, liquid containers (waterlogging) and bucket pickup.
use super::{
Dimension, LevelAccess, Sim,
classes::{Class, Interface},
update::{HORIZONTAL, above, below, rel},
};
use crate::{
fluid::{FluidKind, FluidState},
registry::BlockStateId,
};
use horizon_core::{
geometry::{Axis, Direction, ShapeOp, VoxelShape},
position::BlockPos,
random::RandomSource,
};
use std::collections::HashMap;
/// `LiquidBlock.POSSIBLE_FLOW_DIRECTIONS`.
const POSSIBLE_FLOW_DIRECTIONS: [Direction; 5] = [
Direction::Down,
Direction::South,
Direction::North,
Direction::East,
Direction::West,
];
fn is_water(kind: FluidKind) -> bool {
matches!(kind, FluidKind::Water | FluidKind::FlowingWater)
}
fn source_of(kind: FluidKind) -> FluidKind {
if is_water(kind) {
FluidKind::Water
} else {
FluidKind::Lava
}
}
fn flowing_of(kind: FluidKind) -> FluidKind {
if is_water(kind) {
FluidKind::FlowingWater
} else {
FluidKind::FlowingLava
}
}
/// `FlowingFluid.SpreadContext`: per-spread caches keyed by horizontal offset.
struct SpreadContext {
origin: BlockPos,
states: HashMap<i16, BlockStateId>,
holes: HashMap<i16, bool>,
}
impl SpreadContext {
fn key(&self, pos: BlockPos) -> i16 {
let x = pos.x.wrapping_sub(self.origin.x).wrapping_add(128) & 0xff;
let z = pos.z.wrapping_sub(self.origin.z).wrapping_add(128) & 0xff;
((x << 8) | z) as i16
}
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
fn fast_lava(&self) -> bool {
self.level.dimension() == Dimension::Nether
}
/// `Fluid.getTickDelay`.
pub(crate) fn fluid_tick_delay(&self, kind: FluidKind) -> i32 {
match kind {
FluidKind::Empty => 0,
FluidKind::Water | FluidKind::FlowingWater => 5,
_ => {
if self.fast_lava() {
10
} else {
30
}
}
}
}
fn drop_off(&self, kind: FluidKind) -> i32 {
if is_water(kind) || self.fast_lava() {
1
} else {
2
}
}
fn slope_find_distance(&self, kind: FluidKind) -> i32 {
if is_water(kind) || self.fast_lava() {
4
} else {
2
}
}
fn can_convert_to_source(&self, kind: FluidKind) -> bool {
let rules = self.level.game_rules();
if is_water(kind) {
rules.water_source_conversion
} else {
rules.lava_source_conversion
}
}
fn fluid_height(&self, fluid: FluidState, pos: BlockPos) -> f32 {
if fluid.kind() == FluidKind::Empty {
return 0.0;
}
if fluid.kind().same_family(self.fluid_at(above(pos)).kind()) {
1.0
} else {
fluid.own_height()
}
}
/// `FluidState.canBeReplacedWith(level, pos, other, direction)`.
fn can_be_replaced_with(
&self,
fluid: FluidState,
pos: BlockPos,
other: FluidKind,
direction: Direction,
) -> bool {
match fluid.kind() {
FluidKind::Empty => true,
FluidKind::Water | FluidKind::FlowingWater => {
direction == Direction::Down && !is_water(other)
}
_ => self.fluid_height(fluid, pos) >= 0.444_444_45 && is_water(other),
}
}
// ---- shape occlusion ----
fn collision_or_empty(&self, state: BlockStateId) -> (i32, VoxelShape) {
let index = self.b.facts(state).shape;
match self.b.collision_shape(state) {
Some(shape) => (index, shape.clone()),
None => (-1, VoxelShape::empty()),
}
}
/// `FlowingFluid.canPassThroughWall`.
fn can_pass_through_wall(
&self,
direction: Direction,
source: BlockStateId,
target: BlockStateId,
) -> bool {
let (target_index, target_shape) = self.collision_or_empty(target);
let block = VoxelShape::block();
if target_shape.same_identity(&block) {
return false;
}
let (source_index, source_shape) = self.collision_or_empty(source);
if source_shape.same_identity(&block) {
return false;
}
let empty = VoxelShape::empty();
if source_shape.same_identity(&empty) && target_shape.same_identity(&empty) {
return true;
}
let cacheable = source_index >= 0 && target_index >= 0;
let key = (source_index, target_index, direction as u8);
if cacheable {
if let Some(result) = self
.b
.occlusion_cache
.lock()
.ok()
.and_then(|cache| cache.get(&key).copied())
{
return result;
}
}
let result = !merged_face_occludes(&source_shape, &target_shape, direction);
if cacheable {
if let Ok(mut cache) = self.b.occlusion_cache.lock() {
cache.insert(key, result);
}
}
result
}
// ---- liquid containers ----
/// `LiquidBlockContainer` membership (`canHoldAnyFluid` first clause).
fn is_liquid_container(&self, state: BlockStateId) -> bool {
self.b.implements(state, Interface::LiquidBlockContainer)
|| self.b.implements(state, Interface::SimpleWaterlogged)
}
/// `LiquidBlockContainer.canPlaceLiquid(null, level, pos, state, fluid)`.
pub(crate) fn can_place_liquid(&self, state: BlockStateId, fluid: FluidKind) -> bool {
let b = self.b;
let data = b.data(state);
if data.is(Class::Kelp)
|| data.is(Class::KelpPlant)
|| data.is(Class::Seagrass)
|| data.is(Class::TallSeagrass)
|| data.is(Class::Barrier)
{
return false;
}
if data.is(Class::Slab) && b.table.text(state, b.props.kind) == "double" {
return false;
}
fluid == FluidKind::Water
}
/// `LiquidBlockContainer.placeLiquid`.
pub(crate) fn place_liquid(
&mut self,
pos: BlockPos,
state: BlockStateId,
fluid: FluidState,
) -> bool {
let b = self.b;
if !self.can_place_liquid(state, fluid.kind())
|| fluid.kind() != FluidKind::Water
|| !b.table.has(state, b.props.waterlogged)
{
return false;
}
if b.is_waterlogged(state) {
return false;
}
let mut next = b.table.set_bool(state, b.props.waterlogged, true);
let data = b.data(state);
if (data.is(Class::Candle) || data.is(Class::Campfire)) && b.table.bool(state, b.props.lit)
{
next = b.table.set_bool(next, b.props.lit, false);
if data.is(Class::Campfire) {
self.emit(super::LevelEvent::Sound {
pos,
sound: "minecraft:block.generic.extinguish_fire".into(),
volume: 1.0,
pitch: 1.0,
});
} else {
self.emit(super::LevelEvent::Sound {
pos,
sound: "minecraft:block.candle.extinguish".into(),
volume: 1.0,
pitch: 1.0,
});
}
}
self.set_block_and_update(pos, next);
let delay = self.fluid_tick_delay(fluid.kind());
self.schedule_fluid_tick(pos, fluid.kind(), delay);
true
}
/// `BucketPickup.pickupBlock`: true when a fluid was taken.
pub(crate) fn pickup_block(&mut self, pos: BlockPos, state: BlockStateId) -> bool {
let b = self.b;
if b.instance_of(state, Class::Liquid) {
if b.table.int(state, b.props.level) == 0 {
self.set_block(pos, b.air(), 11);
return true;
}
return false;
}
if b.implements(state, Interface::SimpleWaterlogged)
&& b.table.has(state, b.props.waterlogged)
{
if b.is_waterlogged(state) {
self.set_block_and_update(pos, b.table.set_bool(state, b.props.waterlogged, false));
if !self.can_survive(state, pos) {
self.destroy_block(pos, true, 512);
}
return true;
}
return false;
}
if b.is_block(state, b.named.powder_snow) {
self.set_block(pos, b.air(), 11);
return true;
}
false
}
fn can_hold_any_fluid(&self, state: BlockStateId) -> bool {
self.is_liquid_container(state) || self.b.in_set(state, &self.b.tags.washed_away_by_fluids)
}
fn can_hold_specific_fluid(&self, state: BlockStateId, fluid: FluidKind) -> bool {
if self.is_liquid_container(state) {
self.can_place_liquid(state, fluid)
} else {
true
}
}
fn can_hold_fluid(&self, state: BlockStateId, fluid: FluidKind) -> bool {
self.can_hold_any_fluid(state) && self.can_hold_specific_fluid(state, fluid)
}
// ---- FlowingFluid ----
fn is_source_of(&self, kind: FluidKind, fluid: FluidState) -> bool {
fluid.kind().same_family(kind) && fluid.is_source()
}
/// `FlowingFluid.getNewLiquid`.
fn new_liquid(&self, kind: FluidKind, pos: BlockPos, state: BlockStateId) -> FluidState {
let b = self.b;
let mut highest = 0;
let mut sources = 0;
for direction in HORIZONTAL {
let neighbour = self.rel_state(pos, direction);
let fluid = b.fluid(neighbour);
if fluid.kind().same_family(kind)
&& self.can_pass_through_wall(direction, state, neighbour)
{
if fluid.is_source() {
sources += 1;
}
highest = highest.max(i32::from(fluid.amount()));
}
}
if sources >= 2 && self.can_convert_to_source(kind) {
let below_state = self.below_state(pos);
if b.is_solid(below_state) || self.is_source_of(kind, b.fluid(below_state)) {
return FluidState::new(source_of(kind), 8, false);
}
}
let above_state = self.above_state(pos);
let above_fluid = b.fluid(above_state);
if above_fluid.kind() != FluidKind::Empty
&& above_fluid.kind().same_family(kind)
&& self.can_pass_through_wall(Direction::Up, state, above_state)
{
return FluidState::new(flowing_of(kind), 8, true);
}
let amount = highest - self.drop_off(kind);
if amount <= 0 {
FluidState::EMPTY
} else {
FluidState::new(flowing_of(kind), amount as u8, false)
}
}
fn is_water_hole(&self, kind: FluidKind, top: BlockStateId, bottom: BlockStateId) -> bool {
if !self.can_pass_through_wall(Direction::Down, top, bottom) {
return false;
}
if self.b.fluid(bottom).kind().same_family(kind) {
true
} else {
self.can_hold_fluid(bottom, flowing_of(kind))
}
}
fn can_maybe_pass_through(
&self,
kind: FluidKind,
source: BlockStateId,
direction: Direction,
test: BlockStateId,
test_fluid: FluidState,
) -> bool {
!self.is_source_of(kind, test_fluid)
&& self.can_hold_any_fluid(test)
&& self.can_pass_through_wall(direction, source, test)
}
fn can_pass_through(
&self,
kind: FluidKind,
source: BlockStateId,
direction: Direction,
test: BlockStateId,
test_fluid: FluidState,
) -> bool {
self.can_maybe_pass_through(kind, source, direction, test, test_fluid)
&& self.can_hold_specific_fluid(test, flowing_of(kind))
}
fn context_state(&self, context: &mut SpreadContext, pos: BlockPos) -> BlockStateId {
let key = context.key(pos);
if let Some(state) = context.states.get(&key) {
return *state;
}
let state = self.state(pos);
context.states.insert(key, state);
state
}
fn context_is_hole(&self, kind: FluidKind, context: &mut SpreadContext, pos: BlockPos) -> bool {
let key = context.key(pos);
if let Some(hole) = context.holes.get(&key) {
return *hole;
}
let state = self.context_state(context, pos);
let below_state = self.below_state(pos);
let hole = self.is_water_hole(kind, state, below_state);
context.holes.insert(key, hole);
hole
}
fn slope_distance(
&self,
kind: FluidKind,
pos: BlockPos,
pass: i32,
from: Direction,
state: BlockStateId,
context: &mut SpreadContext,
) -> i32 {
let mut lowest = 1000;
for direction in HORIZONTAL {
if direction == from {
continue;
}
let test_pos = rel(pos, direction);
let test_state = self.context_state(context, test_pos);
let test_fluid = self.b.fluid(test_state);
if self.can_pass_through(kind, state, direction, test_state, test_fluid) {
if self.context_is_hole(kind, context, test_pos) {
return pass;
}
if pass < self.slope_find_distance(kind) {
let distance = self.slope_distance(
kind,
test_pos,
pass + 1,
direction.opposite(),
test_state,
context,
);
lowest = lowest.min(distance);
}
}
}
lowest
}
/// `FlowingFluid.getSpread` (EnumMap: iteration in Direction order).
fn spread_targets(
&self,
kind: FluidKind,
pos: BlockPos,
state: BlockStateId,
) -> Vec<(Direction, FluidState)> {
let mut lowest = 1000;
let mut result: Vec<(Direction, FluidState)> = Vec::new();
let mut context: Option<SpreadContext> = None;
for direction in HORIZONTAL {
let test_pos = rel(pos, direction);
let test_state = self.state(test_pos);
let test_fluid = self.b.fluid(test_state);
if !self.can_maybe_pass_through(kind, state, direction, test_state, test_fluid) {
continue;
}
let new_fluid = self.new_liquid(kind, test_pos, test_state);
if !self.can_hold_specific_fluid(test_state, new_fluid.kind()) {
continue;
}
let context = context.get_or_insert_with(|| SpreadContext {
origin: pos,
states: HashMap::new(),
holes: HashMap::new(),
});
let distance = if self.context_is_hole(kind, context, test_pos) {
0
} else {
self.slope_distance(kind, test_pos, 1, direction.opposite(), test_state, context)
};
if distance < lowest {
result.clear();
}
if distance <= lowest {
if self.can_be_replaced_with(test_fluid, test_pos, new_fluid.kind(), direction) {
result.push((direction, new_fluid));
}
lowest = distance;
}
}
result.sort_by_key(|(direction, _)| *direction as u8);
result
}
fn source_neighbour_count(&self, kind: FluidKind, pos: BlockPos) -> i32 {
HORIZONTAL
.into_iter()
.filter(|d| self.is_source_of(kind, self.fluid_at(rel(pos, *d))))
.count() as i32
}
/// `FlowingFluid.spreadTo` (with LavaFluid's water-to-stone override).
fn spread_to(
&mut self,
kind: FluidKind,
pos: BlockPos,
state: BlockStateId,
direction: Direction,
target: FluidState,
) {
let b = self.b;
if !is_water(kind)
&& direction == Direction::Down
&& b.is_water_fluid(self.fluid_at(pos).kind())
{
if b.instance_of(state, Class::Liquid) {
self.set_block_and_update(pos, b.default_of(b.named.stone));
}
self.level_event(1501, pos, 0);
return;
}
if self.is_liquid_container(state) {
self.place_liquid(pos, state, target);
} else {
if !b.is_air(state) {
if is_water(kind) {
self.drop_resources(state, pos);
} else {
self.level_event(1501, pos, 0);
}
}
let legacy = b.legacy_block(target);
self.set_block_and_update(pos, legacy);
}
}
fn spread_to_sides(
&mut self,
kind: FluidKind,
pos: BlockPos,
fluid: FluidState,
state: BlockStateId,
) {
let mut neighbour = i32::from(fluid.amount()) - self.drop_off(kind);
if fluid.falling() {
neighbour = 7;
}
if neighbour > 0 {
for (direction, new_fluid) in self.spread_targets(kind, pos, state) {
let neighbour_pos = rel(pos, direction);
let neighbour_state = self.state(neighbour_pos);
self.spread_to(kind, neighbour_pos, neighbour_state, direction, new_fluid);
}
}
}
/// `FlowingFluid.spread`.
fn spread(&mut self, kind: FluidKind, pos: BlockPos, state: BlockStateId, fluid: FluidState) {
if fluid.kind() == FluidKind::Empty {
return;
}
let below_pos = below(pos);
let below_state = self.state(below_pos);
let below_fluid = self.b.fluid(below_state);
if self.can_maybe_pass_through(kind, state, Direction::Down, below_state, below_fluid) {
let new_below = self.new_liquid(kind, below_pos, below_state);
if self.can_be_replaced_with(below_fluid, below_pos, new_below.kind(), Direction::Down)
&& self.can_hold_specific_fluid(below_state, new_below.kind())
{
self.spread_to(kind, below_pos, below_state, Direction::Down, new_below);
if self.source_neighbour_count(kind, pos) >= 3 {
self.spread_to_sides(kind, pos, fluid, state);
}
return;
}
}
if fluid.is_source() || !self.is_water_hole(kind, state, below_state) {
self.spread_to_sides(kind, pos, fluid, state);
}
}
/// `FlowingFluid.tick` for the fluid at `pos`.
pub(crate) fn fluid_tick(&mut self, pos: BlockPos) {
let mut state = self.state(pos);
let mut fluid = self.b.fluid(state);
let kind = fluid.kind();
if kind == FluidKind::Empty {
return;
}
if !fluid.is_source() {
let new_fluid = self.new_liquid(kind, pos, state);
let delay = self.spread_delay(kind, pos, fluid, new_fluid);
if new_fluid.kind() == FluidKind::Empty {
fluid = new_fluid;
state = self.b.air();
self.set_block_and_update(pos, state);
} else if new_fluid != fluid {
fluid = new_fluid;
state = self.b.legacy_block(fluid);
self.set_block_and_update(pos, state);
self.schedule_fluid_tick(pos, fluid.kind(), delay);
}
}
self.spread(kind, pos, state, fluid);
}
fn spread_delay(
&mut self,
kind: FluidKind,
pos: BlockPos,
old: FluidState,
new: FluidState,
) -> i32 {
let delay = self.fluid_tick_delay(kind);
if is_water(kind) {
return delay;
}
if old.kind() != FluidKind::Empty
&& new.kind() != FluidKind::Empty
&& !old.falling()
&& !new.falling()
&& self.fluid_height(new, pos) > self.fluid_height(old, pos)
&& self.random().next_int_bound(4).unwrap_or(0) != 0
{
delay * 4
} else {
delay
}
}
// ---- LiquidBlock ----
/// `LiquidBlock.shouldSpreadLiquid`, including lava's conversions.
pub(crate) fn should_spread_liquid(&mut self, pos: BlockPos, state: BlockStateId) -> bool {
let b = self.b;
if !b.is_lava_fluid(b.fluid(state).kind()) {
return true;
}
let over_soul_soil = b.is_block(self.below_state(pos), b.named.soul_soil);
for direction in POSSIBLE_FLOW_DIRECTIONS {
let neighbour = rel(pos, direction.opposite());
if b.is_water_fluid(self.fluid_at(neighbour).kind()) {
let block = if self.fluid_at(pos).is_source() {
b.named.obsidian
} else {
b.named.cobblestone
};
self.set_block_and_update(pos, b.default_of(block));
self.level_event(1501, pos, 0);
return false;
}
if over_soul_soil && b.is_block(self.state(neighbour), b.named.blue_ice) {
self.set_block_and_update(pos, b.default_of(b.named.basalt));
self.level_event(1501, pos, 0);
return false;
}
}
true
}
/// `LiquidBlock.onPlace` / `neighborChanged`.
pub(crate) fn liquid_block_changed(&mut self, pos: BlockPos, state: BlockStateId) {
if self.should_spread_liquid(pos, state) {
let kind = self.b.fluid(state).kind();
let delay = self.fluid_tick_delay(kind);
self.schedule_fluid_tick(pos, kind, delay);
}
if self.should_bubble_column_occupy(state) {
let below_state = self.below_state(pos);
let block = self.b.block(state);
self.try_schedule_bubble_column(pos, below_state, block);
}
}
/// `LavaFluid.randomTick`.
pub(crate) fn lava_random_tick(&mut self, pos: BlockPos) {
if !self.level.can_spread_fire_around(pos) {
return;
}
let passes = self.random().next_int_bound(3).unwrap_or(0);
if passes > 0 {
let mut test = pos;
for _ in 0..passes {
let dx = self.random().next_int_bound(3).unwrap_or(0) - 1;
let dz = self.random().next_int_bound(3).unwrap_or(0) - 1;
test = test.offset(dx, 1, dz);
if !self.level.is_loaded(test) {
return;
}
let state = self.state(test);
if self.b.is_air(state) {
if Direction::ALL
.into_iter()
.any(|d| self.lava_flammable(rel(test, d)))
{
let fire = self.fire_state_for(test);
self.set_block_and_update(test, fire);
return;
}
} else if self
.b
.tag("minecraft:blocks_lava_fire_spread")
.is_some_and(|tag| self.b.in_set(state, tag))
{
return;
}
}
} else {
for _ in 0..3 {
let dx = self.random().next_int_bound(3).unwrap_or(0) - 1;
let dz = self.random().next_int_bound(3).unwrap_or(0) - 1;
let test = pos.offset(dx, 0, dz);
if !self.level.is_loaded(test) {
return;
}
if self.is_empty_block(above(test)) && self.lava_flammable(test) {
let fire = self.fire_state_for(test);
self.set_block_and_update(above(test), fire);
}
}
}
}
fn lava_flammable(&self, pos: BlockPos) -> bool {
if self.is_inside_build_height(pos.y) && !self.level.is_loaded(pos) {
return false;
}
self.b
.has_flag(self.state(pos), super::data::state_flags::IGNITED_BY_LAVA)
}
}
/// `Shapes.mergedFaceOccludes(shape, occluder, direction)`.
pub(crate) fn merged_face_occludes(
shape: &VoxelShape,
occluder: &VoxelShape,
direction: Direction,
) -> bool {
let block = VoxelShape::block();
if shape.same_identity(&block) || occluder.same_identity(&block) {
return true;
}
let positive = matches!(
direction,
Direction::Up | Direction::South | Direction::East
);
let axis = match direction {
Direction::West | Direction::East => Axis::X,
Direction::Down | Direction::Up => Axis::Y,
_ => Axis::Z,
};
let (first, second) = if positive {
(shape, occluder)
} else {
(occluder, shape)
};
let max_face = match axis {
Axis::X => Direction::East,
Axis::Y => Direction::Up,
Axis::Z => Direction::South,
};
let empty = VoxelShape::empty();
// SliceShape(first, axis, last layer) / SliceShape(second, axis, 0): the face
// shapes sample the same boundary layers when the shapes touch the face.
let first_slice = if !first.is_empty() && (first.max(axis) - 1.0).abs() <= 1.0e-7 {
first.face_shape(max_face).unwrap_or_else(|_| empty.clone())
} else {
empty.clone()
};
let second_slice = if !second.is_empty() && second.min(axis).abs() <= 1.0e-7 {
second
.face_shape(max_face.opposite())
.unwrap_or_else(|_| empty.clone())
} else {
empty.clone()
};
let union = match first_slice.join(&second_slice, ShapeOp::OR) {
Ok(shape) => shape,
Err(_) => return false,
};
!block
.join_is_not_empty(&union, ShapeOp::ONLY_FIRST)
.unwrap_or(true)
}
+538
View File
@@ -0,0 +1,538 @@
//! `neighborChanged`, `onPlace`, `affectNeighborsAfterRemoval` and
//! `updateIndirectNeighbourShapes` for the overriding vanilla classes.
use super::{
LevelAccess, Sim,
classes::Class,
states::BlockId,
update::{below, rel},
};
use crate::registry::BlockStateId;
use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource};
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
/// `BlockState.handleNeighborChanged`.
pub fn neighbor_changed(
&mut self,
state: BlockStateId,
pos: BlockPos,
changed: BlockId,
moved: bool,
) {
let b = self.b;
let block = b.block(state);
let chain = &b.data(state).chain;
for &class in chain.iter() {
match class {
Class::AbstractSkull => self.skull_neighbor_changed(pos, state),
Class::BaseRail => self.rail_neighbor_changed(pos, state, changed, moved),
Class::Bell => self.bell_neighbor_changed(pos, state),
Class::BigDripleaf => {
if self.has_neighbor_signal(pos) {
self.big_dripleaf_reset_tilt(pos, state);
}
}
Class::CopperBulb => self.copper_bulb_check(pos, state),
Class::Crafter => self.crafter_neighbor_changed(pos, state),
Class::Diode => self.diode_neighbor_changed(pos, state),
Class::Dispenser => self.dispenser_neighbor_changed(pos, state),
Class::Door => self.door_neighbor_changed(pos, state, changed),
Class::FenceGate => self.gate_neighbor_changed(pos, state),
Class::FrostedIce => {
if b.block_data(changed).is(Class::FrostedIce)
&& self.frosted_ice_fewer_neighbours_than(pos, 2)
{
self.frosted_ice_melt(pos, state);
}
}
Class::Hopper => self.hopper_check_powered(pos, state),
Class::Liquid => self.liquid_block_changed(pos, state),
Class::Note => self.note_neighbor_changed(pos, state),
Class::PistonBase => self.piston_check_if_extend(pos, state),
Class::PistonHead => {
if self.piston_head_can_survive(state, pos) {
let base = rel(pos, b.facing(state).opposite());
self.neighbor_changed_at(base, changed);
}
}
Class::RedstoneLamp => self.lamp_neighbor_changed(pos, state),
Class::RedstoneTorch => self.torch_neighbor_changed(pos, state),
Class::RedstoneWire => {
if self.can_survive(state, pos) {
self.wire_update_power(pos, state);
} else {
self.drop_resources(state, pos);
self.remove_block(pos, false);
}
}
Class::Sponge => self.sponge_try_absorb(pos),
Class::Tnt => self.tnt_check(pos),
Class::TrapDoor => self.trapdoor_neighbor_changed(pos, state),
_ => continue,
}
let _ = block;
return;
}
}
/// `BlockState.onPlace`.
pub fn on_place(&mut self, state: BlockStateId, pos: BlockPos, old: BlockStateId, moved: bool) {
let b = self.b;
let block = b.block(state);
let same = b.block(old) == block;
let chain = &b.data(state).chain;
for &class in chain.iter() {
match class {
Class::Fire => {
self.base_fire_on_place(pos, state, same);
let delay = 30 + self.random().next_int_bound(10).unwrap_or(0);
self.schedule_tick(pos, block, delay);
}
Class::BaseFire => self.base_fire_on_place(pos, state, same),
Class::DetectorRail | Class::BaseRail => {
if !same {
self.rail_update_state(pos, state, moved);
}
}
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);
}
}
Class::CopperBulb => {
if !same {
self.copper_bulb_check(pos, state);
}
}
Class::CoralFan | Class::CoralPlant | Class::CoralWallFan => {
self.coral_try_schedule_die_tick(state, pos)
}
Class::Diode => self.diode_update_neighbors_in_front(pos, state),
Class::FallingBlock => {
let delay = if b.data(state).is(Class::DragonEgg) {
5
} else {
2
};
self.schedule_tick(pos, block, delay);
}
Class::Frogspawn => {
let delay = self.random().next_int_between(3600, 12000).unwrap_or(3600);
self.schedule_tick(pos, block, delay);
}
Class::FrostedIce => {
let delay = self
.random()
.next_int_between_inclusive(60, 120)
.unwrap_or(60);
self.schedule_tick(pos, block, delay);
}
Class::Hopper => {
if !same {
self.hopper_check_powered(pos, state);
}
}
Class::LightningRod => {
if !same
&& b.table.bool(state, b.props.powered)
&& !self.ticks.has_block_tick(pos, block)
{
self.schedule_tick(pos, block, 8);
}
}
Class::Liquid => self.liquid_block_changed(pos, state),
Class::PistonBase => {
if !same && self.moving_piston(pos).is_none() {
self.piston_check_if_extend(pos, state);
}
}
Class::Observer => {
if !same
&& b.table.bool(state, b.props.powered)
&& !self.ticks.has_block_tick(pos, block)
{
let next = b.table.set_bool(state, b.props.powered, false);
self.set_block(pos, next, 18);
self.observer_update_in_front(pos, next);
}
}
Class::RedstoneTorch => self.torch_notify_neighbors(pos, state),
Class::RedstoneWire => {
if !same {
self.wire_update_power(pos, state);
for direction in [Direction::Up, Direction::Down] {
self.update_neighbors_at(rel(pos, direction), block);
}
self.wire_update_neighbors_of_neighboring_wires(pos);
}
}
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);
}
}
Class::Sponge => {
if !same {
self.sponge_try_absorb(pos);
}
}
Class::WetSponge => {
if self.level.dimension() == super::Dimension::Nether {
self.set_block_and_update(pos, b.default_of(b.named.sponge));
self.level_event(2009, pos, 0);
let pitch = (1.0 + self.random().next_float() * 0.2) * 0.7;
self.emit(super::LevelEvent::Sound {
pos,
sound: "minecraft:block.wet_sponge.dries".into(),
volume: 1.0,
pitch,
});
}
}
Class::Target => {
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);
}
}
Class::Tnt => {
if !same {
self.tnt_check(pos);
}
}
Class::TripWire => {
if !same {
self.tripwire_update_source(pos, state);
}
}
Class::TurtleEgg => {
if b.in_set(self.below_state(pos), &b.tags.sand) {
self.level_event(2012, pos, 15);
}
}
_ => continue,
}
return;
}
}
/// `BlockState.affectNeighborsAfterRemoval`.
pub fn affect_neighbors_after_removal(
&mut self,
state: BlockStateId,
pos: BlockPos,
moved: bool,
) {
let b = self.b;
let block = b.block(state);
let chain = &b.data(state).chain;
for &class in chain.iter() {
match class {
Class::AbstractFurnace
| Class::Barrel
| Class::BrewingStand
| Class::Chest
| Class::ChiseledBookShelf
| Class::Crafter
| Class::CreakingHeart
| Class::DecoratedPot
| Class::Dispenser
| Class::Hopper
| 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::BasePressurePlate => {
if !moved && self.plate_signal_for_state(state) > 0 {
self.plate_update_neighbours(pos, block);
}
}
Class::BaseRail => {
if !moved {
if self.rail_shape(state).starts_with("ascending") {
self.update_neighbors_at(super::update::above(pos), block);
}
if !b.data(state).is(Class::Rail) {
self.update_neighbors_at(pos, block);
self.update_neighbors_at(below(pos), block);
}
}
}
Class::Button | Class::Lever => {
if !moved && b.table.bool(state, b.props.powered) {
self.attached_update_neighbours(pos, state);
}
}
Class::LightningRod => {
if b.table.bool(state, b.props.powered) {
let facing = b.facing(state);
self.update_neighbors_at(rel(pos, facing.opposite()), block);
}
}
Class::PistonHead => {
let base_pos = rel(pos, b.facing(state).opposite());
let base = self.state(base_pos);
if self.piston_head_fitting_base(state, base) {
self.destroy_block(base_pos, true, super::flags::UPDATE_LIMIT);
}
}
Class::Lectern => {
if b.table.bool(state, b.props.powered) {
self.update_neighbors_at(below(pos), block);
}
}
Class::Diode => {
if !moved {
self.diode_update_neighbors_in_front(pos, state);
}
}
Class::Observer => {
if b.table.bool(state, b.props.powered) && self.ticks.has_block_tick(pos, block)
{
let off = b.table.set_bool(state, b.props.powered, false);
self.observer_update_in_front(pos, off);
}
}
Class::RedstoneTorch => {
if !moved {
self.torch_notify_neighbors(pos, state);
}
}
Class::RedstoneWire => {
if !moved {
for direction in Direction::ALL {
self.update_neighbors_at(rel(pos, direction), block);
}
self.wire_update_power(pos, state);
self.wire_update_neighbors_of_neighboring_wires(pos);
}
}
Class::SculkSensor => {
if b.table.text(state, b.table_phase_key()) == "active" {
self.update_neighbors_at(pos, block);
self.update_neighbors_at(below(pos), block);
}
}
Class::TripWire => {
if !moved {
let powered = b.table.set_bool(state, b.props.powered, true);
self.tripwire_update_source(pos, powered);
}
}
Class::TripWireHook => {
if !moved {
self.tripwire_hook_removed(pos, state);
}
}
_ => continue,
}
return;
}
}
/// `BlockState.updateIndirectNeighbourShapes` (only redstone wire overrides it).
pub fn update_indirect_neighbour_shapes(
&mut self,
state: BlockStateId,
pos: BlockPos,
flags: i32,
limit: i32,
) {
if self.b.is_block(state, self.b.named.redstone_wire) {
self.wire_update_indirect(state, pos, flags, limit);
}
}
/// `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).
fn base_fire_on_place(&mut self, pos: BlockPos, state: BlockStateId, same: bool) {
if !same && !self.can_survive(state, pos) {
self.remove_block(pos, false);
}
}
/// `SpongeBlock.tryAbsorbWater`.
pub(crate) fn sponge_try_absorb(&mut self, start: BlockPos) {
if self.sponge_remove_water(start) {
let b = self.b;
self.set_block(start, b.default_of(b.named.wet_sponge), 2);
self.emit(super::LevelEvent::Sound {
pos: start,
sound: "minecraft:block.sponge.absorb".into(),
volume: 1.0,
pitch: 1.0,
});
}
}
fn sponge_remove_water(&mut self, start: BlockPos) -> bool {
use std::collections::{HashSet, VecDeque};
let b = self.b;
let mut queue = VecDeque::from([(start, 0)]);
let mut visited = HashSet::new();
let mut count = 0;
while let Some((pos, depth)) = queue.pop_front() {
if !visited.insert(pos) {
continue;
}
let accept = if pos == start {
true
} else {
let state = self.state(pos);
if !b.is_water_fluid(self.fluid_at(pos).kind()) {
false
} else if self.pickup_block(pos, state) {
true
} else {
if b.instance_of(state, Class::Liquid) {
self.set_block_and_update(pos, b.air());
} else {
let n = b.named;
let block = b.block(state);
if block != n.kelp
&& block != n.kelp_plant
&& block != n.seagrass
&& block != n.tall_seagrass
{
continue;
}
self.drop_resources(state, pos);
self.set_block_and_update(pos, b.air());
}
true
}
};
if !accept {
continue;
}
count += 1;
if count >= 65 {
return count > 1;
}
if depth < 6 {
for direction in Direction::ALL {
queue.push_back((rel(pos, direction), depth + 1));
}
}
}
count > 1
}
fn frosted_ice_fewer_neighbours_than(&self, pos: BlockPos, limit: i32) -> bool {
let mut count = 0;
for direction in Direction::ALL {
if self
.b
.data(self.rel_state(pos, direction))
.is(Class::FrostedIce)
{
count += 1;
if count >= limit {
return false;
}
}
}
true
}
/// `FrostedIceBlock.melt` → `IceBlock.melt`.
pub(crate) fn frosted_ice_melt(&mut self, pos: BlockPos, _state: BlockStateId) {
self.ice_melt(pos);
}
/// `IceBlock.melt`.
pub(crate) fn ice_melt(&mut self, pos: BlockPos) {
let b = self.b;
if self.level.dimension() == super::Dimension::Nether {
self.remove_block(pos, false);
} else {
let water = b.default_of(b.named.water);
self.set_block_and_update(pos, water);
self.neighbor_changed_at(pos, b.named.water);
}
}
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 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,
});
}
}
}
impl super::Behaviours {
pub(crate) fn table_phase_key(&self) -> super::states::PropKey {
self.props.sculk_sensor_phase
}
}
+485
View File
@@ -0,0 +1,485 @@
//! `BlockBehaviour.useWithoutItem` (right-click with an empty hand or an item
//! that does not handle the block itself).
use super::{
Behaviours, LevelAccess, LevelEvent, Sim, Ticks, classes::Class, query::axis_of, update::below,
};
use crate::registry::BlockStateId;
use horizon_core::{
geometry::{Axis, Direction, Vec3},
position::BlockPos,
random::RandomSource,
};
use std::sync::Arc;
/// `InteractionResult` as seen by the server.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InteractionResult {
Success,
Consume,
Pass,
}
impl InteractionResult {
pub fn consumes_action(self) -> bool {
!matches!(self, Self::Pass)
}
}
/// The interacting player, as far as block behaviour needs it.
#[derive(Clone, Copy, Debug)]
pub struct PlayerContext {
/// View rotation in degrees.
pub yaw: f32,
pub pitch: f32,
/// `Abilities.mayBuild` (false in adventure mode).
pub may_build: bool,
/// `Player.canEat(false)` (hunger below max, or creative).
pub can_eat: bool,
/// `Player.canUseGameMasterBlocks` (creative operator).
pub game_master: bool,
}
/// Player-side effects of an interaction, reported through
/// [`LevelEvent::Player`]; block changes are already applied.
#[derive(Clone, Debug, PartialEq)]
pub enum PlayerEffect {
/// Open the block's menu (crafting table, furnace, chest, sign editor, ...).
OpenMenu,
/// `CakeBlock.eat`: the player eats a slice (food 2, saturation 0.1).
EatCake,
/// Give the item to the player (dropping it when the inventory is full).
GiveItem(Arc<str>),
/// Pop the item at the block (composter bone meal).
DropItem(Arc<str>),
/// Evaluate the block-interaction loot table and pop the results.
InteractLoot(&'static str),
/// Try to sleep in the bed whose head is at the event position.
Sleep,
/// Respawn anchor: set the respawn point (or explode outside the Nether).
RespawnAnchor,
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
fn player_effect(&mut self, pos: BlockPos, state: BlockStateId, effect: PlayerEffect) {
self.emit(LevelEvent::Player { pos, state, effect });
}
pub(crate) fn use_without_item(
&mut self,
pos: BlockPos,
face: Direction,
hit: Vec3,
player: PlayerContext,
) -> InteractionResult {
let b = self.b;
let p = b.props;
let table = &b.table;
let state = self.state(pos);
let data = b.data(state);
let block = b.block(state);
use InteractionResult::*;
for &class in data.chain.iter() {
return match class {
Class::Door => {
if !data.set_type.as_ref().is_some_and(|s| s.can_open_by_hand) {
return Pass;
}
let next = table.cycle(state, p.open);
self.set_block(pos, next, 10);
let open = table.bool(next, p.open);
self.door_sound(pos, next, open);
self.game_event(
pos,
if open {
"minecraft:block_open"
} else {
"minecraft:block_close"
},
);
Success
}
Class::TrapDoor => {
if !data.set_type.as_ref().is_some_and(|s| s.can_open_by_hand) {
return Pass;
}
let next = table.cycle(state, p.open);
self.set_block(pos, next, 2);
if b.is_waterlogged(next) {
self.schedule_water_tick(pos);
}
self.trapdoor_sound(pos, next, table.bool(next, p.open));
Success
}
Class::FenceGate => {
let next = if table.bool(state, p.open) {
table.set_bool(state, p.open, false)
} else {
let direction = super::place::from_y_rot(f64::from(player.yaw));
let mut next = state;
if b.facing(state) == direction.opposite() {
next = table.set_dir(next, p.facing, direction);
}
table.set_bool(next, p.open, true)
};
self.set_block(pos, next, 10);
let opens = table.bool(next, p.open);
let sound = if opens {
data.gate_open.clone()
} else {
data.gate_close.clone()
};
let pitch = self.random().next_float() * 0.1 + 0.9;
if let Some(sound) = sound {
self.sound(pos, &sound, 1.0, pitch);
}
self.game_event(
pos,
if opens {
"minecraft:block_open"
} else {
"minecraft:block_close"
},
);
Success
}
Class::Button => {
if table.bool(state, p.powered) {
return Consume;
}
self.button_press(pos, state);
Success
}
Class::Lever => {
self.lever_pull(pos, state);
Success
}
Class::Repeater => {
if !player.may_build {
return Pass;
}
self.set_block_and_update(pos, table.cycle(state, p.delay));
Success
}
Class::Comparator => {
if !player.may_build {
return Pass;
}
let next = table.cycle(state, p.mode);
let pitch = if table.text(next, p.mode) == "subtract" {
0.55
} else {
0.5
};
self.emit(LevelEvent::Sound {
pos,
sound: "minecraft:block.comparator.click".into(),
volume: 0.3,
pitch,
});
self.set_block(pos, next, 2);
if b.is_block(self.state(pos), block) {
self.comparator_refresh(pos, next);
}
Success
}
Class::Note => {
let next = table.cycle(state, p.note);
self.set_block_and_update(pos, next);
self.note_play(pos, next);
Success
}
Class::RedstoneWire => self.wire_use(pos, state, player),
Class::DaylightDetector => {
if !player.may_build {
return Pass;
}
let next = table.cycle(state, p.inverted);
self.set_block(pos, next, 2);
self.game_event(pos, "minecraft:block_change");
Success
}
Class::Cake => {
if !player.can_eat {
return Pass;
}
self.player_effect(pos, state, PlayerEffect::EatCake);
self.game_event(pos, "minecraft:eat");
let bites = table.int(state, p.bites);
if bites < 6 {
self.set_block_and_update(pos, table.set_int(state, p.bites, bites + 1));
} else {
self.remove_block(pos, false);
self.game_event(pos, "minecraft:block_destroy");
}
Success
}
Class::CandleCake => {
if !player.can_eat {
return Pass;
}
self.player_effect(pos, state, PlayerEffect::EatCake);
self.game_event(pos, "minecraft:eat");
let cake = b.default_of(b.named.cake);
self.set_block_and_update(pos, table.set_int(cake, p.bites, 1));
self.drop_resources(state, pos);
Success
}
Class::Composter => {
if table.int(state, p.level) != 8 {
return Pass;
}
self.player_effect(
pos,
state,
PlayerEffect::DropItem("minecraft:bone_meal".into()),
);
self.set_block_and_update(pos, table.set_int(state, p.level, 0));
self.game_event(pos, "minecraft:block_change");
self.emit(LevelEvent::Sound {
pos,
sound: "minecraft:block.composter.empty".into(),
volume: 1.0,
pitch: 1.0,
});
Success
}
Class::CaveVines | Class::CaveVinesPlant => {
if !table.bool(state, p.berries) {
return Pass;
}
self.player_effect(
pos,
state,
PlayerEffect::InteractLoot("minecraft:harvest/cave_vine"),
);
let pitch = self.random().next_float() * 0.4 + 0.8;
self.emit(LevelEvent::Sound {
pos,
sound: "minecraft:block.cave_vines.pick_berries".into(),
volume: 1.0,
pitch,
});
let next = table.set_bool(state, p.berries, false);
self.set_block(pos, next, 2);
self.game_event(pos, "minecraft:block_change");
Success
}
Class::SweetBerryBush => {
if table.int(state, p.age) <= 1 {
return Pass;
}
self.player_effect(
pos,
state,
PlayerEffect::InteractLoot("minecraft:harvest/sweet_berry_bush"),
);
let pitch = 0.8 + self.random().next_float() * 0.4;
self.emit(LevelEvent::Sound {
pos,
sound: "minecraft:block.sweet_berry_bush.pick_berries".into(),
volume: 1.0,
pitch,
});
self.set_block(pos, table.set_int(state, p.age, 1), 2);
self.game_event(pos, "minecraft:block_change");
Success
}
Class::FlowerPot => {
let Some(potted) = data.link else {
return Consume;
};
if b.is_air(b.default_of(potted)) {
return Consume;
}
let item = b.block_data(potted).item.clone();
self.player_effect(pos, state, PlayerEffect::GiveItem(item));
self.set_block_and_update(pos, b.default_of(b.named.flower_pot));
self.game_event(pos, "minecraft:block_change");
Success
}
Class::DragonEgg => {
self.dragon_egg_teleport(pos, state);
Success
}
Class::AbstractBed => {
let part = table.text(state, p.part).to_owned();
let facing = b.facing(state);
let other_dir = if part == "foot" {
facing
} else {
facing.opposite()
};
let other = self.state(super::update::rel(pos, other_dir));
if b.is_block(other, block) && table.text(other, p.part) != part {
let head = if part == "head" {
pos
} else {
super::update::rel(pos, facing)
};
let head_state = self.state(head);
self.player_effect(head, head_state, PlayerEffect::Sleep);
Success
} else {
Consume
}
}
Class::RespawnAnchor => {
if table.int(state, p.charges) == 0 {
return Pass;
}
self.player_effect(pos, state, PlayerEffect::RespawnAnchor);
Success
}
Class::Light => {
if player.game_master {
self.set_block(pos, table.cycle(state, p.level), 2);
Success
} else {
Consume
}
}
Class::Bell => {
let click_y = hit.y - f64::from(pos.y);
let proper = axis_of(face) != Axis::Y && click_y <= 0.8124 && {
let facing_axis = axis_of(b.facing(state));
match table.text(state, p.attachment) {
"floor" => facing_axis == axis_of(face),
"single_wall" | "double_wall" => facing_axis != axis_of(face),
"ceiling" => true,
_ => false,
}
};
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");
Success
} else {
Pass
}
}
Class::AbstractFurnace
| Class::Anvil
| Class::Barrel
| Class::Beacon
| Class::BrewingStand
| Class::CartographyTable
| Class::Chest
| Class::Crafter
| Class::CraftingTable
| Class::Dispenser
| Class::EnchantingTable
| Class::EnderChest
| Class::Grindstone
| Class::Hopper
| Class::Loom
| Class::ShulkerBox
| Class::Sign
| Class::SmithingTable
| Class::Stonecutter
| Class::Lectern => {
self.player_effect(pos, state, PlayerEffect::OpenMenu);
Success
}
Class::Command | Class::Structure | Class::Jigsaw => {
if player.game_master {
self.player_effect(pos, state, PlayerEffect::OpenMenu);
Success
} else {
Pass
}
}
_ => continue,
};
}
let _ = below;
Pass
}
/// `RedstoneWireBlock.useWithoutItem`: toggle between dot and cross.
fn wire_use(
&mut self,
pos: BlockPos,
state: BlockStateId,
player: PlayerContext,
) -> InteractionResult {
let b = self.b;
if !player.may_build {
return InteractionResult::Pass;
}
let connected = |s: BlockStateId, d: Direction| b.table.text(s, b.dir_prop(d)) != "none";
let horizontal = super::update::HORIZONTAL;
let cross = horizontal.into_iter().all(|d| connected(state, d));
let dot = !horizontal.into_iter().any(|d| connected(state, d));
if !(cross || dot) {
return InteractionResult::Pass;
}
let power = b.table.int(state, b.props.power);
let base = if cross {
b.table
.set_int(b.default_of(b.named.redstone_wire), b.props.power, power)
} else {
self.wire_cross_state(power)
};
let next = self.wire_connection_state(base, pos);
if next == state {
return InteractionResult::Pass;
}
self.set_block_and_update(pos, next);
for direction in horizontal {
let relative = super::update::rel(pos, direction);
if connected(state, direction) != connected(next, direction)
&& self.is_redstone_conductor(self.state(relative), relative)
{
let block = b.block(next);
self.update_neighbors_at_except(relative, block, direction.opposite());
}
}
InteractionResult::Success
}
/// `DragonEggBlock.teleport`.
fn dragon_egg_teleport(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
for _ in 0..1000 {
let dx = self.random().next_int_bound(16).unwrap_or(0)
- self.random().next_int_bound(16).unwrap_or(0);
let dy = self.random().next_int_bound(8).unwrap_or(0)
- self.random().next_int_bound(8).unwrap_or(0);
let dz = self.random().next_int_bound(16).unwrap_or(0)
- self.random().next_int_bound(16).unwrap_or(0);
let test = pos.offset(dx, dy, dz);
if b.is_air(self.state(test))
&& !b.is_air(self.below_state(test))
&& self.is_inside_build_height(test.y)
{
// BlockUtil.packDifferenceInPosition(pos, test, 16, 8, 16)
let packed = ((dx + 16) << 16) | ((dy + 8) << 8) | (dz + 16);
self.level_event(2015, pos, packed);
self.set_block(test, state, 2);
self.remove_block(pos, false);
return;
}
}
}
}
impl Behaviours {
/// `BlockState.useWithoutItem` for a right-click on `pos` (hit face and
/// absolute hit location as in `BlockHitResult`).
pub fn use_without_item<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
face: Direction,
hit: Vec3,
player: PlayerContext,
) -> InteractionResult {
self.sim(level, ticks)
.use_without_item(pos, face, hit, player)
}
}
+591
View File
@@ -0,0 +1,591 @@
//! Server-side vanilla block behaviour: `Level.setBlock` with neighbour and
//! shape-update propagation, scheduled block/fluid ticks, random ticks,
//! placement (`getStateForPlacement`) and interaction (`useWithoutItem`).
//!
//! The library is client-agnostic. A game owns its chunk storage and exposes
//! it through [`LevelAccess`]; it also owns one [`Ticks`] per level (scheduled
//! tick queues, the in-flight neighbour-update queue and the random-tick LCG).
//! [`Behaviours`] holds immutable tables loaded once from the pinned client
//! resources (`block-behaviours.json`, `gameplay-facts.json`,
//! `block-tags.json`, `cached-collision.nbt`; see
//! `tools/prepare_native_client.py`).
//!
//! # Driving a level
//!
//! Per server tick, in vanilla order (`ServerLevel.tick`):
//! 1. [`Behaviours::tick_scheduled`] runs due block ticks then fluid ticks
//! (`blockTicks.tick(time, 65536, ...)`, then `fluidTicks`).
//! 2. For every ticking chunk, [`Behaviours::tick_chunk_random`] performs
//! `ServerLevel.tickChunk`'s random ticks: for each non-empty section,
//! `randomTickSpeed` (game rule, default 3) positions are drawn with
//! `Level.getBlockRandomPos` and randomly-ticking block and fluid states are
//! ticked. The caller decides which sections are randomly ticking (vanilla
//! counts randomly-ticking states per section); [`Behaviours::random_tick`]
//! ticks a single position.
//! 3. [`Behaviours::run_block_events`] runs queued block events (pistons),
//! then (after entities) [`Behaviours::tick_block_entities`] advances
//! moving pistons ([`Ticks::moving_pistons`]).
//! 4. Player actions call [`Behaviours::place_block`] /
//! [`Behaviours::use_without_item`] / [`Behaviours::destroy_block`].
//!
//! Every block mutation goes through [`Behaviours::set_block`] with vanilla's
//! update flags ([`flags`]). The library writes storage only through
//! [`LevelAccess::set_raw`]; the caller updates heightmaps, light, block
//! entities and render meshes for the written position.
//!
//! Side effects the library cannot perform (sounds, particles, item drops,
//! spawning falling-block or TNT entities, growing trees) are reported as
//! [`LevelEvent`]s through [`LevelAccess::emit`], in vanilla call order.
//!
//! Randomness is drawn from [`LevelAccess::random`] (vanilla `level.random`, a
//! `LegacyRandomSource`) in the same order as vanilla.
//!
//! # Integration sketch
//!
//! ```ignore
//! use horizon_world::level::{self, Behaviours, LevelAccess, LevelEvent, PlaceContext, Ticks, flags};
//!
//! struct GameLevel { chunks: Chunks, random: LegacyRandom, time: i64, events: Vec<LevelEvent> }
//! impl LevelAccess for GameLevel {
//! fn block_state(&self, pos: BlockPos) -> BlockStateId { self.chunks.get(pos) }
//! fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option<BlockStateId> {
//! let old = self.chunks.set(pos, state)?; // also mark light/heightmap/mesh dirty
//! Some(old)
//! }
//! fn is_loaded(&self, pos: BlockPos) -> bool { self.chunks.contains(pos.chunk()) }
//! fn random(&mut self) -> &mut LegacyRandom { &mut self.random }
//! fn game_time(&self) -> i64 { self.time }
//! fn block_light(&self, pos: BlockPos) -> i32 { self.chunks.block_light(pos) }
//! fn sky_light(&self, pos: BlockPos) -> i32 { self.chunks.sky_light(pos) }
//! fn emit(&mut self, event: LevelEvent) { self.events.push(event) }
//! }
//!
//! let registry = level::data::load_registry(&resources)?;
//! let behaviours = Behaviours::load(&registry, &resources)?;
//! let mut ticks = Ticks::new(seed as i32);
//! ticks.add_empty_chunk(chunk_pos)?; // when a chunk loads (remove_chunk on unload)
//!
//! // Every server tick:
//! level.time += 1;
//! behaviours.tick_scheduled(&mut level, &mut ticks);
//! for chunk in ticking_chunks {
//! behaviours.tick_chunk_random(&mut level, &mut ticks, chunk, randomly_ticking_section_min_ys(chunk));
//! }
//! behaviours.run_block_events(&mut level, &mut ticks);
//! /* tick entities */
//! behaviours.tick_block_entities(&mut level, &mut ticks);
//! for event in level.events.drain(..) { /* play sounds, spawn drops/falling blocks, grow trees */ }
//!
//! // Player actions:
//! behaviours.place_block(&mut level, &mut ticks, &PlaceContext { clicked_pos, face, hit, inside: false,
//! yaw, pitch, sneaking, item: "minecraft:oak_stairs".into(), can_use_game_master_blocks: false });
//! behaviours.use_without_item(&mut level, &mut ticks, pos, face, hit, player_context);
//! behaviours.player_destroy_block(&mut level, &mut ticks, pos, creative);
//! // Falling-block entity landed:
//! behaviours.falling_block_landed(&mut level, &mut ticks, landing_pos, carried_state, false);
//! ```
use crate::{
fluid::{FluidBlockBindings, FluidKind, FluidState},
registry::{BlockRegistry, BlockStateId},
};
use horizon_core::{
geometry::{Aabb, Direction, VoxelShape},
position::{BlockPos, ChunkPos},
random::LegacyRandom,
};
use std::{collections::HashMap, io, path::Path, sync::Arc, sync::Mutex};
pub mod classes;
pub mod data;
pub mod states;
pub mod ticks;
mod falling;
mod fluids;
mod hooks;
mod interact;
pub mod pistons;
mod place;
mod query;
mod rails;
mod redstone;
mod shapes;
mod speleothem;
mod survive;
mod tick;
mod update;
#[cfg(test)]
mod tests;
pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags};
pub use falling::Landing;
pub use interact::{InteractionResult, PlayerContext, PlayerEffect};
pub use pistons::{BlockEventData, MovingPiston};
pub use place::{PlaceContext, PlaceOutcome};
pub use states::{BlockId, PropKey, StateTable};
pub use tick::{Precipitation, PrecipitationKind};
pub use ticks::Ticks;
/// `Block.UPDATE_*` flags accepted by [`Behaviours::set_block`].
pub mod flags {
pub const UPDATE_NEIGHBORS: i32 = 1;
pub const UPDATE_CLIENTS: i32 = 2;
pub const UPDATE_INVISIBLE: i32 = 4;
pub const UPDATE_IMMEDIATE: i32 = 8;
pub const UPDATE_KNOWN_SHAPE: i32 = 16;
pub const UPDATE_SUPPRESS_DROPS: i32 = 32;
pub const UPDATE_MOVE_BY_PISTON: i32 = 64;
pub const UPDATE_SKIP_SHAPE_UPDATE_ON_WIRE: i32 = 128;
pub const UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS: i32 = 256;
pub const UPDATE_SKIP_ON_PLACE: i32 = 512;
pub const UPDATE_NONE: i32 = 260;
pub const UPDATE_ALL: i32 = 3;
pub const UPDATE_ALL_IMMEDIATE: i32 = 11;
pub const UPDATE_SKIP_ALL_SIDEEFFECTS: i32 = 816;
/// `Block.UPDATE_LIMIT`, the recursion budget of shape updates.
pub const UPDATE_LIMIT: i32 = 512;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Dimension {
Overworld,
Nether,
End,
}
/// Game rules consulted by block behaviour (vanilla defaults).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GameRules {
pub water_source_conversion: bool,
pub lava_source_conversion: bool,
pub random_tick_speed: i32,
pub block_drops: bool,
pub mob_griefing: bool,
pub max_snow_accumulation_height: i32,
}
impl Default for GameRules {
fn default() -> Self {
Self {
water_source_conversion: true,
lava_source_conversion: false,
random_tick_speed: 3,
block_drops: true,
mob_griefing: true,
max_snow_accumulation_height: 1,
}
}
}
/// Entity filters for the entity-sensing blocks (pressure plates, tripwire).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EntityQuery {
/// Any entity that does not ignore block triggers (wooden plates, tripwire).
Everything,
/// Living entities only (stone plates).
Mobs,
}
/// Side effects reported to the caller, in vanilla call order.
#[derive(Clone, Debug, PartialEq)]
pub enum LevelEvent {
/// `Level.levelEvent(type, pos, data)`, using vanilla's numeric event IDs
/// (e.g. 2001 block destroyed with `data` = state ID, 1501 lava
/// extinguished, 1009 fire extinguished, 1502 redstone torch burnout,
/// 2009 dripping water/sponge, 1033/1034 ... per `LevelEvent.java`).
LevelEvent { id: i32, pos: BlockPos, data: i32 },
/// `Level.playSound(null, pos, sound, BLOCKS, volume, pitch)`.
Sound {
pos: BlockPos,
sound: Arc<str>,
volume: f32,
pitch: f32,
},
/// `Block.dropResources(state, level, pos)`: the caller evaluates the
/// block's loot table (no tool, no breaker) and pops the items.
DropResources { pos: BlockPos, state: BlockStateId },
/// `FallingBlockEntity.fall`: the block at `pos` was already replaced by its
/// fluid's legacy block; the caller spawns and simulates a falling-block
/// entity carrying `state` and calls [`Behaviours::falling_block_landed`]
/// (or drops the item) when it lands.
FallingBlock { pos: BlockPos, state: BlockStateId },
/// A sapling reached stage 1 and tried to grow (`TreeGrower.growTree`).
/// The caller runs the grower's configured feature and, on success,
/// replaces the sapling (vanilla leaves the sapling on failure).
GrowTree {
pos: BlockPos,
state: BlockStateId,
grower: Arc<str>,
},
/// A configured feature placement request from a bonemealed or random-ticked
/// block (huge mushrooms, fungi). The block was already removed when vanilla
/// does so before placing; on failure the caller restores `state`.
PlaceFeature {
pos: BlockPos,
state: BlockStateId,
feature: Arc<str>,
},
/// `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,
},
/// A player-side effect of [`Behaviours::use_without_item`].
Player {
pos: BlockPos,
state: BlockStateId,
effect: PlayerEffect,
},
/// `Level.gameEvent` (vibration system), by vanilla identifier.
GameEvent { pos: BlockPos, event: &'static str },
}
/// The world as seen by block behaviour. Implemented by the game and tests.
pub trait LevelAccess {
/// `getBlockState`. Unloaded or out-of-bounds positions read as air.
fn block_state(&self, pos: BlockPos) -> BlockStateId;
/// Storage write (`LevelChunkSection.setBlockState`). Returns the previous
/// state, or None when nothing could be stored (unloaded chunk).
fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option<BlockStateId>;
fn is_loaded(&self, pos: BlockPos) -> bool;
/// Inclusive minimum and exclusive maximum build height.
fn min_y(&self) -> i32 {
-64
}
fn max_y(&self) -> i32 {
320
}
/// Vanilla `level.random` (a `LegacyRandomSource`).
fn random(&mut self) -> &mut LegacyRandom;
fn game_time(&self) -> i64;
fn block_light(&self, _pos: BlockPos) -> i32 {
0
}
fn sky_light(&self, _pos: BlockPos) -> i32 {
15
}
/// `Level.getSkyDarken` (0 at noon, up to 11 at night).
fn sky_darken(&self) -> i32 {
0
}
fn is_raining(&self) -> bool {
false
}
fn is_thundering(&self) -> bool {
false
}
fn is_raining_at(&self, _pos: BlockPos) -> bool {
false
}
fn dimension(&self) -> Dimension {
Dimension::Overworld
}
fn game_rules(&self) -> GameRules {
GameRules::default()
}
/// `Difficulty.getId()` (peaceful 0 .. hard 3).
fn difficulty(&self) -> i32 {
2
}
/// `ServerLevel.canSpreadFireAround` (fire-spread radius around players).
fn can_spread_fire_around(&self, _pos: BlockPos) -> bool {
true
}
/// `Level.isUnobstructed(state, pos, context)`: whether the state's
/// collision shape at `pos` would intersect an entity.
fn is_unobstructed(&self, _pos: BlockPos, _state: BlockStateId) -> bool {
true
}
/// Comparator input from a block entity (`getAnalogOutputSignal` of
/// containers, jukeboxes, lecterns, ...). State-only sources (cake,
/// composter, cauldrons, beehives, ...) are evaluated by the library.
fn block_entity_analog_signal(
&self,
_pos: BlockPos,
_state: BlockStateId,
_direction: Direction,
) -> i32 {
0
}
/// Weak/strong signal of a block-entity-driven source (trapped chest
/// openers); other sources are evaluated by the library.
fn block_entity_signal(
&self,
_pos: BlockPos,
_state: BlockStateId,
_direction: Direction,
) -> i32 {
0
}
/// Biome answers for a precipitation tick at the column of `pos` (see
/// [`Precipitation`]); None skips snow/ice formation and cauldron filling.
fn precipitation(&self, _pos: BlockPos) -> Option<Precipitation> {
None
}
/// Count of entities intersecting `area` that trigger pressure plates or
/// tripwires under `query`.
fn count_entities(&self, _area: Aabb, _query: EntityQuery) -> usize {
0
}
/// `ServerLevel.isPositionTickingWithEntitiesLoaded` for scheduled ticks.
fn is_ticking_chunk(&self, _chunk: ChunkPos) -> bool {
true
}
fn emit(&mut self, _event: LevelEvent) {}
}
/// Raw brightness as `Level.getRawBrightness(pos, skyDarken)`.
pub fn raw_brightness<L: LevelAccess + ?Sized>(level: &L, pos: BlockPos, sky_darken: i32) -> i32 {
(level.sky_light(pos) - sky_darken).max(level.block_light(pos))
}
/// Immutable vanilla block-behaviour tables. Build once with [`Behaviours::load`].
pub struct Behaviours {
pub table: StateTable,
pub props: Props,
pub named: Named,
pub tags: Tags,
all_tags: HashMap<String, Arc<data::BlockSet>>,
facts: Vec<StateFacts>,
shapes: Vec<VoxelShape>,
shape_info: Vec<data::ShapeInfo>,
pub fluid_tags: data::FluidTags,
blocks: Vec<BlockData>,
items: HashMap<String, ItemBinding>,
liquid_blocks: FluidBlockBindings,
/// Uncached (position- or block-entity-dependent) collision shapes.
dynamic: HashMap<BlockStateId, crate::dynamic_support::DynamicSupport>,
occlusion_cache: Mutex<HashMap<(i32, i32, u8), bool>>,
}
impl Behaviours {
/// Load from a prepared client resource directory (`.local/horizon-client/<version>`).
pub fn load(registry: &BlockRegistry, resources_dir: &Path) -> io::Result<Self> {
data::load(registry, resources_dir)
}
pub fn facts(&self, state: BlockStateId) -> &StateFacts {
&self.facts[state.0 as usize]
}
pub fn block_data(&self, block: BlockId) -> &BlockData {
&self.blocks[block.0 as usize]
}
pub fn data(&self, state: BlockStateId) -> &BlockData {
self.block_data(self.table.block(state))
}
pub fn block(&self, state: BlockStateId) -> BlockId {
self.table.block(state)
}
pub fn item_binding(&self, item: &str) -> Option<&ItemBinding> {
self.items.get(item)
}
pub fn tag(&self, name: &str) -> Option<&data::BlockSet> {
self.all_tags.get(name).map(|s| &**s)
}
pub fn fluid(&self, state: BlockStateId) -> FluidState {
self.facts(state).fluid
}
/// `FluidState.createLegacyBlock`.
pub fn legacy_block(&self, fluid: FluidState) -> BlockStateId {
self.liquid_blocks.block(fluid)
}
/// Cached collision shape (`getCollisionShape(level, pos)` for states whose
/// shape does not depend on the world); None for dynamic shapes.
pub fn collision_shape(&self, state: BlockStateId) -> Option<&VoxelShape> {
let index = self.facts(state).shape;
(index >= 0).then(|| &self.shapes[index as usize])
}
/// Precomputed shape queries; dynamic shapes read as empty.
pub fn shape_info(&self, state: BlockStateId) -> data::ShapeInfo {
let index = self.facts(state).shape;
if index < 0 {
data::ShapeInfo::default()
} else {
self.shape_info[index as usize]
}
}
pub(crate) fn has_flag(&self, state: BlockStateId, flag: u32) -> bool {
self.facts(state).flags & flag != 0
}
pub fn is_air(&self, state: BlockStateId) -> bool {
self.has_flag(state, data::state_flags::AIR)
}
pub fn is_solid(&self, state: BlockStateId) -> bool {
self.has_flag(state, data::state_flags::SOLID)
}
pub fn is_replaceable(&self, state: BlockStateId) -> bool {
self.has_flag(state, data::state_flags::REPLACEABLE)
}
pub fn is_randomly_ticking(&self, state: BlockStateId) -> bool {
self.has_flag(state, data::state_flags::RANDOM_TICKS)
}
/// `isFaceSturdy(level, pos, direction, FULL)` from the empty-level cache.
pub fn is_face_sturdy(&self, state: BlockStateId, direction: Direction) -> bool {
self.facts(state).sturdy & (1 << direction as u32) != 0
}
pub fn is_face_sturdy_center(&self, state: BlockStateId, direction: Direction) -> bool {
self.facts(state).sturdy & (1 << (6 + direction as u32)) != 0
}
pub fn is_face_sturdy_rigid(&self, state: BlockStateId, direction: Direction) -> bool {
self.facts(state).sturdy & (1 << (12 + direction as u32)) != 0
}
/// Tick type ID of a fluid for [`Ticks::schedule_fluid`].
pub fn fluid_kind(&self, state: BlockStateId) -> FluidKind {
self.fluid(state).kind()
}
}
/// 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)
}
/// `BlockState.updateShape(level, ticks, pos, direction, neighbourPos,
/// neighbourState, random)`: the state `state` at `pos` would take after its
/// neighbour in `direction` became `neighbour` (ticks it requests are queued).
#[allow(clippy::too_many_arguments)]
pub fn update_shape<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
state: BlockStateId,
pos: BlockPos,
direction: Direction,
neighbour_pos: BlockPos,
neighbour: BlockStateId,
) -> BlockStateId {
self.sim(level, ticks)
.update_shape(state, pos, direction, neighbour_pos, neighbour)
}
/// `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,
pub level: &'a mut L,
pub ticks: &'a mut Ticks,
/// `RedstoneWireBlock.shouldSignal` is false while a wire samples its
/// neighbours (`getBlockSignal`).
pub wire_signal_off: std::cell::Cell<bool>,
}
impl Behaviours {
pub(crate) fn sim<'a, L: LevelAccess + ?Sized>(
&'a self,
level: &'a mut L,
ticks: &'a mut Ticks,
) -> Sim<'a, L> {
Sim {
b: self,
level,
ticks,
wire_signal_off: std::cell::Cell::new(false),
}
}
}
+761
View File
@@ -0,0 +1,761 @@
//! Pistons: `PistonBaseBlock` (signal checks, block events, `moveBlocks`),
//! `PistonStructureResolver`, `PistonHeadBlock`, and the
//! `PistonMovingBlockEntity` progress ticking, plus the level's block-event
//! queue (`ServerLevel.blockEvent` / `runBlockEvents`).
//!
//! Entity pushing by moving blocks is the caller's (see `piston_movement`).
use super::{
Behaviours, LevelAccess, LevelEvent, Sim, Ticks,
data::PushReaction,
states::BlockId,
update::{above, rel},
};
use crate::{
java_hash_map::{JavaHashMap, JavaKey},
registry::BlockStateId,
};
use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource};
use std::cmp::Ordering;
/// `PistonMovingBlockEntity` state, owned by [`Ticks::moving_pistons`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MovingPiston {
pub moved_state: BlockStateId,
pub direction: Direction,
pub extending: bool,
pub source: bool,
pub progress: f32,
pub progress_o: f32,
pub last_ticked: i64,
/// Identity of this block entity (a replaced entity is a new ticker).
pub id: u64,
}
impl MovingPiston {
pub fn movement_direction(&self) -> Direction {
if self.extending {
self.direction
} else {
self.direction.opposite()
}
}
}
/// `BlockEventData`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockEventData {
pub pos: BlockPos,
pub block: BlockId,
pub param_a: i32,
pub param_b: i32,
}
#[derive(PartialEq, Eq)]
struct PosKey(BlockPos);
impl JavaKey for PosKey {
fn java_hash(&self) -> i32 {
(self.0.y.wrapping_add(self.0.z.wrapping_mul(31)))
.wrapping_mul(31)
.wrapping_add(self.0.x)
}
fn comparable_compare(&self, other: &Self) -> Option<Ordering> {
// Vec3i implements Comparable: y, then z, then x.
Some(
self.0
.y
.cmp(&other.0.y)
.then(self.0.z.cmp(&other.0.z))
.then(self.0.x.cmp(&other.0.x)),
)
}
fn tie_break(&self, _other: &Self) -> Ordering {
Ordering::Less
}
}
struct Resolver {
piston_pos: BlockPos,
extending: bool,
start: BlockPos,
push_direction: Direction,
piston_direction: Direction,
to_push: Vec<BlockPos>,
to_destroy: Vec<BlockPos>,
}
fn rel_n(pos: BlockPos, direction: Direction, n: i32) -> BlockPos {
let [x, y, z] = direction.normal();
pos.offset(x * n, y * n, z * n)
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
// ---- block events ----
pub(crate) fn block_event(
&mut self,
pos: BlockPos,
block: BlockId,
param_a: i32,
param_b: i32,
) {
let event = BlockEventData {
pos,
block,
param_a,
param_b,
};
if !self.ticks.block_events.contains(&event) {
self.ticks.block_events.push(event);
}
}
/// `BlockState.triggerEvent`.
fn trigger_event(&mut self, state: BlockStateId, pos: BlockPos, a: i32, b: i32) -> bool {
let data = self.b.data(state);
if data.is(super::classes::Class::PistonBase) {
self.piston_trigger_event(pos, state, a, b)
} else {
false
}
}
// ---- moving piston block entities ----
pub(crate) fn moving_piston(&self, pos: BlockPos) -> Option<MovingPiston> {
self.ticks
.moving_pistons
.iter()
.find(|(p, _)| *p == pos)
.map(|(_, m)| *m)
}
fn set_moving_piston(&mut self, pos: BlockPos, mut piston: MovingPiston) {
self.ticks.moving_pistons.retain(|(p, _)| *p != pos);
self.ticks.next_block_entity_id += 1;
piston.id = self.ticks.next_block_entity_id;
self.ticks.moving_pistons.push((pos, piston));
}
pub(crate) fn remove_moving_piston(&mut self, pos: BlockPos) -> Option<MovingPiston> {
let index = self
.ticks
.moving_pistons
.iter()
.position(|(p, _)| *p == pos)?;
Some(self.ticks.moving_pistons.remove(index).1)
}
/// `PistonMovingBlockEntity.finalTick`.
fn moving_piston_final_tick(&mut self, pos: BlockPos) {
let Some(piston) = self.moving_piston(pos) else {
return;
};
if piston.progress_o >= 1.0 {
return;
}
self.remove_moving_piston(pos);
let b = self.b;
if b.is_block(self.state(pos), b.named.moving_piston) {
let new = if piston.source {
b.air()
} else {
self.update_from_neighbour_shapes(piston.moved_state, pos)
};
self.set_block_and_update(pos, new);
let block = b.block(new);
self.neighbor_changed_at(pos, block);
}
}
/// `PistonMovingBlockEntity.tick` (entity pushing excluded).
fn moving_piston_tick(&mut self, pos: BlockPos) {
let Some(mut piston) = self.moving_piston(pos) else {
return;
};
let b = self.b;
piston.last_ticked = self.level.game_time();
piston.progress_o = piston.progress;
if piston.progress_o >= 1.0 {
self.remove_moving_piston(pos);
if b.is_block(self.state(pos), b.named.moving_piston) {
let mut new = self.update_from_neighbour_shapes(piston.moved_state, pos);
if b.is_air(new) {
self.set_block(pos, piston.moved_state, 340);
self.update_or_destroy(
piston.moved_state,
new,
pos,
3,
super::flags::UPDATE_LIMIT,
);
} else {
if b.is_waterlogged(new) {
new = b.table.set_bool(new, b.props.waterlogged, false);
}
self.set_block(pos, new, 67);
let block = b.block(new);
self.neighbor_changed_at(pos, block);
}
}
} else {
piston.progress = (piston.progress + 0.5).min(1.0);
if let Some(entry) = self
.ticks
.moving_pistons
.iter_mut()
.find(|(p, _)| *p == pos)
{
entry.1 = piston;
}
}
}
// ---- PistonBaseBlock ----
fn is_sticky_piston(&self, state: BlockStateId) -> bool {
self.b.is_block(state, self.b.named.sticky_piston)
}
fn piston_neighbor_signal(&self, pos: BlockPos, push: Direction) -> bool {
for direction in Direction::ALL {
if direction != push && self.has_signal(rel(pos, direction), direction) {
return true;
}
}
if self.has_signal(pos, Direction::Down) {
return true;
}
let up = above(pos);
Direction::ALL.into_iter().any(|direction| {
direction != Direction::Down && self.has_signal(rel(up, direction), direction)
})
}
/// `PistonBaseBlock.checkIfExtend`.
pub(crate) fn piston_check_if_extend(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
let direction = b.facing(state);
let extend = self.piston_neighbor_signal(pos, direction);
let extended = b.table.bool(state, b.props.extended);
let block = b.block(state);
if extend && !extended {
if self.piston_resolve(pos, direction, true).is_some() {
self.block_event(pos, block, 0, direction as i32);
}
} else if !extend && extended {
let pushed_pos = rel_n(pos, direction, 2);
let pushed = self.state(pushed_pos);
let mut event = 1;
if b.is_block(pushed, b.named.moving_piston) && b.facing(pushed) == direction {
if let Some(piston) = self.moving_piston(pushed_pos) {
if piston.extending
&& (piston.progress_o < 0.5
|| self.level.game_time() == piston.last_ticked
|| self.ticks.handling_tick)
{
event = 2;
}
}
}
self.block_event(pos, block, event, direction as i32);
}
}
/// `PistonBaseBlock.isPushable`.
fn is_pushable(
&self,
state: BlockStateId,
pos: BlockPos,
direction: Direction,
allow_destroyable: bool,
connection: Direction,
) -> bool {
let b = self.b;
let (min_y, max_y) = (self.level.min_y(), self.level.max_y() - 1);
if pos.y < min_y || pos.y > max_y {
return false;
}
if b.is_air(state) {
return true;
}
if direction == Direction::Down && pos.y == min_y {
return false;
}
if direction == Direction::Up && pos.y == max_y {
return false;
}
let is_piston =
b.is_block(state, b.named.piston) || b.is_block(state, b.named.sticky_piston);
if !is_piston {
if b.facts(state).hardness == -1.0 {
return false;
}
match b.facts(state).push {
PushReaction::Immoveable => return false,
PushReaction::Popped => return allow_destroyable,
PushReaction::Push => return direction == connection,
_ => {}
}
} else if b.table.bool(state, b.props.extended) {
return false;
}
!b.has_flag(state, super::data::state_flags::BLOCK_ENTITY)
}
fn is_slime_or_honey(&self, state: BlockStateId) -> bool {
self.b.is_block(state, self.b.named.slime_block)
|| self.b.is_block(state, self.b.named.honey_block)
}
fn can_stick(&self, first: BlockStateId, second: BlockStateId) -> bool {
let n = self.b.named;
let (honey1, slime1) = (
self.b.is_block(first, n.honey_block),
self.b.is_block(first, n.slime_block),
);
let (honey2, slime2) = (
self.b.is_block(second, n.honey_block),
self.b.is_block(second, n.slime_block),
);
if (honey1 && slime2) || (slime1 && honey2) {
return false;
}
self.is_slime_or_honey(first) || self.is_slime_or_honey(second)
}
/// `PistonStructureResolver.resolve`; None when the structure cannot move.
fn piston_resolve(
&self,
piston_pos: BlockPos,
direction: Direction,
extending: bool,
) -> Option<(Vec<BlockPos>, Vec<BlockPos>, Direction)> {
let mut r = Resolver {
piston_pos,
extending,
start: if extending {
rel(piston_pos, direction)
} else {
rel_n(piston_pos, direction, 2)
},
push_direction: if extending {
direction
} else {
direction.opposite()
},
piston_direction: direction,
to_push: Vec::new(),
to_destroy: Vec::new(),
};
let next = self.state(r.start);
if !self.is_pushable(next, r.start, r.push_direction, false, r.piston_direction) {
if r.extending && self.b.facts(next).push == PushReaction::Popped {
r.to_destroy.push(r.start);
return Some((r.to_push, r.to_destroy, r.push_direction));
}
return None;
}
let start = r.start;
let push = r.push_direction;
if !self.add_block_line(&mut r, start, push) {
return None;
}
let mut i = 0;
while i < r.to_push.len() {
let pos = r.to_push[i];
if self.is_slime_or_honey(self.state(pos)) && !self.add_branching_blocks(&mut r, pos) {
return None;
}
i += 1;
}
Some((r.to_push, r.to_destroy, r.push_direction))
}
fn add_block_line(&self, r: &mut Resolver, start: BlockPos, direction: Direction) -> bool {
let mut next = self.state(start);
if self.b.is_air(next) {
return true;
}
if !self.is_pushable(next, start, r.push_direction, false, direction)
|| start == r.piston_pos
|| r.to_push.contains(&start)
{
return true;
}
let mut count = 1;
if count + r.to_push.len() > 12 {
return false;
}
while self.is_slime_or_honey(next) {
let pos = rel_n(start, r.push_direction.opposite(), count as i32);
let previous = next;
next = self.state(pos);
if self.b.is_air(next)
|| !self.can_stick(previous, next)
|| !self.is_pushable(
next,
pos,
r.push_direction,
false,
r.push_direction.opposite(),
)
|| pos == r.piston_pos
{
break;
}
count += 1;
if count + r.to_push.len() > 12 {
return false;
}
}
let mut added = 0;
for i in (0..count).rev() {
r.to_push
.push(rel_n(start, r.push_direction.opposite(), i as i32));
added += 1;
}
let mut i = 1;
loop {
let pos = rel_n(start, r.push_direction, i);
if let Some(collision) = r.to_push.iter().position(|p| *p == pos) {
self.reorder_at_collision(r, added, collision);
for j in 0..=collision + added {
let block_pos = r.to_push[j];
if self.is_slime_or_honey(self.state(block_pos))
&& !self.add_branching_blocks(r, block_pos)
{
return false;
}
}
return true;
}
next = self.state(pos);
if self.b.is_air(next) {
return true;
}
if !self.is_pushable(next, pos, r.push_direction, true, r.push_direction)
|| pos == r.piston_pos
{
return false;
}
if self.b.facts(next).push == PushReaction::Popped {
r.to_destroy.push(pos);
return true;
}
if r.to_push.len() >= 12 {
return false;
}
r.to_push.push(pos);
added += 1;
i += 1;
}
}
fn reorder_at_collision(&self, r: &mut Resolver, added: usize, collision: usize) {
let len = r.to_push.len();
let head: Vec<BlockPos> = r.to_push[..collision].to_vec();
let last_line: Vec<BlockPos> = r.to_push[len - added..].to_vec();
let middle: Vec<BlockPos> = r.to_push[collision..len - added].to_vec();
r.to_push.clear();
r.to_push.extend(head);
r.to_push.extend(last_line);
r.to_push.extend(middle);
}
fn add_branching_blocks(&self, r: &mut Resolver, from: BlockPos) -> bool {
let from_state = self.state(from);
for direction in Direction::ALL {
if super::query::axis_of(direction) != super::query::axis_of(r.push_direction) {
let neighbour = rel(from, direction);
let neighbour_state = self.state(neighbour);
if self.can_stick(neighbour_state, from_state)
&& !self.add_block_line(r, neighbour, direction)
{
return false;
}
}
}
true
}
fn moving_piston_state(&self, direction: Direction, sticky: bool) -> BlockStateId {
let b = self.b;
let state = b.table.set_dir(
b.default_of(b.named.moving_piston),
b.props.facing,
direction,
);
b.table.set_text(
state,
b.props.kind,
if sticky { "sticky" } else { "normal" },
)
}
/// `PistonBaseBlock.moveBlocks`.
fn piston_move_blocks(
&mut self,
piston_pos: BlockPos,
direction: Direction,
extending: bool,
sticky: bool,
) -> bool {
let b = self.b;
let arm = rel(piston_pos, direction);
if !extending && b.is_block(self.state(arm), b.named.piston_head) {
self.set_block(arm, b.air(), 276);
}
let Some((to_push, to_destroy, push_direction)) =
self.piston_resolve(piston_pos, direction, extending)
else {
return false;
};
let mut delete_after: JavaHashMap<PosKey, BlockStateId> = JavaHashMap::default();
let mut shapes = Vec::with_capacity(to_push.len());
for pos in &to_push {
let state = self.state(*pos);
shapes.push(state);
delete_after.put(PosKey(*pos), state);
}
let mut to_update = Vec::with_capacity(to_push.len() + to_destroy.len());
let move_direction = if extending {
direction
} else {
direction.opposite()
};
for pos in to_destroy.iter().rev() {
let state = self.state(*pos);
self.drop_resources(state, *pos);
self.set_block(*pos, b.air(), 18);
self.game_event(*pos, "minecraft:block_destroy");
to_update.push(state);
}
for (i, pos) in to_push.iter().enumerate().rev() {
let state = self.state(*pos);
let target = rel(*pos, move_direction);
delete_after.remove(&PosKey(target));
let moving = b.table.set_dir(
b.default_of(b.named.moving_piston),
b.props.facing,
direction,
);
self.set_block(target, moving, 324);
self.set_moving_piston(
target,
MovingPiston {
moved_state: shapes[i],
direction,
extending,
source: false,
progress: 0.0,
progress_o: 0.0,
last_ticked: 0,
id: 0,
},
);
to_update.push(state);
}
if extending {
let head = b.table.set_text(
b.table
.set_dir(b.default_of(b.named.piston_head), b.props.facing, direction),
b.props.kind,
if sticky { "sticky" } else { "normal" },
);
let moving = self.moving_piston_state(direction, sticky);
delete_after.remove(&PosKey(arm));
self.set_block(arm, moving, 324);
self.set_moving_piston(
arm,
MovingPiston {
moved_state: head,
direction,
extending: true,
source: true,
progress: 0.0,
progress_o: 0.0,
last_ticked: 0,
id: 0,
},
);
}
let air = b.air();
let entries: Vec<(BlockPos, BlockStateId)> =
delete_after.entries().map(|(k, v)| (k.0, *v)).collect();
for (pos, _) in &entries {
self.set_block(*pos, air, 82);
}
for (pos, old) in &entries {
self.update_indirect_neighbour_shapes(*old, *pos, 2, super::flags::UPDATE_LIMIT);
self.update_neighbour_shapes(air, *pos, 2, super::flags::UPDATE_LIMIT);
self.update_indirect_neighbour_shapes(air, *pos, 2, super::flags::UPDATE_LIMIT);
}
let mut index = 0;
for pos in to_destroy.iter().rev() {
let state = to_update[index];
index += 1;
self.affect_neighbors_after_removal(state, *pos, false);
self.update_indirect_neighbour_shapes(state, *pos, 2, super::flags::UPDATE_LIMIT);
let block = b.block(state);
self.update_neighbors_at(*pos, block);
}
for pos in to_push.iter().rev() {
let block = b.block(to_update[index]);
index += 1;
self.update_neighbors_at(*pos, block);
}
if extending {
self.update_neighbors_at(arm, b.named.piston_head);
}
let _ = push_direction;
true
}
/// `PistonBaseBlock.triggerEvent`.
fn piston_trigger_event(
&mut self,
pos: BlockPos,
state: BlockStateId,
a: i32,
param_b: i32,
) -> bool {
let b = self.b;
let p = b.props;
let direction = b.facing(state);
let extended_state = b.table.set_bool(state, p.extended, true);
let sticky = self.is_sticky_piston(state);
let extend = self.piston_neighbor_signal(pos, direction);
if extend && (a == 1 || a == 2) {
self.set_block(pos, extended_state, 2);
return false;
}
if !extend && a == 0 {
return false;
}
if a == 0 {
if !self.piston_move_blocks(pos, direction, true, sticky) {
return false;
}
self.set_block(pos, extended_state, 67);
let pitch = self.random().next_float() * 0.25 + 0.6;
self.emit(LevelEvent::Sound {
pos,
sound: "minecraft:block.piston.extend".into(),
volume: 0.5,
pitch,
});
self.game_event(pos, "minecraft:block_activate");
} else if a == 1 || a == 2 {
self.moving_piston_final_tick(rel(pos, direction));
let moving = self.moving_piston_state(direction, sticky);
self.set_block(pos, moving, 276);
let piston_default = b.table.set_dir(
b.default_of(b.block(state)),
p.facing,
Direction::ALL[(param_b & 7).min(5) as usize],
);
self.set_moving_piston(
pos,
MovingPiston {
moved_state: piston_default,
direction,
extending: false,
source: true,
progress: 0.0,
progress_o: 0.0,
last_ticked: 0,
id: 0,
},
);
self.update_neighbors_at(pos, b.named.moving_piston);
self.update_neighbour_shapes(moving, pos, 2, super::flags::UPDATE_LIMIT);
if sticky {
let two = rel_n(pos, direction, 2);
let moving_state = self.state(two);
let mut piston_piece = false;
if b.is_block(moving_state, b.named.moving_piston) {
if let Some(entity) = self.moving_piston(two) {
if entity.direction == direction && entity.extending {
self.moving_piston_final_tick(two);
piston_piece = true;
}
}
}
if !piston_piece {
let is_piston = b.is_block(moving_state, b.named.piston)
|| b.is_block(moving_state, b.named.sticky_piston);
if a != 1
|| b.is_air(moving_state)
|| !self.is_pushable(
moving_state,
two,
direction.opposite(),
false,
direction,
)
|| (b.facts(moving_state).push != PushReaction::PushPull && !is_piston)
{
self.remove_block(rel(pos, direction), false);
} else {
self.piston_move_blocks(pos, direction, false, sticky);
}
}
} else {
self.remove_block(rel(pos, direction), false);
}
let pitch = self.random().next_float() * 0.15 + 0.6;
self.emit(LevelEvent::Sound {
pos,
sound: "minecraft:block.piston.contract".into(),
volume: 0.5,
pitch,
});
self.game_event(pos, "minecraft:block_deactivate");
}
true
}
// ---- PistonHeadBlock ----
pub(crate) fn piston_head_fitting_base(&self, head: BlockStateId, base: BlockStateId) -> bool {
let b = self.b;
let expected = if b.table.text(head, b.props.kind) == "sticky" {
b.named.sticky_piston
} else {
b.named.piston
};
b.is_block(base, expected)
&& b.table.bool(base, b.props.extended)
&& b.facing(base) == b.facing(head)
}
pub(crate) fn piston_head_can_survive(&self, head: BlockStateId, pos: BlockPos) -> bool {
let b = self.b;
let base = self.rel_state(pos, b.facing(head).opposite());
self.piston_head_fitting_base(head, base)
|| (b.is_block(base, b.named.moving_piston) && b.facing(base) == b.facing(head))
}
}
impl Behaviours {
/// `ServerLevel.runBlockEvents`: run queued block events (piston moves).
/// Call once per tick after scheduled and random ticks.
pub fn run_block_events<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks) {
let mut reschedule = Vec::new();
while !ticks.block_events.is_empty() {
let event = ticks.block_events.remove(0);
if !level.is_ticking_chunk(event.pos.chunk()) {
reschedule.push(event);
continue;
}
let mut sim = self.sim(level, ticks);
let state = sim.state(event.pos);
if self.block(state) == event.block {
sim.trigger_event(state, event.pos, event.param_a, event.param_b);
}
}
for event in reschedule {
if !ticks.block_events.contains(&event) {
ticks.block_events.push(event);
}
}
}
/// `Level.tickBlockEntities` for moving pistons (the only block entities
/// whose ticking changes blocks). Entries added during the pass wait for
/// the next tick, as vanilla's pending tickers do.
pub fn tick_block_entities<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks) {
let tickers: Vec<(BlockPos, u64)> = ticks
.moving_pistons
.iter()
.map(|(p, m)| (*p, m.id))
.collect();
for (pos, id) in tickers {
if !level.is_ticking_chunk(pos.chunk())
|| !ticks
.moving_pistons
.iter()
.any(|(p, m)| *p == pos && m.id == id)
{
continue;
}
self.sim(level, ticks).moving_piston_tick(pos);
}
}
}
File diff suppressed because it is too large Load Diff
+235
View File
@@ -0,0 +1,235 @@
//! Block-state queries shared by the ported behaviour (`BlockStateBase`
//! accessors and `Block` static helpers).
use super::{
Behaviours, LevelAccess, Sim,
classes::{Class, Interface},
data::{BlockSet, state_flags},
states::{BlockId, PropKey},
update::{above, below, rel},
};
use crate::{fluid::FluidKind, registry::BlockStateId};
use horizon_core::{geometry::Direction, position::BlockPos};
pub(crate) const fn clockwise(direction: Direction) -> Direction {
match direction {
Direction::North => Direction::East,
Direction::East => Direction::South,
Direction::South => Direction::West,
Direction::West => Direction::North,
other => other,
}
}
pub(crate) const fn counter_clockwise(direction: Direction) -> Direction {
match direction {
Direction::North => Direction::West,
Direction::West => Direction::South,
Direction::South => Direction::East,
Direction::East => Direction::North,
other => other,
}
}
pub(crate) const fn is_horizontal(direction: Direction) -> bool {
!matches!(direction, Direction::Up | Direction::Down)
}
pub(crate) fn axis_of(direction: Direction) -> horizon_core::geometry::Axis {
use horizon_core::geometry::Axis;
match direction {
Direction::West | Direction::East => Axis::X,
Direction::Up | Direction::Down => Axis::Y,
Direction::North | Direction::South => Axis::Z,
}
}
/// `Direction.from2DDataValue` (S, W, N, E).
pub(crate) fn from_2d(value: i32) -> Direction {
[
Direction::South,
Direction::West,
Direction::North,
Direction::East,
][value.rem_euclid(4) as usize]
}
pub(crate) fn data_2d(direction: Direction) -> i32 {
match direction {
Direction::South => 0,
Direction::West => 1,
Direction::North => 2,
Direction::East => 3,
_ => -1,
}
}
impl Behaviours {
pub(crate) fn in_set(&self, state: BlockStateId, set: &BlockSet) -> bool {
set.contains(self.table.block(state))
}
pub(crate) fn is_block(&self, state: BlockStateId, block: BlockId) -> bool {
self.table.is(state, block)
}
pub(crate) fn instance_of(&self, state: BlockStateId, class: Class) -> bool {
self.data(state).is(class)
}
pub(crate) fn implements(&self, state: BlockStateId, interface: Interface) -> bool {
self.data(state).implements(interface)
}
pub(crate) fn fluid_in(&self, kind: FluidKind, mask: u8) -> bool {
mask & (1 << kind as u8) != 0
}
pub(crate) fn is_water_fluid(&self, kind: FluidKind) -> bool {
self.fluid_in(kind, self.fluid_tags.water)
}
pub(crate) fn is_lava_fluid(&self, kind: FluidKind) -> bool {
self.fluid_in(kind, self.fluid_tags.lava)
}
pub(crate) fn liquid(&self, state: BlockStateId) -> bool {
self.has_flag(state, state_flags::LIQUID)
}
pub(crate) fn solid_render(&self, state: BlockStateId) -> bool {
self.has_flag(state, state_flags::SOLID_RENDER)
}
pub(crate) fn full_collision(&self, state: BlockStateId) -> bool {
self.has_flag(state, state_flags::FULL_COLLISION)
}
/// `Block.isFaceFull(state.getCollisionShape(level, pos), direction)`.
pub(crate) fn collision_face_full(&self, state: BlockStateId, direction: Direction) -> bool {
self.shape_info(state).full_faces & (1 << direction as u8) != 0
}
/// `MultifaceBlock.canAttachTo(level, direction, neighbourPos, neighbourState)`.
pub(crate) fn multiface_can_attach(
&self,
neighbour: BlockStateId,
direction: Direction,
) -> bool {
let face = direction.opposite();
self.is_face_sturdy(neighbour, face) || self.collision_face_full(neighbour, face)
}
/// `Block.isExceptionForConnection`.
pub(crate) fn is_exception_for_connection(&self, state: BlockStateId) -> bool {
let n = &self.named;
let block = self.table.block(state);
self.instance_of(state, Class::Leaves)
|| block == n.barrier
|| block == n.carved_pumpkin
|| block == n.jack_o_lantern
|| block == n.melon
|| block == n.pumpkin
|| self.tags.shulker_boxes.contains(block)
}
pub(crate) fn is_waterlogged(&self, state: BlockStateId) -> bool {
self.table.bool(state, self.props.waterlogged)
}
pub(crate) fn facing(&self, state: BlockStateId) -> Direction {
self.table
.dir(state, self.props.facing)
.unwrap_or(Direction::North)
}
/// The boolean/enum property named after `direction` (`north`, `up`, ...).
pub(crate) fn dir_prop(&self, direction: Direction) -> PropKey {
let p = &self.props;
match direction {
Direction::Down => p.down,
Direction::Up => p.up,
Direction::North => p.north,
Direction::South => p.south,
Direction::West => p.west,
Direction::East => p.east,
}
}
pub(crate) fn default_of(&self, block: BlockId) -> BlockStateId {
self.table.default_state(block)
}
pub(crate) fn air(&self) -> BlockStateId {
self.table.default_state(self.named.air)
}
}
/// Block-entity lookups for dynamic shapes: Horizon's level keeps no shulker
/// box animation state, so boxes read as closed (a full cube).
struct NoBlockEntities;
impl crate::dynamic_support::DynamicSupportWorld for NoBlockEntities {
type Error = std::convert::Infallible;
fn shulker_is_closed(&mut self, _position: [i32; 3]) -> Result<Option<bool>, Self::Error> {
Ok(None)
}
fn moving_piston_shape(
&mut self,
_position: [i32; 3],
) -> Result<Option<horizon_core::geometry::VoxelShape>, Self::Error> {
Ok(None)
}
}
impl crate::block_collision::DynamicCollisionWorld for NoBlockEntities {
fn shulker_collision_state(
&mut self,
_position: [i32; 3],
) -> Result<Option<crate::block_collision::ShulkerCollisionState>, Self::Error> {
Ok(None)
}
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
/// Shape queries over `getCollisionShape(level, pos)`, including the
/// position-dependent shapes (bamboo, speleothems, shulker boxes).
pub(crate) fn shape_info_at(
&self,
state: BlockStateId,
pos: BlockPos,
) -> super::data::ShapeInfo {
if self.b.facts(state).shape >= 0 {
return self.b.shape_info(state);
}
match self.b.dynamic.get(&state) {
Some(support) => support
.collision_shape(&mut NoBlockEntities, [pos.x, pos.y, pos.z])
.ok()
.and_then(|shape| super::data::analyse_shape(&shape).ok())
.unwrap_or_default(),
None => super::data::ShapeInfo::default(),
}
}
pub fn sturdy(&self, pos: BlockPos, direction: Direction) -> bool {
self.b.is_face_sturdy(self.state(pos), direction)
}
/// `Block.canSupportRigidBlock(level, below)`.
pub fn can_support_rigid_block(&self, pos: BlockPos) -> bool {
self.b.is_face_sturdy_rigid(self.state(pos), Direction::Up)
}
/// `Block.canSupportCenter(level, pos, direction)`.
pub fn can_support_center(&self, pos: BlockPos, direction: Direction) -> bool {
let state = self.state(pos);
if direction == Direction::Down && self.b.in_set(state, &self.b.tags.unstable_bottom_center)
{
return false;
}
self.b.is_face_sturdy_center(state, direction)
}
pub fn is_empty_block(&self, pos: BlockPos) -> bool {
self.b.is_air(self.state(pos))
}
/// `LevelReader.isWaterAt`: the fluid at `pos` is in the water tag.
pub fn is_water_at(&self, pos: BlockPos) -> bool {
self.b.is_water_fluid(self.fluid_at(pos).kind())
}
/// `Level.getRawBrightness(pos, darken)`.
pub fn raw_brightness(&self, pos: BlockPos, darken: i32) -> i32 {
super::raw_brightness(self.level, pos, darken)
}
/// `LevelReader.getMaxLocalRawBrightness(pos)`.
pub fn max_local_raw_brightness(&self, pos: BlockPos) -> i32 {
self.raw_brightness(pos, self.level.sky_darken())
}
pub fn is_redstone_conductor(&self, state: BlockStateId, _pos: BlockPos) -> bool {
self.b.has_flag(state, state_flags::CONDUCTOR)
}
pub(crate) fn above_state(&self, pos: BlockPos) -> BlockStateId {
self.state(above(pos))
}
pub(crate) fn below_state(&self, pos: BlockPos) -> BlockStateId {
self.state(below(pos))
}
pub(crate) fn rel_state(&self, pos: BlockPos, direction: Direction) -> BlockStateId {
self.state(rel(pos, direction))
}
pub(crate) fn is_inside_build_height(&self, y: i32) -> bool {
y >= self.level.min_y() && y < self.level.max_y()
}
}
+721
View File
@@ -0,0 +1,721 @@
//! 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);
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,369 @@
//! `SpeleothemBlock` growth (pointed dripstone, sulfur spikes) and
//! `PointedDripstoneBlock` fluid transfer into cauldrons and mud.
use super::{
LevelAccess, Sim,
classes::Class,
states::BlockId,
update::{above, below, rel},
};
use crate::{fluid::FluidKind, registry::BlockStateId};
use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource};
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
fn speleothem_tag(&self, state: BlockStateId) -> bool {
self.b
.tag("minecraft:speleothems")
.is_some_and(|tag| self.b.in_set(state, tag))
}
fn speleothem_with(&self, state: BlockStateId, direction: Direction) -> bool {
self.speleothem_tag(state)
&& self.b.table.dir(state, self.b.props.vertical_direction) == Some(direction)
}
fn speleothem_is_tip(&self, state: BlockStateId, include_merged: bool) -> bool {
if !self.speleothem_tag(state) {
return false;
}
let thickness = self.b.table.text(state, self.b.props.thickness);
thickness == "tip" || (include_merged && thickness == "tip_merge")
}
fn is_free_hanging_stalactite(&self, state: BlockStateId) -> bool {
self.speleothem_with(state, Direction::Down)
&& self.b.table.text(state, self.b.props.thickness) == "tip"
&& !self.b.is_waterlogged(state)
}
/// `SpeleothemBlock.findBlockVertical`.
fn find_block_vertical(
&self,
pos: BlockPos,
up: bool,
path: impl Fn(&Self, BlockPos, BlockStateId) -> bool,
target: impl Fn(&Self, BlockStateId) -> bool,
max_steps: i32,
) -> Option<BlockPos> {
let mut current = pos;
for _ in 1..max_steps {
current = if up { above(current) } else { below(current) };
let state = self.state(current);
if target(self, state) {
return Some(current);
}
if !self.is_inside_build_height(current.y) || !path(self, current, state) {
return None;
}
}
None
}
fn speleothem_find_tip(
&self,
state: BlockStateId,
pos: BlockPos,
max: i32,
include_merged: bool,
) -> Option<BlockPos> {
if self.speleothem_is_tip(state, include_merged) {
return Some(pos);
}
let b = self.b;
let direction = b
.table
.dir(state, b.props.vertical_direction)
.unwrap_or(Direction::Up);
let block = b.block(state);
self.find_block_vertical(
pos,
direction == Direction::Up,
|sim, _, s| {
sim.b.is_block(s, block)
&& sim.b.table.dir(s, sim.b.props.vertical_direction) == Some(direction)
},
|sim, s| sim.speleothem_is_tip(s, include_merged),
max,
)
}
/// `SpeleothemBlock.randomTick` (+ `PointedDripstoneBlock.maybeTransferFluid`).
pub(crate) fn speleothem_random_tick(&mut self, state: BlockStateId, pos: BlockPos) {
let b = self.b;
if b.instance_of(state, Class::PointedDripstone) {
let value = self.random().next_float();
self.dripstone_transfer_fluid(state, pos, value);
}
let start = self.speleothem_with(state, Direction::Down)
&& !b.is_block(self.above_state(pos), b.block(state));
if self.random().next_float() < 0.011_377_778 && start {
self.speleothem_grow(state, pos);
}
}
fn speleothem_grow(&mut self, state: BlockStateId, pos: BlockPos) {
let b = self.b;
let block = b.block(state);
let data = b.data(state);
let mut can_grow = data
.link
.is_some_and(|grow_on| b.is_block(self.above_state(pos), grow_on));
if data.is(Class::PointedDripstone) {
let fluid = b.fluid(self.state(pos.offset(0, 2, 0)));
can_grow &= fluid.kind() == FluidKind::Water;
}
if !can_grow {
return;
}
let max = if data.is(Class::SulfurSpike) { 2 } else { 7 };
let Some(tip_pos) = self.speleothem_find_tip(state, pos, max, false) else {
return;
};
let tip = self.state(tip_pos);
if self.is_free_hanging_stalactite(tip) && self.speleothem_can_tip_grow(block, tip, tip_pos)
{
if self.random().next_boolean() {
self.speleothem_grow_to(block, tip_pos, Direction::Down);
} else {
self.speleothem_grow_stalagmite_below(block, tip_pos);
}
}
}
fn speleothem_unmerged_tip(
&self,
block: BlockId,
state: BlockStateId,
direction: Direction,
) -> bool {
self.speleothem_is_tip(state, false)
&& self.b.table.dir(state, self.b.props.vertical_direction) == Some(direction)
&& self.b.is_block(state, block)
}
fn speleothem_can_tip_grow(
&self,
block: BlockId,
tip: BlockStateId,
tip_pos: BlockPos,
) -> bool {
let direction = self
.b
.table
.dir(tip, self.b.props.vertical_direction)
.unwrap_or(Direction::Up);
let grow = self.rel_state(tip_pos, direction);
if self.b.fluid(grow).kind() != FluidKind::Empty {
false
} else {
self.b.is_air(grow) || self.speleothem_unmerged_tip(block, grow, direction.opposite())
}
}
fn speleothem_create(
&mut self,
block: BlockId,
pos: BlockPos,
direction: Direction,
thickness: &str,
) {
let b = self.b;
let state = b
.table
.set_dir(b.default_of(block), b.props.vertical_direction, direction);
let state = b.table.set_text(state, b.props.thickness, thickness);
let water = self.fluid_at(pos) == crate::fluid::FluidState::WATER
|| self.fluid_at(pos).kind() == FluidKind::Water;
self.set_block_and_update(pos, b.table.set_bool(state, b.props.waterlogged, water));
}
fn speleothem_grow_to(&mut self, block: BlockId, from: BlockPos, direction: Direction) {
let b = self.b;
let target = rel(from, direction);
let existing = self.state(target);
if self.speleothem_unmerged_tip(block, existing, direction.opposite()) {
let (stalactite, stalagmite) =
if b.table.dir(existing, b.props.vertical_direction) == Some(Direction::Up) {
(above(target), target)
} else {
(target, below(target))
};
self.speleothem_create(block, stalactite, Direction::Down, "tip_merge");
self.speleothem_create(block, stalagmite, Direction::Up, "tip_merge");
} else if b.is_air(existing) || b.is_block(existing, b.named.water) {
self.speleothem_create(block, target, direction, "tip");
}
}
fn speleothem_grow_stalagmite_below(&mut self, block: BlockId, from: BlockPos) {
let b = self.b;
let mut pos = from;
for _ in 0..10 {
pos = below(pos);
let state = self.state(pos);
if b.fluid(state).kind() != FluidKind::Empty {
return;
}
if self.speleothem_unmerged_tip(block, state, Direction::Up)
&& self.speleothem_can_tip_grow(block, state, pos)
{
self.speleothem_grow_to(block, pos, Direction::Up);
return;
}
if self.is_valid_speleothem_placement(block, pos, Direction::Up)
&& !self.is_water_at(below(pos))
{
self.speleothem_grow_to(block, below(pos), Direction::Up);
return;
}
if b.data(b.default_of(block)).is(Class::PointedDripstone)
&& !self.dripstone_can_drip_through(state)
{
return;
}
}
}
/// `PointedDripstoneBlock.canDripThrough`.
fn dripstone_can_drip_through(&self, state: BlockStateId) -> bool {
let b = self.b;
if b.is_air(state) {
return true;
}
if b.solid_render(state) || b.fluid(state).kind() != FluidKind::Empty {
return false;
}
// REQUIRED_SPACE_TO_DRIP_THROUGH_NON_SOLID_BLOCK = column(4, 0, 16).
match b.collision_shape(state) {
None => true,
Some(shape) => {
let column = horizon_core::geometry::VoxelShape::from_box(
horizon_core::geometry::Aabb::new(
horizon_core::geometry::Vec3::new(0.375, 0.0, 0.375),
horizon_core::geometry::Vec3::new(0.625, 1.0, 0.625),
),
);
column.is_ok_and(|column| {
!column
.join_is_not_empty(shape, horizon_core::geometry::ShapeOp::AND)
.unwrap_or(true)
})
}
}
}
/// `PointedDripstoneBlock.getFluidAboveStalactite`: (position above the
/// root, fluid, state there).
fn dripstone_fluid_above(
&self,
state: BlockStateId,
pos: BlockPos,
) -> Option<(BlockPos, FluidKind, BlockStateId)> {
let b = self.b;
if !self.speleothem_with(state, Direction::Down) {
return None;
}
let block = b.block(state);
let direction = Direction::Down;
let root = self.find_block_vertical(
pos,
true,
|sim, _, s| {
sim.b.is_block(s, block)
&& sim.b.table.dir(s, sim.b.props.vertical_direction) == Some(direction)
},
|sim, s| !sim.b.is_block(s, block),
11,
)?;
let above_pos = above(root);
let above_state = self.state(above_pos);
let fluid = if b.is_block(above_state, b.named.mud)
&& self.level.dimension() != super::Dimension::Nether
{
FluidKind::Water
} else {
b.fluid(above_state).kind()
};
Some((above_pos, fluid, above_state))
}
fn dripstone_transfer_fluid(&mut self, state: BlockStateId, pos: BlockPos, value: f32) {
let b = self.b;
if value > 0.175_781_25 {
return;
}
if !(self.speleothem_with(state, Direction::Down)
&& !b.is_block(self.above_state(pos), b.block(state)))
{
return;
}
let Some((source_pos, fluid, source_state)) = self.dripstone_fluid_above(state, pos) else {
return;
};
let probability = match fluid {
FluidKind::Water => 0.175_781_25,
FluidKind::Lava => 0.058_593_75,
_ => return,
};
if value >= probability {
return;
}
let Some(tip) = self.speleothem_find_tip(state, pos, 11, false) else {
return;
};
if b.is_block(source_state, b.named.mud) && fluid == FluidKind::Water {
self.set_block_and_update(source_pos, b.default_of(b.named.clay));
self.game_event(source_pos, "minecraft:block_change");
self.level_event(1504, tip, 0);
} else if let Some(cauldron) = self.dripstone_find_cauldron(tip, fluid) {
self.level_event(1504, tip, 0);
let delay = 50 + tip.y - cauldron.y;
let block = b.block(self.state(cauldron));
self.schedule_tick(cauldron, block, delay);
}
}
fn cauldron_can_receive(&self, state: BlockStateId, fluid: FluidKind) -> bool {
let b = self.b;
let data = b.data(state);
if data.is(Class::Cauldron) {
true
} else if data.is(Class::LayeredCauldron) {
fluid == FluidKind::Water && b.is_block(state, b.named.water_cauldron)
} else {
false
}
}
fn dripstone_find_cauldron(&self, tip: BlockPos, fluid: FluidKind) -> Option<BlockPos> {
self.find_block_vertical(
tip,
false,
|sim, _, s| sim.dripstone_can_drip_through(s),
|sim, s| sim.cauldron_can_receive(s, fluid),
11,
)
}
/// `AbstractCauldronBlock.tick`: receive a drip from a stalactite above.
pub(crate) fn cauldron_tick(&mut self, state: BlockStateId, pos: BlockPos) {
let b = self.b;
let Some(tip) = self.find_block_vertical(
pos,
true,
|sim, _, s| sim.dripstone_can_drip_through(s),
|sim, s| sim.is_free_hanging_stalactite(s),
11,
) else {
return;
};
let tip_state = self.state(tip);
let fluid = self
.dripstone_fluid_above(tip_state, tip)
.map(|(_, f, _)| f)
.filter(|f| matches!(f, FluidKind::Water | FluidKind::Lava))
.unwrap_or(FluidKind::Empty);
if fluid == FluidKind::Empty || !self.cauldron_can_receive(state, fluid) {
return;
}
let data = b.data(state);
if data.is(Class::Cauldron) {
let (next, event) = if fluid == FluidKind::Water {
(b.named.water_cauldron, 1047)
} else {
(b.named.lava_cauldron, 1046)
};
self.set_block_and_update(pos, b.default_of(next));
self.game_event(pos, "minecraft:block_change");
self.level_event(event, pos, 0);
} else if data.is(Class::LayeredCauldron) {
let level = b.table.int(state, b.props.level);
if level < 3 {
self.set_block_and_update(pos, b.table.set_int(state, b.props.level, level + 1));
self.game_event(pos, "minecraft:block_change");
self.level_event(1047, pos, 0);
}
}
}
}
+353
View File
@@ -0,0 +1,353 @@
//! O(1) block-state property access over the pinned registry.
//!
//! Vanilla's `StateDefinition` enumerates a block's states as the cartesian
//! product of its properties sorted by name, the last property varying fastest,
//! and the global state registry lists every block's states contiguously. The
//! table below derives each property's stride from that layout and verifies it
//! against every registry descriptor at load, so `setValue` is arithmetic.
use crate::{
compression::invalid,
registry::{BlockRegistry, BlockStateId},
};
use horizon_core::geometry::{Axis, Direction};
use std::{collections::HashMap, io};
/// Registry-order block index; equals vanilla's `Block` registry ID.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BlockId(pub u16);
/// Interned property name (`facing`, `waterlogged`, ...), shared by all blocks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PropKey(pub u16);
#[derive(Clone, Debug)]
pub struct PropValue {
pub text: Box<str>,
pub int: Option<i32>,
pub boolean: Option<bool>,
pub direction: Option<Direction>,
}
impl PropValue {
fn new(text: &str) -> Self {
Self {
int: text.parse().ok(),
boolean: match text {
"true" => Some(true),
"false" => Some(false),
_ => None,
},
direction: direction_from_name(text),
text: text.into(),
}
}
}
#[derive(Clone, Debug)]
struct Slot {
key: PropKey,
stride: u32,
values: Vec<PropValue>,
}
#[derive(Clone, Debug)]
pub struct BlockInfo {
pub name: Box<str>,
pub base: BlockStateId,
pub count: u32,
pub default: BlockStateId,
slots: Vec<Slot>,
}
pub struct StateTable {
blocks: Vec<BlockInfo>,
state_block: Vec<u16>,
keys: HashMap<String, PropKey>,
key_names: Vec<String>,
by_name: HashMap<Box<str>, BlockId>,
}
pub fn direction_from_name(name: &str) -> Option<Direction> {
Some(match name {
"down" => Direction::Down,
"up" => Direction::Up,
"north" => Direction::North,
"south" => Direction::South,
"west" => Direction::West,
"east" => Direction::East,
_ => return None,
})
}
pub const fn direction_name(direction: Direction) -> &'static str {
match direction {
Direction::Down => "down",
Direction::Up => "up",
Direction::North => "north",
Direction::South => "south",
Direction::West => "west",
Direction::East => "east",
}
}
pub const fn axis_name(axis: Axis) -> &'static str {
match axis {
Axis::X => "x",
Axis::Y => "y",
Axis::Z => "z",
}
}
impl StateTable {
pub fn new(registry: &BlockRegistry) -> io::Result<Self> {
let mut table = Self {
blocks: Vec::new(),
state_block: Vec::with_capacity(registry.len()),
keys: HashMap::new(),
key_names: Vec::new(),
by_name: HashMap::new(),
};
let mut index = 0;
while index < registry.len() {
let first = registry.state(BlockStateId(index as u32)).unwrap();
let mut end = index + 1;
while end < registry.len()
&& registry.state(BlockStateId(end as u32)).unwrap().name == first.name
{
end += 1;
}
let count = (end - index) as u32;
let names: Vec<&String> = first.properties.keys().collect();
let mut slots = Vec::with_capacity(names.len());
let mut stride = count;
for name in &names {
let mut values = Vec::new();
// Values of this property cycle with period (stride / len); the
// first states with stride steps give each value in order.
let mut seen = Vec::<&str>::new();
for offset in 0..count {
let value = registry
.state(BlockStateId(index as u32 + offset))
.unwrap()
.properties[*name]
.as_str();
if !seen.contains(&value) {
seen.push(value);
}
}
stride /= seen.len() as u32;
for value in seen {
values.push(PropValue::new(value));
}
let key = table.key_or_insert(name);
slots.push(Slot {
key,
stride,
values,
});
}
if stride != 1 {
return Err(invalid("block state count is not a property product"));
}
// Order of values: derive from the states at multiples of stride.
for slot in &mut slots {
let len = slot.values.len() as u32;
let name = &table.key_names[slot.key.0 as usize];
slot.values = (0..len)
.map(|i| {
PropValue::new(
&registry
.state(BlockStateId(index as u32 + i * slot.stride))
.unwrap()
.properties[name],
)
})
.collect();
}
let block =
BlockId(u16::try_from(table.blocks.len()).map_err(|_| invalid("too many blocks"))?);
let default = registry
.default_state(&first.name)
.ok_or_else(|| invalid("block without default state"))?;
let info = BlockInfo {
name: first.name.as_str().into(),
base: BlockStateId(index as u32),
count,
default,
slots,
};
for offset in 0..count {
let state = registry.state(BlockStateId(index as u32 + offset)).unwrap();
for slot in &info.slots {
let value =
&slot.values[((offset / slot.stride) % slot.values.len() as u32) as usize];
if *value.text != *state.properties[&table.key_names[slot.key.0 as usize]] {
return Err(invalid(
"registry state order differs from vanilla's state definition",
));
}
}
table.state_block.push(block.0);
}
if table.by_name.insert(info.name.clone(), block).is_some() {
return Err(invalid("block states are not contiguous"));
}
table.blocks.push(info);
index = end;
}
Ok(table)
}
fn key_or_insert(&mut self, name: &str) -> PropKey {
if let Some(key) = self.keys.get(name) {
return *key;
}
let key = PropKey(self.key_names.len() as u16);
self.key_names.push(name.to_owned());
self.keys.insert(name.to_owned(), key);
key
}
/// Property keys absent from every block resolve to an unused key, so
/// lookups through them simply report "no such property".
pub fn key(&mut self, name: &str) -> PropKey {
self.key_or_insert(name)
}
pub fn state_count(&self) -> usize {
self.state_block.len()
}
pub fn block_count(&self) -> usize {
self.blocks.len()
}
pub fn block(&self, state: BlockStateId) -> BlockId {
BlockId(self.state_block[state.0 as usize])
}
pub fn info(&self, block: BlockId) -> &BlockInfo {
&self.blocks[block.0 as usize]
}
pub fn name(&self, state: BlockStateId) -> &str {
&self.info(self.block(state)).name
}
pub fn block_by_name(&self, name: &str) -> Option<BlockId> {
self.by_name.get(name).copied()
}
pub fn default_state(&self, block: BlockId) -> BlockStateId {
self.info(block).default
}
pub fn is(&self, state: BlockStateId, block: BlockId) -> bool {
self.state_block[state.0 as usize] == block.0
}
fn slot(&self, state: BlockStateId, key: PropKey) -> Option<&Slot> {
self.info(self.block(state))
.slots
.iter()
.find(|slot| slot.key == key)
}
pub fn has(&self, state: BlockStateId, key: PropKey) -> bool {
self.slot(state, key).is_some()
}
fn index_in(&self, state: BlockStateId, slot: &Slot) -> u32 {
let base = self.info(self.block(state)).base.0;
((state.0 - base) / slot.stride) % slot.values.len() as u32
}
pub fn value(&self, state: BlockStateId, key: PropKey) -> Option<&PropValue> {
let slot = self.slot(state, key)?;
Some(&slot.values[self.index_in(state, slot) as usize])
}
pub fn text(&self, state: BlockStateId, key: PropKey) -> &str {
self.value(state, key).map_or("", |v| &v.text)
}
/// Missing boolean properties read as false.
pub fn bool(&self, state: BlockStateId, key: PropKey) -> bool {
self.value(state, key)
.and_then(|v| v.boolean)
.unwrap_or(false)
}
/// Missing integer properties read as 0.
pub fn int(&self, state: BlockStateId, key: PropKey) -> i32 {
self.value(state, key).and_then(|v| v.int).unwrap_or(0)
}
pub fn dir(&self, state: BlockStateId, key: PropKey) -> Option<Direction> {
self.value(state, key).and_then(|v| v.direction)
}
/// Number of values and minimum/maximum for integer properties.
pub fn int_range(&self, state: BlockStateId, key: PropKey) -> Option<(i32, i32)> {
let slot = self.slot(state, key)?;
let ints = slot.values.iter().filter_map(|v| v.int);
Some((ints.clone().min()?, ints.max()?))
}
pub fn values(&self, block: BlockId, key: PropKey) -> impl Iterator<Item = &PropValue> {
self.info(block)
.slots
.iter()
.filter(move |slot| slot.key == key)
.flat_map(|slot| slot.values.iter())
}
fn with_index(&self, state: BlockStateId, slot: &Slot, index: u32) -> BlockStateId {
let current = self.index_in(state, slot);
BlockStateId(state.0 - current * slot.stride + index * slot.stride)
}
/// `setValue` by text; None if the block lacks the property or value.
pub fn with_text(&self, state: BlockStateId, key: PropKey, text: &str) -> Option<BlockStateId> {
let slot = self.slot(state, key)?;
let index = slot.values.iter().position(|v| &*v.text == text)?;
Some(self.with_index(state, slot, index as u32))
}
pub fn with_int(&self, state: BlockStateId, key: PropKey, value: i32) -> Option<BlockStateId> {
let slot = self.slot(state, key)?;
let index = slot.values.iter().position(|v| v.int == Some(value))?;
Some(self.with_index(state, slot, index as u32))
}
pub fn with_bool(
&self,
state: BlockStateId,
key: PropKey,
value: bool,
) -> Option<BlockStateId> {
let slot = self.slot(state, key)?;
let index = slot.values.iter().position(|v| v.boolean == Some(value))?;
Some(self.with_index(state, slot, index as u32))
}
pub fn with_dir(
&self,
state: BlockStateId,
key: PropKey,
value: Direction,
) -> Option<BlockStateId> {
self.with_text(state, key, direction_name(value))
}
/// Vanilla `setValue` callers always pass legal values; when Horizon's port
/// would compute an illegal one the state is returned unchanged.
pub fn set_text(&self, state: BlockStateId, key: PropKey, text: &str) -> BlockStateId {
self.with_text(state, key, text).unwrap_or(state)
}
pub fn set_int(&self, state: BlockStateId, key: PropKey, value: i32) -> BlockStateId {
self.with_int(state, key, value).unwrap_or(state)
}
pub fn set_bool(&self, state: BlockStateId, key: PropKey, value: bool) -> BlockStateId {
self.with_bool(state, key, value).unwrap_or(state)
}
pub fn set_dir(&self, state: BlockStateId, key: PropKey, value: Direction) -> BlockStateId {
self.with_dir(state, key, value).unwrap_or(state)
}
/// `cycle`: the next value in definition order, wrapping around.
pub fn cycle(&self, state: BlockStateId, key: PropKey) -> BlockStateId {
let Some(slot) = self.slot(state, key) else {
return state;
};
let next = (self.index_in(state, slot) + 1) % slot.values.len() as u32;
self.with_index(state, slot, next)
}
/// `Block.withPropertiesOf`: copy every property the target block shares.
pub fn with_properties_of(&self, target: BlockId, source: BlockStateId) -> BlockStateId {
let mut result = self.default_state(target);
for slot in &self.info(self.block(source)).slots {
let value = &slot.values[self.index_in(source, slot) as usize];
if let Some(next) = self.with_text(result, slot.key, &value.text) {
result = next;
}
}
result
}
pub fn property_names(&self, block: BlockId) -> impl Iterator<Item = &str> {
self.info(block)
.slots
.iter()
.map(|slot| self.key_names[slot.key.0 as usize].as_str())
}
}
+589
View File
@@ -0,0 +1,589 @@
//! `canSurvive` and `VegetationBlock.mayPlaceOn` for every overriding class.
//! Rules mirror the natively-validated `block_survival` port; dispatch follows
//! the Java class chain so `super.canSurvive` reaches the next override.
use super::{
LevelAccess, Sim,
classes::Class,
query::is_horizontal,
update::{HORIZONTAL, above, below, rel},
};
use crate::registry::BlockStateId;
use horizon_core::{geometry::Direction, position::BlockPos};
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
/// `BlockState.canSurvive(level, pos)`.
pub fn can_survive(&self, state: BlockStateId, pos: BlockPos) -> bool {
self.can_survive_at(0, state, pos)
}
fn can_survive_at(&self, depth: usize, state: BlockStateId, pos: BlockPos) -> bool {
let chain = &self.b.data(state).chain;
for (index, class) in chain.iter().enumerate().skip(depth) {
if let Some(result) = self.can_survive_class(*class, index, state, pos) {
return result;
}
}
true
}
fn can_survive_class(
&self,
class: Class,
depth: usize,
state: BlockStateId,
pos: BlockPos,
) -> Option<bool> {
let b = self.b;
let p = &b.props;
let t = &b.tags;
let n = &b.named;
let block = b.block(state);
Some(match class {
Class::AmethystCluster | Class::ShelfMushroom | Class::BaseCoralWallFan => {
let facing = b.facing(state);
self.sturdy(rel(pos, facing.opposite()), facing)
}
Class::BambooSapling | Class::BambooStalk => {
b.in_set(self.below_state(pos), &t.supports_bamboo)
}
Class::Banner | Class::Cake | Class::CandleCake | Class::StandingSign => {
b.is_solid(self.below_state(pos))
}
Class::BaseCoralPlantType | Class::LeafLitter => self.sturdy(below(pos), Direction::Up),
Class::BasePressurePlate => {
let below = below(pos);
self.can_support_rigid_block(below) || self.can_support_center(below, Direction::Up)
}
Class::BaseRail => self.can_support_rigid_block(below(pos)),
Class::BaseTorch | Class::Candle => self.can_support_center(below(pos), Direction::Up),
Class::Bell => {
let connection = self.bell_connected_direction(state).opposite();
if connection == Direction::Up {
self.can_support_center(above(pos), Direction::Down)
} else {
self.sturdy(rel(pos, connection), connection.opposite())
}
}
Class::BigDripleaf => {
let below = self.below_state(pos);
b.is_block(below, block)
|| b.is_block(below, n.big_dripleaf_stem)
|| b.in_set(below, &t.supports_big_dripleaf)
}
Class::BigDripleafStem => {
let below = self.below_state(pos);
let above = self.above_state(pos);
(b.is_block(below, block) || b.in_set(below, &t.supports_big_dripleaf))
&& (b.is_block(above, block) || b.is_block(above, n.big_dripleaf))
}
Class::BubbleColumn => {
let below = self.below_state(pos);
b.is_block(below, block)
|| b.in_set(below, &t.enables_bubble_column_push_up)
|| b.in_set(below, &t.enables_bubble_column_drag_down)
}
Class::Cactus => {
for direction in HORIZONTAL {
let at = rel(pos, direction);
if b.is_solid(self.state(at)) || b.is_lava_fluid(self.fluid_at(at).kind()) {
return Some(false);
}
}
let below = self.below_state(pos);
(b.is_block(below, block) || b.in_set(below, &t.supports_cactus))
&& !b.liquid(self.above_state(pos))
}
Class::Carpet => !self.is_empty_block(below(pos)),
Class::CeilingHangingSign => {
b.is_face_sturdy_center(self.above_state(pos), Direction::Down)
}
Class::ChorusFlower => {
let below = self.below_state(pos);
if b.is_block(below, n.chorus_plant) || b.in_set(below, &t.supports_chorus_flower) {
return Some(true);
}
if !b.is_air(below) {
return Some(false);
}
let mut one = false;
for direction in HORIZONTAL {
let neighbour = self.rel_state(pos, direction);
if b.is_block(neighbour, n.chorus_plant) {
if one {
return Some(false);
}
one = true;
} else if !b.is_air(neighbour) {
return Some(false);
}
}
one
}
Class::ChorusPlant => {
let below_state = self.below_state(pos);
let vertical = !b.is_air(self.above_state(pos)) && !b.is_air(below_state);
for direction in HORIZONTAL {
let neighbour_pos = rel(pos, direction);
if b.is_block(self.state(neighbour_pos), block) {
if vertical {
return Some(false);
}
let under = self.below_state(neighbour_pos);
if b.is_block(under, block) || b.in_set(under, &t.supports_chorus_plant) {
return Some(true);
}
}
}
b.is_block(below_state, block) || b.in_set(below_state, &t.supports_chorus_plant)
}
Class::Cocoa => b.in_set(self.rel_state(pos, b.facing(state)), &t.supports_cocoa),
Class::Crop => {
self.raw_brightness(pos, 0) >= 8 && self.can_survive_at(depth + 1, state, pos)
}
Class::Diode => b.is_face_sturdy_rigid(self.below_state(pos), Direction::Up),
Class::Door => {
let below_state = self.below_state(pos);
if b.table.text(state, p.half) == "lower" {
b.is_face_sturdy(below_state, Direction::Up)
} else {
b.is_block(below_state, block)
}
}
Class::DoublePlant => {
if b.table.text(state, p.half) != "upper" {
return Some(self.can_survive_at(depth + 1, state, pos));
}
let below_state = self.below_state(pos);
b.is_block(below_state, block) && b.table.text(below_state, p.half) == "lower"
}
Class::SmallDripleaf => {
if b.table.text(state, p.half) == "upper" {
return Some(self.can_survive_at(depth + 1, state, pos));
}
let below = below(pos);
self.may_place_on(state, self.state(below), below)
}
Class::TallSeagrass => {
if b.table.text(state, p.half) == "upper" {
let below_state = self.below_state(pos);
return Some(
b.is_block(below_state, block)
&& b.table.text(below_state, p.half) == "lower",
);
}
let fluid = self.fluid_at(pos);
self.can_survive_at(depth + 1, state, pos)
&& b.is_water_fluid(fluid.kind())
&& fluid.is_full()
}
Class::PitcherCrop => {
let lower =
b.is_block(state, n.pitcher_crop) && b.table.text(state, p.half) == "lower";
if lower && self.raw_brightness(pos, 0) < 8 {
false
} else {
self.can_survive_at(depth + 1, state, pos)
}
}
Class::FaceAttachedHorizontalDirectional => {
let direction = self.face_attached_connected(state).opposite();
self.sturdy(rel(pos, direction), direction.opposite())
}
Class::Grindstone => true,
Class::PistonHead => self.piston_head_can_survive(state, pos),
Class::Farmland => {
let above = self.above_state(pos);
!b.is_solid(above) || b.in_set(above, &t.maintains_farmland)
}
Class::Fire => {
self.sturdy(below(pos), Direction::Up) || self.is_valid_fire_location(pos)
}
Class::SoulFire => b.in_set(self.below_state(pos), &t.soul_fire_base_blocks),
Class::Frogspawn => self.frogspawn_may_place_on(below(pos)),
Class::GrowingPlant => {
let data = b.data(state);
let growth = data.growth_direction;
let attached_pos = rel(pos, growth.opposite());
let attached = self.state(attached_pos);
if !self.growing_plant_can_attach_to(state, attached) {
return Some(false);
}
let (head, body) = self.growing_plant_pair(block);
b.is_block(attached, head)
|| b.is_block(attached, body)
|| b.is_face_sturdy(attached, growth)
}
Class::HangingMoss => {
let neighbour = self.above_state(pos);
b.multiface_can_attach(neighbour, Direction::Up) || b.is_block(neighbour, block)
}
Class::HangingRoots => self.sturdy(above(pos), Direction::Down),
Class::Ladder => {
let facing = b.facing(state);
self.sturdy(rel(pos, facing.opposite()), facing)
}
Class::Lantern => {
let direction = if b.table.bool(state, p.hanging) {
Direction::Up
} else {
Direction::Down
};
self.can_support_center(rel(pos, direction), direction.opposite())
}
Class::MangrovePropagule => {
if b.table.bool(state, p.hanging) {
b.in_set(
self.above_state(pos),
&t.supports_hanging_mangrove_propagule,
)
} else {
self.can_survive_at(depth + 1, state, pos)
}
}
Class::MossyCarpet => {
let below_state = self.below_state(pos);
if b.table.bool(state, p.bottom) {
!b.is_air(below_state)
} else {
b.is_block(below_state, block) && b.table.bool(below_state, p.bottom)
}
}
Class::Multiface => {
let mut any = false;
for direction in Direction::ALL {
if self.multiface_has_face(state, direction) {
if !b.multiface_can_attach(self.rel_state(pos, direction), direction) {
return Some(false);
}
any = true;
}
}
any
}
Class::Mushroom => {
let below_pos = below(pos);
let below_state = self.state(below_pos);
if b.in_set(below_state, &t.overrides_mushroom_light_requirement) {
true
} else {
self.raw_brightness(pos, 0) < 13
&& self.may_place_on(state, below_state, below_pos)
}
}
Class::Path => {
let above = self.above_state(pos);
!b.is_solid(above) || b.instance_of(above, Class::FenceGate)
}
Class::RedstoneWallTorch | Class::WallTorch => {
let facing = b.facing(state);
self.sturdy(rel(pos, facing.opposite()), facing)
}
Class::RedstoneWire => {
let below_state = self.below_state(pos);
b.is_face_sturdy(below_state, Direction::Up) || b.is_block(below_state, n.hopper)
}
Class::Scaffolding => self.scaffolding_distance(pos) < 7,
Class::SeaPickle => {
let below = below(pos);
self.may_place_on(state, self.state(below), below)
}
Class::SnowLayer => {
let below_state = self.below_state(pos);
if b.in_set(below_state, &t.cannot_support_snow_layer) {
false
} else if b.in_set(below_state, &t.support_override_snow_layer) {
true
} else {
self.shape_info_at(below_state, below(pos)).full_faces
& (1 << Direction::Up as u8)
!= 0
|| (b.is_block(below_state, block)
&& b.table.int(below_state, p.layers) == 8)
}
}
Class::Speleothem => {
let tip = b
.table
.dir(state, p.vertical_direction)
.unwrap_or(Direction::Up);
self.is_valid_speleothem_placement(block, pos, tip)
}
Class::SporeBlossom => {
self.can_support_center(above(pos), Direction::Down) && !self.is_water_at(pos)
}
Class::SugarCane => {
let below_state = self.below_state(pos);
if b.is_block(below_state, block) {
return Some(true);
}
if b.in_set(below_state, &t.supports_sugar_cane) {
let below = below(pos);
for direction in HORIZONTAL {
let at = rel(below, direction);
let fluid = self.fluid_at(at);
if b.fluid_in(fluid.kind(), b.fluid_tags.supports_sugar_cane_adjacently)
|| b.in_set(self.state(at), &t.supports_sugar_cane_adjacently)
{
return Some(true);
}
}
}
false
}
Class::TripWireHook => {
let facing = b.facing(state);
is_horizontal(facing) && self.sturdy(rel(pos, facing.opposite()), facing)
}
Class::Vegetation => {
let below = below(pos);
self.may_place_on(state, self.state(below), below)
}
Class::Vine => {
let updated = self.vine_updated_state(state, pos);
self.vine_count_faces(updated) > 0
}
Class::WallBanner | Class::WallSign => {
b.is_solid(self.rel_state(pos, b.facing(state).opposite()))
}
_ => return None,
})
}
/// `VegetationBlock.mayPlaceOn` (virtual) for `state`'s block.
pub fn may_place_on(
&self,
state: BlockStateId,
ground: BlockStateId,
ground_pos: BlockPos,
) -> bool {
let b = self.b;
let t = &b.tags;
let data = b.data(state);
for class in &data.chain {
let result = match class {
Class::AttachedStem | Class::NetherFungus | Class::NetherRoots | Class::Stem => {
data.support_tag
.as_ref()
.is_some_and(|tag| b.in_set(ground, tag))
}
Class::Azalea => b.in_set(ground, &t.supports_azalea),
Class::CactusFlower => {
let below = self.state(ground_pos);
b.in_set(below, &t.support_override_cactus_flower)
|| b.is_face_sturdy_center(below, Direction::Up)
}
Class::Crop | Class::PitcherCrop => b.in_set(ground, &t.supports_crops),
Class::DryVegetation => b.in_set(ground, &t.supports_dry_vegetation),
Class::LilyPad => {
let fluid = self.fluid_at(ground_pos);
let above = self.fluid_at(above(ground_pos));
(b.fluid_in(fluid.kind(), b.fluid_tags.supports_lily_pad)
|| b.in_set(ground, &t.supports_lily_pad))
&& above.kind() == crate::fluid::FluidKind::Empty
}
Class::MangrovePropagule => b.in_set(ground, &t.supports_mangrove_propagule),
Class::Mushroom => b.solid_render(ground),
Class::NetherSprouts => b.in_set(ground, &t.supports_nether_sprouts),
Class::NetherWart => b.in_set(ground, &t.supports_nether_wart),
Class::SeaPickle => {
self.shape_info_at(ground, ground_pos).nonempty_faces
& (1 << Direction::Up as u8)
!= 0
|| b.is_face_sturdy(ground, Direction::Up)
}
Class::Seagrass | Class::TallSeagrass => {
b.is_face_sturdy(ground, Direction::Up)
&& !b.in_set(ground, &t.cannot_support_seagrass)
}
Class::SmallDripleaf => {
b.in_set(ground, &t.supports_small_dripleaf)
|| (self.fluid_at(above(ground_pos)) == crate::fluid::FluidState::WATER
&& b.in_set(ground, &t.supports_vegetation))
}
Class::WitherRose => b.in_set(ground, &t.supports_wither_rose),
Class::Vegetation => b.in_set(ground, &t.supports_vegetation),
_ => continue,
};
return result;
}
false
}
fn frogspawn_may_place_on(&self, pos: BlockPos) -> bool {
let b = self.b;
let fluid = self.fluid_at(pos);
let above = self.fluid_at(above(pos));
(b.fluid_in(fluid.kind(), b.fluid_tags.supports_frogspawn)
|| b.in_set(self.state(pos), &b.tags.supports_frogspawn))
&& above.kind() == crate::fluid::FluidKind::Empty
}
pub(crate) fn bell_connected_direction(&self, state: BlockStateId) -> Direction {
match self.b.table.text(state, self.b.props.attachment) {
"floor" => Direction::Up,
"ceiling" => Direction::Down,
_ => self.b.facing(state).opposite(),
}
}
/// `FaceAttachedHorizontalDirectionalBlock.getConnectedDirection`.
pub(crate) fn face_attached_connected(&self, state: BlockStateId) -> Direction {
match self.b.table.text(state, self.b.props.face) {
"ceiling" => Direction::Down,
"floor" => Direction::Up,
_ => self.b.facing(state),
}
}
pub(crate) fn multiface_has_face(&self, state: BlockStateId, direction: Direction) -> bool {
self.b.table.bool(state, self.direction_prop(direction))
}
pub(crate) fn direction_prop(&self, direction: Direction) -> super::states::PropKey {
let p = &self.b.props;
match direction {
Direction::Down => p.down,
Direction::Up => p.up,
Direction::North => p.north,
Direction::South => p.south,
Direction::West => p.west,
Direction::East => p.east,
}
}
/// Head and body blocks of a growing-plant family.
pub(crate) fn growing_plant_pair(
&self,
block: super::states::BlockId,
) -> (super::states::BlockId, super::states::BlockId) {
let name = &*self.b.table.info(block).name;
let head = name.strip_suffix("_plant").unwrap_or(name);
let head = self.b.table.block_by_name(head).unwrap_or(block);
let body = self
.b
.table
.block_by_name(&format!("{}_plant", &*self.b.table.info(head).name))
.unwrap_or(block);
(head, body)
}
/// `GrowingPlantBlock.canAttachTo` (kelp refuses `cannot_support_kelp`).
fn growing_plant_can_attach_to(&self, state: BlockStateId, attached: BlockStateId) -> bool {
let b = self.b;
if b.instance_of(state, Class::Kelp) || b.instance_of(state, Class::KelpPlant) {
!b.in_set(attached, &b.tags.cannot_support_kelp)
} else {
true
}
}
/// `FireBlock.isValidFireLocation`.
pub(crate) fn is_valid_fire_location(&self, pos: BlockPos) -> bool {
Direction::ALL
.into_iter()
.any(|direction| self.can_burn(self.rel_state(pos, direction)))
}
/// `FireBlock.canBurn`: ignite odds above zero (waterlogged states never burn).
pub(crate) fn can_burn(&self, state: BlockStateId) -> bool {
self.ignite_odds(state) > 0
}
pub(crate) fn ignite_odds(&self, state: BlockStateId) -> i32 {
if self.b.is_waterlogged(state) {
0
} else {
self.b.data(state).ignite_odds
}
}
pub(crate) fn burn_odds(&self, state: BlockStateId) -> i32 {
if self.b.is_waterlogged(state) {
0
} else {
self.b.data(state).burn_odds
}
}
/// `ScaffoldingBlock.getDistance`.
pub(crate) fn scaffolding_distance(&self, pos: BlockPos) -> i32 {
let b = self.b;
let below_pos = below(pos);
let below_state = self.state(below_pos);
let mut distance = 7;
if b.is_block(below_state, b.named.scaffolding) {
distance = b.table.int(below_state, b.props.distance);
} else if b.is_face_sturdy(below_state, Direction::Up) {
return 0;
}
for direction in HORIZONTAL {
let neighbour = self.rel_state(pos, direction);
if b.is_block(neighbour, b.named.scaffolding) {
distance = distance.min(b.table.int(neighbour, b.props.distance) + 1);
if distance == 1 {
break;
}
}
}
distance
}
/// `SpeleothemBlock.isValidSpeleothemPlacement`.
pub(crate) fn is_valid_speleothem_placement(
&self,
block: super::states::BlockId,
pos: BlockPos,
tip: Direction,
) -> bool {
let behind_pos = rel(pos, tip.opposite());
let behind = self.state(behind_pos);
self.b.is_face_sturdy(behind, tip)
|| (self.b.is_block(behind, block)
&& self.b.table.dir(behind, self.b.props.vertical_direction) == Some(tip))
}
/// `VineBlock.getUpdatedState`.
pub(crate) fn vine_updated_state(
&self,
mut state: BlockStateId,
pos: BlockPos,
) -> BlockStateId {
let b = self.b;
let p = &b.props;
let above_pos = above(pos);
if b.table.bool(state, p.up) {
let accept = b.multiface_can_attach(self.state(above_pos), Direction::Down);
state = b.table.set_bool(state, p.up, accept);
}
let mut above_state = None;
for direction in HORIZONTAL {
let key = self.direction_prop(direction);
if b.table.bool(state, key) {
let mut support = self.vine_can_support_at_face(state, pos, direction);
if !support {
let above = *above_state.get_or_insert_with(|| self.state(above_pos));
support = b.is_block(above, b.block(state)) && b.table.bool(above, key);
}
state = b.table.set_bool(state, key, support);
}
}
state
}
fn vine_can_support_at_face(
&self,
state: BlockStateId,
pos: BlockPos,
direction: Direction,
) -> bool {
let b = self.b;
if direction == Direction::Down {
return false;
}
if b.multiface_can_attach(self.rel_state(pos, direction), direction) {
return true;
}
if direction == Direction::Up {
return false;
}
let above = self.above_state(pos);
b.is_block(above, b.block(state)) && b.table.bool(above, self.direction_prop(direction))
}
pub(crate) fn vine_count_faces(&self, state: BlockStateId) -> usize {
[
Direction::Up,
Direction::North,
Direction::East,
Direction::South,
Direction::West,
]
.into_iter()
.filter(|d| self.b.table.bool(state, self.direction_prop(*d)))
.count()
}
}
+919
View File
@@ -0,0 +1,919 @@
//! 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);
}
/// Scheduled ticks, block events and block entities, as `ServerLevel.tick`.
fn full_tick(&mut self) {
self.tick();
self.f
.behaviours
.run_block_events(&mut self.level, &mut self.ticks);
self.f
.behaviours
.tick_block_entities(&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");
}
impl World<'_> {
/// Right-click `item` on the `face` of `clicked`, hitting the face centre
/// (offset vertically by `dy`), looking with `yaw`/`pitch`.
fn place(
&mut self,
item: &str,
clicked: BlockPos,
face: Direction,
yaw: f32,
pitch: f32,
dy: f64,
) -> PlaceOutcome {
let [nx, ny, nz] = face.normal();
let hit = horizon_core::geometry::Vec3::new(
f64::from(clicked.x) + 0.5 + f64::from(nx) * 0.5,
f64::from(clicked.y) + 0.5 + f64::from(ny) * 0.5 + dy,
f64::from(clicked.z) + 0.5 + f64::from(nz) * 0.5,
);
let ctx = PlaceContext {
clicked_pos: clicked,
face,
hit,
inside: false,
yaw,
pitch,
sneaking: false,
item: format!("minecraft:{item}"),
can_use_game_master_blocks: false,
};
self.f
.behaviours
.place_block(&mut self.level, &mut self.ticks, &ctx)
}
fn use_block(&mut self, pos: BlockPos) -> InteractionResult {
let player = PlayerContext {
yaw: 0.0,
pitch: 0.0,
may_build: true,
can_eat: true,
game_master: false,
};
let hit = horizon_core::geometry::Vec3::new(
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 0.5,
f64::from(pos.z),
);
self.f.behaviours.use_without_item(
&mut self.level,
&mut self.ticks,
pos,
Direction::North,
hit,
player,
)
}
}
#[test]
fn placement_orients_blocks() {
let mut w = world!();
w.floor(0, 6, "stone");
let ground = BlockPos::new(0, 0, 0);
// Looking north (yaw 180) at the top of the floor.
w.place("oak_stairs", ground, Direction::Up, 180.0, 30.0, 0.0);
assert_eq!(
w.name(BlockPos::new(0, 1, 0)),
"oak_stairs[facing=north,half=bottom,shape=straight,waterlogged=false]"
);
w.place(
"oak_log",
BlockPos::new(1, 0, 0),
Direction::Up,
0.0,
0.0,
0.0,
);
w.place(
"oak_log",
BlockPos::new(1, 1, 0),
Direction::East,
0.0,
0.0,
0.0,
);
assert_eq!(w.prop(BlockPos::new(2, 1, 0), "axis"), "x");
// Torch against the log's east face becomes a wall torch facing east.
w.place(
"torch",
BlockPos::new(2, 1, 0),
Direction::East,
270.0,
0.0,
0.0,
);
assert_eq!(w.name(BlockPos::new(3, 1, 0)), "wall_torch[facing=east]");
// Furnaces face the player; observers face where the player looks.
w.place(
"furnace",
BlockPos::new(-2, 0, 0),
Direction::Up,
0.0,
0.0,
0.0,
);
assert_eq!(w.prop(BlockPos::new(-2, 1, 0), "facing"), "north");
w.place(
"observer",
BlockPos::new(-3, 0, 0),
Direction::Up,
0.0,
0.0,
0.0,
);
assert_eq!(w.prop(BlockPos::new(-3, 1, 0), "facing"), "south");
}
#[test]
fn placement_merges_slabs_and_stacks() {
let mut w = world!();
w.floor(0, 4, "stone");
let ground = BlockPos::new(0, 0, 0);
w.place("oak_slab", ground, Direction::Up, 0.0, 60.0, 0.0);
assert_eq!(w.prop(BlockPos::new(0, 1, 0), "type"), "bottom");
w.place(
"oak_slab",
BlockPos::new(0, 1, 0),
Direction::Up,
0.0,
60.0,
-0.5,
);
assert_eq!(w.prop(BlockPos::new(0, 1, 0), "type"), "double");
// Clicking the upper half of a side face places a top slab.
w.place(
"oak_slab",
BlockPos::new(0, 1, 0),
Direction::East,
0.0,
0.0,
0.25,
);
assert_eq!(w.prop(BlockPos::new(1, 1, 0), "type"), "top");
w.place(
"snow",
BlockPos::new(3, 0, 0),
Direction::Up,
0.0,
60.0,
0.0,
);
w.place(
"snow",
BlockPos::new(3, 1, 0),
Direction::Up,
0.0,
60.0,
-0.375,
);
assert_eq!(w.prop(BlockPos::new(3, 1, 0), "layers"), "2");
w.place(
"candle",
BlockPos::new(-3, 0, 0),
Direction::Up,
0.0,
60.0,
0.0,
);
w.place(
"candle",
BlockPos::new(-3, 1, 0),
Direction::Up,
0.0,
60.0,
-0.4,
);
assert_eq!(w.prop(BlockPos::new(-3, 1, 0), "candles"), "2");
}
#[test]
fn doors_beds_and_plants_place_both_halves() {
let mut w = world!();
w.floor(0, 6, "grass_block");
let ground = BlockPos::new(0, 0, 0);
w.place("oak_door", ground, Direction::Up, 180.0, 30.0, 0.0);
assert_eq!(w.prop(BlockPos::new(0, 1, 0), "half"), "lower");
assert_eq!(w.prop(BlockPos::new(0, 2, 0), "half"), "upper");
assert_eq!(
w.use_block(BlockPos::new(0, 1, 0)),
InteractionResult::Success
);
assert_eq!(w.prop(BlockPos::new(0, 1, 0), "open"), "true");
assert_eq!(
w.prop(BlockPos::new(0, 2, 0), "open"),
"true",
"the upper half follows"
);
w.place(
"red_bed",
BlockPos::new(3, 0, 0),
Direction::Up,
180.0,
30.0,
0.0,
);
assert_eq!(w.prop(BlockPos::new(3, 1, 0), "part"), "foot");
assert_eq!(w.prop(BlockPos::new(3, 1, -1), "part"), "head");
w.place(
"sunflower",
BlockPos::new(-3, 0, 0),
Direction::Up,
0.0,
30.0,
0.0,
);
assert_eq!(w.prop(BlockPos::new(-3, 2, 0), "half"), "upper");
// Iron doors cannot be opened by hand.
w.place(
"iron_door",
BlockPos::new(5, 0, 0),
Direction::Up,
180.0,
30.0,
0.0,
);
assert_eq!(w.use_block(BlockPos::new(5, 1, 0)), InteractionResult::Pass);
// A placement into a solid block fails.
assert_eq!(
w.place(
"stone",
BlockPos::new(0, 0, 0),
Direction::West,
0.0,
0.0,
0.0
),
PlaceOutcome::Failed
);
}
#[test]
fn levers_power_wire_through_interaction() {
let mut w = world!();
w.floor(0, 8, "stone");
w.place(
"lever",
BlockPos::new(0, 0, 0),
Direction::Up,
0.0,
60.0,
0.0,
);
for x in 1..=3 {
w.place(
"redstone",
BlockPos::new(x, 0, 0),
Direction::Up,
0.0,
60.0,
0.0,
);
}
assert_eq!(
w.use_block(BlockPos::new(0, 1, 0)),
InteractionResult::Success
);
assert_eq!(w.prop(BlockPos::new(0, 1, 0), "powered"), "true");
assert_eq!(w.prop(BlockPos::new(3, 1, 0), "power"), "13");
w.use_block(BlockPos::new(0, 1, 0));
assert_eq!(w.prop(BlockPos::new(1, 1, 0), "power"), "0");
// Buttons release after their pressed time.
w.place(
"stone_button",
BlockPos::new(5, 0, 0),
Direction::Up,
0.0,
60.0,
0.0,
);
w.use_block(BlockPos::new(5, 1, 0));
assert_eq!(w.prop(BlockPos::new(5, 1, 0), "powered"), "true");
for _ in 0..20 {
w.tick();
}
assert_eq!(w.prop(BlockPos::new(5, 1, 0), "powered"), "false");
}
#[test]
fn pistons_push_and_sticky_pistons_pull() {
let mut w = world!();
w.floor(0, 10, "stone");
let piston = w.id("sticky_piston", &[("facing", "east")]);
let block = w.id("redstone_block", &[]);
let dirt = w.id("dirt", &[]);
let air = w.b().air();
w.set(BlockPos::new(0, 1, 0), piston);
w.set(BlockPos::new(1, 1, 0), dirt);
w.set(BlockPos::new(-1, 1, 0), block);
for _ in 0..4 {
w.full_tick();
}
assert_eq!(w.prop(BlockPos::new(0, 1, 0), "extended"), "true");
assert_eq!(
w.name(BlockPos::new(1, 1, 0)),
"piston_head[facing=east,short=false,type=sticky]"
);
assert_eq!(w.get(BlockPos::new(2, 1, 0)), dirt);
assert!(w.ticks.moving_pistons.is_empty());
w.set(BlockPos::new(-1, 1, 0), air);
for _ in 0..4 {
w.full_tick();
}
assert_eq!(w.prop(BlockPos::new(0, 1, 0), "extended"), "false");
assert_eq!(
w.get(BlockPos::new(1, 1, 0)),
dirt,
"the sticky piston pulled the block back"
);
assert_eq!(w.get(BlockPos::new(2, 1, 0)), air);
}
#[test]
fn pistons_pop_fragile_blocks_and_refuse_obsidian() {
let mut w = world!();
w.floor(0, 10, "stone");
let piston = w.id("piston", &[("facing", "east")]);
let block = w.id("redstone_block", &[]);
let torch = w.id("torch", &[]);
let obsidian = w.id("obsidian", &[]);
w.set(BlockPos::new(0, 1, 0), piston);
w.set(BlockPos::new(1, 1, 0), torch);
w.set(BlockPos::new(-1, 1, 0), block);
for _ in 0..4 {
w.full_tick();
}
assert_eq!(
w.name(BlockPos::new(1, 1, 0)),
"piston_head[facing=east,short=false,type=normal]"
);
assert!(
w.level
.events
.iter()
.any(|e| matches!(e, LevelEvent::DropResources { state, .. } if *state == torch))
);
let mut w = world!();
w.floor(0, 10, "stone");
w.set(BlockPos::new(0, 1, 0), piston);
w.set(BlockPos::new(1, 1, 0), obsidian);
w.set(BlockPos::new(-1, 1, 0), block);
for _ in 0..4 {
w.full_tick();
}
assert_eq!(w.prop(BlockPos::new(0, 1, 0), "extended"), "false");
assert_eq!(w.get(BlockPos::new(1, 1, 0)), obsidian);
}
#[test]
fn dripstone_fills_cauldrons() {
let mut w = world!();
let block = w.id("dripstone_block", &[]);
let water = w.id("water", &[]);
let tip = w.id(
"pointed_dripstone",
&[("vertical_direction", "down"), ("thickness", "tip")],
);
let cauldron = w.id("cauldron", &[]);
w.put(BlockPos::new(0, 11, 0), water);
w.put(BlockPos::new(0, 10, 0), block);
w.put(BlockPos::new(0, 9, 0), tip);
w.put(BlockPos::new(0, 5, 0), cauldron);
for _ in 0..100 {
w.b()
.random_tick(&mut w.level, &mut w.ticks, BlockPos::new(0, 9, 0));
}
for _ in 0..80 {
w.tick();
}
assert_eq!(w.name(BlockPos::new(0, 5, 0)), "water_cauldron[level=1]");
}
File diff suppressed because it is too large Load Diff
+141
View File
@@ -0,0 +1,141 @@
//! Per-level mutable simulation state: scheduled block and fluid ticks plus the
//! in-flight neighbour-update queue and the random-tick position generator.
use super::{states::BlockId, update::NeighborUpdater};
use crate::fluid::FluidKind;
use horizon_core::{
position::{BlockPos, ChunkPos},
ticks::{
ChunkTicks, LevelTicks, ScheduleResult, ScheduledTick, TickError, TickPriority, TickTypeId,
},
};
/// Owned by the caller next to its chunk storage. Chunks must be registered
/// with [`Ticks::add_chunk`] before ticks can be scheduled in them, mirroring
/// vanilla's `LevelTicks.allContainers` (scheduling elsewhere is dropped).
pub struct Ticks {
/// Block ticks keyed by `BlockId` (vanilla Block registry ID).
pub blocks: LevelTicks,
/// Fluid ticks keyed by vanilla Fluid registry ID (`FluidKind as u32`).
pub fluids: LevelTicks,
sub_tick: i64,
/// `Level.randValue`, the LCG behind `getBlockRandomPos`.
pub random_tick_value: i32,
pub(crate) updater: NeighborUpdater,
/// `ComparatorBlockEntity.output` per comparator position (block-entity
/// state owned by the level; persist it with the chunk if desired).
pub comparator_outputs: std::collections::HashMap<BlockPos, i32>,
/// `RedstoneTorchBlock.RECENT_TOGGLES` (position, game time).
pub torch_toggles: Vec<(BlockPos, i64)>,
/// Moving-piston block entities in ticker order (render and collide
/// moving blocks from these; see `piston_shape`).
pub moving_pistons: Vec<(BlockPos, super::pistons::MovingPiston)>,
pub(crate) next_block_entity_id: u64,
/// `ServerLevel.blockEvents`, run by `Behaviours::run_block_events`.
pub block_events: Vec<super::pistons::BlockEventData>,
/// `ServerLevel.isHandlingTick` (true while scheduled ticks run).
pub(crate) handling_tick: bool,
}
impl Default for Ticks {
fn default() -> Self {
Self::new(0)
}
}
impl Ticks {
/// `random_tick_seed` seeds `Level.randValue` (vanilla draws it from a
/// thread-local random at level construction).
pub fn new(random_tick_seed: i32) -> Self {
Self {
blocks: LevelTicks::default(),
fluids: LevelTicks::default(),
sub_tick: 0,
random_tick_value: random_tick_seed,
updater: NeighborUpdater::default(),
comparator_outputs: Default::default(),
torch_toggles: Vec::new(),
moving_pistons: Vec::new(),
next_block_entity_id: 0,
block_events: Vec::new(),
handling_tick: false,
}
}
/// Register a loaded chunk's saved block and fluid ticks.
pub fn add_chunk(
&mut self,
pos: ChunkPos,
blocks: ChunkTicks,
fluids: ChunkTicks,
) -> Result<(), TickError> {
self.blocks.add_chunk(pos, blocks)?;
self.fluids.add_chunk(pos, fluids)
}
/// Register a chunk without saved ticks.
pub fn add_empty_chunk(&mut self, pos: ChunkPos) -> Result<(), TickError> {
self.add_chunk(pos, ChunkTicks::default(), ChunkTicks::default())
}
pub fn remove_chunk(&mut self, pos: ChunkPos) -> (Option<ChunkTicks>, Option<ChunkTicks>) {
(self.blocks.remove_chunk(pos), self.fluids.remove_chunk(pos))
}
/// `ServerLevel.nextSubTickCount`, shared by block and fluid ticks.
pub fn next_sub_tick(&mut self) -> i64 {
let value = self.sub_tick;
self.sub_tick = self.sub_tick.wrapping_add(1);
value
}
pub fn schedule_block(
&mut self,
game_time: i64,
pos: BlockPos,
block: BlockId,
delay: i32,
priority: TickPriority,
) -> ScheduleResult {
let tick = ScheduledTick {
kind: TickTypeId(u32::from(block.0)),
pos,
trigger_tick: game_time.wrapping_add(i64::from(delay)),
priority,
sub_tick_order: self.next_sub_tick(),
};
self.blocks.schedule(tick)
}
pub fn schedule_fluid(
&mut self,
game_time: i64,
pos: BlockPos,
fluid: FluidKind,
delay: i32,
) -> ScheduleResult {
let tick = ScheduledTick {
kind: TickTypeId(fluid as u32),
pos,
trigger_tick: game_time.wrapping_add(i64::from(delay)),
priority: TickPriority::Normal,
sub_tick_order: self.next_sub_tick(),
};
self.fluids.schedule(tick)
}
pub fn has_block_tick(&self, pos: BlockPos, block: BlockId) -> bool {
self.blocks
.has_scheduled(pos, TickTypeId(u32::from(block.0)))
}
pub fn has_fluid_tick(&self, pos: BlockPos, fluid: FluidKind) -> bool {
self.fluids.has_scheduled(pos, TickTypeId(fluid as u32))
}
pub fn will_block_tick_this_tick(&mut self, pos: BlockPos, block: BlockId) -> bool {
self.blocks
.will_tick_this_tick(pos, TickTypeId(u32::from(block.0)))
}
/// `Level.getBlockRandomPos`.
pub fn block_random_pos(&mut self, x: i32, y: i32, z: i32, y_mask: i32) -> BlockPos {
self.random_tick_value = self
.random_tick_value
.wrapping_mul(3)
.wrapping_add(1_013_904_223);
let value = self.random_tick_value >> 2;
BlockPos::new(
x + (value & 15),
y + ((value >> 16) & y_mask),
z + ((value >> 8) & 15),
)
}
}
+547
View File
@@ -0,0 +1,547 @@
//! `Level.setBlock`, `LevelChunk.setBlockState` and the
//! `CollectingNeighborUpdater` that orders neighbour and shape updates.
use super::{LevelAccess, LevelEvent, Sim, flags, states::BlockId};
use crate::{fluid::FluidState, registry::BlockStateId};
use horizon_core::{
geometry::Direction,
position::BlockPos,
random::LegacyRandom,
ticks::{ScheduleResult, TickPriority},
};
/// `NeighborUpdater.UPDATE_ORDER`.
pub(crate) const UPDATE_ORDER: [Direction; 6] = [
Direction::West,
Direction::East,
Direction::Down,
Direction::Up,
Direction::North,
Direction::South,
];
/// `BlockBehaviour.UPDATE_SHAPE_ORDER`.
pub(crate) const UPDATE_SHAPE_ORDER: [Direction; 6] = [
Direction::West,
Direction::East,
Direction::North,
Direction::South,
Direction::Down,
Direction::Up,
];
pub(crate) const HORIZONTAL: [Direction; 4] = [
Direction::North,
Direction::East,
Direction::South,
Direction::West,
];
/// `MinecraftServer.getMaxChainedNeighborUpdates` default.
const MAX_CHAINED_NEIGHBOR_UPDATES: i32 = 1_000_000;
pub(crate) fn rel(pos: BlockPos, direction: Direction) -> BlockPos {
let [x, y, z] = direction.normal();
pos.offset(x, y, z)
}
pub(crate) fn above(pos: BlockPos) -> BlockPos {
pos.offset(0, 1, 0)
}
pub(crate) fn below(pos: BlockPos) -> BlockPos {
pos.offset(0, -1, 0)
}
#[derive(Clone, Copy, Debug)]
enum Update {
Shape {
direction: Direction,
neighbor_state: BlockStateId,
pos: BlockPos,
neighbor_pos: BlockPos,
flags: i32,
limit: i32,
},
Simple {
pos: BlockPos,
block: BlockId,
},
Full {
state: BlockStateId,
pos: BlockPos,
block: BlockId,
moved: bool,
},
Multi {
source: BlockPos,
block: BlockId,
skip: Option<Direction>,
index: usize,
},
}
enum Step {
Shape {
direction: Direction,
neighbor_state: BlockStateId,
pos: BlockPos,
neighbor_pos: BlockPos,
flags: i32,
limit: i32,
},
Neighbor {
state: Option<BlockStateId>,
pos: BlockPos,
block: BlockId,
moved: bool,
},
}
#[derive(Default)]
pub(crate) struct NeighborUpdater {
stack: Vec<Update>,
added: Vec<Update>,
count: i32,
}
impl Update {
/// `runNext`: the update to execute now and whether more remain.
fn next(&mut self) -> (Step, bool) {
match *self {
Self::Shape {
direction,
neighbor_state,
pos,
neighbor_pos,
flags,
limit,
} => (
Step::Shape {
direction,
neighbor_state,
pos,
neighbor_pos,
flags,
limit,
},
false,
),
Self::Simple { pos, block } => (
Step::Neighbor {
state: None,
pos,
block,
moved: false,
},
false,
),
Self::Full {
state,
pos,
block,
moved,
} => (
Step::Neighbor {
state: Some(state),
pos,
block,
moved,
},
false,
),
Self::Multi {
source,
block,
skip,
ref mut index,
} => {
let direction = UPDATE_ORDER[*index];
*index += 1;
if *index < UPDATE_ORDER.len() && Some(UPDATE_ORDER[*index]) == skip {
*index += 1;
}
(
Step::Neighbor {
state: None,
pos: rel(source, direction),
block,
moved: false,
},
*index < UPDATE_ORDER.len(),
)
}
}
}
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
pub fn state(&self, pos: BlockPos) -> BlockStateId {
self.level.block_state(pos)
}
pub fn fluid_at(&self, pos: BlockPos) -> FluidState {
self.b.fluid(self.state(pos))
}
pub fn random(&mut self) -> &mut LegacyRandom {
self.level.random()
}
pub fn emit(&mut self, event: LevelEvent) {
self.level.emit(event);
}
pub fn level_event(&mut self, id: i32, pos: BlockPos, data: i32) {
self.level.emit(LevelEvent::LevelEvent { id, pos, data });
}
pub fn sound(&mut self, pos: BlockPos, sound: &std::sync::Arc<str>, volume: f32, pitch: f32) {
self.level.emit(LevelEvent::Sound {
pos,
sound: sound.clone(),
volume,
pitch,
});
}
pub fn game_event(&mut self, pos: BlockPos, event: &'static str) {
self.level.emit(LevelEvent::GameEvent { pos, event });
}
pub fn block_of(&self, state: BlockStateId) -> BlockId {
self.b.table.block(state)
}
pub fn is_in_valid_bounds(&self, pos: BlockPos) -> bool {
pos.y >= self.level.min_y()
&& pos.y < self.level.max_y()
&& (-30_000_000..30_000_000).contains(&pos.x)
&& (-30_000_000..30_000_000).contains(&pos.z)
}
// ---- scheduled ticks ----
pub fn schedule_tick(&mut self, pos: BlockPos, block: BlockId, delay: i32) -> ScheduleResult {
self.schedule_tick_priority(pos, block, delay, TickPriority::Normal)
}
pub fn schedule_tick_priority(
&mut self,
pos: BlockPos,
block: BlockId,
delay: i32,
priority: TickPriority,
) -> ScheduleResult {
let time = self.level.game_time();
self.ticks.schedule_block(time, pos, block, delay, priority)
}
pub fn schedule_fluid_tick(
&mut self,
pos: BlockPos,
fluid: crate::fluid::FluidKind,
delay: i32,
) -> ScheduleResult {
let time = self.level.game_time();
self.ticks.schedule_fluid(time, pos, fluid, delay)
}
// ---- Level.setBlock ----
pub fn set_block(&mut self, pos: BlockPos, state: BlockStateId, flags: i32) -> bool {
self.set_block_limit(pos, state, flags, flags::UPDATE_LIMIT)
}
pub fn set_block_and_update(&mut self, pos: BlockPos, state: BlockStateId) -> bool {
self.set_block(pos, state, flags::UPDATE_ALL)
}
pub fn set_block_limit(
&mut self,
pos: BlockPos,
state: BlockStateId,
update_flags: i32,
limit: i32,
) -> bool {
if !self.is_in_valid_bounds(pos) || !self.level.is_loaded(pos) {
return false;
}
let Some(old) = self.chunk_set_block_state(pos, state, update_flags) else {
return false;
};
let new = self.state(pos);
if new == state {
if update_flags & flags::UPDATE_NEIGHBORS != 0 {
let old_block = self.block_of(old);
self.update_neighbors_at(pos, old_block);
if self
.b
.has_flag(state, super::data::state_flags::ANALOG_OUTPUT)
{
let block = self.block_of(state);
self.update_neighbour_for_output_signal(pos, block);
}
}
if update_flags & flags::UPDATE_KNOWN_SHAPE == 0 && limit > 0 {
let neighbour_flags =
update_flags & !(flags::UPDATE_NEIGHBORS | flags::UPDATE_SUPPRESS_DROPS);
self.update_indirect_neighbour_shapes(old, pos, neighbour_flags, limit - 1);
self.update_neighbour_shapes(state, pos, neighbour_flags, limit - 1);
self.update_indirect_neighbour_shapes(state, pos, neighbour_flags, limit - 1);
}
}
true
}
/// `LevelChunk.setBlockState`: the previous state when the write happened.
fn chunk_set_block_state(
&mut self,
pos: BlockPos,
state: BlockStateId,
update_flags: i32,
) -> Option<BlockStateId> {
let current = self.state(pos);
if current == state {
return None;
}
let old = self.level.set_raw(pos, state)?;
if old == state {
return None;
}
let new_block = self.block_of(state);
let block_changed = self.block_of(old) != new_block;
if block_changed && self.block_of(old) == self.b.named.moving_piston {
// PistonMovingBlockEntity.preRemoveSideEffects -> finalTick; the
// block is already replaced, so only the entity goes away.
self.remove_moving_piston(pos);
}
let moved = update_flags & flags::UPDATE_MOVE_BY_PISTON != 0;
if (block_changed
|| self
.b
.block_data(new_block)
.is(super::classes::Class::BaseRail))
&& (update_flags & flags::UPDATE_NEIGHBORS != 0 || moved)
{
self.affect_neighbors_after_removal(old, pos, moved);
}
if self.block_of(self.state(pos)) != new_block {
return None;
}
if update_flags & flags::UPDATE_SKIP_ON_PLACE == 0 {
self.on_place(state, pos, old, moved);
}
Some(old)
}
/// `Level.removeBlock`.
pub fn remove_block(&mut self, pos: BlockPos, moved_by_piston: bool) -> bool {
let fluid = self.fluid_at(pos);
let legacy = self.b.legacy_block(fluid);
self.set_block(pos, legacy, 3 | if moved_by_piston { 64 } else { 0 })
}
/// `Level.destroyBlock(pos, dropResources, null, limit)`.
pub fn destroy_block(&mut self, pos: BlockPos, drop: bool, limit: i32) -> bool {
let state = self.state(pos);
if self.b.is_air(state) {
return false;
}
self.level_event(2001, pos, state.0 as i32);
if drop {
self.drop_resources(state, pos);
}
let fluid = self.fluid_at(pos);
let legacy = self.b.legacy_block(fluid);
let destroyed = self.set_block_limit(pos, legacy, 3, limit);
if destroyed {
self.game_event(pos, "minecraft:block_destroy");
}
destroyed
}
pub fn drop_resources(&mut self, state: BlockStateId, pos: BlockPos) {
if self.level.game_rules().block_drops {
self.emit(LevelEvent::DropResources { pos, state });
}
}
/// `Block.updateOrDestroy`.
pub fn update_or_destroy(
&mut self,
old: BlockStateId,
new: BlockStateId,
pos: BlockPos,
update_flags: i32,
limit: i32,
) {
if new != old {
if self.b.is_air(new) {
self.destroy_block(pos, update_flags & flags::UPDATE_SUPPRESS_DROPS == 0, limit);
} else {
self.set_block_limit(
pos,
new,
update_flags & !flags::UPDATE_SUPPRESS_DROPS,
limit,
);
}
}
}
/// `Block.updateFromNeighbourShapes`.
pub fn update_from_neighbour_shapes(
&mut self,
state: BlockStateId,
pos: BlockPos,
) -> BlockStateId {
let mut new = state;
for direction in UPDATE_SHAPE_ORDER {
let neighbour = rel(pos, direction);
let neighbour_state = self.state(neighbour);
new = self.update_shape(new, pos, direction, neighbour, neighbour_state);
}
new
}
/// `BlockStateBase.updateNeighbourShapes`.
pub fn update_neighbour_shapes(
&mut self,
state: BlockStateId,
pos: BlockPos,
update_flags: i32,
limit: i32,
) {
for direction in UPDATE_SHAPE_ORDER {
let neighbour = rel(pos, direction);
self.neighbor_shape_changed(
direction.opposite(),
neighbour,
pos,
state,
update_flags,
limit,
);
}
}
// ---- neighbour updater ----
pub fn update_neighbors_at(&mut self, pos: BlockPos, block: BlockId) {
self.add_and_run(Update::Multi {
source: pos,
block,
skip: None,
index: 0,
});
}
pub fn update_neighbors_at_except(&mut self, pos: BlockPos, block: BlockId, skip: Direction) {
let index = usize::from(UPDATE_ORDER[0] == skip);
self.add_and_run(Update::Multi {
source: pos,
block,
skip: Some(skip),
index,
});
}
pub fn neighbor_changed_at(&mut self, pos: BlockPos, block: BlockId) {
self.add_and_run(Update::Simple { pos, block });
}
pub fn neighbor_changed_full(
&mut self,
state: BlockStateId,
pos: BlockPos,
block: BlockId,
moved: bool,
) {
self.add_and_run(Update::Full {
state,
pos,
block,
moved,
});
}
pub fn neighbor_shape_changed(
&mut self,
direction: Direction,
pos: BlockPos,
neighbor_pos: BlockPos,
neighbor_state: BlockStateId,
update_flags: i32,
limit: i32,
) {
self.add_and_run(Update::Shape {
direction,
neighbor_state,
pos,
neighbor_pos,
flags: update_flags,
limit,
});
}
fn add_and_run(&mut self, update: Update) {
let updater = &mut self.ticks.updater;
let running = updater.count > 0;
let too_many = updater.count >= MAX_CHAINED_NEIGHBOR_UPDATES;
updater.count += 1;
if !too_many {
if running {
updater.added.push(update);
} else {
updater.stack.push(update);
}
}
if !running {
self.run_updates();
}
}
fn run_updates(&mut self) {
loop {
let updater = &mut self.ticks.updater;
if updater.stack.is_empty() && updater.added.is_empty() {
break;
}
while let Some(update) = updater.added.pop() {
updater.stack.push(update);
}
while let Some(top) = self.ticks.updater.stack.last_mut() {
let (step, more) = top.next();
self.execute(step);
if !more {
self.ticks.updater.stack.pop();
break;
}
if !self.ticks.updater.added.is_empty() {
break;
}
}
}
let updater = &mut self.ticks.updater;
updater.stack.clear();
updater.added.clear();
updater.count = 0;
}
fn execute(&mut self, step: Step) {
match step {
Step::Shape {
direction,
neighbor_state,
pos,
neighbor_pos,
flags: update_flags,
limit,
} => {
let current = self.state(pos);
if update_flags & flags::UPDATE_SKIP_SHAPE_UPDATE_ON_WIRE == 0
|| !self.b.table.is(current, self.b.named.redstone_wire)
{
let new =
self.update_shape(current, pos, direction, neighbor_pos, neighbor_state);
self.update_or_destroy(current, new, pos, update_flags, limit);
}
}
Step::Neighbor {
state,
pos,
block,
moved,
} => {
let state = state.unwrap_or_else(|| self.state(pos));
self.neighbor_changed(state, pos, block, moved);
}
}
}
/// `Level.updateNeighbourForOutputSignal`.
pub fn update_neighbour_for_output_signal(&mut self, pos: BlockPos, block: BlockId) {
for direction in super::update::HORIZONTAL {
let mut relative = rel(pos, direction);
if !self.level.is_loaded(relative) {
continue;
}
let mut state = self.state(relative);
if self.b.table.is(state, self.b.named.comparator) {
self.neighbor_changed_full(state, relative, block, false);
} else if self.is_redstone_conductor(state, relative) {
relative = rel(relative, direction);
state = self.state(relative);
if self.b.table.is(state, self.b.named.comparator) {
self.neighbor_changed_full(state, relative, block, false);
}
}
}
}
}
+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;
@@ -0,0 +1,255 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.RecordComponent;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Optional;
import net.minecraft.SharedConstants;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.Bootstrap;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.EmptyBlockGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.SupportType;
import net.minecraft.world.level.material.FlowingFluid;
import net.minecraft.world.level.material.Fluid;
/**
* Original exporter of the block-behaviour inputs Horizon's level simulation needs:
* every block's class chain and immutable instance configuration (read reflectively),
* per-state support/redstone/fluid facts from vanilla's accessors over an empty level,
* fire odds and block-item placement bindings. No behaviour is evaluated here.
*/
public final class VanillaBlockBehaviourExporter {
private static JsonElement value(Object v, int depth) {
if (v == null) {
return JsonNull.INSTANCE;
} else if (v instanceof Boolean b) {
return new JsonPrimitive(b);
} else if (v instanceof Number n) {
return new JsonPrimitive(n);
} else if (v instanceof String || v instanceof Character) {
return new JsonPrimitive(v.toString());
} else if (v instanceof Enum<?> e) {
return new JsonPrimitive(e.name());
} else if (v instanceof Block b) {
return new JsonPrimitive(BuiltInRegistries.BLOCK.getKey(b).toString());
} else if (v instanceof BlockState s) {
var o = new JsonObject();
o.addProperty("state", Block.getId(s));
return o;
} else if (v instanceof Item i) {
return new JsonPrimitive(BuiltInRegistries.ITEM.getKey(i).toString());
} else if (v instanceof Fluid f) {
return new JsonPrimitive(BuiltInRegistries.FLUID.getKey(f).toString());
} else if (v instanceof SoundEvent s) {
return new JsonPrimitive(s.location().toString());
} else if (v instanceof Identifier id) {
return new JsonPrimitive(id.toString());
} else if (v instanceof ResourceKey<?> key) {
return new JsonPrimitive(key.identifier().toString());
} else if (v instanceof TagKey<?> tag) {
return new JsonPrimitive("#" + tag.location());
} else if (v instanceof Holder<?> holder) {
if (holder.isBound() && depth > 0) {
return value(holder.value(), depth - 1);
}
return holder.unwrapKey().<JsonElement>map(k -> new JsonPrimitive(k.identifier().toString())).orElse(JsonNull.INSTANCE);
} else if (v instanceof Optional<?> optional) {
return optional.isPresent() ? value(optional.get(), depth) : JsonNull.INSTANCE;
} else if (depth > 0 && v instanceof java.util.Map<?, ?> map) {
var o = new JsonObject();
for (var entry : map.entrySet()) {
var key = value(entry.getKey(), 0);
o.add(key.isJsonPrimitive() ? key.getAsString() : key.toString(), value(entry.getValue(), depth - 1));
}
return o;
} else if (depth > 0 && v.getClass().isRecord()) {
var o = new JsonObject();
for (RecordComponent component : v.getClass().getRecordComponents()) {
try {
component.getAccessor().setAccessible(true);
o.add(component.getName(), value(component.getAccessor().invoke(v), depth - 1));
} catch (Exception e) {
o.addProperty(component.getName(), "<error>");
}
}
return o;
} else if (depth > 0 && v instanceof SoundType sound) {
var o = new JsonObject();
o.addProperty("volume", sound.getVolume());
o.addProperty("pitch", sound.getPitch());
o.addProperty("break", sound.getBreakSound().location().toString());
o.addProperty("place", sound.getPlaceSound().location().toString());
return o;
} else if (v instanceof net.minecraft.core.particles.ParticleType<?> particle) {
return new JsonPrimitive(BuiltInRegistries.PARTICLE_TYPE.getKey(particle).toString());
} else if (depth > 0 && v.getClass().getName().startsWith("net.minecraft.world.level.block.grower.")) {
return fields(v, Object.class);
}
return new JsonPrimitive("<" + v.getClass().getSimpleName() + ">");
}
private static JsonObject fields(Object instance, Class<?> top) {
var o = new JsonObject();
for (Class<?> c = instance.getClass(); c != null && c != top; c = c.getSuperclass()) {
for (Field field : c.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers()) || o.has(field.getName())) {
continue;
}
try {
field.setAccessible(true);
o.add(field.getName(), value(field.get(instance), 3));
} catch (Exception e) {
o.addProperty(field.getName(), "<error>");
}
}
}
return o;
}
private static JsonArray chain(Class<?> c, Class<?> top) {
var result = new JsonArray();
for (; c != null && c != top; c = c.getSuperclass()) {
result.add(c.getSimpleName());
}
return result;
}
private static JsonArray blocks() {
var blocks = new JsonArray();
for (Block block : BuiltInRegistries.BLOCK) {
var o = new JsonObject();
o.addProperty("name", BuiltInRegistries.BLOCK.getKey(block).toString());
o.add("class", chain(block.getClass(), BlockBehaviour.class));
var interfaces = new JsonArray();
for (Class<?> c = block.getClass(); c != null; c = c.getSuperclass()) {
for (Class<?> i : c.getInterfaces()) {
interfaces.add(i.getSimpleName());
}
}
o.add("interfaces", interfaces);
o.add("fields", fields(block, Block.class));
o.addProperty("dynamic_shape", block.hasDynamicShape());
o.addProperty("item", BuiltInRegistries.ITEM.getKey(block.asItem()).toString());
blocks.add(o);
}
return blocks;
}
private static final SupportType[] SUPPORTS = {SupportType.FULL, SupportType.CENTER, SupportType.RIGID};
private static JsonArray states() {
var states = new JsonArray();
var level = EmptyBlockGetter.INSTANCE;
for (BlockState state : Block.BLOCK_STATE_REGISTRY) {
var o = new JsonArray();
int sturdy = 0;
for (int s = 0; s < SUPPORTS.length; s++) {
for (Direction d : Direction.values()) {
try {
if (state.isFaceSturdy(level, BlockPos.ZERO, d, SUPPORTS[s])) {
sturdy |= 1 << (s * 6 + d.ordinal());
}
} catch (Exception e) {
sturdy |= 1 << 30;
}
}
}
int flags = 0;
if (state.isSolid()) flags |= 1;
if (state.isAir()) flags |= 2;
try {
if (state.isRedstoneConductor(level, BlockPos.ZERO)) flags |= 4;
} catch (Exception e) {
flags |= 1 << 20;
}
if (state.isSignalSource()) flags |= 8;
if (state.hasAnalogOutputSignal()) flags |= 16;
try {
if (state.getCollisionShape(level, BlockPos.ZERO).isEmpty()) flags |= 32;
} catch (Exception e) {
flags |= 1 << 21;
}
try {
if (state.isSuffocating(level, BlockPos.ZERO)) flags |= 64;
} catch (Exception e) {
flags |= 1 << 22;
}
var fluid = state.getFluidState();
int fluidId = BuiltInRegistries.FLUID.getId(fluid.getType());
int fluidAmount = fluid.getAmount();
boolean falling = fluid.hasProperty(FlowingFluid.FALLING) && fluid.getValue(FlowingFluid.FALLING);
// Weak/strong signals over an empty level, packed 4 bits per direction.
long weak = 0;
long strong = 0;
boolean signalError = false;
if (state.isSignalSource()) {
for (Direction d : Direction.values()) {
try {
weak |= ((long) state.getSignal(level, BlockPos.ZERO, d) & 15) << (4 * d.ordinal());
strong |= ((long) state.getDirectSignal(level, BlockPos.ZERO, d) & 15) << (4 * d.ordinal());
} catch (Exception e) {
signalError = true;
}
}
}
o.add(sturdy);
o.add(flags);
o.add(fluidId);
o.add(fluidAmount);
o.add(falling);
o.add(weak);
o.add(strong);
o.add(signalError);
o.add(state.instrument().name());
states.add(o);
}
return states;
}
private static JsonObject items() {
var items = new JsonObject();
for (Item item : BuiltInRegistries.ITEM) {
if (!(item instanceof BlockItem)) {
continue;
}
var o = new JsonObject();
o.add("class", chain(item.getClass(), Item.class));
o.add("fields", fields(item, Item.class));
items.add(BuiltInRegistries.ITEM.getKey(item).toString(), o);
}
return items;
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
var result = new JsonObject();
result.add("blocks", blocks());
result.add("states", states());
result.add("items", items());
var fluids = new JsonArray();
for (Fluid fluid : BuiltInRegistries.FLUID) {
fluids.add(BuiltInRegistries.FLUID.getKey(fluid).toString());
}
result.add("fluids", fluids);
result.add("fire", fields(Blocks.FIRE, Block.class));
Files.writeString(Path.of(args[0]), new Gson().toJson(result), StandardCharsets.UTF_8);
}
}
@@ -0,0 +1,133 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.serialization.JsonOps;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.tags.*;
import net.minecraft.util.RandomSource;
import net.minecraft.world.attribute.EnvironmentAttributeReader;
import net.minecraft.world.level.*;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.ticks.LevelTickAccess;
import net.minecraft.world.ticks.TickPriority;
/**
* Native BlockState.updateShape and canSurvive over small generated neighbourhoods.
* The level is a reflective LevelReader over the case cells; scheduled ticks requested
* through ScheduledTickAccess are recorded instead of queued.
*/
public final class VanillaLevelShapeOracle {
static void bindFluidTags(Path dir) throws Exception {
var registry = BuiltInRegistries.FLUID;
var loader = new TagLoader<Holder<Fluid>>((id, required) -> registry.get(id).map(value -> (Holder<Fluid>) value), "tags/fluid");
var definitions = new HashMap<Identifier, List<TagLoader.EntryWithSource>>();
try (var files = Files.list(dir)) {
for (var file : (Iterable<Path>) files::iterator) {
var name = file.getFileName().toString().replace(".json", "");
var parsed = TagFile.CODEC.parse(JsonOps.INSTANCE, JsonParser.parseString(Files.readString(file))).getOrThrow();
var entries = new ArrayList<TagLoader.EntryWithSource>();
for (var entry : parsed.entries()) entries.add(new TagLoader.EntryWithSource(entry, "vanilla"));
definitions.put(Identifier.parse("minecraft:" + name), entries);
}
}
var tags = new HashMap<TagKey<Fluid>, List<Holder<Fluid>>>();
loader.build(definitions).forEach((id, values) -> tags.put(TagKey.create(Registries.FLUID, id), List.copyOf(values)));
registry.prepareTagReload(new TagLoader.LoadResult<>(Registries.FLUID, tags)).apply();
}
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();
net.minecraft.server.Bootstrap.bootStrap();
Path resources = Path.of(args[0]);
VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(resources.resolve("block-tags.json"))).getAsJsonObject());
bindFluidTags(resources.resolve("data/minecraft/tags/fluid"));
var registryAccess = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY);
var air = net.minecraft.world.level.block.Blocks.AIR.defaultBlockState();
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2]))); var lines = Files.lines(Path.of(args[1]))) {
for (var line : (Iterable<String>) lines::iterator) {
var f = JsonParser.parseString(line).getAsJsonObject();
var cells = new HashMap<BlockPos, BlockState>();
for (var cell : f.getAsJsonArray("cells")) {
var c = cell.getAsJsonArray();
cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), Block.stateById(c.get(3).getAsInt()));
}
int light = f.get("light").getAsInt();
var noTicks = (LevelTickAccess<?>) Proxy.newProxyInstance(LevelTickAccess.class.getClassLoader(), new Class<?>[]{LevelTickAccess.class}, (proxy, method, values) -> {
if (method.getReturnType() == boolean.class) return false;
if (method.getReturnType() == int.class) return 0;
return null;
});
var level = (LevelReader) Proxy.newProxyInstance(LevelReader.class.getClassLoader(), new Class<?>[]{LevelReader.class}, (proxy, method, values) -> {
switch (method.getName()) {
case "getBlockState": return cells.getOrDefault((BlockPos) values[0], air);
case "getFluidState": return cells.getOrDefault((BlockPos) values[0], air).getFluidState();
case "getBlockEntity": return null;
case "getRawBrightness": return Math.max(0, light - (int) values[1]);
case "getMaxLocalRawBrightness": return light;
case "getBrightness": return light;
case "isClientSide": return false;
case "registryAccess": return registryAccess;
case "enabledFeatures": return net.minecraft.world.flag.FeatureFlags.DEFAULT_FLAGS;
case "environmentAttributes": return EnvironmentAttributeReader.EMPTY;
case "getMinY": return -64;
case "getHeight": return values == null || values.length == 0 ? 384 : null;
case "getSkyDarken": return 0;
case "hashCode": return System.identityHashCode(proxy);
case "equals": return proxy == values[0];
default:
if (method.isDefault()) return InvocationHandler.invokeDefault(proxy, method, values);
throw new AssertionError(method.toString());
}
});
var scheduled = new TreeSet<String>();
var ticks = (ScheduledTickAccess) Proxy.newProxyInstance(ScheduledTickAccess.class.getClassLoader(), new Class<?>[]{ScheduledTickAccess.class}, (proxy, method, values) -> {
switch (method.getName()) {
case "scheduleTick": {
var pos = (BlockPos) values[0];
String type = values[1] instanceof Block block ? BuiltInRegistries.BLOCK.getKey(block).toString() : BuiltInRegistries.FLUID.getKey((Fluid) values[1]).toString();
int priority = values.length > 3 ? ((TickPriority) values[3]).getValue() : 0;
scheduled.add(type + "@" + pos.getX() + "," + pos.getY() + "," + pos.getZ() + "+" + values[2] + "p" + priority);
return null;
}
case "getBlockTicks":
case "getFluidTicks":
return noTicks;
default:
throw new AssertionError(method.toString());
}
});
RandomSource random = new LegacyRandomSource(f.get("seed").getAsLong());
var p = f.getAsJsonArray("pos");
var pos = new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt());
var state = cells.getOrDefault(pos, air);
var direction = Direction.from3DDataValue(f.get("dir").getAsInt());
var neighbourPos = pos.relative(direction);
String shape;
try {
var result = state.updateShape(level, ticks, pos, direction, neighbourPos, level.getBlockState(neighbourPos), random);
shape = Integer.toString(Block.getId(result));
} catch (RuntimeException | AssertionError e) {
shape = "error " + e.getClass().getSimpleName();
}
String survive;
try {
survive = Boolean.toString(state.canSurvive(level, pos));
} catch (RuntimeException | AssertionError e) {
survive = "error";
}
out.println("shape " + shape + " ticks " + String.join(" ", scheduled) + " survive " + survive);
}
}
}
}
@@ -1,100 +1,159 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.serialization.JsonOps;
import java.io.*;
import java.lang.reflect.Proxy;
import java.lang.reflect.InvocationHandler;
import java.nio.charset.StandardCharsets;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.*;
import net.minecraft.world.level.biome.*;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.levelgen.*;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunctions;
import net.minecraft.world.level.levelgen.material.rule.BlockRule;
import net.minecraft.world.level.levelgen.placement.*;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.CollisionContext;
/** Original transport invoking actual placement codecs and modifier callbacks. */
/**
* Native BlockItem placement-state selection (BlockPlaceContext resolution,
* updatePlacementContext and getPlacementState) over generated neighbourhoods.
* Entities never obstruct; nothing is written to the world.
*/
public final class VanillaPlacementOracle {
private static final class Stop extends RuntimeException {}
private static PlacementContext context(JsonObject f) {return context(f,null);}
private static PlacementContext context(JsonObject f,PrintWriter out) {
var v=f.getAsJsonArray("context");int min=v.get(0).getAsInt(),height=v.get(1).getAsInt(),sea=v.get(2).getAsInt();
var zero=DensityFunctions.zero();
var settings=new NoiseGeneratorSettings(new NoiseSettings(min,height),Blocks.STONE.defaultBlockState(),Blocks.WATER.defaultBlockState(),new NoiseRouter(zero,zero,zero,zero,zero,zero,zero,zero),Holder.direct(new BlockRule(Blocks.STONE.defaultBlockState())),List.of(),sea,false,Optional.empty(),false,NoiseGeneratorSettings.DebugFunctions.EMPTY);
var biome=Holder.Reference.createStandAlone(new HolderOwner<Biome>(){},Biomes.PLAINS);
var generator=new NoiseBasedChunkGenerator(new FixedBiomeSource(biome),Holder.direct(settings));
int worldMin=f.has("world_min")?f.get("world_min").getAsInt():min;int mode=f.has("height_mode")?f.get("height_mode").getAsInt():0;int fail=f.has("query_fail")?f.get("query_fail").getAsInt():-1;int[] calls={0};boolean layerWorld=f.has("layer_world")&&f.get("layer_world").getAsBoolean();
var level=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class<?>[]{WorldGenLevel.class},(proxy,method,args)->switch(method.getName()) {
case "isInsideBuildHeight"->{
if(args[0] instanceof BlockPos p) {
if(out!=null)out.println("inside "+p.getX()+" "+p.getY()+" "+p.getZ());
if(calls[0]++==fail)throw new IllegalArgumentException("bounds query failure");
var result=InvocationHandler.invokeDefault(proxy,method,args);
if(out!=null)out.println("bounds_result "+result);yield result;
}
yield InvocationHandler.invokeDefault(proxy,method,args);
}
case "isOutsideBuildHeight"->{
if(out!=null)out.println("outside "+args[0]);
if(calls[0]++==fail)throw new IllegalArgumentException("bounds query failure");
var result=InvocationHandler.invokeDefault(proxy,method,args);
if(out!=null)out.println("bounds_result "+result);yield result;
}
case "getMaxY"->InvocationHandler.invokeDefault(proxy,method,args);
case "getMinY"->worldMin;
case "getHeight"->{
if(args==null||args.length==0)yield height;
var kind=(Heightmap.Types)args[0];int x=(Integer)args[1],z=(Integer)args[2];
if(out!=null)out.println("height "+kind.name()+" "+x+" "+z);
if(calls[0]++==fail)throw new IllegalArgumentException("height query failure");
int result;
if(layerWorld)result=min+24+((x^z)&3);
else if(mode==0)result=min+Math.floorMod(x*31+z*17+kind.ordinal()*7,129)-64;
else {int[] values={Integer.MIN_VALUE,Integer.MAX_VALUE,0,-1,min,min+1};result=values[(kind.ordinal()+((x^z)&3))%6];}
if(out!=null)out.println("height_result "+result);yield result;
}
case "getBlockState"->{
var p=(BlockPos)args[0];if(out!=null)out.println("block "+p.getX()+" "+p.getY()+" "+p.getZ());
if(calls[0]++==fail)throw new IllegalArgumentException("block query failure");
var blocks=new net.minecraft.world.level.block.Block[]{Blocks.BEDROCK,Blocks.STONE,Blocks.AIR,Blocks.WATER,Blocks.DIRT,Blocks.CAVE_AIR,Blocks.LAVA,Blocks.BUBBLE_COLUMN,Blocks.VOID_AIR,Blocks.GRASS_BLOCK,Blocks.AIR,Blocks.WATER};
int index=p.getY()<=min?0:Math.floorMod(p.getY()-min+((p.getX()*31+p.getZ()*17)&3),12);
var block=blocks[index];if(out!=null)out.println("block_result "+net.minecraft.core.registries.BuiltInRegistries.BLOCK.getKey(block));yield block.defaultBlockState();
}
case "getSeaLevel"->sea;
default->throw new AssertionError("unexpected world method "+method);
});
var context=new PlacementContext(level,generator,Optional.empty());return context;
static Object unsafe;
static Method allocate;
static int errors;
static final Set<BlockItem> bound = new HashSet<>();
static <T> T make(Class<T> type) {
try {
return type.cast(allocate.invoke(unsafe, type));
} catch (Exception e) {
throw new AssertionError(e);
}
}
static final class FakePlayer extends ServerPlayer {
float yaw, pitch;
boolean sneak;
World world;
ItemStack held;
FakePlayer() {
super(null, null, null, null);
}
@Override public float getViewXRot(final float a) { return pitch; }
@Override public float getViewYRot(final float a) { return yaw; }
@Override public float getXRot() { return pitch; }
@Override public float getYRot() { return yaw; }
@Override public Direction getDirection() { return Direction.fromYRot(yaw); }
@Override public boolean isSecondaryUseActive() { return sneak; }
@Override public boolean isShiftKeyDown() { return sneak; }
@Override public boolean isDescending() { return sneak; }
@Override public ItemStack getMainHandItem() { return held; }
@Override public boolean canUseGameMasterBlocks() { return false; }
@Override public net.minecraft.server.level.ServerLevel level() { return world; }
}
static final class World extends net.minecraft.server.level.ServerLevel {
Map<BlockPos, BlockState> cells;
RandomSource random;
World() {
super(null, null, null, null, null, null, false, 0L, List.of(), false);
}
@Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, net.minecraft.world.level.block.Blocks.AIR.defaultBlockState()); }
@Override public FluidState getFluidState(BlockPos p) { return getBlockState(p).getFluidState(); }
@Override public net.minecraft.world.level.block.entity.BlockEntity getBlockEntity(BlockPos p) { return null; }
@Override public boolean isClientSide() { return false; }
@Override public RandomSource getRandom() { return random; }
@Override public int getMinY() { return -64; }
@Override public int getHeight() { return 384; }
@Override public boolean isUnobstructed(BlockState state, BlockPos pos, CollisionContext context) { return true; }
@Override public boolean isUnobstructed(Entity entity) { return true; }
@Override public void scheduleTick(BlockPos pos, Block block, int delay) { }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.DEFAULT_FLAGS; }
@Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { return new net.minecraft.world.level.border.WorldBorder(); }
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, BlockPos p, net.minecraft.world.level.gameevent.GameEvent.Context c) { }
@Override public int getSeaLevel() { return 63; }
@Override public int getBrightness(net.minecraft.world.level.LightLayer layer, BlockPos p) { return layer == net.minecraft.world.level.LightLayer.SKY ? 15 : 0; }
@Override public int getRawBrightness(BlockPos p, int darkening) { return 15 - darkening; }
@Override public int getSkyDarken() { return 0; }
@Override public List<Entity> getEntities(Entity except, net.minecraft.world.phys.AABB box, java.util.function.Predicate<? super Entity> filter) { return List.of(); }
}
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]);
try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) {
for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) {
var f=JsonParser.parseString(line).getAsJsonObject();var context=context(f,out);long seed=f.get("seed").getAsLong();
RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed);
Optional<PlacementModifier> decoded;
try {decoded=PlacementModifier.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(f.get("definition").getAsString())).result();}catch(IllegalArgumentException error){decoded=Optional.empty();}
if(decoded.isEmpty())out.println("decode error");else {
out.println("decode ok");var provider=decoded.get();
for(var value:f.getAsJsonArray("positions")) {
var p=value.getAsJsonArray();var position=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt());
if(f.has("count_only")&&f.get("count_only").getAsBoolean()) {
try {out.println("count "+((RepeatingPlacement)provider).count(random,position));}catch(IllegalArgumentException error){out.println("count error");}
out.println("next "+random.nextLong());continue;
net.minecraft.SharedConstants.tryDetectVersion();
net.minecraft.server.Bootstrap.bootStrap();
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"));
var position = Entity.class.getDeclaredField("position");
position.setAccessible(true);
var allocator = Class.forName("sun.misc.Unsafe");
var field = allocator.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = field.get(null);
allocate = allocator.getMethod("allocateInstance", Class.class);
Method getPlacementState = BlockItem.class.getDeclaredMethod("getPlacementState", BlockPlaceContext.class);
getPlacementState.setAccessible(true);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2]))); var lines = Files.lines(Path.of(args[1]))) {
for (var line : (Iterable<String>) lines::iterator) {
var f = JsonParser.parseString(line).getAsJsonObject();
var world = make(World.class);
world.cells = new HashMap<>();
for (var cell : f.getAsJsonArray("cells")) {
var c = cell.getAsJsonArray();
world.cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), Block.stateById(c.get(3).getAsInt()));
}
world.random = new LegacyRandomSource(f.get("seed").getAsLong());
var player = make(FakePlayer.class);
player.world = world;
player.yaw = f.get("yaw").getAsFloat();
player.pitch = f.get("pitch").getAsFloat();
player.sneak = f.get("sneak").getAsBoolean();
position.set(player, Vec3.ZERO);
var item = (BlockItem) BuiltInRegistries.ITEM.getValue(Identifier.parse(f.get("item").getAsString()));
if (bound.add(item)) {
item.builtInRegistryHolder().bindComponents(net.minecraft.core.component.DataComponentMap.EMPTY);
}
var h = f.getAsJsonArray("hit");
var p = f.getAsJsonArray("pos");
var hit = new BlockHitResult(new Vec3(h.get(0).getAsDouble(), h.get(1).getAsDouble(), h.get(2).getAsDouble()),
Direction.from3DDataValue(f.get("face").getAsInt()), new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt()), false);
String result;
try {
player.held = new ItemStack(item);
var context = new BlockPlaceContext(player, InteractionHand.MAIN_HAND, player.held, hit);
if (!context.canPlace()) {
result = "none";
} else {
var updated = item.updatePlacementContext(context);
if (updated == null) {
result = "none";
} else {
var state = (BlockState) getPlacementState.invoke(item, updated);
var at = updated.getClickedPos();
result = state == null ? "none" : at.getX() + "," + at.getY() + "," + at.getZ() + " " + Block.getId(state);
}
int[] count={0};int fail=f.get("fail").getAsInt();boolean draw=f.get("draw").getAsBoolean();
try {provider.modify(context,random,position,result->{
if(count[0]++==fail)throw new Stop();
out.println("position "+result.getX()+" "+result.getY()+" "+result.getZ());
if(draw)out.println("consumer "+random.nextLong());
});out.println("modify ok");}catch(Stop|IllegalArgumentException error){out.println("modify error");}
out.println("next "+random.nextLong());
}
} catch (Exception | AssertionError e) {
Throwable cause = e instanceof java.lang.reflect.InvocationTargetException ite ? ite.getCause() : e;
result = "error " + cause.getClass().getSimpleName();
if (errors++ < 3) {
cause.printStackTrace();
}
}
out.println("tail "+random.nextLong());
out.println("place " + result);
}
}
}
+17
View File
@@ -248,6 +248,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.
@@ -289,6 +305,7 @@ def main():
'model_state_exporters_sha256': binding_sources,
'gameplay_exporters_sha256': gameplay_sources,
'entity_model_exporters_sha256': entity_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})
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Compare horizon-world's placement port (BlockItem placement state) with pinned vanilla.
Generates random neighbourhoods and use-item-on-block actions for random block
items, resolves the placed position and state with the native oracle
(VanillaPlacementOracle) and with Behaviours (level_place_fixture), and reports
differing cases grouped by item.
"""
import argparse
import json
import os
import random
import subprocess
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
# Items whose placement reads block-entity data or entities.
SKIP = {'minecraft:lectern', 'minecraft:test_block', 'minecraft:moving_piston'}
def generate(resources, count, seed):
facts = json.loads((resources / 'facts.json').read_text())
behaviours = json.loads((resources / 'block-behaviours.json').read_text())
by_block = {}
for index, state in enumerate(facts['states']):
by_block.setdefault(state[0], []).append(index)
items = sorted(name for name, item in behaviours['items'].items() if name not in SKIP and item['fields'].get('block') in by_block)
names = list(by_block)
common = [by_block[name][0] for name in ['minecraft:stone', 'minecraft:dirt', 'minecraft:grass_block', 'minecraft:water',
'minecraft:oak_planks', 'minecraft:glass', 'minecraft:sand', 'minecraft:oak_log']]
rng = random.Random(seed)
cases = []
for _ in range(count):
item = rng.choice(items)
block = behaviours['items'][item]['fields']['block']
related = by_block[block]
cells = []
for x in range(-2, 3):
for y in range(-2, 3):
for z in range(-2, 3):
roll = rng.random()
if (x, y, z) == (0, 0, 0):
roll = rng.random() * 1.2
if roll < 0.35:
continue
if roll < 0.6:
cells.append([x, y, z, rng.choice(common)])
elif roll < 0.8:
cells.append([x, y, z, rng.choice(related)])
else:
cells.append([x, y, z, rng.choice(by_block[rng.choice(names)])])
face = rng.randrange(6)
normal = [(0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1), (-1, 0, 0), (1, 0, 0)][face]
hit = []
for axis in range(3):
if normal[axis] < 0:
hit.append(0.0)
elif normal[axis] > 0:
hit.append(1.0)
else:
hit.append(rng.choice([0.5, rng.random()]))
cases.append({'seed': rng.randrange(1 << 40), 'item': item, 'pos': [0, 0, 0], 'face': face, 'hit': hit,
'yaw': rng.randrange(-180 * 64, 180 * 64) / 64, 'pitch': rng.randrange(-90 * 64, 90 * 64) / 64,
'sneak': rng.random() < 0.2, 'cells': cells})
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', type=int, default=20000)
parser.add_argument('--seed', type=int, default=1)
args = parser.parse_args()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
work = lab.LOCAL / 'level-place-parity'
work.mkdir(parents=True, exist_ok=True)
cases = generate(resources, args.count, args.seed)
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in cases))
classes = work / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
parity = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
sources = [parity / 'VanillaPlacementOracle.java', parity / 'VanillaHeightmapOracle.java', parity / 'VanillaLevelShapeOracle.java']
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-cp', dependencies,
'-d', str(classes), *map(str, sources)], check=True)
subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies,
'dev.horizonlab.parity.VanillaPlacementOracle', str(resources), str(work / 'cases.jsonl'),
str(work / 'native.txt')], check=True)
subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'level_place_fixture', '--',
str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT)
native = (work / 'native.txt').read_text().splitlines()
rust = (work / 'rust.txt').read_text().splitlines()
differences = {}
for case, a, b in zip(cases, native, rust):
if a != b:
differences.setdefault(case['item'], []).append((case, a, b))
total = sum(len(v) for v in differences.values())
facts = json.loads((resources / 'facts.json').read_text())['states']
def describe(line):
parts = line.split()
return line if len(parts) < 3 or not parts[2].isdigit() else f'{parts[1]} {facts[int(parts[2])][3]}'
for item, entries in sorted(differences.items(), key=lambda entry: -len(entry[1])):
case, a, b = entries[0]
print(f'{item}: {len(entries)} differing; e.g. face={case["face"]} yaw={case["yaw"]} pitch={case["pitch"]} sneak={case["sneak"]}'
f'\n native {describe(a)}\n rust {describe(b)}')
print(f'{len(cases) - total}/{len(cases)} cases match')
(work / 'differences.json').write_text(json.dumps({k: [[c, a, b] for c, a, b in v[:5]] for k, v in differences.items()}))
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Compare horizon-world's level updateShape/canSurvive port with pinned vanilla.
Generates random 5x5x5 neighbourhoods around a random block state, evaluates
BlockState.updateShape towards one neighbour and canSurvive with the native
oracle (VanillaLevelShapeOracle) and with Behaviours (level_shape_fixture),
and reports every differing case.
"""
import argparse
import json
import os
import random
import subprocess
from pathlib import Path
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
# Blocks whose updateShape needs a full level (portal frames) are skipped.
SKIP = {'minecraft:nether_portal', 'minecraft:moving_piston'}
def generate(resources, count, seed):
facts = json.loads((resources / 'facts.json').read_text())
states = facts['states']
by_block = {}
for index, state in enumerate(states):
by_block.setdefault(state[0], []).append(index)
names = [name for name in by_block if name not in SKIP]
common = [by_block[name][0] for name in ['minecraft:stone', 'minecraft:dirt', 'minecraft:grass_block', 'minecraft:water',
'minecraft:oak_planks', 'minecraft:glass', 'minecraft:sand', 'minecraft:farmland']]
rng = random.Random(seed)
cases = []
for _ in range(count):
block = rng.choice(names)
center = rng.choice(by_block[block])
related = by_block[block]
cells = []
for x in range(-2, 3):
for y in range(-2, 3):
for z in range(-2, 3):
if (x, y, z) == (0, 0, 0):
cells.append([0, 0, 0, center])
continue
roll = rng.random()
if roll < 0.35:
continue
if roll < 0.55:
cells.append([x, y, z, rng.choice(common)])
elif roll < 0.75:
cells.append([x, y, z, rng.choice(related)])
else:
other = rng.choice(names)
cells.append([x, y, z, rng.choice(by_block[other])])
cases.append({'seed': rng.randrange(1 << 40), 'light': rng.randrange(16), 'pos': [0, 0, 0],
'dir': rng.randrange(6), 'cells': cells, 'block': block})
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', type=int, default=20000)
parser.add_argument('--seed', type=int, default=1)
args = parser.parse_args()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
work = lab.LOCAL / 'level-shape-parity'
work.mkdir(parents=True, exist_ok=True)
cases = generate(resources, args.count, args.seed)
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in cases))
classes = work / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
parity = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
sources = [parity / 'VanillaLevelShapeOracle.java', parity / 'VanillaHeightmapOracle.java']
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies,
'-d', str(classes), *map(str, sources)], check=True)
subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies,
'dev.horizonlab.parity.VanillaLevelShapeOracle', str(resources), str(work / 'cases.jsonl'),
str(work / 'native.txt')], check=True)
subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'level_shape_fixture', '--',
str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT)
native = (work / 'native.txt').read_text().splitlines()
rust = (work / 'rust.txt').read_text().splitlines()
differences = {}
for case, a, b in zip(cases, native, rust):
if a != b:
differences.setdefault(case['block'], []).append((case, a, b))
total = sum(len(v) for v in differences.values())
for block, items in sorted(differences.items(), key=lambda item: -len(item[1])):
case, a, b = items[0]
print(f'{block}: {len(items)} differing; e.g. dir={case["dir"]}\n native {a}\n rust {b}')
print(f'{len(cases) - total}/{len(cases)} cases match')
(work / 'differences.json').write_text(json.dumps({k: [[c, a, b] for c, a, b in v[:5]] for k, v in differences.items()}))
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()