From f79b6aacedbc7a4867595522c13b1853f0660e32 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:23:56 +0200 Subject: [PATCH] WIP: checkpoint interrupted agent work Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/horizon-world/src/fluid.rs | 11 + crates/horizon-world/src/level/classes.rs | 340 +++++++ crates/horizon-world/src/level/data.rs | 939 ++++++++++++++++++ crates/horizon-world/src/level/mod.rs | 351 +++++++ crates/horizon-world/src/level/query.rs | 183 ++++ crates/horizon-world/src/level/states.rs | 318 ++++++ crates/horizon-world/src/level/survive.rs | 499 ++++++++++ crates/horizon-world/src/level/ticks.rs | 100 ++ crates/horizon-world/src/level/update.rs | 459 +++++++++ .../parity/VanillaBlockBehaviourExporter.java | 255 +++++ 10 files changed, 3455 insertions(+) create mode 100644 crates/horizon-world/src/level/classes.rs create mode 100644 crates/horizon-world/src/level/data.rs create mode 100644 crates/horizon-world/src/level/mod.rs create mode 100644 crates/horizon-world/src/level/query.rs create mode 100644 crates/horizon-world/src/level/states.rs create mode 100644 crates/horizon-world/src/level/survive.rs create mode 100644 crates/horizon-world/src/level/ticks.rs create mode 100644 crates/horizon-world/src/level/update.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockBehaviourExporter.java diff --git a/crates/horizon-world/src/fluid.rs b/crates/horizon-world/src/fluid.rs index 4e08a5145..4a89764a8 100644 --- a/crates/horizon-world/src/fluid.rs +++ b/crates/horizon-world/src/fluid.rs @@ -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, diff --git a/crates/horizon-world/src/level/classes.rs b/crates/horizon-world/src/level/classes.rs new file mode 100644 index 000000000..764edbebe --- /dev/null +++ b/crates/horizon-world/src/level/classes.rs @@ -0,0 +1,340 @@ +//! 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(u8)] + pub enum Class { $($name,)* } + impl Class { + pub const ALL: &'static [Class] = &[$(Class::$name,)*]; + pub fn from_java(name: &str) -> Option { + 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", + 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 { + 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; 4]); +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 + } +} diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs new file mode 100644 index 000000000..6b3c429f1 --- /dev/null +++ b/crates/horizon-world/src/level/data.rs @@ -0,0 +1,939 @@ +//! Behaviour tables built once from the pinned client resources. +use super::{ + Behaviours, + classes::{Class, ClassSet, Interface}, + states::{BlockId, PropKey, StateTable}, +}; +use crate::{ + collision::CachedCollisionRegistry, + compression::invalid, + fluid::{FluidBlockBindings, FluidKind, FluidState}, + nbt::{self, Limits}, + registry::{BlockRegistry, BlockStateId}, + worldgen::tags::TagDefinitions, +}; +use horizon_core::geometry::{Aabb, Direction, ShapeOp, Vec3, VoxelShape}; +use serde_json::Value; +use std::{ + collections::HashMap, + fs::{self, File}, + io::{self, BufReader}, + path::Path, + sync::Arc, +}; + +/// Per-state flags read from vanilla accessors over an empty level. +pub mod state_flags { + pub const SOLID: u32 = 1; + pub const AIR: u32 = 1 << 1; + pub const CONDUCTOR: u32 = 1 << 2; + pub const SIGNAL_SOURCE: u32 = 1 << 3; + pub const ANALOG_OUTPUT: u32 = 1 << 4; + pub const COLLISION_EMPTY: u32 = 1 << 5; + pub const SUFFOCATING: u32 = 1 << 6; + pub const REPLACEABLE: u32 = 1 << 7; + pub const RANDOM_TICKS: u32 = 1 << 8; + pub const SOLID_RENDER: u32 = 1 << 9; + pub const LIQUID: u32 = 1 << 10; + pub const BLOCK_ENTITY: u32 = 1 << 11; + pub const IGNITED_BY_LAVA: u32 = 1 << 12; + pub const CAN_OCCLUDE: u32 = 1 << 13; + pub const FULL_COLLISION: u32 = 1 << 14; + pub const SKYLIGHT_DOWN: u32 = 1 << 15; + pub const REQUIRES_TOOL: u32 = 1 << 16; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PushReaction { + Normal, + Destroy, + Block, + Ignore, + PushOnly, +} + +#[derive(Clone, Copy, Debug)] +pub struct StateFacts { + pub flags: u32, + /// isFaceSturdy bits: support type (FULL, CENTER, RIGID) * 6 + direction. + pub sturdy: u32, + /// getSignal / getDirectSignal over an empty level, 4 bits per direction. + pub weak: u32, + pub strong: u32, + pub fluid: FluidState, + pub emission: u8, + pub dampening: u8, + pub hardness: f32, + pub push: PushReaction, + pub instrument: u8, + /// Index into `Behaviours::shapes`, or -1 for an uncached (dynamic) shape. + pub shape: i32, +} + +#[derive(Clone, Debug)] +pub struct SetType { + pub name: Box, + pub can_open_by_hand: bool, + pub can_open_by_wind_charge: bool, + pub arrows: bool, + /// true: MOBS sensitivity (living entities only); false: EVERYTHING. + pub mobs_only: bool, + pub door_open: Arc, + pub door_close: Arc, + pub trapdoor_open: Arc, + pub trapdoor_close: Arc, + pub plate_on: Arc, + pub plate_off: Arc, + pub button_on: Arc, + pub button_off: Arc, +} + +#[derive(Clone, Debug)] +pub struct Sounds { + pub volume: f32, + pub pitch: f32, + pub place: Arc, + pub break_: Arc, + pub fall: Arc, +} + +/// Precomputed queries over one cached collision shape. +#[derive(Clone, Copy, Debug, Default)] +pub struct ShapeInfo { + /// `Block.isFaceFull(shape, direction)` per direction bit. + pub full_faces: u8, + /// `!shape.getFaceShape(direction).isEmpty()` per direction bit. + pub nonempty_faces: u8, + /// WallBlock `isCovered(shape.getFaceShape(DOWN), test)` for the post (bit 0) + /// and the north/east/south/west wall tests (bits 1..=4). + pub wall_cover: u8, +} + +fn analyse_shape(shape: &VoxelShape) -> io::Result { + let err = |e: horizon_core::geometry::ShapeError| invalid(e.to_string()); + let mut info = ShapeInfo::default(); + let block = VoxelShape::block(); + for direction in Direction::ALL { + let face = shape.face_shape(direction).map_err(err)?; + if !block.join_is_not_empty(&face, ShapeOp::XOR).map_err(err)? { + info.full_faces |= 1 << direction as u8; + } + if !face.is_empty() { + info.nonempty_faces |= 1 << direction as u8; + } + } + let above = shape.face_shape(Direction::Down).map_err(err)?; + let px = |v: f64| v / 16.0; + let tests = [ + (7.0, 7.0, 9.0, 9.0), + (7.0, 0.0, 9.0, 9.0), + (7.0, 7.0, 16.0, 9.0), + (7.0, 7.0, 9.0, 16.0), + (0.0, 7.0, 9.0, 9.0), + ]; + for (bit, (x0, z0, x1, z1)) in tests.into_iter().enumerate() { + let test = VoxelShape::from_box(Aabb::new(Vec3::new(px(x0), 0.0, px(z0)), Vec3::new(px(x1), 1.0, px(z1)))).map_err(err)?; + if !test.join_is_not_empty(&above, ShapeOp::ONLY_FIRST).map_err(err)? { + info.wall_cover |= 1 << bit; + } + } + Ok(info) +} + +/// Fluid tags as masks over `FluidKind::mask`. +#[derive(Clone, Copy, Debug, Default)] +pub struct FluidTags { + pub water: u8, + pub lava: u8, + pub supports_frogspawn: u8, + pub supports_lily_pad: u8, + pub supports_sugar_cane_adjacently: u8, + pub bubble_column_can_occupy: u8, +} + +/// A set of blocks (a resolved block tag). +#[derive(Clone, Debug, Default)] +pub struct BlockSet(Vec); +impl BlockSet { + pub fn with_capacity(blocks: usize) -> Self { + Self(vec![0; blocks.div_ceil(64)]) + } + pub fn insert(&mut self, block: BlockId) { + let i = block.0 as usize; + if i / 64 >= self.0.len() { + self.0.resize(i / 64 + 1, 0); + } + self.0[i / 64] |= 1 << (i % 64); + } + pub fn contains(&self, block: BlockId) -> bool { + let i = block.0 as usize; + self.0.get(i / 64).is_some_and(|w| w & (1 << (i % 64)) != 0) + } +} + +#[derive(Clone, Debug)] +pub struct BlockData { + pub class: Class, + /// Recognised classes of the Java class chain, most derived first; ported + /// overrides dispatch along it so `super` calls reach the next override. + pub chain: Vec, + pub classes: ClassSet, + pub interfaces: u16, + pub set_type: Option>, + pub gate_open: Option>, + pub gate_close: Option>, + pub open_sound: Option>, + pub close_sound: Option>, + pub ticks_to_stay_pressed: i32, + pub max_weight: i32, + /// Block-valued configuration: concrete (powder), fruit (stems), potted + /// content, dead coral, stair base, candle (candle cakes), required nylium. + pub link: Option, + /// Second block link: attached stem (stems) or stem (attached stems). + pub link2: Option, + pub support_tag: Option>, + pub support_tag2: Option>, + pub feature: Option>, + pub grow_probability: f64, + pub growth_direction: Direction, + pub schedule_fluid_ticks: bool, + pub weather: u8, + pub ignite_odds: i32, + pub burn_odds: i32, + pub sounds: Arc, + pub item: Arc, + pub dynamic_shape: bool, +} +impl BlockData { + pub fn is(&self, class: Class) -> bool { + self.class == class || self.classes.contains(class) + } + pub fn implements(&self, interface: Interface) -> bool { + self.interfaces & interface.mask() != 0 + } +} + +/// Item-to-block placement bindings (BlockItem and its subclasses). +#[derive(Clone, Debug)] +pub struct ItemBinding { + pub block: BlockId, + pub wall_block: Option, + /// StandingAndWallBlockItem.attachmentDirection (DOWN for torches/signs, UP for hanging signs). + pub attachment: Option, + pub kind: ItemKind, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ItemKind { + Block, + DoubleHigh, + StandingAndWall, + Bed, + Scaffolding, + PlaceOnWater, + Sign, + HangingSign, + SolidBucket, + Other, +} + +macro_rules! named_blocks { + ($($field:ident = $name:literal,)*) => { + /// Blocks referenced by identity in vanilla code (`Blocks.X`). + #[derive(Clone, Copy, Debug)] + pub struct Named { $(pub $field: BlockId,)* } + impl Named { + fn resolve(table: &StateTable) -> io::Result { + Ok(Self { $($field: table.block_by_name(concat!("minecraft:", $name)).ok_or_else(|| invalid(concat!("missing block ", $name)))?,)* }) + } + } + }; +} +named_blocks! { + air = "air", + cave_air = "cave_air", + void_air = "void_air", + water = "water", + lava = "lava", + stone = "stone", + cobblestone = "cobblestone", + obsidian = "obsidian", + basalt = "basalt", + soul_soil = "soul_soil", + blue_ice = "blue_ice", + ice = "ice", + frosted_ice = "frosted_ice", + snow = "snow", + snow_block = "snow_block", + powder_snow = "powder_snow", + dirt = "dirt", + grass_block = "grass_block", + mycelium = "mycelium", + podzol = "podzol", + farmland = "farmland", + dirt_path = "dirt_path", + mud = "mud", + clay = "clay", + sponge = "sponge", + wet_sponge = "wet_sponge", + fire = "fire", + soul_fire = "soul_fire", + redstone_wire = "redstone_wire", + comparator = "comparator", + repeater = "repeater", + redstone_torch = "redstone_torch", + redstone_wall_torch = "redstone_wall_torch", + redstone_block = "redstone_block", + redstone_lamp = "redstone_lamp", + observer = "observer", + piston = "piston", + sticky_piston = "sticky_piston", + piston_head = "piston_head", + moving_piston = "moving_piston", + tnt = "tnt", + magma_block = "magma_block", + soul_sand = "soul_sand", + bubble_column = "bubble_column", + kelp = "kelp", + kelp_plant = "kelp_plant", + seagrass = "seagrass", + tall_seagrass = "tall_seagrass", + cactus = "cactus", + cactus_flower = "cactus_flower", + sugar_cane = "sugar_cane", + bamboo = "bamboo", + bamboo_sapling = "bamboo_sapling", + scaffolding = "scaffolding", + melon = "melon", + pumpkin = "pumpkin", + carved_pumpkin = "carved_pumpkin", + jack_o_lantern = "jack_o_lantern", + barrier = "barrier", + cake = "cake", + flower_pot = "flower_pot", + cauldron = "cauldron", + water_cauldron = "water_cauldron", + lava_cauldron = "lava_cauldron", + powder_snow_cauldron = "powder_snow_cauldron", + dragon_egg = "dragon_egg", + tripwire = "tripwire", + tripwire_hook = "tripwire_hook", + slime_block = "slime_block", + honey_block = "honey_block", + hopper = "hopper", + note_block = "note_block", + chorus_plant = "chorus_plant", + chorus_flower = "chorus_flower", + end_stone = "end_stone", + vine = "vine", + lily_pad = "lily_pad", + small_dripleaf = "small_dripleaf", + big_dripleaf = "big_dripleaf", + big_dripleaf_stem = "big_dripleaf_stem", + pointed_dripstone = "pointed_dripstone", + ladder = "ladder", + sweet_berry_bush = "sweet_berry_bush", + torchflower = "torchflower", + pitcher_plant = "pitcher_plant", + pitcher_crop = "pitcher_crop", + moss_block = "moss_block", + short_grass = "short_grass", + tall_grass = "tall_grass", + fern = "fern", + large_fern = "large_fern", + dead_bush = "dead_bush", + netherrack = "netherrack", + soul_campfire = "soul_campfire", + campfire = "campfire", + light = "light", + sculk_sensor = "sculk_sensor", + lectern = "lectern", + target = "target", + daylight_detector = "daylight_detector", + lever = "lever", + beehive = "beehive", + bee_nest = "bee_nest", + composter = "composter", + respawn_anchor = "respawn_anchor", + end_portal_frame = "end_portal_frame", + crafter = "crafter", + copper_bulb = "copper_bulb", + glow_lichen = "glow_lichen", + hanging_roots = "hanging_roots", + mangrove_roots = "mangrove_roots", + big_dripleaf_fallback = "big_dripleaf", + nether_portal = "nether_portal", + frogspawn = "frogspawn", + turtle_egg = "turtle_egg", + sniffer_egg = "sniffer_egg", + sea_pickle = "sea_pickle", + coarse_dirt = "coarse_dirt", + rooted_dirt = "rooted_dirt", + crimson_nylium = "crimson_nylium", + warped_nylium = "warped_nylium", +} + +macro_rules! tags { + ($($field:ident = $name:literal,)*) => { + /// Block tags consulted by ported behaviour. + #[derive(Clone, Debug, Default)] + pub struct Tags { $(pub $field: Arc,)* } + impl Tags { + fn resolve(all: &HashMap>) -> Self { + Self { $($field: all.get(concat!("minecraft:", $name)).cloned().unwrap_or_default(),)* } + } + } + }; +} +tags! { + leaves = "leaves", + logs = "logs", + prevents_nearby_leaf_decay = "prevents_nearby_leaf_decay", + walls = "walls", + fences = "fences", + wooden_fences = "wooden_fences", + fence_gates = "fence_gates", + stairs = "stairs", + slabs = "slabs", + doors = "doors", + trapdoors = "trapdoors", + rails = "rails", + beds = "beds", + wall_post_override = "wall_post_override", + replaceable = "replaceable", + dirt = "dirt", + sand = "sand", + ice = "ice", + snow = "snow", + infiniburn_overworld = "infiniburn_overworld", + infiniburn_nether = "infiniburn_nether", + infiniburn_end = "infiniburn_end", + soul_fire_base_blocks = "soul_fire_base_blocks", + washed_away_by_fluids = "washed_away_by_fluids", + blocks_fluid_flow = "blocks_fluid_flow", + blocks_motion = "blocks_motion", + unstable_bottom_center = "unstable_bottom_center", + cannot_support_snow_layer = "cannot_support_snow_layer", + support_override_snow_layer = "support_override_snow_layer", + maintains_farmland = "maintains_farmland", + supports_vegetation = "supports_vegetation", + supports_crops = "supports_crops", + supports_cactus = "supports_cactus", + supports_sugar_cane = "supports_sugar_cane", + supports_sugar_cane_adjacently = "supports_sugar_cane_adjacently", + supports_bamboo = "supports_bamboo", + supports_cocoa = "supports_cocoa", + supports_azalea = "supports_azalea", + supports_dry_vegetation = "supports_dry_vegetation", + supports_nether_sprouts = "supports_nether_sprouts", + supports_nether_wart = "supports_nether_wart", + supports_wither_rose = "supports_wither_rose", + supports_lily_pad = "supports_lily_pad", + supports_frogspawn = "supports_frogspawn", + supports_big_dripleaf = "supports_big_dripleaf", + supports_small_dripleaf = "supports_small_dripleaf", + supports_mangrove_propagule = "supports_mangrove_propagule", + supports_hanging_mangrove_propagule = "supports_hanging_mangrove_propagule", + supports_chorus_plant = "supports_chorus_plant", + supports_chorus_flower = "supports_chorus_flower", + support_override_cactus_flower = "support_override_cactus_flower", + cannot_support_seagrass = "cannot_support_seagrass", + cannot_support_kelp = "cannot_support_kelp", + overrides_mushroom_light_requirement = "overrides_mushroom_light_requirement", + enables_bubble_column_push_up = "enables_bubble_column_push_up", + enables_bubble_column_drag_down = "enables_bubble_column_drag_down", + shulker_boxes = "shulker_boxes", + convertible_to_mud = "convertible_to_mud", + grows_crops = "grows_crops", + candles = "candles", + candle_cakes = "candle_cakes", + campfires = "campfires", + buttons = "buttons", + pressure_plates = "pressure_plates", + wool = "wool", + crops = "crops", + small_flowers = "small_flowers", + flowers = "flowers", + saplings = "saplings", + anvil = "anvil", + lanterns = "lanterns", + climbable = "climbable", + nylium = "nylium", + mushroom_grow_block = "mushroom_grow_block", + guarded_by_piglins = "guarded_by_piglins", + copper = "copper", +} + +/// Property keys interned at load. +macro_rules! props { + ($($field:ident = $name:literal,)*) => { + #[derive(Clone, Copy, Debug)] + pub struct Props { $(pub $field: PropKey,)* } + impl Props { + fn resolve(table: &mut StateTable) -> Self { + Self { $($field: table.key($name),)* } + } + } + }; +} +props! { + waterlogged = "waterlogged", + facing = "facing", + half = "half", + shape = "shape", + open = "open", + powered = "powered", + hinge = "hinge", + in_wall = "in_wall", + axis = "axis", + age = "age", + level = "level", + layers = "layers", + snowy = "snowy", + north = "north", + south = "south", + east = "east", + west = "west", + up = "up", + down = "down", + distance = "distance", + persistent = "persistent", + moisture = "moisture", + face = "face", + lit = "lit", + power = "power", + delay = "delay", + locked = "locked", + mode = "mode", + triggered = "triggered", + extended = "extended", + kind = "type", + part = "part", + occupied = "occupied", + hanging = "hanging", + attached = "attached", + candles = "candles", + pickles = "pickles", + eggs = "eggs", + hatch = "hatch", + note = "note", + instrument = "instrument", + bites = "bites", + rotation = "rotation", + stage = "stage", + leaves = "leaves", + bottom = "bottom", + falling = "falling", + drag = "drag", + tilt = "tilt", + attachment = "attachment", + vertical_direction = "vertical_direction", + thickness = "thickness", + berries = "berries", + flower_amount = "flower_amount", + segment_amount = "segment_amount", + charges = "charges", + eye = "eye", + has_bottle_0 = "has_bottle_0", + disarmed = "disarmed", + inverted = "inverted", + enabled = "enabled", + conditional = "conditional", + short = "short", + unstable = "unstable", + tip = "tip", + honey_level = "honey_level", + bloom = "bloom", + natural = "natural", + cracked = "cracked", + has_book = "has_book", + signal_fire = "signal_fire", + orientation = "orientation", + crafting = "crafting", + side_chain = "side_chain", +} + +fn fail(message: &str) -> io::Error { + invalid(message) +} + +fn read_json(path: &Path) -> io::Result { + serde_json::from_reader(BufReader::new(File::open(path)?)).map_err(|e| invalid(e.to_string())) +} + +fn interned(cache: &mut HashMap>, text: &str) -> Arc { + cache.entry(text.to_owned()).or_insert_with(|| Arc::from(text)).clone() +} + +fn set_type(value: &Value, cache: &mut HashMap>) -> Option { + let text = |key: &str| value.get(key).and_then(Value::as_str).unwrap_or(""); + Some(SetType { + name: value.get("name")?.as_str()?.into(), + can_open_by_hand: value.get("canOpenByHand")?.as_bool()?, + can_open_by_wind_charge: value.get("canOpenByWindCharge")?.as_bool()?, + arrows: value.get("canButtonBeActivatedByArrows")?.as_bool()?, + mobs_only: value.get("pressurePlateSensitivity")?.as_str()? == "MOBS", + door_open: interned(cache, text("doorOpen")), + door_close: interned(cache, text("doorClose")), + trapdoor_open: interned(cache, text("trapdoorOpen")), + trapdoor_close: interned(cache, text("trapdoorClose")), + plate_on: interned(cache, text("pressurePlateClickOn")), + plate_off: interned(cache, text("pressurePlateClickOff")), + button_on: interned(cache, text("buttonClickOn")), + button_off: interned(cache, text("buttonClickOff")), + }) +} + +pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result { + let mut table = StateTable::new(registry)?; + let props = Props::resolve(&mut table); + let named = Named::resolve(&table)?; + let behaviour = read_json(&root.join("block-behaviours.json"))?; + let gameplay = read_json(&root.join("gameplay-facts.json"))?; + let blocks_json = behaviour["blocks"].as_array().ok_or_else(|| fail("missing behaviour blocks"))?; + let states_json = behaviour["states"].as_array().ok_or_else(|| fail("missing behaviour states"))?; + let gameplay_states = gameplay["states"].as_array().ok_or_else(|| fail("missing gameplay states"))?; + if blocks_json.len() != table.block_count() + || states_json.len() != table.state_count() + || gameplay_states.len() != table.state_count() + { + return Err(fail("behaviour exports do not match the block registry")); + } + // Fluid registry order fixes the fluid tick type IDs. + let fluids: Vec<&str> = behaviour["fluids"] + .as_array() + .ok_or_else(|| fail("missing fluid registry"))? + .iter() + .filter_map(Value::as_str) + .collect(); + if fluids.iter().copied().ne(FluidKind::ALL.iter().map(|k| k.name())) { + return Err(fail("fluid registry order differs from Horizon's")); + } + + // Tags. + let bundle = read_json(&root.join("block-tags.json"))?; + let mut definitions = TagDefinitions::default(); + for (name, text) in bundle.as_object().ok_or_else(|| fail("invalid block tag bundle"))? { + definitions + .apply_json(name, "vanilla", text.as_str().ok_or_else(|| fail("invalid block tag text"))?) + .map_err(|e| invalid(e.to_string()))?; + } + let built = definitions + .build(|name, _| table.block_by_name(name).map(|_| name.to_owned())) + .map_err(|e| invalid(e.to_string()))?; + let mut all_tags = HashMap::new(); + for (name, members) in &built.tags { + let mut set = BlockSet::with_capacity(table.block_count()); + for member in members { + if let Some(block) = table.block_by_name(member) { + set.insert(block); + } + } + all_tags.insert(name.clone(), Arc::new(set)); + } + let tags = Tags::resolve(&all_tags); + let tag = |name: &str| -> Option> { + all_tags.get(name.strip_prefix('#').unwrap_or(name)).cloned() + }; + + // Collision shapes. + let collision_tag = nbt::read_named(&fs::read(root.join("cached-collision.nbt"))?, Limits::default()) + .map_err(|e| invalid(e.to_string()))? + .0 + .tag; + let cached = CachedCollisionRegistry::from_nbt(&collision_tag, registry)?; + let mut shapes: Vec = Vec::new(); + let mut shape_ids = Vec::with_capacity(table.state_count()); + for id in 0..table.state_count() { + let Some(shape) = cached.cached_shape(BlockStateId(id as u32))? else { + shape_ids.push(-1); + continue; + }; + let index = match shapes.iter().position(|s| s.same_identity(shape)) { + Some(index) => index, + None => { + shapes.push(shape.clone()); + shapes.len() - 1 + } + }; + shape_ids.push(index as i32); + } + + let shape_info = shapes.iter().map(analyse_shape).collect::>>()?; + + // Fluid tags. + let mut fluid_definitions = TagDefinitions::default(); + let fluid_dir = root.join("data/minecraft/tags/fluid"); + for entry in fs::read_dir(&fluid_dir)? { + let path = entry?.path(); + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + fluid_definitions + .apply_json(&format!("minecraft:{stem}"), "vanilla", &fs::read_to_string(&path)?) + .map_err(|e| invalid(e.to_string()))?; + } + let fluid_built = fluid_definitions + .build(|name, _| FluidKind::from_name(name).map(|kind| kind as u8)) + .map_err(|e| invalid(e.to_string()))?; + let fluid_mask = |name: &str| -> u8 { + fluid_built + .tags + .get(name) + .into_iter() + .flatten() + .fold(0, |mask, kind| mask | 1 << kind) + }; + let fluid_tags = FluidTags { + water: fluid_mask("minecraft:water"), + lava: fluid_mask("minecraft:lava"), + supports_frogspawn: fluid_mask("minecraft:supports_frogspawn"), + supports_lily_pad: fluid_mask("minecraft:supports_lily_pad"), + supports_sugar_cane_adjacently: fluid_mask("minecraft:supports_sugar_cane_adjacently"), + bubble_column_can_occupy: fluid_mask("minecraft:bubble_column_can_occupy"), + }; + + // Per-state facts. + let mut facts = Vec::with_capacity(table.state_count()); + for (id, (exported, game)) in states_json.iter().zip(gameplay_states).enumerate() { + let row = exported.as_array().ok_or_else(|| fail("invalid behaviour state row"))?; + let int = |i: usize| row.get(i).and_then(Value::as_i64).unwrap_or(0); + let gb = |key: &str| game.get(key).and_then(Value::as_bool).unwrap_or(false); + let mut flags = int(1) as u32 & 0x7f; + for (key, bit) in [ + ("replaceable", state_flags::REPLACEABLE), + ("random_ticks", state_flags::RANDOM_TICKS), + ("solid_render", state_flags::SOLID_RENDER), + ("liquid", state_flags::LIQUID), + ("block_entity", state_flags::BLOCK_ENTITY), + ("ignited_by_lava", state_flags::IGNITED_BY_LAVA), + ("can_occlude", state_flags::CAN_OCCLUDE), + ("full_collision", state_flags::FULL_COLLISION), + ("skylight_down", state_flags::SKYLIGHT_DOWN), + ("requires_tool", state_flags::REQUIRES_TOOL), + ] { + if gb(key) { + flags |= bit; + } + } + let fluid_kind = FluidKind::ALL + .get(int(2) as usize) + .copied() + .ok_or_else(|| fail("invalid exported fluid"))?; + let fluid = FluidState::new(fluid_kind, int(3) as u8, row.get(4).and_then(Value::as_bool).unwrap_or(false)); + facts.push(StateFacts { + flags, + sturdy: int(0) as u32, + weak: int(5) as u32, + strong: int(6) as u32, + fluid, + emission: game.get("emission").and_then(Value::as_u64).unwrap_or(0) as u8, + dampening: game.get("dampening").and_then(Value::as_u64).unwrap_or(0) as u8, + hardness: game.get("hardness").and_then(Value::as_f64).unwrap_or(0.0) as f32, + push: match game.get("push").and_then(Value::as_str).unwrap_or("NORMAL") { + "DESTROY" => PushReaction::Destroy, + "BLOCK" => PushReaction::Block, + "IGNORE" => PushReaction::Ignore, + "PUSH_ONLY" => PushReaction::PushOnly, + _ => PushReaction::Normal, + }, + instrument: instrument_index(row.get(8).and_then(Value::as_str).unwrap_or("HARP")), + shape: shape_ids[id], + }); + } + + // Per-block data. + let fire = &behaviour["fire"]; + let odds = |key: &str, name: &str| -> i32 { + fire.get(key).and_then(|m| m.get(name)).and_then(Value::as_i64).unwrap_or(0) as i32 + }; + let mut strings = HashMap::new(); + let mut blocks = Vec::with_capacity(table.block_count()); + for (index, json) in blocks_json.iter().enumerate() { + let block = BlockId(index as u16); + let name = json["name"].as_str().ok_or_else(|| fail("block without name"))?; + if name != &*table.info(block).name { + return Err(fail("behaviour block order differs from registry")); + } + let mut classes = ClassSet::default(); + let mut chain = Vec::new(); + for java in json["class"].as_array().into_iter().flatten().filter_map(Value::as_str) { + if let Some(c) = Class::from_java(java) { + classes.insert(c); + chain.push(c); + } + } + let class = chain.first().copied().unwrap_or(Class::Block); + let mut interfaces = 0; + for java in json["interfaces"].as_array().into_iter().flatten().filter_map(Value::as_str) { + if let Some(i) = Interface::from_java(java) { + interfaces |= i.mask(); + } + } + let fields = &json["fields"]; + let field = |key: &str| fields.get(key); + let block_field = |key: &str| field(key).and_then(Value::as_str).and_then(|n| table.block_by_name(n)); + let wood = field("type").filter(|t| t.get("setType").is_some()); + let set_type = match wood { + Some(wood) => set_type(&wood["setType"], &mut strings), + None => field("type").and_then(|t| set_type(t, &mut strings)), + } + .map(Arc::new); + let text = |value: Option<&Value>, strings: &mut HashMap>| { + value.and_then(Value::as_str).map(|s| interned(strings, s)) + }; + let gate_open = text(wood.and_then(|w| w.get("fenceGateOpen")), &mut strings); + let gate_close = text(wood.and_then(|w| w.get("fenceGateClose")), &mut strings); + let open_sound = text(field("openSound"), &mut strings); + let close_sound = text(field("closeSound"), &mut strings); + let link = [ + "concrete", + "fruit", + "potted", + "deadBlock", + "base", + "candleBlock", + "requiredBlock", + ] + .into_iter() + .find_map(block_field); + let link2 = ["attachedStem", "stem"].into_iter().find_map(block_field); + let support_tag = ["stemSupportBlocks", "supportBlocks"] + .into_iter() + .find_map(|k| field(k).and_then(Value::as_str)) + .and_then(tag); + let support_tag2 = field("fruitSupportBlocks").and_then(Value::as_str).and_then(tag); + let feature = field("feature") + .and_then(Value::as_str) + .or_else(|| field("treeGrower").and_then(|g| g.get("name")).and_then(Value::as_str)) + .map(|s| interned(&mut strings, s)); + let growth_direction = match field("growthDirection").and_then(Value::as_str) { + Some("DOWN") => Direction::Down, + _ => Direction::Up, + }; + let default = table.default_state(block); + let sound = &gameplay_states[default.0 as usize]["sound"]; + let sound_id = |key: &str, strings: &mut HashMap>| { + interned(strings, sound.get(key).and_then(|s| s.get("id")).and_then(Value::as_str).unwrap_or("")) + }; + let sounds = Arc::new(Sounds { + volume: sound.get("volume").and_then(Value::as_f64).unwrap_or(1.0) as f32, + pitch: sound.get("pitch").and_then(Value::as_f64).unwrap_or(1.0) as f32, + place: sound_id("place", &mut strings), + break_: sound_id("break", &mut strings), + fall: sound_id("fall", &mut strings), + }); + blocks.push(BlockData { + class, + chain, + classes, + interfaces, + set_type, + gate_open, + gate_close, + open_sound, + close_sound, + ticks_to_stay_pressed: field("ticksToStayPressed").and_then(Value::as_i64).unwrap_or(0) as i32, + max_weight: field("maxWeight").and_then(Value::as_i64).unwrap_or(0) as i32, + link, + link2, + support_tag, + support_tag2, + feature, + grow_probability: field("growPerTickProbability").and_then(Value::as_f64).unwrap_or(0.0), + growth_direction, + schedule_fluid_ticks: field("scheduleFluidTicks").and_then(Value::as_bool).unwrap_or(false), + weather: match field("weatherState").and_then(Value::as_str) { + Some("EXPOSED") => 1, + Some("WEATHERED") => 2, + Some("OXIDIZED") => 3, + _ => 0, + }, + ignite_odds: odds("igniteOdds", name), + burn_odds: odds("burnOdds", name), + sounds, + item: interned(&mut strings, json["item"].as_str().unwrap_or("minecraft:air")), + dynamic_shape: json["dynamic_shape"].as_bool().unwrap_or(false), + }); + } + + // Item bindings. + let mut items = HashMap::new(); + for (item, binding) in behaviour["items"].as_object().ok_or_else(|| fail("missing item bindings"))? { + let fields = &binding["fields"]; + let Some(block) = fields.get("block").and_then(Value::as_str).and_then(|n| table.block_by_name(n)) else { + continue; + }; + let classes: Vec<&str> = binding["class"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + let kind = match classes.first().copied().unwrap_or("BlockItem") { + "BlockItem" | "GameMasterBlockItem" => ItemKind::Block, + "DoubleHighBlockItem" => ItemKind::DoubleHigh, + "StandingAndWallBlockItem" => ItemKind::StandingAndWall, + "SignItem" => ItemKind::Sign, + "HangingSignItem" => ItemKind::HangingSign, + "BedItem" => ItemKind::Bed, + "ScaffoldingBlockItem" => ItemKind::Scaffolding, + "PlaceOnWaterBlockItem" => ItemKind::PlaceOnWater, + "SolidBucketItem" => ItemKind::SolidBucket, + _ => ItemKind::Other, + }; + items.insert( + item.clone(), + ItemBinding { + block, + wall_block: fields.get("wallBlock").and_then(Value::as_str).and_then(|n| table.block_by_name(n)), + attachment: match fields.get("attachmentDirection").and_then(Value::as_str) { + Some("UP") => Some(Direction::Up), + Some("DOWN") => Some(Direction::Down), + _ => None, + }, + kind, + }, + ); + } + + let liquid_blocks = FluidBlockBindings::new(registry)?; + Ok(Behaviours { + table, + props, + named, + tags, + all_tags, + facts, + shapes, + shape_info, + fluid_tags, + blocks, + items, + liquid_blocks, + occlusion_cache: Default::default(), + }) +} + +pub const INSTRUMENTS: [&str; 23] = [ + "HARP", + "BASEDRUM", + "SNARE", + "HAT", + "BASS", + "FLUTE", + "BELL", + "GUITAR", + "CHIME", + "XYLOPHONE", + "IRON_XYLOPHONE", + "COW_BELL", + "DIDGERIDOO", + "BIT", + "BANJO", + "PLING", + "TRUMPET", + "TRUMPET_EXPOSED", + "TRUMPET_WEATHERED", + "TRUMPET_OXIDIZED", + "ZOMBIE", + "SKELETON", + "CREEPER", +]; +fn instrument_index(name: &str) -> u8 { + INSTRUMENTS.iter().position(|n| *n == name).map_or(255, |i| i as u8) +} diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs new file mode 100644 index 000000000..6ee6a8e09 --- /dev/null +++ b/crates/horizon-world/src/level/mod.rs @@ -0,0 +1,351 @@ +//! 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. 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. +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 connect; +mod falling; +mod fluids; +mod interact; +mod place; +mod plants; +mod redstone; +mod shapes; +mod survive; +mod tick; +mod update; + +#[cfg(test)] +mod tests; + +pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags}; +pub use place::{PlaceContext, PlaceOutcome}; +pub use interact::{InteractionResult, PlayerContext}; +pub use states::{BlockId, PropKey, StateTable}; +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, + 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, + }, + /// 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, + }, + /// `TntBlock.prime`: the TNT block is removed; spawn primed TNT. + PrimeTnt { pos: BlockPos }, + /// `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; + 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 + } + /// 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(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>, + facts: Vec, + shapes: Vec, + shape_info: Vec, + pub fluid_tags: data::FluidTags, + blocks: Vec, + items: HashMap, + liquid_blocks: FluidBlockBindings, + occlusion_cache: Mutex>, +} + +impl Behaviours { + /// Load from a prepared client resource directory (`.local/horizon-client/`). + pub fn load(registry: &BlockRegistry, resources_dir: &Path) -> io::Result { + 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() + } +} + +/// 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, +} diff --git a/crates/horizon-world/src/level/query.rs b/crates/horizon-world/src/level/query.rs new file mode 100644 index 000000000..4b13e8377 --- /dev/null +++ b/crates/horizon-world/src/level/query.rs @@ -0,0 +1,183 @@ +//! 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, + } +} +pub(crate) fn step_x(direction: Direction) -> i32 { + direction.normal()[0] +} +pub(crate) fn step_z(direction: Direction) -> i32 { + direction.normal()[2] +} +/// `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) + } + pub(crate) fn collision_empty(&self, state: BlockStateId) -> bool { + self.has_flag(state, state_flags::COLLISION_EMPTY) + } + pub(crate) fn has_block_entity(&self, state: BlockStateId) -> bool { + self.has_flag(state, state_flags::BLOCK_ENTITY) + } + /// `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 bool_prop(&self, state: BlockStateId, key: PropKey) -> bool { + self.table.bool(state, key) + } + 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) + } + 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) + } +} + +impl Sim<'_, L> { + 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() + } +} diff --git a/crates/horizon-world/src/level/states.rs b/crates/horizon-world/src/level/states.rs new file mode 100644 index 000000000..b26bcf805 --- /dev/null +++ b/crates/horizon-world/src/level/states.rs @@ -0,0 +1,318 @@ +//! 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, + pub int: Option, + pub boolean: Option, + pub direction: Option, +} +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, +} + +#[derive(Clone, Debug)] +pub struct BlockInfo { + pub name: Box, + pub base: BlockStateId, + pub count: u32, + pub default: BlockStateId, + slots: Vec, +} + +pub struct StateTable { + blocks: Vec, + state_block: Vec, + keys: HashMap, + key_names: Vec, + by_name: HashMap, BlockId>, +} + +pub fn direction_from_name(name: &str) -> Option { + 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 { + 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( + ®istry.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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + self.info(block).slots.iter().map(|slot| self.key_names[slot.key.0 as usize].as_str()) + } +} diff --git a/crates/horizon-world/src/level/survive.rs b/crates/horizon-world/src/level/survive.rs new file mode 100644 index 000000000..2893aef1c --- /dev/null +++ b/crates/horizon-world/src/level/survive.rs @@ -0,0 +1,499 @@ +//! `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 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 { + 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::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 { + b.collision_face_full(below_state, Direction::Up) + || (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 => { + b.shape_info(ground).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() + } +} diff --git a/crates/horizon-world/src/level/ticks.rs b/crates/horizon-world/src/level/ticks.rs new file mode 100644 index 000000000..f6b17e047 --- /dev/null +++ b/crates/horizon-world/src/level/ticks.rs @@ -0,0 +1,100 @@ +//! 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, +} +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(), + } + } + /// 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, Option) { + (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)) + } +} diff --git a/crates/horizon-world/src/level/update.rs b/crates/horizon-world/src/level/update.rs new file mode 100644 index 000000000..17ea2f64e --- /dev/null +++ b/crates/horizon-world/src/level/update.rs @@ -0,0 +1,459 @@ +//! `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, + index: usize, + }, +} + +enum Step { + Shape { + direction: Direction, + neighbor_state: BlockStateId, + pos: BlockPos, + neighbor_pos: BlockPos, + flags: i32, + limit: i32, + }, + Neighbor { + state: Option, + pos: BlockPos, + block: BlockId, + moved: bool, + }, +} + +#[derive(Default)] +pub(crate) struct NeighborUpdater { + stack: Vec, + added: Vec, + 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 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, 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 { + 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; + 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); + } + loop { + let Some(top) = self.ticks.updater.stack.last_mut() else { + break; + }; + 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); + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockBehaviourExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockBehaviourExporter.java new file mode 100644 index 000000000..4a475133b --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockBehaviourExporter.java @@ -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().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(), ""); + } + } + 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(), ""); + } + } + } + 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); + } +}