From 0a4a4ea643b1b3bb5ce3af6dbdf876fd1d421b72 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:09:34 +0200 Subject: [PATCH 1/8] Grow saplings, fungi and mushrooms and apply bone meal through live feature placement Port TreeGrower (all growers incl. 2x2 dark oak, pale oak, mega spruce/jungle, mangrove, azalea, poplar), BoneMealItem.useOn/growCrop/growWaterPlant and every BonemealableBlock. Configured and placed features run on the live level via a FeatureWorld/PlacementContext adapter with vanilla setBlock semantics. Also fix torchflower crops never maturing and kelp growth into flowing water. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-world/src/level/bonemeal.rs | 1131 +++++++++++++++++ crates/horizon-world/src/level/data.rs | 1 + .../horizon-world/src/level/feature_world.rs | 293 +++++ crates/horizon-world/src/level/growth.rs | 342 +++++ .../horizon-world/src/level/growth_tests.rs | 342 +++++ crates/horizon-world/src/level/mod.rs | 15 + crates/horizon-world/src/level/tick.rs | 25 +- crates/horizon-world/src/worldgen.rs | 1 + crates/horizon-world/src/worldgen/live.rs | 316 +++++ 9 files changed, 2452 insertions(+), 14 deletions(-) create mode 100644 crates/horizon-world/src/level/bonemeal.rs create mode 100644 crates/horizon-world/src/level/feature_world.rs create mode 100644 crates/horizon-world/src/level/growth.rs create mode 100644 crates/horizon-world/src/level/growth_tests.rs create mode 100644 crates/horizon-world/src/worldgen/live.rs diff --git a/crates/horizon-world/src/level/bonemeal.rs b/crates/horizon-world/src/level/bonemeal.rs new file mode 100644 index 000000000..a59a1c7e1 --- /dev/null +++ b/crates/horizon-world/src/level/bonemeal.rs @@ -0,0 +1,1131 @@ +//! Bone meal: `BoneMealItem.useOn` / `growCrop` / `growWaterPlant` and every +//! vanilla `BonemealableBlock` (`isValidBonemealTarget`, `isBonemealSuccess`, +//! `performBonemeal`), ported in vanilla's random draw order. +use super::{ + Behaviours, LevelAccess, LevelEvent, Sim, Ticks, + classes::{Class, Interface}, + growth::grower, + update::{HORIZONTAL, above, below, rel}, +}; +use crate::{fluid::FluidState, registry::BlockStateId}; +use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; + +/// The `BonemealableBlock` implementation a block uses (most derived wins). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Sapling, + Propagule, + Mushroom, + Fungus, + Azalea, + Grass, + Nylium, + Netherrack, + FeaturePlacer, + RootedDirt, + MangroveLeaves, + Crop, + Stem, + Pitcher, + BambooSapling, + Bamboo, + Cocoa, + SweetBerry, + TallGrass, + TallFlower, + SpreadingBush, + FlowerBed, + CaveVines, + PlantHead, + CaveVinesPlant, + PlantBody, + Seagrass, + SeaPickle, + BigDripleaf, + BigDripleafStem, + SmallDripleaf, + GlowLichen, + HangingMoss, + MossyCarpet, + ShortDryGrass, + TallDryGrass, + ShelfMushroom, +} + +fn kind_of(class: Class) -> Option { + Some(match class { + Class::MangrovePropagule => Kind::Propagule, + Class::Sapling => Kind::Sapling, + Class::Mushroom => Kind::Mushroom, + Class::NetherFungus => Kind::Fungus, + Class::Azalea => Kind::Azalea, + Class::Grass => Kind::Grass, + Class::Nylium => Kind::Nylium, + Class::Netherrack => Kind::Netherrack, + Class::BonemealableFeaturePlacer => Kind::FeaturePlacer, + Class::RootedDirt => Kind::RootedDirt, + Class::MangroveLeaves => Kind::MangroveLeaves, + Class::Crop => Kind::Crop, + Class::Stem => Kind::Stem, + Class::PitcherCrop => Kind::Pitcher, + Class::BambooSapling => Kind::BambooSapling, + Class::BambooStalk => Kind::Bamboo, + Class::Cocoa => Kind::Cocoa, + Class::SweetBerryBush => Kind::SweetBerry, + Class::TallGrass => Kind::TallGrass, + Class::TallFlower => Kind::TallFlower, + Class::Bush | Class::FireflyBush => Kind::SpreadingBush, + Class::FlowerBed => Kind::FlowerBed, + Class::CaveVines => Kind::CaveVines, + Class::GrowingPlantHead => Kind::PlantHead, + Class::CaveVinesPlant => Kind::CaveVinesPlant, + Class::GrowingPlantBody => Kind::PlantBody, + Class::Seagrass => Kind::Seagrass, + Class::SeaPickle => Kind::SeaPickle, + Class::BigDripleaf => Kind::BigDripleaf, + Class::BigDripleafStem => Kind::BigDripleafStem, + Class::SmallDripleaf => Kind::SmallDripleaf, + Class::GlowLichen => Kind::GlowLichen, + Class::HangingMoss => Kind::HangingMoss, + Class::MossyCarpet => Kind::MossyCarpet, + Class::ShortDryGrass => Kind::ShortDryGrass, + Class::TallDryGrass => Kind::TallDryGrass, + Class::ShelfMushroom => Kind::ShelfMushroom, + _ => return None, + }) +} + +/// `Mth.nextInt(random, min, max)`. +fn next_int_between(random: &mut R, min: i32, max: i32) -> i32 { + if min >= max { + min + } else { + random.next_int_bound(max - min + 1).unwrap_or(0) + min + } +} + +impl Behaviours { + /// `BoneMealItem.useOn` for a player clicking `pos` on `face`. Returns + /// whether bone meal was used (the caller then shrinks the stack unless + /// the player is in creative mode). Reports level event 1505 (growth + /// particles and sound) at the grown position. + pub fn use_bone_meal( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + face: Direction, + ) -> bool { + let mut sim = self.sim(level, ticks); + if sim.grow_crop(pos) { + sim.level_event(1505, pos, 15); + return true; + } + let clicked = sim.state(pos); + let relative = rel(pos, face); + if self.is_face_sturdy(clicked, face) && sim.grow_water_plant(relative, Some(face)) { + sim.level_event(1505, relative, 15); + return true; + } + false + } + /// `BoneMealItem.growCrop` (dispensers call this directly). + pub fn grow_crop( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) -> bool { + self.sim(level, ticks).grow_crop(pos) + } + /// `BoneMealItem.growWaterPlant` (dispensers pass no clicked face). + pub fn grow_water_plant( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + face: Option, + ) -> bool { + self.sim(level, ticks).grow_water_plant(pos, face) + } + /// The `BonemealableBlock.Type` particle spread of a block at level event + /// 1505: Some(true) for `NEIGHBOR_SPREADER` (particles over a 3-block + /// area above), Some(false) for `GROWER`, None when not bonemealable. + pub fn bone_meal_spreads(&self, state: BlockStateId) -> Option { + let kind = self.bonemeal_kind(state)?; + Some(matches!( + kind, + Kind::Grass | Kind::Nylium | Kind::Netherrack | Kind::FeaturePlacer + )) + } + fn bonemeal_kind(&self, state: BlockStateId) -> Option { + let data = self.data(state); + if !data.implements(Interface::Bonemealable) { + return None; + } + data.chain.iter().find_map(|&c| kind_of(c)) + } +} + +impl Sim<'_, L> { + fn next_int(&mut self, bound: i32) -> i32 { + self.random().next_int_bound(bound).unwrap_or(0) + } + fn block_named(&self, name: &str) -> Option { + let b = self.b; + b.table.block_by_name(name).map(|id| b.default_of(id)) + } + fn in_tag(&self, state: BlockStateId, tag: &str) -> bool { + self.b.tag(tag).is_some_and(|set| self.b.in_set(state, set)) + } + + /// `BoneMealItem.growCrop`: true when the block is a valid target (bone + /// meal is consumed even when `isBonemealSuccess` fails). + pub(crate) fn grow_crop(&mut self, pos: BlockPos) -> bool { + let state = self.state(pos); + let Some(kind) = self.b.bonemeal_kind(state) else { + return false; + }; + if !self.bonemeal_valid(kind, pos, state) { + return false; + } + if self.bonemeal_success(kind, pos, state) { + self.perform_bonemeal(kind, pos, state); + } + true + } + + /// `BonemealableBlock.isValidBonemealTarget`. + fn bonemeal_valid(&mut self, kind: Kind, pos: BlockPos, state: BlockStateId) -> bool { + let b = self.b; + let p = b.props; + let up = above(pos); + match kind { + Kind::Sapling => { + let Some(g) = b.data(state).feature.as_deref().and_then(grower) else { + return false; + }; + if b.live_features().is_none() || !self.tree_can_grow(g, pos, state) { + return false; + } + let height = self.tree_minimum_height(g); + self.is_inside_build_height(pos.y + height) + } + Kind::Propagule => !b.table.bool(state, p.hanging) || b.table.int(state, p.age) != 4, + Kind::Mushroom => { + let Some(feature) = b.data(state).feature.as_deref() else { + return false; + }; + let Some(json) = b.live_features().and_then(|f| f.configured_json(feature)) else { + return false; + }; + let huge = matches!( + json["type"].as_str(), + Some("minecraft:huge_red_mushroom" | "minecraft:huge_brown_mushroom") + ); + let radius = json["foliage_radius"].as_i64().unwrap_or(2) as i32; + huge && self.is_inside_build_height(pos.y + 4 + radius) + } + Kind::Fungus => { + let below_state = self.below_state(pos); + b.data(state) + .link + .is_some_and(|required| b.is_block(below_state, required)) + && self.is_inside_build_height(pos.y + 1) + } + Kind::Azalea => { + let Some(g) = grower("azalea") else { + return false; + }; + let height = self.tree_minimum_height(g); + self.is_inside_build_height(pos.y + height + 2) + && self.fluid_at(up) == FluidState::EMPTY + } + Kind::Grass | Kind::Nylium | Kind::BambooSapling => { + b.is_air(self.state(up)) && self.is_inside_build_height(up.y) + } + Kind::Netherrack => { + if !b.has_flag(self.state(up), super::data::state_flags::SKYLIGHT_DOWN) { + return false; + } + self.netherrack_nylium_near(pos) != (false, false) + } + Kind::FeaturePlacer => b.is_air(self.state(up)), + Kind::RootedDirt => { + b.is_air(self.state(below(pos))) && self.is_inside_build_height(pos.y - 1) + } + Kind::MangroveLeaves => b.is_air(self.state(below(pos))), + Kind::Crop => b.table.int(state, p.age) < self.crop_max_age(state), + Kind::Stem => b.table.int(state, p.age) != 7, + Kind::Pitcher => match self.pitcher_lower(pos, state) { + Some((lower_pos, lower)) => { + let age = b.table.int(lower, p.age) + 1; + self.pitcher_can_grow(lower_pos, lower, age) + } + None => false, + }, + Kind::Bamboo => { + let height_above = self.bamboo_height_above(pos); + let height_below = self.bamboo_height_below(pos); + let growth = pos.offset(0, height_above + 1, 0); + height_above + height_below + 1 < 16 + && b.table + .int(self.state(pos.offset(0, height_above, 0)), p.stage) + != 1 + && self.is_inside_build_height(growth.y) + && self.is_empty_block(growth) + } + Kind::Cocoa => b.table.int(state, p.age) < 2, + Kind::SweetBerry => b.table.int(state, p.age) < 3, + Kind::TallGrass => { + let Some(grown) = self.tall_grass_grown(state) else { + return false; + }; + self.can_survive(grown, pos) + && self.is_empty_block(up) + && self.is_inside_build_height(up.y) + } + Kind::TallFlower | Kind::FlowerBed | Kind::SmallDripleaf | Kind::ShortDryGrass => true, + Kind::SpreadingBush => self.spreadable_neighbour(pos, state, false).is_some(), + Kind::TallDryGrass => { + let Some(short) = self.block_named("minecraft:short_dry_grass") else { + return false; + }; + self.spreadable_neighbour(pos, short, false).is_some() + } + Kind::PlantHead => { + let growth = rel(pos, b.data(state).growth_direction); + self.plant_can_grow_into(state, self.state(growth)) + && self.is_inside_build_height(growth.y) + } + Kind::CaveVines | Kind::CaveVinesPlant => !b.table.bool(state, p.berries), + Kind::PlantBody => match self.plant_head_pos(pos, state) { + Some(head) => { + let head_state = self.state(head); + let growth = rel(head, b.data(state).growth_direction); + self.plant_can_grow_into(head_state, self.state(growth)) + && self.is_inside_build_height(growth.y) + } + None => false, + }, + Kind::Seagrass => b.is_block(self.state(up), b.named.water), + Kind::SeaPickle => { + b.table.bool(state, p.waterlogged) + && self.in_tag(self.below_state(pos), "minecraft:coral_blocks") + } + Kind::BigDripleaf => self.dripleaf_can_grow_into(up), + Kind::BigDripleafStem => { + let Some(leaf) = b.table.block_by_name("minecraft:big_dripleaf") else { + return false; + }; + self.top_connected(pos, b.block(state), Direction::Up, leaf) + .is_some_and(|head| self.dripleaf_can_grow_into(above(head))) + } + Kind::GlowLichen => Direction::ALL + .iter() + .any(|&face| self.lichen_can_spread_in_any_direction(state, pos, face.opposite())), + Kind::HangingMoss => { + let grow = below(self.hanging_moss_tip(pos, state)); + b.is_air(self.state(grow)) && self.is_inside_build_height(grow.y) + } + Kind::MossyCarpet => { + b.table.bool(state, p.bottom) && !b.is_air(self.mossy_topper_all_sides(pos)) + } + Kind::ShelfMushroom => b.table.int(state, p.age) < 1, + } + } + + /// `BonemealableBlock.isBonemealSuccess`. + fn bonemeal_success(&mut self, kind: Kind, _pos: BlockPos, state: BlockStateId) -> bool { + let b = self.b; + match kind { + Kind::Sapling | Kind::Azalea => self.random().next_float() < 0.45, + Kind::Propagule => { + if b.table.bool(state, b.props.hanging) { + b.table.int(state, b.props.age) != 4 + } else { + self.random().next_float() < 0.45 + } + } + Kind::Mushroom | Kind::Fungus => self.random().next_float() < 0.4, + _ => true, + } + } + + /// `BonemealableBlock.performBonemeal`. + fn perform_bonemeal(&mut self, kind: Kind, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let p = b.props; + let up = above(pos); + match kind { + Kind::Sapling => self.advance_tree(pos, state), + Kind::Propagule => { + if b.table.bool(state, p.hanging) && b.table.int(state, p.age) != 4 { + self.set_block(pos, b.table.cycle(state, p.age), 2); + } else { + self.advance_tree(pos, state); + } + } + Kind::Mushroom => { + self.grow_mushroom(pos, state); + } + Kind::Fungus => { + if let Some(feature) = b.data(state).feature.clone() { + self.place_configured_feature(&feature, pos); + } + } + Kind::Azalea => { + if let Some(g) = grower("azalea") { + self.grow_tree(g, pos, state); + } + } + Kind::Grass => self.grass_bonemeal(pos, state), + Kind::Nylium => { + if self.is_inside_build_height(up.y) { + self.place_configured_feature("minecraft:nylium_bonemeal", up); + } + } + Kind::Netherrack => { + let (warped, crimson) = self.netherrack_nylium_near(pos); + let warped_state = self.block_named("minecraft:warped_nylium"); + let crimson_state = self.block_named("minecraft:crimson_nylium"); + let next = if warped && crimson { + if self.random().next_boolean() { + warped_state + } else { + crimson_state + } + } else if warped { + warped_state + } else if crimson { + crimson_state + } else { + None + }; + if let Some(next) = next { + self.set_block_and_update(pos, next); + } + } + Kind::FeaturePlacer => { + if let Some(feature) = b.data(state).feature.clone() { + self.place_configured_feature(&feature, up); + } + } + Kind::RootedDirt => { + if let Some(roots) = self.block_named("minecraft:hanging_roots") { + self.set_block_and_update(below(pos), roots); + } + } + Kind::MangroveLeaves => { + if let Some(propagule) = self.block_named("minecraft:mangrove_propagule") { + let hanging = b.table.set_bool(propagule, p.hanging, true); + self.set_block(below(pos), b.table.set_int(hanging, p.age, 0), 2); + } + } + Kind::Crop => { + let max = self.crop_max_age(state); + let increase = self.crop_bonemeal_increase(state); + let age = max.min(b.table.int(state, p.age) + increase); + let next = self.crop_state_for_age(state, age); + self.set_block(pos, next, 2); + } + Kind::Stem => { + let increase = next_int_between(self.random(), 2, 5); + let age = 7.min(b.table.int(state, p.age) + increase); + let next = b.table.set_int(state, p.age, age); + self.set_block(pos, next, 2); + if age == 7 { + self.random_tick_block(next, pos); + } + } + Kind::Pitcher => { + if let Some((lower_pos, lower)) = self.pitcher_lower(pos, state) { + self.pitcher_grow(lower, lower_pos, 1); + } + } + Kind::BambooSapling => self.bamboo_sapling_grow(pos), + Kind::Bamboo => { + let mut height_above = self.bamboo_height_above(pos); + let height_below = self.bamboo_height_below(pos); + let mut total = height_above + height_below + 1; + let count = 1 + self.next_int(2); + for _ in 0..count { + let top = pos.offset(0, height_above, 0); + let top_state = self.state(top); + let growth = above(top); + if total >= 16 + || b.table.int(top_state, p.stage) == 1 + || !self.is_empty_block(growth) + || !self.is_inside_build_height(growth.y) + { + return; + } + self.bamboo_grow(top_state, top, total); + height_above += 1; + total += 1; + } + } + Kind::Cocoa => { + let age = b.table.int(state, p.age); + self.set_block(pos, b.table.set_int(state, p.age, age + 1), 2); + } + Kind::SweetBerry => { + let age = 3.min(b.table.int(state, p.age) + 1); + self.set_block(pos, b.table.set_int(state, p.age, age), 2); + } + Kind::TallGrass => { + if let Some(grown) = self.tall_grass_grown(state) { + self.double_plant_place_at(grown, pos, 2); + } + } + Kind::TallFlower => self.pop_block_item(pos, state), + Kind::SpreadingBush => { + if let Some(at) = self.spreadable_neighbour(pos, state, true) { + self.set_block_and_update(at, b.default_of(b.block(state))); + } + } + Kind::TallDryGrass => { + if let Some(short) = self.block_named("minecraft:short_dry_grass") + && let Some(at) = self.spreadable_neighbour(pos, short, true) + { + self.set_block_and_update(at, short); + } + } + Kind::ShortDryGrass => { + if let Some(tall) = self.block_named("minecraft:tall_dry_grass") { + self.set_block_and_update(pos, tall); + } + } + Kind::FlowerBed => { + let amount = b.table.int(state, p.flower_amount); + if amount < 4 { + self.set_block(pos, b.table.set_int(state, p.flower_amount, amount + 1), 2); + } else { + self.pop_block_item(pos, state); + } + } + Kind::PlantHead => self.plant_head_bonemeal(pos, state), + Kind::CaveVines | Kind::CaveVinesPlant => { + self.set_block(pos, b.table.set_bool(state, p.berries, true), 2); + } + Kind::PlantBody => { + if let Some(head) = self.plant_head_pos(pos, state) { + let head_state = self.state(head); + match b.bonemeal_kind(head_state) { + Some(Kind::CaveVines) => { + self.set_block(head, b.table.set_bool(head_state, p.berries, true), 2); + } + Some(Kind::PlantHead) => self.plant_head_bonemeal(head, head_state), + _ => {} + } + } + } + Kind::Seagrass => { + let lower = b.default_of(b.named.tall_seagrass); + let upper = b.table.set_text(lower, p.half, "upper"); + self.set_block(pos, lower, 2); + self.set_block(up, upper, 2); + } + Kind::SeaPickle => self.sea_pickle_bonemeal(pos, state), + Kind::BigDripleaf => { + if self.dripleaf_can_grow_into(up) { + let facing = b.facing(state); + let fluid = b.fluid(state); + self.dripleaf_stem_place(pos, fluid, facing); + let fluid_above = self.fluid_at(up); + self.dripleaf_place(up, fluid_above, facing); + } + } + Kind::BigDripleafStem => { + let Some(leaf) = b.table.block_by_name("minecraft:big_dripleaf") else { + return; + }; + if let Some(head) = self.top_connected(pos, b.block(state), Direction::Up, leaf) { + let facing = b.facing(state); + let fluid = self.fluid_at(head); + self.dripleaf_stem_place(head, fluid, facing); + let fluid_above = self.fluid_at(above(head)); + self.dripleaf_place(above(head), fluid_above, facing); + } + } + Kind::SmallDripleaf => { + if b.table.text(state, p.half) == "lower" { + let empty = b.legacy_block(self.fluid_at(up)); + self.set_block(up, empty, 18); + let facing = b.facing(state); + self.dripleaf_place_random_height(pos, facing); + } else { + let below_pos = below(pos); + let below_state = self.state(below_pos); + if b.bonemeal_kind(below_state) == Some(Kind::SmallDripleaf) { + self.perform_bonemeal(Kind::SmallDripleaf, below_pos, below_state); + } else { + // performBonemeal on a non-dripleaf below: vanilla reads + // FACING/HALF of that state and would throw; do nothing. + } + } + } + Kind::GlowLichen => self.lichen_spread_random(pos, state), + Kind::HangingMoss => { + let tip = below(self.hanging_moss_tip(pos, state)); + if b.is_air(self.state(tip)) { + self.set_block_and_update(tip, b.table.set_bool(state, p.tip, true)); + } + } + Kind::MossyCarpet => { + let topper = self.mossy_topper_all_sides(pos); + if !b.is_air(topper) { + self.set_block_and_update(up, topper); + } + } + Kind::ShelfMushroom => { + let age = b.table.int(state, p.age); + self.set_block(pos, b.table.set_int(state, p.age, age + 1), 2); + } + } + } + + // ---- helpers ---- + + /// `Block.popResource(level, pos, new ItemStack(this))`. + fn pop_block_item(&mut self, pos: BlockPos, state: BlockStateId) { + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "pop_block_item", + }); + } + /// `CropBlock.getMaxAge`. + pub(crate) fn crop_max_age(&self, state: BlockStateId) -> i32 { + let b = self.b; + if b.instance_of(state, Class::TorchflowerCrop) { + 2 + } else { + b.table.int_range(state, b.props.age).map_or(7, |r| r.1) + } + } + /// `CropBlock.getStateForAge` (torchflower crops become torchflowers). + pub(crate) fn crop_state_for_age(&self, state: BlockStateId, age: i32) -> BlockStateId { + let b = self.b; + if b.instance_of(state, Class::TorchflowerCrop) + && age == 2 + && let Some(flower) = self.block_named("minecraft:torchflower") + { + return flower; + } + b.table + .set_int(b.default_of(b.block(state)), b.props.age, age) + } + /// `CropBlock.getBonemealAgeIncrease` and its overrides. + fn crop_bonemeal_increase(&mut self, state: BlockStateId) -> i32 { + let b = self.b; + if b.instance_of(state, Class::TorchflowerCrop) { + 1 + } else if b.instance_of(state, Class::Beetroot) { + next_int_between(self.random(), 2, 5) / 3 + } else { + next_int_between(self.random(), 2, 5) + } + } + /// `PitcherCropBlock.getLowerHalf`. + fn pitcher_lower( + &self, + pos: BlockPos, + state: BlockStateId, + ) -> Option<(BlockPos, BlockStateId)> { + let b = self.b; + let is_lower = |s: BlockStateId| { + b.is_block(s, b.named.pitcher_crop) && b.table.text(s, b.props.half) == "lower" + }; + if is_lower(state) { + return Some((pos, state)); + } + let below_pos = below(pos); + let below_state = self.state(below_pos); + is_lower(below_state).then_some((below_pos, below_state)) + } + /// `PitcherCropBlock.canGrow`. + fn pitcher_can_grow(&self, lower_pos: BlockPos, lower: BlockStateId, new_age: i32) -> bool { + let b = self.b; + let upper = self.state(above(lower_pos)); + b.table.int(lower, b.props.age) < 4 + && self.raw_brightness(lower_pos, 0) >= 8 + && self.is_inside_build_height(lower_pos.y + 1) + && (new_age < 3 || b.is_air(upper) || b.is_block(upper, b.named.pitcher_crop)) + } + /// `TallGrassBlock.getGrownBlock`. + fn tall_grass_grown(&self, state: BlockStateId) -> Option { + let name = if self.b.table.name(state) == "minecraft:fern" { + "minecraft:large_fern" + } else { + "minecraft:tall_grass" + }; + self.block_named(name) + } + /// `DoublePlantBlock.placeAt`. + fn double_plant_place_at(&mut self, state: BlockStateId, lower: BlockPos, flags: i32) { + let b = self.b; + let p = b.props; + let upper = above(lower); + let lower_state = b.table.set_text(state, p.half, "lower"); + let lower_state = b + .table + .with_bool(lower_state, p.waterlogged, self.is_water_at(lower)) + .unwrap_or(lower_state); + self.set_block(lower, lower_state, flags); + let upper_state = b.table.set_text(state, p.half, "upper"); + let upper_state = b + .table + .with_bool(upper_state, p.waterlogged, self.is_water_at(upper)) + .unwrap_or(upper_state); + self.set_block(upper, upper_state, flags); + } + /// `BonemealableBlock.getSpreadableNeighbourPos` (shuffled order when + /// `shuffle`, as `findSpreadableNeighbourPos`). + fn spreadable_neighbour( + &mut self, + pos: BlockPos, + to_place: BlockStateId, + shuffle: bool, + ) -> Option { + let mut directions = HORIZONTAL; + if shuffle { + // Util.shuffle. + for i in (2..=directions.len()).rev() { + let swap = self.next_int(i as i32) as usize; + directions.swap(i - 1, swap); + } + } + directions + .into_iter() + .map(|d| rel(pos, d)) + .find(|&n| self.is_empty_block(n) && self.can_survive(to_place, n)) + } + /// `NetherrackBlock`: (warped nylium nearby, crimson nylium nearby). + fn netherrack_nylium_near(&self, pos: BlockPos) -> (bool, bool) { + let (mut warped, mut crimson) = (false, false); + for x in -1..=1 { + for y in -1..=1 { + for z in -1..=1 { + let state = self.state(pos.offset(x, y, z)); + if !self.in_tag(state, "minecraft:nylium") { + continue; + } + match self.b.table.name(state) { + "minecraft:warped_nylium" => warped = true, + "minecraft:crimson_nylium" => crimson = true, + _ => {} + } + if warped && crimson { + return (true, true); + } + } + } + } + (warped, crimson) + } + /// `GrowingPlantHeadBlock.canGrowInto` of the head's block. + fn plant_can_grow_into(&self, head: BlockStateId, state: BlockStateId) -> bool { + let b = self.b; + if b.instance_of(head, Class::Kelp) { + b.is_block(state, b.named.water) + } else { + b.is_air(state) + } + } + /// `GrowingPlantHeadBlock.performBonemeal`. + fn plant_head_bonemeal(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let direction = b.data(state).growth_direction; + let mut forward = rel(pos, direction); + let mut next_age = (b.table.int(state, b.props.age) + 1).min(25); + let count = if b.instance_of(state, Class::TwistingVines) + || b.instance_of(state, Class::WeepingVines) + { + // NetherVines.getBlocksToGrowWhenBonemealed. + let mut probability = 1.0; + let mut count = 0; + while self.random().next_double() < probability { + probability *= 0.826; + count += 1; + } + count + } else { + 1 + }; + for _ in 0..count { + if !self.plant_can_grow_into(state, self.state(forward)) + || !self.is_inside_build_height(forward.y) + { + break; + } + self.set_block_and_update(forward, b.table.set_int(state, b.props.age, next_age)); + forward = rel(forward, direction); + next_age = (next_age + 1).min(25); + } + } + /// `GrowingPlantBodyBlock.getHeadPos` (`BlockUtil.getTopConnectedBlock`). + fn plant_head_pos(&self, pos: BlockPos, state: BlockStateId) -> Option { + let b = self.b; + let name = b.table.name(state); + let head = b.table.block_by_name(name.strip_suffix("_plant")?)?; + self.top_connected(pos, b.block(state), b.data(state).growth_direction, head) + } + /// `BlockUtil.getTopConnectedBlock`. + fn top_connected( + &self, + pos: BlockPos, + body: super::states::BlockId, + direction: Direction, + head: super::states::BlockId, + ) -> Option { + let mut forward = pos; + loop { + forward = rel(forward, direction); + let state = self.state(forward); + if !self.b.is_block(state, body) { + return self.b.is_block(state, head).then_some(forward); + } + if !self.level.is_loaded(forward) || !self.is_in_valid_bounds(forward) { + return None; + } + } + } + /// `HangingMossBlock.getTip`. + fn hanging_moss_tip(&self, pos: BlockPos, state: BlockStateId) -> BlockPos { + let block = self.b.block(state); + let mut forward = pos; + loop { + forward = below(forward); + if !self.b.is_block(self.state(forward), block) || forward.y < self.level.min_y() { + return above(forward); + } + } + } + /// `MossyCarpetBlock.createTopperWithSideChance(level, pos, () -> true)`. + fn mossy_topper_all_sides(&mut self, pos: BlockPos) -> BlockStateId { + let b = self.b; + let p = b.props; + let block = b.block(self.state(pos)); + let above_pos = above(pos); + let above_state = self.state(above_pos); + let is_carpet = b.is_block(above_state, block); + if (!is_carpet || !b.table.bool(above_state, p.bottom)) + && (is_carpet || b.is_replaceable(above_state)) + { + let carpet = b.table.set_bool(b.default_of(block), p.bottom, false); + let topper = self.mossy_carpet_updated_state(carpet, above_pos, true); + if self.mossy_carpet_has_faces(topper) && topper != above_state { + return topper; + } + } + b.air() + } + /// `SeaPickleBlock.performBonemeal`. + fn sea_pickle_bonemeal(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let p = b.props; + let (mut z_span, mut z_offset) = (1, 0); + let x_start = pos.x - 2; + for (count, x) in (0..5).enumerate() { + for z in 0..z_span { + let end_y = 2 + pos.y - 1; + for y in (end_y - 2)..end_y { + let position = BlockPos::new(x_start + x, y, pos.z - z_offset + z); + if position != pos + && self.next_int(6) == 0 + && b.is_block(self.state(position), b.named.water) + && self.in_tag(self.below_state(position), "minecraft:coral_blocks") + { + let pickles = self.next_int(4) + 1; + let pickle = + b.table + .set_int(b.default_of(b.block(state)), p.pickles, pickles); + self.set_block_and_update(position, pickle); + } + } + } + if count < 2 { + z_span += 2; + z_offset += 1; + } else { + z_span -= 2; + z_offset -= 1; + } + } + self.set_block(pos, b.table.set_int(state, p.pickles, 4), 2); + } + /// `BigDripleafBlock.canGrowInto` / `canPlaceAt`. + fn dripleaf_can_grow_into(&self, pos: BlockPos) -> bool { + let b = self.b; + let state = self.state(pos); + self.is_inside_build_height(pos.y) + && (b.is_air(state) + || b.is_block(state, b.named.water) + || b.table.name(state) == "minecraft:small_dripleaf") + } + fn dripleaf_set(&mut self, name: &str, pos: BlockPos, fluid: FluidState, facing: Direction) { + let b = self.b; + let Some(state) = self.block_named(name) else { + return; + }; + let state = b + .table + .set_bool(state, b.props.waterlogged, fluid == FluidState::WATER); + let state = b.table.set_dir(state, b.props.facing, facing); + self.set_block_and_update(pos, state); + } + fn dripleaf_place(&mut self, pos: BlockPos, fluid: FluidState, facing: Direction) { + self.dripleaf_set("minecraft:big_dripleaf", pos, fluid, facing); + } + fn dripleaf_stem_place(&mut self, pos: BlockPos, fluid: FluidState, facing: Direction) { + self.dripleaf_set("minecraft:big_dripleaf_stem", pos, fluid, facing); + } + /// `BigDripleafBlock.placeWithRandomHeight`. + fn dripleaf_place_random_height(&mut self, bottom: BlockPos, facing: Direction) { + let desired = next_int_between(self.random(), 2, 5); + let mut pos = bottom; + let mut height = 0; + while height < desired && self.dripleaf_can_grow_into(pos) { + height += 1; + pos = above(pos); + } + let leaf_y = bottom.y + height - 1; + pos = bottom; + while pos.y < leaf_y { + let fluid = self.fluid_at(pos); + self.dripleaf_stem_place(pos, fluid, facing); + pos = above(pos); + } + let fluid = self.fluid_at(pos); + self.dripleaf_place(pos, fluid, facing); + } + + // ---- MultifaceSpreader (glow lichen, default config) ---- + + /// `SpreadType.getSpreadPos` for SAME_POSITION, SAME_PLANE, WRAP_AROUND. + fn spread_positions( + pos: BlockPos, + spread: Direction, + from: Direction, + ) -> [(BlockPos, Direction); 3] { + [ + (pos, spread), + (rel(pos, spread), from), + (rel(rel(pos, spread), from), spread.opposite()), + ] + } + /// `DefaultSpreaderConfig.canSpreadInto`. + fn lichen_can_spread_into( + &self, + block: super::states::BlockId, + at: BlockPos, + face: Direction, + ) -> bool { + let b = self.b; + let existing = self.state(at); + let replaceable = b.is_air(existing) + || b.is_block(existing, block) + || (b.is_block(existing, b.named.water) && b.fluid(existing).is_source()); + replaceable + && !(b.is_block(existing, block) && self.multiface_has_face(existing, face)) + && b.multiface_can_attach(self.state(rel(at, face)), face) + } + /// `MultifaceSpreader.getSpreadFromFaceTowardDirection`. + fn lichen_spread_target( + &self, + state: BlockStateId, + pos: BlockPos, + from: Direction, + spread: Direction, + ) -> Option<(BlockPos, Direction)> { + if crate::level::query::axis_of(spread) == crate::level::query::axis_of(from) { + return None; + } + if !(self.multiface_has_face(state, from) && !self.multiface_has_face(state, spread)) { + return None; + } + let block = self.b.block(state); + Self::spread_positions(pos, spread, from) + .into_iter() + .find(|&(at, face)| self.lichen_can_spread_into(block, at, face)) + } + fn lichen_can_spread_in_any_direction( + &self, + state: BlockStateId, + pos: BlockPos, + from: Direction, + ) -> bool { + Direction::ALL.iter().any(|&spread| { + self.lichen_spread_target(state, pos, from, spread) + .is_some() + }) + } + fn shuffled_directions(&mut self) -> [Direction; 6] { + let mut directions = Direction::ALL; + for i in (2..=directions.len()).rev() { + let swap = self.next_int(i as i32) as usize; + directions.swap(i - 1, swap); + } + directions + } + /// `MultifaceSpreader.spreadFromRandomFaceTowardRandomDirection`. + fn lichen_spread_random(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let block = b.block(state); + for from in self.shuffled_directions() { + if !self.multiface_has_face(state, from) { + continue; + } + for spread in self.shuffled_directions() { + let Some((at, face)) = self.lichen_spread_target(state, pos, from, spread) else { + continue; + }; + let old = self.state(at); + // MultifaceBlock.getStateForPlacement then setBlock(..., 2). + let base = if b.is_block(old, block) { + old + } else if b.fluid(old) == FluidState::WATER { + b.table + .set_bool(b.default_of(block), b.props.waterlogged, true) + } else { + b.default_of(block) + }; + let placed = b.table.set_bool(base, self.direction_prop(face), true); + if self.set_block(at, placed, 2) { + return; + } + } + } + } + + // ---- water plants and grass ---- + + /// `BoneMealItem.growWaterPlant`. + pub(crate) fn grow_water_plant(&mut self, pos: BlockPos, face: Option) -> bool { + let b = self.b; + let start = self.state(pos); + if !(b.is_block(start, b.named.water) && b.fluid(start).amount() == 8) { + return false; + } + let seagrass = b.default_of(b.named.seagrass); + let features = b.live_features(); + 'attempts: for j in 0..128 { + let mut test = pos; + let mut grow = seagrass; + for _ in 0..j / 16 { + let dx = self.next_int(3) - 1; + let dy = (self.next_int(3) - 1) * self.next_int(3) / 2; + let dz = self.next_int(3) - 1; + test = test.offset(dx, dy, dz); + if b.full_collision(self.state(test)) { + continue 'attempts; + } + } + let corals = match (features, self.level.biome_name(test)) { + (Some(f), Some(biome)) => { + f.biome_in_tag(biome, "minecraft:produces_corals_from_bonemeal") + } + _ => false, + }; + if corals { + if j == 0 && face.is_some_and(|f| !matches!(f, Direction::Up | Direction::Down)) { + if let Some(coral) = self.random_tag_element("minecraft:wall_corals") { + grow = coral; + if b.table.has(grow, b.props.facing) { + grow = b.table.set_dir(grow, b.props.facing, face.unwrap()); + } + } + } else if self.next_int(4) == 0 + && let Some(plant) = self.random_tag_element("minecraft:underwater_bonemeals") + { + grow = plant; + } + } + if self.in_tag(grow, "minecraft:wall_corals") && b.table.has(grow, b.props.facing) { + let mut d = 0; + while !self.can_survive(grow, test) && d < 4 { + let facing = HORIZONTAL[self.next_int(4) as usize]; + grow = b.table.set_dir(grow, b.props.facing, facing); + d += 1; + } + } + if self.can_survive(grow, test) { + let test_state = self.state(test); + if b.is_block(test_state, b.named.water) && b.fluid(test_state).amount() == 8 { + self.set_block_and_update(test, grow); + } else if b.is_block(test_state, b.named.seagrass) + && b.is_block(self.state(above(test)), b.named.water) + && self.next_int(10) == 0 + { + self.perform_bonemeal(Kind::Seagrass, test, test_state); + } + } + } + true + } + /// `Registry.getRandomElementOf(tag, random)`: default state of a random member. + fn random_tag_element(&mut self, tag: &str) -> Option { + let features = self.b.live_features()?; + let entries = features.block_tag_entries(tag); + if entries.is_empty() { + return None; + } + let index = self.next_int(entries.len() as i32) as usize; + self.block_named(&entries[index]) + } + /// `GrassBlock.performBonemeal`. + fn grass_bonemeal(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let block = b.block(state); + let start = above(pos); + 'attempts: for attempt in 0..128 { + let mut test = start; + for _ in 0..attempt / 16 { + let dx = self.next_int(3) - 1; + let dy = (self.next_int(3) - 1) * self.next_int(3) / 2; + let dz = self.next_int(3) - 1; + test = test.offset(dx, dy, dz); + // stopBonemealSpread + if !b.is_block(self.below_state(test), block) || b.full_collision(self.state(test)) + { + continue 'attempts; + } + } + self.grass_bonemeal_effect(test); + } + } + /// `GrassBlock.placeBonemealEffect`. + fn grass_bonemeal_effect(&mut self, test: BlockPos) { + let b = self.b; + let test_state = self.state(test); + if b.table.name(test_state) == "minecraft:short_grass" + && self.random().next_float() < 0.1 + && self.bonemeal_valid(Kind::TallGrass, test, test_state) + { + self.perform_bonemeal(Kind::TallGrass, test, test_state); + } + if b.is_air(test_state) && self.is_inside_build_height(test.y) { + if self.random().next_float() < 0.125 { + let Some(features) = b.live_features() else { + return; + }; + let Some(biome) = self + .level + .biome_name(test) + .and_then(|name| features.biome_id(name)) + else { + return; + }; + let list = features.bone_meal_features(biome); + if list.is_empty() { + return; + } + let feature = list[self.next_int(list.len() as i32) as usize].clone(); + self.place_configured_feature(&feature, test); + } else { + self.place_placed_feature("minecraft:grass_bonemeal", test); + } + } + } +} diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 854248aa7..73efe9158 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -1084,6 +1084,7 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result { + pub sim: &'s mut Sim<'a, L>, + pub features: &'s LiveFeatures, +} + +fn pos([x, y, z]: [i32; 3]) -> BlockPos { + BlockPos::new(x, y, z) +} + +impl LevelFeatureWorld<'_, '_, L> { + fn sea(&self) -> i32 { + match self.sim.level.dimension() { + super::Dimension::Nether => 32, + super::Dimension::End => 0, + super::Dimension::Overworld => 63, + } + } + fn in_tag(&self, state: BlockStateId, tag: &str) -> bool { + let name = tag.trim_start_matches('#'); + self.sim + .b + .tag(name) + .is_some_and(|set| set.contains(self.sim.b.block(state))) + } +} + +impl FeatureWorld for LevelFeatureWorld<'_, '_, L> { + type Error = PlacementQueryError; + fn block(&mut self, position: [i32; 3]) -> Result { + Ok(self.sim.state(pos(position))) + } + fn set_block( + &mut self, + position: [i32; 3], + state: BlockStateId, + flags: i32, + ) -> Result { + Ok(self.sim.set_block(pos(position), state, flags)) + } +} + +impl PlacementContext for LevelFeatureWorld<'_, '_, L> { + /// `StructureTemplate.updateShapeAtEdge` for one face. + fn update_shape_at_face( + &mut self, + position: [i32; 3], + direction: Direction, + flags: i32, + ) -> Result<(), PlacementQueryError> { + let place = pos(position); + let neighbour_pos = rel(place, direction); + let state = self.sim.state(place); + let neighbour = self.sim.state(neighbour_pos); + let new_state = self + .sim + .update_shape(state, place, direction, neighbour_pos, neighbour); + if new_state != state { + self.sim.set_block(place, new_state, flags & !1); + } + let new_neighbour = self.sim.update_shape( + neighbour, + neighbour_pos, + direction.opposite(), + place, + new_state, + ); + if new_neighbour != neighbour { + self.sim.set_block(neighbour_pos, new_neighbour, flags & !1); + } + Ok(()) + } + fn set_section_block( + &mut self, + position: [i32; 3], + state: BlockStateId, + ) -> Result<(), PlacementQueryError> { + self.sim.level.set_raw(pos(position), state); + Ok(()) + } + fn collision_full_block( + &mut self, + state: BlockStateId, + _position: [i32; 3], + ) -> Result { + Ok(self.sim.b.full_collision(state)) + } + fn world_seed(&mut self) -> Result { + Ok(self.sim.level.world_seed()) + } + fn state_collision_empty( + &mut self, + state: BlockStateId, + _position: [i32; 3], + ) -> Result { + Ok(self.sim.b.has_flag(state, state_flags::COLLISION_EMPTY)) + } + /// Live levels hold no loot-table containers placed by these features. + fn set_block_entity_loot_table( + &mut self, + _position: [i32; 3], + _table: &str, + _random: &mut impl RandomSource, + ) -> Result<(), PlacementQueryError> { + Ok(()) + } + fn block_brightness(&mut self, position: [i32; 3]) -> Result { + Ok(self.sim.level.block_light(pos(position))) + } + fn fluid_state(&mut self, position: [i32; 3]) -> Result { + Ok(self.sim.fluid_at(pos(position))) + } + fn destroy_block_without_entity( + &mut self, + position: [i32; 3], + drop_resources: bool, + ) -> Result { + Ok(self + .sim + .destroy_block(pos(position), drop_resources, super::flags::UPDATE_LIMIT)) + } + fn sea_level(&mut self) -> Result { + Ok(self.sea()) + } + fn schedule_fluid_tick( + &mut self, + position: [i32; 3], + fluid: FluidKind, + delay: i32, + ) -> Result<(), PlacementQueryError> { + self.sim.schedule_fluid_tick(pos(position), fluid, delay); + Ok(()) + } + /// Live chunks are already post-processed. + fn mark_postprocessing(&mut self, _position: [i32; 3]) -> Result<(), PlacementQueryError> { + Ok(()) + } + fn water_at(&mut self, position: [i32; 3]) -> Result { + let kind = self.sim.fluid_at(pos(position)).kind(); + Ok(self.sim.b.is_water_fluid(kind)) + } + fn attachment_at( + &mut self, + position: [i32; 3], + direction: Direction, + ) -> Result { + let neighbour = self.sim.state(rel(pos(position), direction)); + Ok(self.sim.b.multiface_can_attach(neighbour, direction)) + } + fn next_world_boolean(&mut self) -> Result { + Ok(self.sim.random().next_boolean()) + } + fn next_world_float(&mut self) -> Result { + Ok(self.sim.random().next_float()) + } + fn next_world_int(&mut self, bound: i32) -> Result { + self.sim + .random() + .next_int_bound(bound) + .map_err(|e| PlacementQueryError::Failed(e.to_string())) + } + fn schedule_block_tick( + &mut self, + position: [i32; 3], + block: BlockStateId, + delay: i32, + ) -> Result<(), PlacementQueryError> { + let block = self.sim.b.block(block); + self.sim.schedule_tick(pos(position), block, delay); + Ok(()) + } + fn block_survives( + &mut self, + state: BlockStateId, + position: [i32; 3], + ) -> Result { + Ok(self.sim.can_survive(state, pos(position))) + } + fn state_face_sturdy( + &mut self, + state: BlockStateId, + _position: [i32; 3], + direction: Direction, + ) -> Result { + Ok(self.sim.b.is_face_sturdy(state, direction)) + } + fn face_sturdy( + &mut self, + position: [i32; 3], + direction: Direction, + ) -> Result { + let state = self.sim.state(pos(position)); + Ok(self.sim.b.is_face_sturdy(state, direction)) + } + fn center_sturdy( + &mut self, + position: [i32; 3], + direction: Direction, + ) -> Result { + let state = self.sim.state(pos(position)); + Ok(self.sim.b.is_face_sturdy_center(state, direction)) + } + fn unobstructed_block(&mut self, position: [i32; 3]) -> Result { + let stone = self.sim.b.default_of(self.sim.b.named.stone); + Ok(self.sim.level.is_unobstructed(pos(position), stone)) + } + fn biome_identity(&mut self, position: [i32; 3]) -> Result { + self.sim + .level + .biome_name(pos(position)) + .and_then(|name| self.features.biome_id(name)) + .ok_or(PlacementQueryError::Unavailable) + } + fn block_state(&mut self, position: [i32; 3]) -> Result { + Ok(self.sim.state(pos(position))) + } + fn block_matches_tag( + &mut self, + position: [i32; 3], + tag: &str, + ) -> Result { + let state = self.sim.state(pos(position)); + Ok(self.in_tag(state, tag)) + } + fn max_y(&mut self) -> Result { + Ok(self.sim.level.max_y() - 1) + } + fn layer_block(&mut self, position: [i32; 3]) -> Result { + let state = self.sim.state(pos(position)); + let b = self.sim.b; + let block = b.block(state); + Ok( + if b.is_air(state) || block == b.named.water || block == b.named.lava { + LayerBlock::Empty + } else if b.table.name(state) == "minecraft:bedrock" { + LayerBlock::Bedrock + } else { + LayerBlock::Ground + }, + ) + } + fn generation(&self) -> WorldGenerationContext { + let min_y = self.sim.level.min_y(); + WorldGenerationContext::new(min_y, self.sim.level.max_y() - min_y, self.sea()) + } + fn min_y(&mut self) -> Result { + Ok(self.sim.level.min_y()) + } + /// `Level.getHeight(type, x, z)`: one above the highest matching block. + fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result { + let (min, max) = (self.sim.level.min_y(), self.sim.level.max_y()); + for y in (min..max).rev() { + let state = self.sim.state(BlockPos::new(x, y, z)); + let fluid = self.sim.b.fluid(state).kind() != FluidKind::Empty; + let matches = match kind { + HeightmapType::WorldSurface | HeightmapType::WorldSurfaceWg => { + !self.sim.b.is_air(state) + } + HeightmapType::OceanFloor | HeightmapType::OceanFloorWg => { + self.in_tag(state, "minecraft:blocks_motion_in_heightmap") + } + HeightmapType::MotionBlocking => { + fluid || self.in_tag(state, "minecraft:blocks_motion_in_heightmap") + } + HeightmapType::MotionBlockingNoLeaves => { + fluid || self.in_tag(state, "minecraft:blocks_motion_in_heightmap_no_leaves") + } + }; + if matches { + return Ok(y + 1); + } + } + Ok(min) + } +} diff --git a/crates/horizon-world/src/level/growth.rs b/crates/horizon-world/src/level/growth.rs new file mode 100644 index 000000000..bfc1d4482 --- /dev/null +++ b/crates/horizon-world/src/level/growth.rs @@ -0,0 +1,342 @@ +//! Feature-placing growth: `TreeGrower.growTree` (saplings, mangrove +//! propagules, azaleas), huge mushrooms and nether fungi, run on the live level +//! through [`LiveFeatures`]. +use super::{Behaviours, LevelAccess, LevelEvent, Sim, feature_world::LevelFeatureWorld, flags}; +use crate::{registry::BlockStateId, worldgen::live::LiveFeatures}; +use horizon_core::{position::BlockPos, random::RandomSource}; +use std::sync::{Arc, OnceLock}; + +/// Runtime extensions of [`Behaviours`] that depend on the worldgen bundle. +#[derive(Default)] +pub struct Growth { + features: OnceLock>, +} + +impl Behaviours { + /// Install the live feature registry used by sapling growth and bone meal. + /// Without it, saplings report [`LevelEvent::GrowTree`] instead of growing. + pub fn set_live_features(&self, features: Arc) -> bool { + self.growth.features.set(features).is_ok() + } + pub fn live_features(&self) -> Option<&Arc> { + self.growth.features.get() + } +} + +/// `TreeGrower` (vanilla's registered growers, by name). +pub(crate) struct TreeGrower { + pub name: &'static str, + trees: &'static [(&'static str, i32)], + mega_trees: &'static [(&'static str, i32)], + flower_trees: &'static [(&'static str, i32)], + shortest: Option<&'static str>, +} + +pub(crate) const GROWERS: &[TreeGrower] = &[ + TreeGrower { + name: "oak", + trees: &[("minecraft:oak", 9), ("minecraft:fancy_oak", 1)], + mega_trees: &[], + flower_trees: &[ + ("minecraft:oak_bees_005", 9), + ("minecraft:fancy_oak_bees_005", 1), + ], + shortest: Some("minecraft:oak"), + }, + TreeGrower { + name: "spruce", + trees: &[("minecraft:spruce", 1)], + mega_trees: &[("minecraft:mega_spruce", 1), ("minecraft:mega_pine", 1)], + flower_trees: &[], + shortest: Some("minecraft:spruce"), + }, + TreeGrower { + name: "mangrove", + trees: &[("minecraft:mangrove", 15), ("minecraft:tall_mangrove", 85)], + mega_trees: &[], + flower_trees: &[], + shortest: Some("minecraft:mangrove"), + }, + TreeGrower { + name: "azalea", + trees: &[("minecraft:azalea_tree", 1)], + mega_trees: &[], + flower_trees: &[], + shortest: Some("minecraft:azalea_tree"), + }, + TreeGrower { + name: "birch", + trees: &[("minecraft:birch", 1)], + mega_trees: &[], + flower_trees: &[("minecraft:birch_bees_005", 1)], + shortest: Some("minecraft:birch"), + }, + TreeGrower { + name: "jungle", + trees: &[("minecraft:jungle_tree_no_vine", 1)], + mega_trees: &[("minecraft:mega_jungle_tree", 1)], + flower_trees: &[], + shortest: Some("minecraft:jungle_tree_no_vine"), + }, + TreeGrower { + name: "acacia", + trees: &[("minecraft:acacia", 1)], + mega_trees: &[], + flower_trees: &[], + shortest: Some("minecraft:acacia"), + }, + TreeGrower { + name: "cherry", + trees: &[("minecraft:cherry", 1)], + mega_trees: &[], + flower_trees: &[("minecraft:cherry_bees_005", 1)], + shortest: Some("minecraft:cherry"), + }, + TreeGrower { + name: "dark_oak", + trees: &[], + mega_trees: &[("minecraft:dark_oak", 1)], + flower_trees: &[], + shortest: None, + }, + TreeGrower { + name: "pale_oak", + trees: &[], + mega_trees: &[("minecraft:pale_oak_bonemeal", 1)], + flower_trees: &[], + shortest: None, + }, + TreeGrower { + name: "poplar", + trees: &[ + ("minecraft:red_poplar", 1), + ("minecraft:orange_poplar", 1), + ("minecraft:yellow_poplar", 1), + ], + mega_trees: &[], + flower_trees: &[], + shortest: Some("minecraft:red_poplar"), + }, +]; + +pub(crate) fn grower(name: &str) -> Option<&'static TreeGrower> { + GROWERS.iter().find(|g| g.name == name) +} + +/// `WeightedList.getRandom`: no draw for an empty list. +fn weighted( + list: &'static [(&'static str, i32)], + random: &mut R, +) -> Option<&'static str> { + let total: i32 = list.iter().map(|e| e.1).sum(); + if total == 0 { + return None; + } + let mut selection = random.next_int_bound(total).unwrap_or(0); + for &(name, weight) in list { + if selection < weight { + return Some(name); + } + selection -= weight; + } + None +} + +impl Sim<'_, L> { + /// `ConfiguredFeature.place(level, generator, level.random, pos)`. The + /// feature draws from a copy of the level random that replaces it after. + pub(crate) fn place_configured_feature(&mut self, name: &str, pos: BlockPos) -> bool { + let b = self.b; + let Some(features) = b.live_features() else { + return false; + }; + let mut random = self.random().clone(); + let placed = { + let mut world = LevelFeatureWorld { + sim: self, + features, + }; + features.place_configured(name, &mut world, &mut random, [pos.x, pos.y, pos.z]) + }; + *self.random() = random; + placed + } + /// `PlacedFeature.place(level, generator, level.random, pos)`. + pub(crate) fn place_placed_feature(&mut self, name: &str, pos: BlockPos) -> bool { + let b = self.b; + let Some(features) = b.live_features() else { + return false; + }; + let mut random = self.random().clone(); + let placed = { + let mut world = LevelFeatureWorld { + sim: self, + features, + }; + features.place_placed(name, &mut world, &mut random, [pos.x, pos.y, pos.z]) + }; + *self.random() = random; + placed + } + fn feature_exists(&self, name: &str) -> bool { + self.b + .live_features() + .is_some_and(|f| f.configured(name).is_some()) + } + + /// `TreeGrower.hasFlowers`: a flower within 2 blocks horizontally, 1 vertically. + fn tree_has_flowers(&self, pos: BlockPos) -> bool { + let b = self.b; + let Some(flowers) = b.tag("minecraft:flowers") else { + return false; + }; + for y in -1..=1 { + for z in -2..=2 { + for x in -2..=2 { + if b.in_set(self.state(pos.offset(x, y, z)), flowers) { + return true; + } + } + } + } + false + } + /// `TreeGrower.findTwoByTwoSaplingPos`. + fn two_by_two( + &self, + state: BlockStateId, + pos: BlockPos, + ) -> Option<(i32, i32, [(BlockStateId, BlockPos); 4])> { + let block = self.b.block(state); + for dx in [0, -1] { + for dz in [0, -1] { + let at = |x: i32, z: i32| { + let p = pos.offset(dx + x, 0, dz + z); + (self.state(p), p) + }; + let around = [at(0, 0), at(1, 0), at(0, 1), at(1, 1)]; + if around.iter().all(|(s, _)| self.b.is_block(*s, block)) { + return Some((dx, dz, around)); + } + } + } + None + } + /// `TreeGrower.removeSapling`: the fluid's legacy block, flags 818. + fn remove_sapling(&mut self, pos: BlockPos) { + let empty = self.b.legacy_block(self.fluid_at(pos)); + self.set_block( + pos, + empty, + flags::UPDATE_SKIP_ALL_SIDEEFFECTS | flags::UPDATE_CLIENTS, + ); + } + /// `TreeGrower.growTree`. + pub(crate) fn grow_tree( + &mut self, + grower: &TreeGrower, + pos: BlockPos, + state: BlockStateId, + ) -> bool { + if let Some(mega) = weighted(grower.mega_trees, self.random()) + && self.feature_exists(mega) + && let Some((dx, dz, around)) = self.two_by_two(state, pos) + { + for &(_, p) in &around { + self.remove_sapling(p); + } + if self.place_configured_feature(mega, pos.offset(dx, 0, dz)) { + return true; + } + for &(s, p) in &around { + self.set_block(p, s, flags::UPDATE_NONE); + } + return false; + } + let flowers = self.tree_has_flowers(pos); + let list = if flowers && !grower.flower_trees.is_empty() { + grower.flower_trees + } else { + grower.trees + }; + let Some(feature) = weighted(list, self.random()) else { + return false; + }; + if !self.feature_exists(feature) { + return false; + } + self.remove_sapling(pos); + if self.place_configured_feature(feature, pos) { + return true; + } + self.set_block(pos, state, flags::UPDATE_NONE); + false + } + /// `TreeGrower.canGrow` (draws as vanilla: feature, then mega feature). + pub(crate) fn tree_can_grow( + &mut self, + grower: &TreeGrower, + pos: BlockPos, + state: BlockStateId, + ) -> bool { + let flowers = self.tree_has_flowers(pos); + let list = if flowers && !grower.flower_trees.is_empty() { + grower.flower_trees + } else { + grower.trees + }; + let feature = weighted(list, self.random()); + let mega = weighted(grower.mega_trees, self.random()); + if feature.is_none() && mega.is_some() { + self.two_by_two(state, pos).is_some() + } else { + true + } + } + /// `TreeGrower.getMinimumHeight`: the shortest tree's trunk base height. + pub(crate) fn tree_minimum_height(&self, grower: &TreeGrower) -> i32 { + grower + .shortest + .and_then(|name| self.b.live_features()?.configured_json(name)) + .filter(|json| json["type"] == "minecraft:tree") + .and_then(|json| json["trunk_placer"]["base_height"].as_i64()) + .map_or(0, |h| h as i32) + } + /// `SaplingBlock.advanceTree` with the grower run inline when features are + /// installed; otherwise reported as [`LevelEvent::GrowTree`]. + pub(crate) fn advance_tree(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if b.table.int(state, b.props.stage) == 0 { + self.set_block(pos, b.table.cycle(state, b.props.stage), flags::UPDATE_NONE); + return; + } + let Some(name) = b.data(state).feature.clone() else { + return; + }; + match grower(&name) { + Some(g) if b.live_features().is_some() => { + self.grow_tree(g, pos, state); + } + _ => self.emit(LevelEvent::GrowTree { + pos, + state, + grower: name, + }), + } + } + /// `MushroomBlock.growMushroom`. + pub(crate) fn grow_mushroom(&mut self, pos: BlockPos, state: BlockStateId) -> bool { + let Some(feature) = self.b.data(state).feature.clone() else { + return false; + }; + if !self.feature_exists(&feature) { + return false; + } + self.remove_block(pos, false); + if self.place_configured_feature(&feature, pos) { + return true; + } + self.set_block_and_update(pos, state); + false + } +} diff --git a/crates/horizon-world/src/level/growth_tests.rs b/crates/horizon-world/src/level/growth_tests.rs new file mode 100644 index 000000000..2d120335c --- /dev/null +++ b/crates/horizon-world/src/level/growth_tests.rs @@ -0,0 +1,342 @@ +//! Sapling growth and bone meal through live feature placement. Needs the +//! prepared client resources and worldgen bundle (skipped when absent). +use super::*; +use crate::{chunk::BlockState, worldgen::generator::GeneratorData, worldgen::live::LiveFeatures}; +use std::{ + collections::{BTreeMap, HashMap}, + path::PathBuf, + sync::OnceLock, +}; + +struct Fixture { + registry: &'static BlockRegistry, + behaviours: Behaviours, +} + +fn fixture() -> Option<&'static Fixture> { + static FIXTURE: OnceLock> = OnceLock::new(); + FIXTURE + .get_or_init(|| { + let root = std::env::var_os("HORIZON_RESOURCES") + .map(PathBuf::from) + .unwrap_or_else(|| { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3") + }); + // Trees need the feature block-behaviour exports in the worldgen bundle. + if !root.join("block-behaviours.json").exists() + || !root.join("worldgen/blocks/block-properties.nbt").exists() + { + eprintln!("skipping growth tests: no resources at {}", root.display()); + return None; + } + let registry: &'static BlockRegistry = + Box::leak(Box::new(data::load_registry(&root).expect("registry"))); + let behaviours = Behaviours::load(registry, &root).expect("behaviours"); + let data = + GeneratorData::load(&root.join("worldgen"), registry).expect("worldgen data"); + let features = LiveFeatures::new(&data) + .expect("features") + .expect("feature bundle"); + behaviours.set_live_features(Arc::new(features)); + Some(Fixture { + registry, + behaviours, + }) + }) + .as_ref() +} + +struct Level { + blocks: HashMap, + air: BlockStateId, + random: LegacyRandom, + events: Vec, + biome: &'static str, +} +impl LevelAccess for Level { + fn block_state(&self, pos: BlockPos) -> BlockStateId { + self.blocks.get(&pos).copied().unwrap_or(self.air) + } + fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option { + Some(self.blocks.insert(pos, state).unwrap_or(self.air)) + } + fn is_loaded(&self, _pos: BlockPos) -> bool { + true + } + fn random(&mut self) -> &mut LegacyRandom { + &mut self.random + } + fn game_time(&self) -> i64 { + 0 + } + fn block_light(&self, _pos: BlockPos) -> i32 { + 15 + } + fn emit(&mut self, event: LevelEvent) { + self.events.push(event); + } + fn biome_name(&self, _pos: BlockPos) -> Option<&str> { + Some(self.biome) + } +} + +struct World { + f: &'static Fixture, + level: Level, + ticks: Ticks, +} +impl World { + fn new(f: &'static Fixture, seed: i64) -> Self { + let mut ticks = Ticks::new(0); + for x in -4..4 { + for z in -4..4 { + ticks.add_empty_chunk(ChunkPos::new(x, z)).unwrap(); + } + } + Self { + level: Level { + blocks: HashMap::new(), + air: f.behaviours.air(), + random: LegacyRandom::new(seed), + events: Vec::new(), + biome: "minecraft:plains", + }, + f, + ticks, + } + } + fn id(&self, name: &str, props: &[(&str, &str)]) -> BlockStateId { + let state = BlockState { + name: format!("minecraft:{name}"), + properties: props + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect::>(), + }; + self.f + .registry + .resolve(&state) + .unwrap_or_else(|_| panic!("unknown state {name} {props:?}")) + } + fn floor(&mut self, name: &str, radius: i32) { + let state = self.id(name, &[]); + let stone = self.id("stone", &[]); + for x in -radius..=radius { + for z in -radius..=radius { + self.level.blocks.insert(BlockPos::new(x, 63, z), state); + self.level.blocks.insert(BlockPos::new(x, 62, z), stone); + } + } + } + fn put(&mut self, pos: BlockPos, state: BlockStateId) { + self.level.blocks.insert(pos, state); + } + fn name(&self, pos: BlockPos) -> String { + let state = self.level.block_state(pos); + self.f.registry.state(state).unwrap().name.clone() + } + fn bone_meal(&mut self, pos: BlockPos) -> bool { + self.f + .behaviours + .use_bone_meal(&mut self.level, &mut self.ticks, pos, Direction::Up) + } + fn count(&self, suffix: &str) -> usize { + self.level + .blocks + .values() + .filter(|&&s| self.f.registry.state(s).unwrap().name.ends_with(suffix)) + .count() + } +} + +fn grow(sapling: &str, soil: &str, positions: &[(i32, i32)], log: &str) { + let Some(f) = fixture() else { return }; + let mut grown = 0; + for seed in 0..6 { + let mut w = World::new(f, seed); + w.floor(soil, 12); + let state = w.id(sapling, &[]); + for &(x, z) in positions { + w.put(BlockPos::new(x, 64, z), state); + } + let origin = BlockPos::new(0, 64, 0); + let mut uses = 0; + while w.name(origin) == format!("minecraft:{sapling}") && uses < 64 { + assert!(w.bone_meal(origin), "{sapling} is a bone meal target"); + uses += 1; + } + if w.count(log) > 0 { + grown += 1; + assert_eq!( + w.name(origin), + format!("minecraft:{log}"), + "{sapling} trunk at origin" + ); + } + } + assert!(grown >= 5, "{sapling}: grew {grown} of 6 times"); +} + +#[test] +fn oak_sapling_grows_with_bone_meal() { + grow("oak_sapling", "grass_block", &[(0, 0)], "oak_log"); +} +#[test] +fn single_saplings_grow() { + grow("birch_sapling", "dirt", &[(0, 0)], "birch_log"); + grow("spruce_sapling", "dirt", &[(0, 0)], "spruce_log"); + grow("jungle_sapling", "dirt", &[(0, 0)], "jungle_log"); + grow("acacia_sapling", "dirt", &[(0, 0)], "acacia_log"); + grow("cherry_sapling", "grass_block", &[(0, 0)], "cherry_log"); + grow("poplar_sapling", "grass_block", &[(0, 0)], "poplar_log"); +} +#[test] +fn two_by_two_saplings_grow() { + let square = [(0, 0), (1, 0), (0, 1), (1, 1)]; + grow("dark_oak_sapling", "grass_block", &square, "dark_oak_log"); + grow("pale_oak_sapling", "grass_block", &square, "pale_oak_log"); + grow("spruce_sapling", "podzol", &square, "spruce_log"); + grow("jungle_sapling", "grass_block", &square, "jungle_log"); +} +#[test] +fn lone_dark_oak_sapling_cannot_grow() { + let Some(f) = fixture() else { return }; + let mut w = World::new(f, 1); + w.floor("grass_block", 4); + let sapling = w.id("dark_oak_sapling", &[]); + w.put(BlockPos::new(0, 64, 0), sapling); + assert!(!w.bone_meal(BlockPos::new(0, 64, 0))); +} +#[test] +fn azalea_and_mangrove_grow() { + let Some(f) = fixture() else { return }; + for (block, soil, log) in [ + ("azalea", "grass_block", "oak_log"), + ("mangrove_propagule", "mud", "mangrove_log"), + ] { + let mut grew = false; + for seed in 0..6 { + let mut w = World::new(f, seed); + w.floor(soil, 12); + let state = w.id(block, &[]); + w.put(BlockPos::new(0, 64, 0), state); + for _ in 0..64 { + if w.count(log) > 0 { + break; + } + w.bone_meal(BlockPos::new(0, 64, 0)); + } + grew |= w.count(log) > 0; + } + assert!(grew, "{block} grows into a tree"); + } +} +#[test] +fn random_ticks_advance_sapling_stage_then_grow() { + let Some(f) = fixture() else { return }; + let mut w = World::new(f, 3); + w.floor("grass_block", 8); + let sapling = w.id("oak_sapling", &[]); + let pos = BlockPos::new(0, 64, 0); + w.put(pos, sapling); + for _ in 0..2000 { + let state = w.level.block_state(pos); + if !f.behaviours.is_randomly_ticking(state) { + break; + } + f.behaviours.random_tick(&mut w.level, &mut w.ticks, pos); + } + assert_eq!(w.name(pos), "minecraft:oak_log"); +} +#[test] +fn grass_bone_meal_places_grass_and_flowers() { + let Some(f) = fixture() else { return }; + let mut w = World::new(f, 7); + w.floor("grass_block", 8); + assert!(w.bone_meal(BlockPos::new(0, 63, 0))); + let plants = w.count("short_grass") + w.count("tall_grass"); + let flowers = w.count("dandelion") + + w.count("poppy") + + w.count("cornflower") + + w.count("oxeye_daisy") + + w.count("azure_bluet") + + w.count("_tulip"); + assert!(plants > 10, "grass placed: {plants}"); + assert!(plants + flowers > 15); + assert!( + w.level + .events + .iter() + .any(|e| matches!(e, LevelEvent::LevelEvent { id: 1505, .. })) + ); +} +#[test] +fn huge_mushroom_and_fungus_grow() { + let Some(f) = fixture() else { return }; + let mut grew = (false, false); + for seed in 0..8 { + let mut w = World::new(f, seed); + w.floor("mycelium", 8); + let mushroom = w.id("red_mushroom", &[]); + w.put(BlockPos::new(0, 64, 0), mushroom); + for _ in 0..16 { + w.bone_meal(BlockPos::new(0, 64, 0)); + } + grew.0 |= w.count("red_mushroom_block") > 0 && w.count("mushroom_stem") > 0; + let mut w = World::new(f, seed); + w.floor("crimson_nylium", 8); + let fungus = w.id("crimson_fungus", &[]); + w.put(BlockPos::new(0, 64, 0), fungus); + for _ in 0..16 { + if w.count("crimson_stem") > 0 { + break; + } + w.bone_meal(BlockPos::new(0, 64, 0)); + } + grew.1 |= w.count("crimson_stem") > 0 && w.count("nether_wart_block") > 0; + } + assert!(grew.0, "huge red mushroom"); + assert!(grew.1, "huge crimson fungus"); +} +#[test] +fn crops_age_with_bone_meal() { + let Some(f) = fixture() else { return }; + let mut w = World::new(f, 11); + let farmland = w.id("farmland", &[]); + let pos = BlockPos::new(0, 64, 0); + w.put(BlockPos::new(0, 63, 0), farmland); + w.put(pos, w.id("wheat", &[])); + let mut uses = 0; + while w.bone_meal(pos) { + uses += 1; + } + assert!((2..=4).contains(&uses), "wheat matured after {uses} uses"); + assert_eq!(w.level.block_state(pos), w.id("wheat", &[("age", "7")])); + w.put(pos, w.id("torchflower_crop", &[])); + assert!(w.bone_meal(pos)); + assert!(w.bone_meal(pos)); + assert_eq!(w.name(pos), "minecraft:torchflower"); + assert!(!w.bone_meal(pos), "torchflowers are not bonemealable"); +} +#[test] +fn tall_flowers_and_seagrass() { + let Some(f) = fixture() else { return }; + let mut w = World::new(f, 5); + w.floor("dirt", 2); + let fern = w.id("fern", &[]); + w.put(BlockPos::new(0, 64, 0), fern); + assert!(w.bone_meal(BlockPos::new(0, 64, 0))); + assert_eq!(w.name(BlockPos::new(0, 64, 0)), "minecraft:large_fern"); + assert_eq!(w.name(BlockPos::new(0, 65, 0)), "minecraft:large_fern"); + let lilac = w.id("lilac", &[("half", "lower")]); + w.put(BlockPos::new(1, 64, 0), lilac); + assert!(w.bone_meal(BlockPos::new(1, 64, 0))); + assert!(w.level.events.iter().any(|e| matches!( + e, + LevelEvent::BlockEvent { + kind: "pop_block_item", + .. + } + ))); +} diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index ee7dca6b9..45b6ebaaf 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -100,8 +100,11 @@ pub mod data; pub mod states; pub mod ticks; +mod bonemeal; mod falling; +mod feature_world; mod fluids; +mod growth; mod hooks; mod interact; pub mod pistons; @@ -115,6 +118,8 @@ mod survive; mod tick; mod update; +#[cfg(test)] +mod growth_tests; #[cfg(test)] mod tests; @@ -337,6 +342,15 @@ pub trait LevelAccess { true } fn emit(&mut self, _event: LevelEvent) {} + /// Biome identifier at `pos` (`minecraft:plains`), for features placed by + /// block behaviour (bone meal flowers). None when unknown. + fn biome_name(&self, _pos: BlockPos) -> Option<&str> { + None + } + /// World seed (`WorldGenLevel.getSeed`) for seed-derived feature noise. + fn world_seed(&self) -> i64 { + 0 + } } /// Raw brightness as `Level.getRawBrightness(pos, skyDarken)`. @@ -361,6 +375,7 @@ pub struct Behaviours { /// Uncached (position- or block-entity-dependent) collision shapes. dynamic: HashMap, occlusion_cache: Mutex>, + growth: growth::Growth, } impl Behaviours { diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 555ba2a85..548ba97da 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -708,11 +708,12 @@ impl Sim<'_, L> { return; } let age = b.table.int(state, b.props.age); - let max = b.table.int_range(state, b.props.age).map_or(7, |r| r.1); + let max = self.crop_max_age(state); if age < max { let speed = self.crop_growth_speed(b.block(state), pos); if self.rand_int((25.0 / speed) as i32 + 1) == 0 { - self.set_block(pos, b.table.set_int(state, b.props.age, age + 1), 2); + let next = self.crop_state_for_age(state, age + 1); + self.set_block(pos, next, 2); } } } @@ -789,11 +790,12 @@ impl Sim<'_, L> { self.set_block(upper_pos, upper, 3); } } - fn growing_plant_can_grow_into(&self, plant: BlockStateId, state: BlockStateId) -> bool { + pub(crate) fn growing_plant_can_grow_into(&self, plant: BlockStateId, state: BlockStateId) -> bool { let b = self.b; let data = b.data(plant); if data.is(Class::Kelp) { - b.is_block(state, b.named.water) && b.fluid(state).amount() == 8 + // KelpBlock.canGrowInto: any water block state. + b.is_block(state, b.named.water) } else { // NetherVines.isValidGrowthState / CaveVines: air only. b.is_air(state) @@ -868,12 +870,7 @@ impl Sim<'_, L> { } /// `SaplingBlock.advanceTree`. pub(crate) fn sapling_advance_tree(&mut self, pos: BlockPos, state: BlockStateId) { - let b = self.b; - if b.table.int(state, b.props.stage) == 0 { - self.set_block(pos, b.table.cycle(state, b.props.stage), 260); - } else if let Some(grower) = b.data(state).feature.clone() { - self.emit(LevelEvent::GrowTree { pos, state, grower }); - } + self.advance_tree(pos, state); } fn mushroom_random_tick(&mut self, state: BlockStateId, mut pos: BlockPos) { let b = self.b; @@ -1013,13 +1010,13 @@ impl Sim<'_, L> { self.set_block_and_update(grow, state); } } - fn bamboo_sapling_grow(&mut self, pos: BlockPos) { + pub(crate) fn bamboo_sapling_grow(&mut self, pos: BlockPos) { let b = self.b; let bamboo = b.default_of(b.named.bamboo); let state = b.table.set_text(bamboo, b.props.leaves, "small"); self.set_block(above(pos), state, 3); } - fn bamboo_height_below(&self, pos: BlockPos) -> i32 { + pub(crate) fn bamboo_height_below(&self, pos: BlockPos) -> i32 { let mut height = 0; while height < 16 && self.b.is_block( @@ -1031,7 +1028,7 @@ impl Sim<'_, L> { } height } - fn bamboo_height_above(&self, pos: BlockPos) -> i32 { + pub(crate) fn bamboo_height_above(&self, pos: BlockPos) -> i32 { let mut height = 0; while height < 16 && self.b.is_block( @@ -1044,7 +1041,7 @@ impl Sim<'_, L> { height } /// `BambooStalkBlock.growBamboo`. - fn bamboo_grow(&mut self, state: BlockStateId, pos: BlockPos, height: i32) { + pub(crate) fn bamboo_grow(&mut self, state: BlockStateId, pos: BlockPos, height: i32) { let b = self.b; let p = b.props; let below_state = self.below_state(pos); diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index ec7eeda6f..36fb43fb3 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -43,6 +43,7 @@ mod generator_decoration; mod generator_structures; pub mod height_provider; pub mod iceberg; +pub mod live; pub mod material_condition; pub mod material_extensions; pub mod material_stage; diff --git a/crates/horizon-world/src/worldgen/live.rs b/crates/horizon-world/src/worldgen/live.rs new file mode 100644 index 000000000..7460d1450 --- /dev/null +++ b/crates/horizon-world/src/worldgen/live.rs @@ -0,0 +1,316 @@ +//! Configured and placed features for a live level: what vanilla block +//! behaviour reaches through `Feature.place(level, generator, random, pos)` +//! on a `ServerLevel` (sapling and fungus growth, bone meal on grass, nylium, +//! moss, huge mushrooms). Definitions are decoded lazily by name from the same +//! worldgen bundle as decoration and cached. +use super::{ + biome::BiomeId, + biome_predicate::BiomePredicateBindings, + block_feature::FeatureBlockBindings, + feature::{FeatureBlocks, FeatureWorld}, + feature_catalog::FeatureCatalog, + feature_graph::{FeatureDefinition, PlacedFeatureDefinition}, + generator::{GeneratorData, GeneratorError}, + placement::PlacementContext, + state_provider::{StateProviderBindings, StateProviderCatalog}, + tags::TagDefinitions, +}; +use crate::block_placement::BlockPlacementBindings; +use horizon_core::random::RandomSource; +use serde_json::Value; +use std::{ + collections::{BTreeSet, HashMap}, + sync::{Arc, Mutex}, +}; + +type Cache = Mutex>>>; + +pub struct LiveFeatures { + data: Arc, + catalog: FeatureCatalog, + bindings: FeatureBlockBindings<'static>, + blocks: FeatureBlocks, + configured: Cache, + placed: Cache, + /// `BiomeGenerationSettings.getBoneMealFeatures` per biome, in vanilla order. + bone_meal: Vec>, +} + +fn resource(message: impl Into) -> GeneratorError { + GeneratorError::Resource(message.into()) +} + +/// `ConfiguredFeature.getFeatures`: nested configured-feature references of a +/// feature JSON, depth first (each reference followed by its own children). +fn nested_features( + json: &Value, + features: &std::collections::BTreeMap, + depth: usize, + out: &mut Vec, +) { + if depth > 64 { + return; + } + match json { + Value::Object(map) => { + for (key, value) in map { + if key == "feature" + && let Some(name) = value.as_str() + { + let name = super::tags::identifier(name).unwrap_or_else(|_| name.to_owned()); + out.push(name.clone()); + if let Some(child) = features + .get(&name) + .and_then(|text| serde_json::from_str::(text).ok()) + { + nested_features(&child, features, depth + 1, out); + } + } else { + nested_features(value, features, depth + 1, out); + } + } + } + Value::Array(values) => { + for value in values { + nested_features(value, features, depth + 1, out); + } + } + _ => {} + } +} + +impl LiveFeatures { + /// None when the bundle carries no feature resources. + pub fn new(data: &Arc) -> Result, GeneratorError> { + let Some(resources) = &data.feature_resources else { + return Ok(None); + }; + let registry = data.registry(); + let mut feature_tags = TagDefinitions::default(); + for (name, json) in &resources.feature_tags { + feature_tags.apply_json(name, "vanilla", json)?; + } + let catalog = + FeatureCatalog::from_resources(&resources.features, &resources.placed, &feature_tags)?; + let biomes = Arc::new(BiomePredicateBindings::new( + &data + .biome_names() + .iter() + .enumerate() + .map(|(i, name)| (name.to_string(), BiomeId(i as u32))) + .collect(), + &data.biome_tags, + )?); + let mut bindings = + FeatureBlockBindings::with_tags(registry, data.integers().clone(), &data.block_tags)? + .with_fluid_tags(&resources.fluid_tags)? + .with_biomes(biomes.clone()); + if let Some(structures) = &data.structures { + bindings = bindings.with_structures(structures.clone()); + } + if let Some(blocks) = &resources.blocks { + bindings = bindings + .with_block_properties(&blocks.properties)? + .with_state_providers( + StateProviderBindings::new( + registry, + data.integers().clone(), + &data.block_tags, + )? + .with_block_properties(&blocks.properties)? + .with_fluid_tags(&resources.fluid_tags)? + .with_biomes(biomes), + StateProviderCatalog::from_resources(&resources.state_providers)?, + BlockPlacementBindings::new( + registry, + &blocks.properties, + &blocks.double_plants, + &blocks.mossy_carpets, + )?, + )?; + } + // Configured-feature tag membership (feature_tags names configured features). + let mut bone_meal_tag = BTreeSet::new(); + if let Some(json) = resources + .feature_tags + .get("minecraft:can_spawn_from_bone_meal") + { + let value: Value = serde_json::from_str(json)?; + for entry in value["values"].as_array().into_iter().flatten() { + if let Some(name) = entry.as_str() { + bone_meal_tag.insert(super::tags::identifier(name)?); + } + } + } + let placed_tags = feature_tags + .build(|name, _| resources.placed.contains_key(name).then(|| name.to_owned())) + .map_err(|e| resource(format!("feature tags: {e:?}")))? + .tags; + let mut bone_meal = Vec::with_capacity(data.biome_names().len()); + for i in 0..data.biome_names().len() { + let biome: Value = serde_json::from_str(data.biome_json(BiomeId(i as u32)))?; + let mut list = Vec::new(); + for step in biome["features"].as_array().into_iter().flatten() { + let entries: Vec = match step { + Value::String(tag) if tag.starts_with('#') => placed_tags + .get(&super::tags::identifier(&tag[1..])?) + .cloned() + .unwrap_or_default(), + Value::String(name) => vec![name.clone()], + Value::Array(values) => values + .iter() + .filter_map(|v| v.as_str().map(str::to_owned)) + .collect(), + _ => Vec::new(), + }; + for entry in entries { + let name = super::tags::identifier(&entry)?; + let Some(placed) = resources + .placed + .get(&name) + .and_then(|text| serde_json::from_str::(text).ok()) + else { + continue; + }; + // PlacedFeature.getFeatures: its feature, then that feature's children. + let mut found = Vec::new(); + match &placed["feature"] { + Value::String(feature) => { + let feature = super::tags::identifier(feature)?; + found.push(feature.clone()); + if let Some(child) = resources + .features + .get(&feature) + .and_then(|text| serde_json::from_str::(text).ok()) + { + nested_features(&child, &resources.features, 0, &mut found); + } + } + inline => nested_features(inline, &resources.features, 0, &mut found), + } + list.extend(found.into_iter().filter(|f| bone_meal_tag.contains(f))); + } + } + bone_meal.push(list); + } + Ok(Some(Self { + data: data.clone(), + catalog, + bindings, + blocks: FeatureBlocks::from_registry(registry)?, + configured: Mutex::new(HashMap::new()), + placed: Mutex::new(HashMap::new()), + bone_meal, + })) + } + pub fn data(&self) -> &Arc { + &self.data + } + pub fn biome_id(&self, name: &str) -> Option { + self.data.biome_id(name) + } + /// Raw JSON of a configured feature (for configuration values such as a + /// trunk placer's base height). + pub fn configured_json(&self, name: &str) -> Option { + let resources = self.data.feature_resources.as_ref()?; + serde_json::from_str(resources.features.get(name)?).ok() + } + pub fn configured(&self, name: &str) -> Option> { + let mut cache = self.configured.lock().unwrap(); + cache + .entry(name.to_owned()) + .or_insert_with(|| { + match self + .catalog + .feature_with_blocks(&Value::from(name).to_string(), &self.bindings) + { + Ok(f) => Some(Arc::new(f)), + Err(e) => { + eprintln!("Horizon: feature {name} cannot be placed: {e}"); + None + } + } + }) + .clone() + } + pub fn placed(&self, name: &str) -> Option> { + let mut cache = self.placed.lock().unwrap(); + cache + .entry(name.to_owned()) + .or_insert_with(|| { + match self + .catalog + .placed_feature_with_blocks(&Value::from(name).to_string(), &self.bindings) + { + Ok(f) => Some(Arc::new(f)), + Err(e) => { + eprintln!("Horizon: placed feature {name} cannot be placed: {e}"); + None + } + } + }) + .clone() + } + /// `ConfiguredFeature.place`. Unknown or unsupported features and + /// execution errors report failure. + pub fn place_configured( + &self, + name: &str, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + ) -> bool + where + W::Error: std::fmt::Display, + { + let Some(feature) = self.configured(name) else { + return false; + }; + match feature.place(world, random, origin, self.blocks) { + Ok(placed) => placed, + Err(e) => { + eprintln!("Horizon: placing {name} failed: {e}"); + false + } + } + } + /// `PlacedFeature.place` (placement modifiers, then the feature). + pub fn place_placed( + &self, + name: &str, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + ) -> bool + where + W::Error: std::fmt::Display, + { + let Some(feature) = self.placed(name) else { + return false; + }; + match feature.place(world, random, origin, self.blocks) { + Ok(placed) => placed, + Err(e) => { + eprintln!("Horizon: placing {name} failed: {e}"); + false + } + } + } + /// Whether the named biome is in a biome tag (`minecraft:...`). + pub fn biome_in_tag(&self, biome: &str, tag: &str) -> bool { + self.data + .biome_tags + .get(tag) + .is_some_and(|members| members.iter().any(|m| m == biome)) + } + /// A block tag's members in registry tag order (for `getRandomElementOf`). + pub fn block_tag_entries(&self, tag: &str) -> &[String] { + self.data.block_tags.get(tag).map_or(&[], Vec::as_slice) + } + /// `BiomeGenerationSettings.getBoneMealFeatures` of a biome. + pub fn bone_meal_features(&self, biome: BiomeId) -> &[String] { + self.bone_meal + .get(biome.0 as usize) + .map_or(&[], Vec::as_slice) + } +} From cc32d9e8a0e0154f51282c2d265a7341522de468 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:20:22 +0200 Subject: [PATCH 2/8] Grow trees and apply bone meal in the client; add block control commands Install the live feature registry (sharing the generator's worldgen bundle), route bone meal through BoneMealItem.useOn, report biome names and the world seed to block behaviour, play the bone meal sound and pop items from tall flowers. GameLevel::max_y is now exclusive as LevelAccess documents. New horizon-ctl commands: setblock, fill, getblock, container. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 25 +++- crates/horizon-client/src/game/blockctl.rs | 151 +++++++++++++++++++++ crates/horizon-client/src/game/control.rs | 5 +- crates/horizon-client/src/game/growth.rs | 57 ++++++++ crates/horizon-client/src/vanillagen.rs | 14 +- 5 files changed, 249 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-client/src/game/blockctl.rs create mode 100644 crates/horizon-client/src/game/growth.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6f6b063aa..158fa0335 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1,6 +1,8 @@ //! The playable game loop: streaming world, player simulation at 20 ticks/s, //! block interaction, inventory and HUD. +mod blockctl; mod control; +mod growth; use horizon_client::{ Result, assets::Assets, @@ -196,8 +198,17 @@ struct GameLevel<'w> { raining: bool, thundering: bool, player_box: Option<([f64; 3], [f64; 3])>, + biomes: &'w Biomes, + seed: i64, } impl LevelAccess for GameLevel<'_> { + fn biome_name(&self, pos: BlockPos) -> Option<&str> { + let chunk = self.world.chunks.get(&(pos.x >> 4, pos.z >> 4))?; + Some(&self.biomes.get(chunk.biome(pos.x, pos.y, pos.z)).name) + } + fn world_seed(&self) -> i64 { + self.seed + } fn block_state(&self, pos: BlockPos) -> BlockStateId { self.world.block(pos.x, pos.y, pos.z) } @@ -216,7 +227,8 @@ impl LevelAccess for GameLevel<'_> { if self.dimension == LevelDimension::Nether { 0 } else { MIN_Y } } fn max_y(&self) -> i32 { - if self.dimension == LevelDimension::Nether { 255 } else { MIN_Y + HEIGHT - 1 } + // Exclusive, as LevelAccess::max_y documents. + if self.dimension == LevelDimension::Nether { 256 } else { MIN_Y + HEIGHT } } fn random(&mut self) -> &mut horizon_core::random::LegacyRandom { &mut self.world.random @@ -686,6 +698,8 @@ impl Game<'_> { raining: rain > 0.2, thundering: thunder > 0.9, player_box, + biomes: &self.res.biomes, + seed: self.level.seed, }; f(&self.res.behaviours, &mut level, &mut self.block_ticks) } @@ -760,6 +774,7 @@ impl Game<'_> { 1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)), 1030 => Some(("minecraft:block.anvil.use", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), + 1505 => Some(("minecraft:item.bone_meal.use", 1.0)), _ => None, }; if let Some((name, volume)) = sound { @@ -810,6 +825,10 @@ impl Game<'_> { // Simplified: TNT explodes after its 80-tick fuse immediately. self.explode([f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5], 4.0)?; } + LevelEvent::BlockEvent { pos, state, kind: "pop_block_item" } => { + let item = self.res.facts.get(state).item.clone(); + self.pop_resource([pos.x, pos.y, pos.z], ItemStack { item, count: 1, damage: 0 }); + } LevelEvent::GrowTree { .. } | LevelEvent::PlaceFeature { .. } | LevelEvent::BlockEvent { .. } | LevelEvent::GameEvent { .. } => {} } } @@ -981,6 +1000,9 @@ impl Game<'_> { } return Ok(()); } + if self.use_bone_meal(&stack)? { + return Ok(()); + } if self.use_tool(&stack)? { return Ok(()); } @@ -2918,6 +2940,7 @@ impl Game<'_> { self.dim = dim; self.world_root = save_root.clone(); self.block_ticks = Ticks::new(self.level.seed as i32); + self.install_live_features(); self.tick_chunks.clear(); self.falling.clear(); self.travelling = None; diff --git a/crates/horizon-client/src/game/blockctl.rs b/crates/horizon-client/src/game/blockctl.rs new file mode 100644 index 000000000..872ea76aa --- /dev/null +++ b/crates/horizon-client/src/game/blockctl.rs @@ -0,0 +1,151 @@ +//! Control-socket block commands for scripted tests: `setblock`, `fill`, +//! `getblock` and `container` (list or put items in a block entity). +use super::Game; +use horizon_client::{Result, containers::BlockEntity, items::ItemStack}; +use horizon_world::{chunk::BlockState, registry::BlockStateId}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; + +pub(super) const HELP: &[&str] = &[ + "setblock X Y Z BLOCK[props] set a block with neighbour updates", + "fill X1 Y1 Z1 X2 Y2 Z2 BLOCK set a box of blocks", + "getblock X Y Z block state at a position", + "container X Y Z [ITEM COUNT] list a container, or add items to it", +]; + +fn parse_state(text: &str) -> Result { + let (name, props) = match text.split_once('[') { + Some((name, rest)) => (name, rest.trim_end_matches(']')), + None => (text, ""), + }; + let name = if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }; + let mut properties = BTreeMap::new(); + for pair in props.split(',').filter(|p| !p.is_empty()) { + let (k, v) = pair.split_once('=').ok_or("properties are key=value")?; + properties.insert(k.to_owned(), v.to_owned()); + } + Ok(BlockState { name, properties }) +} + +impl Game<'_> { + fn state_text(&self, state: BlockStateId) -> String { + let Some(s) = self.res.assets.registry.state(state) else { + return "?".into(); + }; + if s.properties.is_empty() { + return s.name.clone(); + } + let props: Vec = s + .properties + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect(); + format!("{}[{}]", s.name, props.join(",")) + } + fn put_block(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> { + let name = self.res.facts.get(state).name.clone(); + self.world.block_entities.remove(&(pos[0], pos[1], pos[2])); + self.level_set(pos, state)?; + if let Some(entity) = BlockEntity::for_block(&name) { + self.world + .block_entities + .insert((pos[0], pos[1], pos[2]), entity); + } + Ok(()) + } + /// Block commands; None when `words[0]` is not one of them. + pub(super) fn block_command(&mut self, words: &[&str]) -> Result> { + let int = |i: usize| -> Result { + Ok(words + .get(i) + .ok_or_else(|| format!("missing argument {i}"))? + .parse()?) + }; + match words[0] { + "setblock" => { + let pos = [int(1)?, int(2)?, int(3)?]; + let state = self + .res + .assets + .registry + .resolve(&parse_state(words.get(4).ok_or("missing block")?)?)?; + self.put_block(pos, state)?; + Ok(Some( + json!({ "ok": true, "block": self.state_text(self.world.block(pos[0], pos[1], pos[2])) }), + )) + } + "fill" => { + let (a, b) = ([int(1)?, int(2)?, int(3)?], [int(4)?, int(5)?, int(6)?]); + let state = self + .res + .assets + .registry + .resolve(&parse_state(words.get(7).ok_or("missing block")?)?)?; + let mut count = 0; + for x in a[0].min(b[0])..=a[0].max(b[0]) { + for y in a[1].min(b[1])..=a[1].max(b[1]) { + for z in a[2].min(b[2])..=a[2].max(b[2]) { + self.put_block([x, y, z], state)?; + count += 1; + } + } + } + Ok(Some(json!({ "ok": true, "count": count }))) + } + "getblock" => { + let pos = [int(1)?, int(2)?, int(3)?]; + Ok(Some( + json!({ "block": self.state_text(self.world.block(pos[0], pos[1], pos[2])) }), + )) + } + "container" => { + let key = (int(1)?, int(2)?, int(3)?); + if let Some(item) = words.get(4) { + let item = if item.contains(':') { + (*item).to_owned() + } else { + format!("minecraft:{item}") + }; + let count: u32 = words.get(5).map_or(Ok(1), |c| c.parse())?; + let entity = self + .world + .block_entities + .get_mut(&key) + .ok_or("no container there")?; + let slot = entity + .slots_mut() + .iter_mut() + .find(|s| s.is_none()) + .ok_or("container is full")?; + *slot = Some(ItemStack { + item: item.as_str().into(), + count, + damage: 0, + }); + } + let entity = self + .world + .block_entities + .get(&key) + .ok_or("no container there")?; + let slots: Vec = entity + .clone() + .slots_mut() + .iter() + .map(|s| { + s.as_ref().map_or( + Value::Null, + |s| json!({ "item": &*s.item, "count": s.count }), + ) + }) + .collect(); + Ok(Some(json!({ "slots": slots }))) + } + _ => Ok(None), + } + } +} diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index f6b2bdcc6..19e7c3382 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -64,8 +64,11 @@ impl Game<'_> { .ok_or_else(|| format!("missing argument {i} for {}", words[0])) }; let ok = || Ok(Some(json!({ "ok": true }))); + if let Some(value) = self.block_command(&words)? { + return Ok(Some(value)); + } match words[0] { - "help" => Ok(Some(json!({ "commands": HELP }))), + "help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::blockctl::HELP).collect::>() }))), "status" => Ok(Some(self.control_status())), "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; diff --git a/crates/horizon-client/src/game/growth.rs b/crates/horizon-client/src/game/growth.rs new file mode 100644 index 000000000..c5a56e539 --- /dev/null +++ b/crates/horizon-client/src/game/growth.rs @@ -0,0 +1,57 @@ +//! Client glue for sapling growth and bone meal: installs the live feature +//! registry and routes `BoneMealItem.useOn` through the behaviour library. +use super::Game; +use horizon_client::{Result, items::ItemStack, vanillagen}; +use horizon_core::{geometry::Direction, position::BlockPos}; +use horizon_world::worldgen::live::LiveFeatures; +use std::sync::Arc; + +impl Game<'_> { + /// Load the configured/placed feature registry used by saplings, fungi + /// and bone meal (once per process; shares the generator's bundle). + pub(super) fn install_live_features(&self) { + if self.res.behaviours.live_features().is_some() { + return; + } + let dir = self.options.resources.join("worldgen"); + let started = std::time::Instant::now(); + let features = vanillagen::shared_data(&dir, self.res.assets.registry) + .map_err(|e| e.to_string()) + .and_then(|data| LiveFeatures::new(&data).map_err(|e| e.to_string())); + match features { + Ok(Some(features)) => { + self.res.behaviours.set_live_features(Arc::new(features)); + eprintln!("Horizon: live features ready in {:?}", started.elapsed()); + } + Ok(None) => { + eprintln!("Horizon: the worldgen bundle has no features; saplings will not grow") + } + Err(e) => eprintln!("Horizon: live features unavailable: {e}"), + } + } + /// `BoneMealItem.useOn` for the targeted block. + pub(super) fn use_bone_meal(&mut self, stack: &ItemStack) -> Result { + if &*stack.item != "minecraft:bone_meal" { + return Ok(false); + } + let Some(hit) = self.pick() else { + return Ok(false); + }; + let face = match hit.face { + [0, 1, 0] => Direction::Up, + [0, -1, 0] => Direction::Down, + [0, 0, -1] => Direction::North, + [0, 0, 1] => Direction::South, + [-1, 0, 0] => Direction::West, + _ => Direction::East, + }; + let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]); + let used = self.with_level(|b, level, ticks| b.use_bone_meal(level, ticks, pos, face)); + self.process_level_events()?; + if used { + self.swing_arm(); + self.consume_held(); + } + Ok(used) + } +} diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 6c49822ea..0ce0003f7 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -27,7 +27,7 @@ impl VanillaTerrain { Self::for_dimension(dir, registry, biomes, seed, "minecraft:overworld") } pub fn for_dimension(dir: &Path, registry: &'static BlockRegistry, biomes: &Biomes, seed: i64, dimension: &str) -> crate::Result { - let data: Arc = GeneratorData::load(dir, registry)?; + let data: Arc = shared_data(dir, registry)?; let biome_map = data.biome_names().iter().map(|name| biomes.id(name)).collect(); let generator = OverworldGenerator::for_dimension(data, seed, "minecraft:normal", dimension)?; let unsupported = generator.unsupported_features(); @@ -40,6 +40,18 @@ impl VanillaTerrain { Ok(Self { generator, biome_map }) } } +/// The worldgen bundle at `dir`, loaded once and shared by every generator +/// and by live feature placement (sapling growth, bone meal). +pub fn shared_data(dir: &Path, registry: &'static BlockRegistry) -> crate::Result> { + static CACHE: std::sync::Mutex)>> = std::sync::Mutex::new(Vec::new()); + let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) { + return Ok(data.clone()); + } + let data = GeneratorData::load(dir, registry)?; + cache.push((dir.to_owned(), data.clone())); + Ok(data) +} impl ChunkGenerator for VanillaTerrain { type Worker = GeneratorWorker; fn worker(&self) -> GeneratorWorker { From 33396ebff17bce53f6614b9600d54e673a604372 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:29:46 +0200 Subject: [PATCH 3/8] Add primed TNT with an 80-tick fuse and port ServerExplosion PrimedTnt entities (gravity, drag, bounce, fuse) spawn from redstone, fire, flint and steel / fire charges, unstable TNT broken by players and chain explosions (random short fuse). TntRenderer swell and white flash via a new entity overlay. Explosions use vanilla ray marching over a Java HashSet (matching iteration and shuffle draws), exposure-scaled damage and knockback for players, mobs, items and TNT, TNT drops without decay, merged drops and container contents. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity.wgsl | 6 +- crates/horizon-client/src/game.rs | 93 +--- crates/horizon-client/src/game/explosion.rs | 460 ++++++++++++++++++++ crates/horizon-client/src/game/tnt.rs | 258 +++++++++++ crates/horizon-world/src/level/hooks.rs | 6 +- 5 files changed, 741 insertions(+), 82 deletions(-) create mode 100644 crates/horizon-client/src/game/explosion.rs create mode 100644 crates/horizon-client/src/game/tnt.rs diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index e56607466..ed2f00277 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -21,6 +21,7 @@ struct Out { @location(1) color: vec4, @location(2) spherical: f32, @location(3) cylindrical: f32, + @location(4) flash: f32, } @vertex fn vs_entity(@location(0) position: vec3, @location(1) uv: vec2, @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4) -> Out { @@ -35,6 +36,8 @@ struct Out { // Hurt overlay (OverlayTexture red tint). if overlay == 1u { c = vec4(mix(c.rgb, vec3(1.0, 0.0, 0.0), 0.3), c.a); } out.color = c; + // Overlay 4: OverlayTexture white flash (primed TNT), applied after texturing. + out.flash = select(0.0, 0.75, overlay == 4u); // Sky geometry (clouds, celestial bodies) is exempt from render-distance fog. out.spherical = select(length(position), 0.0, overlay >= 2u); out.cylindrical = select(max(length(position.xz), abs(position.y)), 0.0, overlay >= 2u); @@ -46,8 +49,9 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { return (d - start) / (end - start); } @fragment fn fs_entity(in: Out) -> @location(0) vec4 { - let color = textureSample(atlas, atlas_sampler, in.uv) * in.color; + var color = textureSample(atlas, atlas_sampler, in.uv) * in.color; if color.a < 0.1 { discard; } + color = vec4(mix(color.rgb, vec3(1.0), in.flash), color.a); let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y), linear_fog(in.cylindrical, globals.fog.z, globals.fog.w)); return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 158fa0335..dccf8cc9c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2,7 +2,9 @@ //! block interaction, inventory and HUD. mod blockctl; mod control; +mod explosion; mod growth; +mod tnt; use horizon_client::{ Result, assets::Assets, @@ -393,6 +395,7 @@ struct Game<'a> { tick_chunks: HashSet<(i32, i32)>, level_events: Vec, falling: Vec, + tnts: Vec, creative_screen: Creative, control: Option, frame_stats: horizon_client::control::FrameStats, @@ -821,10 +824,7 @@ impl Game<'_> { } PlayerEffect::InteractLoot(_) | PlayerEffect::RespawnAnchor => {} }, - LevelEvent::PrimeTnt { pos } => { - // Simplified: TNT explodes after its 80-tick fuse immediately. - self.explode([f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5], 4.0)?; - } + LevelEvent::PrimeTnt { pos } => self.spawn_primed_tnt(pos, false), LevelEvent::BlockEvent { pos, state, kind: "pop_block_item" } => { let item = self.res.facts.get(state).item.clone(); self.pop_resource([pos.x, pos.y, pos.z], ItemStack { item, count: 1, damage: 0 }); @@ -1000,7 +1000,7 @@ impl Game<'_> { } return Ok(()); } - if self.use_bone_meal(&stack)? { + if self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)? { return Ok(()); } if self.use_tool(&stack)? { @@ -1403,6 +1403,7 @@ impl Game<'_> { self.tick_portal()?; self.tick_blocks()?; self.tick_falling()?; + self.tick_tnt()?; if let Some(p) = &self.player { // Player.aiStep bob and Entity.walkDist (0.6 per block). let (dx, dz) = (p.position.x - self.previous_position.x, p.position.z - self.previous_position.z); @@ -2234,6 +2235,7 @@ impl Game<'_> { } } } + self.tnt_geometry(camera, alpha, &mut out); // Camera-facing particle quads. let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); let forward = glam::Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()); @@ -2489,82 +2491,10 @@ impl Game<'_> { true } /// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step. + /// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the + /// default mobGriefing rule). fn explode(&mut self, center: [f64; 3], radius: f32) -> Result<()> { - let mut destroyed = HashSet::new(); - for j in 0..16 { - for k in 0..16 { - for l in 0..16 { - if !(j == 0 || j == 15 || k == 0 || k == 15 || l == 0 || l == 15) { - continue; - } - let mut d = [f64::from(j) / 15.0 * 2.0 - 1.0, f64::from(k) / 15.0 * 2.0 - 1.0, f64::from(l) / 15.0 * 2.0 - 1.0]; - let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); - d = d.map(|v| v / len); - let mut h = radius * (0.7 + self.world.random.next_float() * 0.6); - let mut p = center; - while h > 0.0 { - let b = [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32]; - let state = self.world.block(b[0], b[1], b[2]); - if !self.res.facts.is_air(state) { - let f = self.res.facts.get(state); - let resistance = if f.fluid != Fluid::None && !f.waterlogged { 100.0 } else { f.explosion_resistance }; - h -= (resistance + 0.3) * 0.3; - if h > 0.0 && f.hardness >= 0.0 { - destroyed.insert(b); - } - } - p = [p[0] + d[0] * 0.3, p[1] + d[1] * 0.3, p[2] + d[2] * 0.3]; - h -= 0.225_000_01; - } - } - } - } - for b in destroyed { - let state = self.world.block(b[0], b[1], b[2]); - if self.res.facts.is_air(state) { - continue; - } - // Explosion decay: each drop survives with probability 1 / radius. - if self.world.random.next_float() < 1.0 / radius { - let drops = self.res.items.block_drops(&self.res.assets.registry, state, None, &mut self.world.random); - for d in drops { - self.pop_resource(b, d); - } - } - self.world.set(b[0], b[1], b[2], self.world.air)?; - } - self.audio.play("minecraft:entity.generic.explode", Some(center), 4.0, (1.0 + (self.world.random.next_float() - self.world.random.next_float()) * 0.2) * 0.7); - // Entity damage by distance (exposure approximated as unobstructed). - let diameter = f64::from(radius) * 2.0; - let mut armor_damage = None; - if let Some(player) = self.player.as_mut() { - let p = [player.position.x, player.position.y, player.position.z]; - let dist = ((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2)).sqrt() / diameter; - if dist <= 1.0 { - let impact = 1.0 - dist; - let damage = ((impact * impact + impact) / 2.0 * 7.0 * diameter + 1.0) as f32; - if let Some(id) = self.motion.health.damage.id("minecraft:explosion") { - let _ = player.hurt(&self.motion.health, self.world.health_rules, id, damage); - armor_damage = Some(damage); - } - let (dx, dy, dz) = (p[0] - center[0], p[1] - center[1], p[2] - center[2]); - let l = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-4); - player.velocity = Vec3::new(player.velocity.x + dx / l * impact, player.velocity.y + dy / l * impact, player.velocity.z + dz / l * impact); - } - } - if let Some(d) = armor_damage - && !self.creative - { - self.hurt_armor(d); - } - for m in &mut self.mobs { - let dist = ((m.position.x - center[0]).powi(2) + (m.position.y - center[1]).powi(2) + (m.position.z - center[2]).powi(2)).sqrt() / diameter; - if dist <= 1.0 && m.alive() { - let impact = 1.0 - dist; - m.hurt(((impact * impact + impact) / 2.0 * 7.0 * diameter + 1.0) as f32, Some(center), &mut self.world.random); - } - } - Ok(()) + self.server_explode(center, radius, explosion::BlockInteraction::DestroyWithDecay, false) } fn tick_block_entities(&mut self) -> Result<()> { // ChestLidController: 0.1 per tick towards open/closed. @@ -2943,6 +2873,7 @@ impl Game<'_> { self.install_live_features(); self.tick_chunks.clear(); self.falling.clear(); + self.tnts.clear(); self.travelling = None; self.player = None; self.spawn = None; @@ -3021,6 +2952,7 @@ impl Game<'_> { self.block_ticks = Ticks::new(self.level.seed as i32); self.tick_chunks.clear(); self.falling.clear(); + self.tnts.clear(); self.mobs.clear(); self.arrows.clear(); self.dropped.clear(); @@ -4821,6 +4753,7 @@ pub fn run() -> Result<()> { tick_chunks: HashSet::new(), level_events: Vec::new(), falling: Vec::new(), + tnts: Vec::new(), creative_screen: Creative::load(&game_root)?, control: None, frame_stats: Default::default(), diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs new file mode 100644 index 000000000..eb70a4478 --- /dev/null +++ b/crates/horizon-client/src/game/explosion.rs @@ -0,0 +1,460 @@ +//! `ServerExplosion`: exploded positions (vanilla ray march over a Java +//! HashSet, so iteration and the following shuffle match vanilla's random +//! draws), entity damage with exposure and knockback, block interaction with +//! merged drops and TNT chain priming, and optional fire. +use super::Game; +use horizon_client::{Result, blocks::Fluid, items::ItemStack}; +use horizon_core::{ + geometry::Vec3, + position::BlockPos, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::java_hash_map::{JavaHashMap, JavaKey}; +use std::cmp::Ordering; + +/// `BlockPos` with Java `Vec3i.hashCode` / `compareTo`. +#[derive(Clone, Copy, PartialEq, Eq)] +struct Key([i32; 3]); +impl JavaKey for Key { + fn java_hash(&self) -> i32 { + let [x, y, z] = self.0; + y.wrapping_add(z.wrapping_mul(31)) + .wrapping_mul(31) + .wrapping_add(x) + } + fn comparable_compare(&self, other: &Self) -> Option { + let ([x, y, z], [ox, oy, oz]) = (self.0, other.0); + Some(y.cmp(&oy).then(z.cmp(&oz)).then(x.cmp(&ox))) + } + fn tie_break(&self, _other: &Self) -> Ordering { + Ordering::Less + } +} + +/// `Explosion.BlockInteraction` for the explosions Horizon produces. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum BlockInteraction { + Keep, + Destroy, + DestroyWithDecay, +} + +thread_local! { + /// Client-side randomness (explosion sound pitch), separate from the level random. + static CLIENT_RANDOM: std::cell::RefCell = std::cell::RefCell::new(LegacyRandom::new(0x5eed)); +} +pub(super) fn client_float() -> f32 { + CLIENT_RANDOM.with(|r| r.borrow_mut().next_float()) +} + +impl Game<'_> { + /// `Level.clip(from, to, COLLIDER, NONE)` missing every block, with full + /// collision cubes as obstacles. + fn clear_line(&self, from: [f64; 3], to: [f64; 3]) -> bool { + let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]]; + let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + let steps = (length / 0.1).ceil().max(1.0) as i32; + let mut last = [i32::MIN; 3]; + for i in 0..=steps { + let t = f64::from(i) / f64::from(steps); + let b = [ + (from[0] + d[0] * t).floor() as i32, + (from[1] + d[1] * t).floor() as i32, + (from[2] + d[2] * t).floor() as i32, + ]; + if b == last { + continue; + } + last = b; + if self + .res + .facts + .get(self.world.block(b[0], b[1], b[2])) + .full_collision + { + return false; + } + } + true + } + /// `ServerExplosion.getSeenPercent` for an entity box. + fn seen_percent(&self, center: [f64; 3], min: [f64; 3], max: [f64; 3]) -> f32 { + let xs = 1.0 / ((max[0] - min[0]) * 2.0 + 1.0); + let ys = 1.0 / ((max[1] - min[1]) * 2.0 + 1.0); + let zs = 1.0 / ((max[2] - min[2]) * 2.0 + 1.0); + let x_offset = (1.0 - (1.0 / xs).floor() * xs) / 2.0; + let z_offset = (1.0 - (1.0 / zs).floor() * zs) / 2.0; + if xs < 0.0 || ys < 0.0 || zs < 0.0 { + return 0.0; + } + let (mut hits, mut count) = (0, 0); + let mut xx = 0.0; + while xx <= 1.0 { + let mut yy = 0.0; + while yy <= 1.0 { + let mut zz = 0.0; + while zz <= 1.0 { + let x = min[0] + (max[0] - min[0]) * xx; + let y = min[1] + (max[1] - min[1]) * yy; + let z = min[2] + (max[2] - min[2]) * zz; + if self.clear_line([x + x_offset, y, z + z_offset], center) { + hits += 1; + } + count += 1; + zz += zs; + } + yy += ys; + } + xx += xs; + } + hits as f32 / count as f32 + } + /// `ServerExplosion.calculateExplodedPositions`. + fn exploded_positions(&mut self, center: [f64; 3], radius: f32) -> Vec<[i32; 3]> { + let (min_y, max_y) = self.with_level(|_, level, _| { + use horizon_world::level::LevelAccess; + (level.min_y(), level.max_y()) + }); + let mut set: JavaHashMap = JavaHashMap::default(); + for xx in 0..16 { + for yy in 0..16 { + for zz in 0..16 { + if !(xx == 0 || xx == 15 || yy == 0 || yy == 15 || zz == 0 || zz == 15) { + continue; + } + let mut xd = f64::from(xx as f32 / 15.0 * 2.0 - 1.0); + let mut yd = f64::from(yy as f32 / 15.0 * 2.0 - 1.0); + let mut zd = f64::from(zz as f32 / 15.0 * 2.0 - 1.0); + let d = (xd * xd + yd * yd + zd * zd).sqrt(); + xd /= d; + yd /= d; + zd /= d; + let mut power = radius * (0.7 + self.world.random.next_float() * 0.6); + let (mut xp, mut yp, mut zp) = (center[0], center[1], center[2]); + while power > 0.0 { + let pos = [xp.floor() as i32, yp.floor() as i32, zp.floor() as i32]; + if pos[1] < min_y + || pos[1] >= max_y + || !(-30_000_000..30_000_000).contains(&pos[0]) + || !(-30_000_000..30_000_000).contains(&pos[2]) + { + break; + } + let state = self.world.block(pos[0], pos[1], pos[2]); + let f = self.res.facts.get(state); + let fluid = if f.fluid != Fluid::None { + 100.0f32 + } else { + 0.0 + }; + if !self.res.facts.is_air(state) || f.fluid != Fluid::None { + power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3; + } + if power > 0.0 { + set.put(Key(pos), ()); + } + xp += xd * f64::from(0.3f32); + yp += yd * f64::from(0.3f32); + zp += zd * f64::from(0.3f32); + power -= 0.225_000_01; + } + } + } + } + set.entries().map(|(k, _)| k.0).collect() + } + /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT). + fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32) { + if radius < 1.0e-5 { + return; + } + let diameter = f64::from(radius * 2.0); + let distance = |p: [f64; 3]| { + ((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2)) + .sqrt() + }; + let damage = |dist: f64, exposure: f32| { + let pow = (1.0 - dist) * f64::from(exposure); + ((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32 + }; + let direction = |origin: [f64; 3]| { + let d = [ + origin[0] - center[0], + origin[1] - center[1], + origin[2] - center[2], + ]; + let l = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + if l < 1.0e-4 { + [0.0; 3] + } else { + [d[0] / l, d[1] / l, d[2] / l] + } + }; + // Player. + if let Some(p) = self.player.as_ref() { + let feet = [p.position.x, p.position.y, p.position.z]; + let dist = distance(feet) / diameter; + if dist <= 1.0 && !p.health.dead_or_dying() { + let w = f64::from(p.dimensions.width) / 2.0; + let h = f64::from(p.dimensions.height); + let eye = [ + feet[0], + feet[1] + f64::from(p.dimensions.eye_height), + feet[2], + ]; + let exposure = self.seen_percent( + center, + [feet[0] - w, feet[1], feet[2] - w], + [feet[0] + w, feet[1] + h, feet[2] + w], + ); + let amount = damage(dist, exposure); + let dir = direction(eye); + let power = (1.0 - dist) * f64::from(exposure); + let mut hurt = false; + let creative = self.creative; + if let Some(p) = self.player.as_mut() + && let Some(id) = self.motion.health.damage.id("minecraft:explosion") + { + // Creative players are invulnerable to explosions. + if !creative { + hurt = p + .hurt(&self.motion.health, self.world.health_rules, id, amount) + .unwrap_or(false); + } + p.velocity = Vec3::new( + p.velocity.x + dir[0] * power, + p.velocity.y + dir[1] * power, + p.velocity.z + dir[2] * power, + ); + } + if hurt && !self.creative { + self.hurt_armor(amount); + } + } + } + // Mobs. + let mut mobs = std::mem::take(&mut self.mobs); + for m in mobs.iter_mut().filter(|m| m.alive()) { + let feet = [m.position.x, m.position.y, m.position.z]; + let dist = distance(feet) / diameter; + if dist > 1.0 { + continue; + } + let (w, h) = (m.kind.width / 2.0, m.kind.height); + let eye = [feet[0], feet[1] + m.kind.eye_height, feet[2]]; + let exposure = self.seen_percent( + center, + [feet[0] - w, feet[1], feet[2] - w], + [feet[0] + w, feet[1] + h, feet[2] + w], + ); + m.hurt(damage(dist, exposure), None, &mut self.world.random); + let dir = direction(eye); + let power = (1.0 - dist) * f64::from(exposure); + m.velocity = Vec3::new( + m.velocity.x + dir[0] * power, + m.velocity.y + dir[1] * power, + m.velocity.z + dir[2] * power, + ); + } + self.mobs = mobs; + // Dropped items: 5 health, destroyed by the explosion damage (nether stars resist). + let mut items = std::mem::take(&mut self.dropped); + items.retain_mut(|item| { + let feet = [item.position.x, item.position.y, item.position.z]; + let dist = distance(feet) / diameter; + if dist > 1.0 { + return true; + } + let half = 0.125; + let exposure = self.seen_percent( + center, + [feet[0] - half, feet[1], feet[2] - half], + [feet[0] + half, feet[1] + 0.25, feet[2] + half], + ); + if &*item.stack.item != "minecraft:nether_star" && damage(dist, exposure) >= 5.0 { + return false; + } + let dir = direction([feet[0], feet[1] + 0.2125, feet[2]]); + let power = (1.0 - dist) * f64::from(exposure); + item.velocity = Vec3::new( + item.velocity.x + dir[0] * power, + item.velocity.y + dir[1] * power, + item.velocity.z + dir[2] * power, + ); + true + }); + self.dropped = items; + // Primed TNT: knockback only, from its position (not its eyes). + let mut tnts = std::mem::take(&mut self.tnts); + for t in &mut tnts { + let feet = [t.position.x, t.position.y, t.position.z]; + let dist = distance(feet) / diameter; + if dist > 1.0 { + continue; + } + let half = 0.49; + let exposure = self.seen_percent( + center, + [feet[0] - half, feet[1], feet[2] - half], + [feet[0] + half, feet[1] + 0.98, feet[2] + half], + ); + let dir = direction(feet); + let power = (1.0 - dist) * f64::from(exposure); + t.velocity = Vec3::new( + t.velocity.x + dir[0] * power, + t.velocity.y + dir[1] * power, + t.velocity.z + dir[2] * power, + ); + } + self.tnts = tnts; + } + /// `Level.explode` on the server: positions, entities, blocks, fire; then + /// the client's explosion sound. + pub(super) fn server_explode( + &mut self, + center: [f64; 3], + radius: f32, + interaction: BlockInteraction, + fire: bool, + ) -> Result<()> { + let mut targets = self.exploded_positions(center, radius); + self.explosion_hurt_entities(center, radius); + if interaction != BlockInteraction::Keep { + // Util.shuffle(list, level.random) + for i in (2..=targets.len()).rev() { + let swap = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize; + targets.swap(i - 1, swap); + } + let mut stacks: Vec<([i32; 3], ItemStack)> = Vec::new(); + for &pos in &targets { + self.explosion_hit_block(pos, radius, interaction, &mut stacks)?; + } + for (pos, stack) in stacks { + self.pop_resource(pos, stack); + } + } + if fire { + for &pos in &targets { + if self.world.random.next_int_bound(3).unwrap_or(1) == 0 + && self + .res + .facts + .is_air(self.world.block(pos[0], pos[1], pos[2])) + && self + .res + .facts + .get(self.world.block(pos[0], pos[1] - 1, pos[2])) + .solid_render + && let Some(fire) = self.res.assets.registry.default_state("minecraft:fire") + { + self.level_set(pos, fire)?; + } + } + } + let pitch = (1.0 + (client_float() - client_float()) * 0.2) * 0.7; + self.audio + .play("minecraft:entity.generic.explode", Some(center), 4.0, pitch); + Ok(()) + } + /// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse). + fn explosion_hit_block( + &mut self, + pos: [i32; 3], + radius: f32, + interaction: BlockInteraction, + stacks: &mut Vec<([i32; 3], ItemStack)>, + ) -> Result<()> { + let state = self.world.block(pos[0], pos[1], pos[2]); + if self.res.facts.is_air(state) { + return Ok(()); + } + let name = self.res.facts.get(state).name.clone(); + let is_tnt = &*name == "minecraft:tnt"; + if !is_tnt { + let drops = self.res.items.block_drops( + &self.res.assets.registry, + state, + None, + &mut self.world.random, + ); + for stack in drops { + if &*stack.item == "minecraft:air" || stack.count == 0 { + continue; + } + // survives_explosion / explosion_decay: 1 / radius per stack. + if interaction == BlockInteraction::DestroyWithDecay + && self.world.random.next_float() > 1.0 / radius + { + continue; + } + add_or_append_stack(stacks, stack, pos); + } + } + let contents = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])); + self.level_set(pos, self.world.air)?; + if let Some(entity) = contents { + for stack in entity.contents() { + self.pop_resource(pos, stack); + } + } + if is_tnt { + self.spawn_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), true); + } + Ok(()) + } +} + +/// `ServerExplosion.addOrAppendStack` with `ItemEntity.merge(.., 16)`. +fn add_or_append_stack( + stacks: &mut Vec<([i32; 3], ItemStack)>, + mut stack: ItemStack, + pos: [i32; 3], +) { + for (_, existing) in stacks.iter_mut() { + if existing.item == stack.item && existing.damage == stack.damage && existing.count < 16 { + let moved = (16 - existing.count).min(stack.count); + existing.count += moved; + stack.count -= moved; + if stack.count == 0 { + return; + } + } + } + stacks.push((pos, stack)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn block_pos_hash_matches_vec3i() { + // Vec3i.hashCode: (y + z * 31) * 31 + x + assert_eq!(Key([1, 2, 3]).java_hash(), (2 + 3 * 31) * 31 + 1); + assert_eq!(Key([-5, 64, -7]).java_hash(), (64 - 7 * 31) * 31 - 5); + assert_eq!( + Key([0, 1, 0]).comparable_compare(&Key([5, 0, 9])), + Some(Ordering::Greater) + ); + assert_eq!( + Key([1, 0, 2]).comparable_compare(&Key([0, 0, 3])), + Some(Ordering::Less) + ); + } + + #[test] + fn drops_merge_up_to_sixteen() { + let stack = |item: &str| ItemStack { + item: item.into(), + count: 1, + damage: 0, + }; + let mut stacks = Vec::new(); + for _ in 0..20 { + add_or_append_stack(&mut stacks, stack("minecraft:dirt"), [0, 0, 0]); + } + add_or_append_stack(&mut stacks, stack("minecraft:stone"), [1, 0, 0]); + let counts: Vec = stacks.iter().map(|(_, s)| s.count).collect(); + assert_eq!(counts, vec![16, 4, 1]); + } +} diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs new file mode 100644 index 000000000..1eacb125a --- /dev/null +++ b/crates/horizon-client/src/game/tnt.rs @@ -0,0 +1,258 @@ +//! Primed TNT (`PrimedTnt`): 80-tick fuse, gravity and drag, explosion of +//! power 4, `TntRenderer` swell and white flash, and `TntBlock.useItemOn` +//! (flint and steel / fire charge). +use super::{Game, explosion::BlockInteraction}; +use horizon_client::{Result, collisions::SceneCollisions, items::ItemStack, mesher::Vertex}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + position::BlockPos, + random::RandomSource, +}; +use horizon_world::level::flags as level_flags; + +#[derive(Clone, Debug)] +pub(super) struct PrimedTnt { + pub position: Vec3, + pub previous: Vec3, + pub velocity: Vec3, + pub fuse: i32, + pub on_ground: bool, +} +impl PrimedTnt { + const SIZE: f64 = 0.98; + fn bounds(&self) -> Aabb { + let h = Self::SIZE / 2.0; + Aabb::new( + Vec3::new(self.position.x - h, self.position.y, self.position.z - h), + Vec3::new( + self.position.x + h, + self.position.y + Self::SIZE, + self.position.z + h, + ), + ) + } +} + +impl Game<'_> { + /// `new PrimedTnt(level, x + 0.5, y, z + 0.5, owner)`; `short` applies + /// `wasExploded`'s random short fuse. Plays `entity.tnt.primed` for primes. + pub(super) fn spawn_primed_tnt(&mut self, pos: BlockPos, short: bool) { + let r = &mut self.world.random; + let rot = r.next_double() * f64::from(std::f32::consts::TAU); + let position = Vec3::new( + f64::from(pos.x) + 0.5, + f64::from(pos.y), + f64::from(pos.z) + 0.5, + ); + let mut tnt = PrimedTnt { + position, + previous: position, + velocity: Vec3::new(-rot.sin() * 0.02, f64::from(0.2f32), -rot.cos() * 0.02), + fuse: 80, + on_ground: false, + }; + if short { + // PrimedTnt.getRandomShortFuse + tnt.fuse = r.next_int_bound((tnt.fuse / 4).max(1)).unwrap_or(0) + tnt.fuse / 8; + } else { + self.audio.play( + "minecraft:entity.tnt.primed", + Some([position.x, position.y, position.z]), + 1.0, + 1.0, + ); + } + self.tnts.push(tnt); + } + /// `PrimedTnt.tick` for every primed TNT, in order; an expired fuse + /// explodes immediately (later TNT in the list feel its knockback this + /// tick). TNT primed by an explosion starts ticking next tick. + pub(super) fn tick_tnt(&mut self) -> Result<()> { + let mut count = self.tnts.len(); + let mut i = 0; + while i < count { + let t = &mut self.tnts[i]; + t.previous = t.position; + t.velocity.y -= 0.04; + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + }; + let wanted = t.velocity; + let moved = scene + .resolve(t.bounds(), wanted, 0.0, t.on_ground) + .unwrap_or(Vec3::ZERO); + t.position = Vec3::new( + t.position.x + moved.x, + t.position.y + moved.y, + t.position.z + moved.z, + ); + t.on_ground = wanted.y < 0.0 && moved.y != wanted.y; + if moved.x != wanted.x { + t.velocity.x = 0.0; + } + if moved.z != wanted.z { + t.velocity.z = 0.0; + } + if moved.y != wanted.y { + t.velocity.y = 0.0; + } + t.velocity = Vec3::new( + t.velocity.x * 0.98, + t.velocity.y * 0.98, + t.velocity.z * 0.98, + ); + if t.on_ground { + t.velocity = Vec3::new(t.velocity.x * 0.7, t.velocity.y * -0.5, t.velocity.z * 0.7); + } + t.fuse -= 1; + if t.fuse <= 0 { + let center = [ + t.position.x, + t.position.y + PrimedTnt::SIZE * 0.0625, + t.position.z, + ]; + self.tnts.remove(i); + count -= 1; + self.server_explode(center, 4.0, BlockInteraction::Destroy, false)?; + } else { + i += 1; + } + } + Ok(()) + } + /// `TntBlock.useItemOn`: flint and steel or a fire charge primes TNT. + pub(super) fn ignite_tnt(&mut self, stack: &ItemStack) -> Result { + let item = &*stack.item; + if item != "minecraft:flint_and_steel" && item != "minecraft:fire_charge" { + return Ok(false); + } + let Some(hit) = self.pick() else { + return Ok(false); + }; + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + if &*self.res.facts.get(state).name != "minecraft:tnt" { + return Ok(false); + } + let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]); + self.spawn_primed_tnt(pos, false); + let air = self.world.air; + self.with_level(|b, level, ticks| { + b.set_block(level, ticks, pos, air, level_flags::UPDATE_ALL_IMMEDIATE) + }); + self.process_level_events()?; + self.swing_arm(); + if item == "minecraft:flint_and_steel" { + self.damage_held(1); + } else { + self.consume_held(); + } + Ok(true) + } + /// `TntRenderer`: the block centred on the entity, swelling over the last + /// 10 ticks and flashing white every 5 ticks. + pub(super) fn tnt_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { + if self.tnts.is_empty() { + return; + } + let Some(state) = self.res.assets.registry.default_state("minecraft:tnt") else { + return; + }; + // Face sprites from the block model: up, down, north, south, west, east. + let Ok(models) = self + .res + .assets + .model_catalog + .collect(state, BlockPos::new(0, 0, 0)) + else { + return; + }; + let mut sprites = [None; 6]; + for face in models.iter().flat_map(|(_, m)| m.faces.iter()) { + use horizon_assets::model::Direction as D; + let index = match face.quad.facing { + D::Up => 0, + D::Down => 1, + D::North => 2, + D::South => 3, + D::West => 4, + D::East => 5, + }; + if sprites[index].is_none() { + sprites[index] = self + .res + .layer_names + .get(&face.layer) + .and_then(|name| self.res.atlas.sprites.get(name).copied()); + } + } + for t in &self.tnts { + let fuse = t.fuse as f32 - alpha as f32 + 1.0; + let scale = if fuse < 10.0 { + let g = (1.0 - fuse / 10.0).clamp(0.0, 1.0); + 1.0 + g * g * g * g * 0.3 + } else { + 1.0 + }; + let lit = fuse >= 0.0 && (fuse / 5.0) as i32 % 2 == 0; + let base = glam::DVec3::new( + t.previous.x + (t.position.x - t.previous.x) * alpha, + t.previous.y + (t.position.y - t.previous.y) * alpha + 0.5, + t.previous.z + (t.position.z - t.previous.z) * alpha, + ) - camera; + let o = base.as_vec3(); + let light = self.world.light( + t.position.x.floor() as i32, + (t.position.y + 0.5).floor() as i32, + t.position.z.floor() as i32, + ); + let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; + let v = |x: f32, y: f32, z: f32| o + glam::Vec3::new(x - 0.5, y - 0.5, z - 0.5) * scale; + let faces = [ + ( + [v(0., 1., 1.), v(1., 1., 1.), v(1., 1., 0.), v(0., 1., 0.)], + 1.0, + ), + ( + [v(0., 0., 0.), v(1., 0., 0.), v(1., 0., 1.), v(0., 0., 1.)], + 0.5, + ), + ( + [v(1., 0., 0.), v(0., 0., 0.), v(0., 1., 0.), v(1., 1., 0.)], + 0.8, + ), + ( + [v(0., 0., 1.), v(1., 0., 1.), v(1., 1., 1.), v(0., 1., 1.)], + 0.8, + ), + ( + [v(0., 0., 0.), v(0., 0., 1.), v(0., 1., 1.), v(0., 1., 0.)], + 0.6, + ), + ( + [v(1., 0., 1.), v(1., 0., 0.), v(1., 1., 0.), v(1., 1., 1.)], + 0.6, + ), + ]; + for ((corners, shade), sprite) in faces.into_iter().zip(sprites) { + let Some(r) = sprite else { continue }; + let c = (255.0 * shade) as u32; + let color = 0xFF00_0000 | c << 16 | c << 8 | c; + for (p, uv) in + corners + .iter() + .zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]) + { + // Overlay 4: OverlayTexture white flash. + out.push(Vertex { + pos: p.to_array(), + uv, + layer: if lit { 4 } else { 0 }, + color, + light: packed, + }); + } + } + } + } +} diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index a56e42738..66e949ff1 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -1,7 +1,7 @@ //! `neighborChanged`, `onPlace`, `affectNeighborsAfterRemoval` and //! `updateIndirectNeighbourShapes` for the overriding vanilla classes. use super::{ - LevelAccess, Sim, + LevelAccess, LevelEvent, Sim, classes::Class, states::BlockId, update::{below, rel}, @@ -389,6 +389,10 @@ impl Sim<'_, L> { self.level_event(2001, head_pos, head.0 as i32); } } + // TntBlock.playerWillDestroy: unstable TNT primes unless instabuild. + if !creative && data.is(Class::Tnt) && b.table.bool(state, p.unstable) { + self.emit(LevelEvent::PrimeTnt { pos }); + } self.level_event(2001, pos, state.0 as i32); self.game_event(pos, "minecraft:block_destroy"); self.remove_block(pos, false) From af6d8610a24e38faf6bd34e94aae4439520cbb72 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:39:36 +0200 Subject: [PATCH 4/8] Move items with hoppers, dispensers and droppers; feed comparators from containers Port HopperBlockEntity (push/pull, item entities, furnace faces, double chests, transfer cooldowns), DispenserBlock/DropperBlock.dispenseFrom with the default, bone meal, TNT, flint and steel, bucket and arrow behaviours, and container comparator signals with setChanged notifications. Hopper and dispenser/dropper block entities save with their own ids; their screens use the vanilla layouts. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/containers.rs | 39 +- crates/horizon-client/src/game.rs | 23 +- crates/horizon-client/src/game/machines.rs | 1085 ++++++++++++++++++++ crates/horizon-client/src/save.rs | 12 +- crates/horizon-world/src/level/mod.rs | 1 + crates/horizon-world/src/level/signals.rs | 21 + 6 files changed, 1172 insertions(+), 9 deletions(-) create mode 100644 crates/horizon-client/src/game/machines.rs create mode 100644 crates/horizon-world/src/level/signals.rs diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 2eed1860c..0ab975941 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -63,15 +63,36 @@ impl BlockEntity { speed: 1.0, })); } - matches!( - name, - "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" - ) - .then(|| Self::Chest(vec![None; 27])) + let size = match name { + "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27, + "minecraft:hopper" => 5, + "minecraft:dispenser" | "minecraft:dropper" => 9, + _ => return None, + }; + Some(Self::Chest(vec![None; size])) + } + /// The vanilla block entity type id of a container block. + pub fn id_for_block(name: &str) -> Option<&'static str> { + Some(match name { + "minecraft:chest" => "minecraft:chest", + "minecraft:trapped_chest" => "minecraft:trapped_chest", + "minecraft:barrel" => "minecraft:barrel", + "minecraft:hopper" => "minecraft:hopper", + "minecraft:dispenser" => "minecraft:dispenser", + "minecraft:dropper" => "minecraft:dropper", + "minecraft:furnace" => "minecraft:furnace", + "minecraft:blast_furnace" => "minecraft:blast_furnace", + "minecraft:smoker" => "minecraft:smoker", + _ => return None, + }) } pub fn id(&self) -> &'static str { match self { - Self::Chest(_) => "minecraft:chest", + Self::Chest(items) => match items.len() { + 5 => "minecraft:hopper", + 9 => "minecraft:dispenser", + _ => "minecraft:chest", + }, Self::Furnace(f) => match f.kind { FurnaceKind::Furnace => "minecraft:furnace", FurnaceKind::BlastFurnace => "minecraft:blast_furnace", @@ -85,6 +106,12 @@ impl BlockEntity { Self::Furnace(f) => f.items.iter().flatten().cloned().collect(), } } + pub fn slots(&self) -> &[Option] { + match self { + Self::Chest(items) => items, + Self::Furnace(f) => &f.items, + } + } pub fn slots_mut(&mut self) -> &mut [Option] { match self { Self::Chest(items) => items, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index dccf8cc9c..e88f91635 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4,6 +4,7 @@ mod blockctl; mod control; mod explosion; mod growth; +mod machines; mod tnt; use horizon_client::{ Result, @@ -202,8 +203,14 @@ struct GameLevel<'w> { player_box: Option<([f64; 3], [f64; 3])>, biomes: &'w Biomes, seed: i64, + behaviours: &'w Behaviours, + items: &'w Items, + registry: &'static horizon_world::registry::BlockRegistry, } impl LevelAccess for GameLevel<'_> { + fn block_entity_analog_signal(&self, pos: BlockPos, _state: BlockStateId, _direction: Direction) -> i32 { + machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos) + } fn biome_name(&self, pos: BlockPos) -> Option<&str> { let chunk = self.world.chunks.get(&(pos.x >> 4, pos.z >> 4))?; Some(&self.biomes.get(chunk.biome(pos.x, pos.y, pos.z)).name) @@ -396,6 +403,7 @@ struct Game<'a> { level_events: Vec, falling: Vec, tnts: Vec, + hoppers: HashMap<(i32, i32, i32), machines::HopperState>, creative_screen: Creative, control: Option, frame_stats: horizon_client::control::FrameStats, @@ -703,6 +711,9 @@ impl Game<'_> { player_box, biomes: &self.res.biomes, seed: self.level.seed, + behaviours: &self.res.behaviours, + items: &self.res.items, + registry: self.res.assets.registry, }; f(&self.res.behaviours, &mut level, &mut self.block_ticks) } @@ -825,6 +836,7 @@ impl Game<'_> { PlayerEffect::InteractLoot(_) | PlayerEffect::RespawnAnchor => {} }, LevelEvent::PrimeTnt { pos } => self.spawn_primed_tnt(pos, false), + LevelEvent::BlockEvent { pos, state, kind: "dispense" } => self.dispense_from(pos, state)?, LevelEvent::BlockEvent { pos, state, kind: "pop_block_item" } => { let item = self.res.facts.get(state).item.clone(); self.pop_resource([pos.x, pos.y, pos.z], ItemStack { item, count: 1, damage: 0 }); @@ -1741,7 +1753,7 @@ impl Game<'_> { batch } fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) { - ((batch.width - 176.0) / 2.0, (batch.height - 166.0) / 2.0) + ((batch.width - 176.0) / 2.0, (batch.height - self.screen_height()) / 2.0) } /// Slot ids: 0..36 player inventory, 100..109 crafting grid, 200 result. fn container_kind(&self) -> Option<&BlockEntity> { @@ -1765,6 +1777,9 @@ impl Game<'_> { } /// InventoryMenu / CraftingMenu slot layouts. fn slot_position(&self, i: usize) -> (f32, f32) { + if let Some(p) = self.machine_slot_position(i) { + return p; + } let table = self.craft_size == 3; // ContainerScreen (3 rows) shifts the player inventory down by one pixel. let shift = if matches!(self.container_kind(), Some(BlockEntity::Chest(_))) { 1.0 } else { 0.0 }; @@ -1834,6 +1849,7 @@ impl Game<'_> { }; let grey = rgba(64, 64, 64, 255); match self.container.and_then(|k| self.world.block_entities.get(&k)) { + Some(BlockEntity::Chest(_)) if self.draw_machine_screen(batch, ox, oy) => {} Some(BlockEntity::Chest(_)) => { // ContainerScreen with 3 rows: top 71px, then the player inventory from v=126. part(batch, "gui/container/generic_54", 0.0, 0.0, 176.0, 71.0, ox, oy); @@ -2497,6 +2513,7 @@ impl Game<'_> { self.server_explode(center, radius, explosion::BlockInteraction::DestroyWithDecay, false) } fn tick_block_entities(&mut self) -> Result<()> { + self.tick_hoppers()?; // ChestLidController: 0.1 per tick towards open/closed. if let Some(key) = self.container { self.chest_open.entry(key).or_insert((0.0, 0.0)); @@ -4424,6 +4441,9 @@ impl ApplicationHandler for Game<'_> { } Screen::Inventory if pressed => { self.click_inventory(button == MouseButton::Right); + if let Some(key) = self.container { + self.container_changed(key); + } } Screen::Creative if pressed => { self.click_creative(button == MouseButton::Right); @@ -4754,6 +4774,7 @@ pub fn run() -> Result<()> { level_events: Vec::new(), falling: Vec::new(), tnts: Vec::new(), + hoppers: HashMap::new(), creative_screen: Creative::load(&game_root)?, control: None, frame_stats: Default::default(), diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs new file mode 100644 index 000000000..8fde05a1e --- /dev/null +++ b/crates/horizon-client/src/game/machines.rs @@ -0,0 +1,1085 @@ +//! Item-moving blocks: `HopperBlockEntity` (push, pull, item entities, +//! transfer cooldowns), `DispenserBlock` / `DropperBlock.dispenseFrom` with +//! the vanilla dispense behaviours Horizon has entities for, and container +//! comparator signals (`AbstractContainerMenu.getRedstoneSignalFromContainer`). +use super::Game; +use horizon_client::{ + Result, + containers::BlockEntity, + entities::Arrow, + items::{ItemStack, Items}, + world::World, +}; +use horizon_core::{ + geometry::{Direction, Vec3}, + position::BlockPos, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::{level::Behaviours, registry::BlockStateId}; + +type Pos = (i32, i32, i32); + +/// `HopperBlockEntity` transient state (`TransferCooldown`, `tickedGameTime`). +#[derive(Clone, Copy, Debug)] +pub(super) struct HopperState { + cooldown: i32, + ticked: i64, +} +impl Default for HopperState { + fn default() -> Self { + Self { + cooldown: -1, + ticked: 0, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Generic, + /// `AbstractFurnaceBlockEntity` (a `WorldlyContainer`). + Furnace, + Hopper, +} + +/// A container: one block entity, or a double chest (`CompoundContainer`). +#[derive(Clone, Debug)] +struct View { + parts: Vec<(Pos, usize)>, + kind: Kind, +} +impl View { + fn len(&self) -> usize { + self.parts.iter().map(|p| p.1).sum() + } + fn locate(&self, mut slot: usize) -> Option<(Pos, usize)> { + for &(pos, size) in &self.parts { + if slot < size { + return Some((pos, slot)); + } + slot -= size; + } + None + } + /// `WorldlyContainer.getSlotsForFace` or every slot. + fn slots_for_face(&self, face: Option) -> Vec { + match (self.kind, face) { + (Kind::Furnace, Some(Direction::Down)) => vec![2, 1], + (Kind::Furnace, Some(Direction::Up)) => vec![0], + (Kind::Furnace, Some(_)) => vec![1], + _ => (0..self.len()).collect(), + } + } +} + +thread_local! { + /// Entity-owned randomness (projectile spread), separate from the level random. + static ENTITY_RANDOM: std::cell::RefCell = std::cell::RefCell::new(LegacyRandom::new(0x0d15_7e45)); +} + +fn dir_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, + }) +} +fn step(d: Direction) -> [i32; 3] { + match d { + Direction::Down => [0, -1, 0], + Direction::Up => [0, 1, 0], + Direction::North => [0, 0, -1], + Direction::South => [0, 0, 1], + Direction::West => [-1, 0, 0], + Direction::East => [1, 0, 0], + } +} +fn offset(p: Pos, d: Direction) -> Pos { + let s = step(d); + (p.0 + s[0], p.1 + s[1], p.2 + s[2]) +} +fn clockwise(d: Direction) -> Direction { + match d { + Direction::North => Direction::East, + Direction::East => Direction::South, + Direction::South => Direction::West, + Direction::West => Direction::North, + other => other, + } +} + +/// State-level container queries shared by the game and comparator signals. +struct Containers<'a> { + world: &'a World, + behaviours: &'a Behaviours, + items: &'a Items, + registry: &'static horizon_world::registry::BlockRegistry, +} +impl Containers<'_> { + fn prop(&self, state: BlockStateId, key: &str) -> Option<&str> { + self.registry + .state(state)? + .properties + .get(key) + .map(String::as_str) + } + fn name(&self, state: BlockStateId) -> &str { + self.registry.state(state).map_or("", |s| s.name.as_str()) + } + fn max_stack(&self, stack: &ItemStack) -> u32 { + self.items + .get(&stack.item) + .map_or(64, |i| i.max_stack) + .max(1) + } + /// `HopperBlockEntity.getBlockContainer` (double chests combined, right half + /// first). `blocked_chests`: `ChestBlock.getContainer(.., false)` returns + /// nothing for a chest under a redstone conductor. + fn view(&self, pos: Pos, blocked_chests: bool) -> Option { + let entity = self.world.block_entities.get(&pos)?; + let state = self.world.block(pos.0, pos.1, pos.2); + let name = self.name(state); + let kind = match (entity, name) { + (BlockEntity::Furnace(_), _) => Kind::Furnace, + (_, "minecraft:hopper") => Kind::Hopper, + _ => Kind::Generic, + }; + let size = entity.slots().len(); + if matches!(name, "minecraft:chest" | "minecraft:trapped_chest") { + let is_blocked = |p: Pos| { + let above = self.world.block(p.0, p.1 + 1, p.2); + self.behaviours.facts(above).flags + & horizon_world::level::data::state_flags::CONDUCTOR + != 0 + }; + if blocked_chests && is_blocked(pos) { + return None; + } + let kind_prop = self.prop(state, "type").unwrap_or("single"); + if kind_prop != "single" + && let Some(facing) = self.prop(state, "facing").and_then(dir_from_name) + { + // ChestBlock.getConnectedDirection + let connected = if kind_prop == "left" { + clockwise(facing) + } else { + clockwise(clockwise(clockwise(facing))) + }; + let other = offset(pos, connected); + let other_state = self.world.block(other.0, other.1, other.2); + let paired = self.name(other_state) == name + && self + .prop(other_state, "type") + .is_some_and(|t| t != "single" && t != kind_prop) + && self + .world + .block_entities + .get(&other) + .is_some_and(|e| e.slots().len() == 27); + if paired { + if blocked_chests && is_blocked(other) { + return None; + } + let parts = if kind_prop == "right" { + vec![(pos, size), (other, 27)] + } else { + vec![(other, 27), (pos, size)] + }; + return Some(View { parts, kind }); + } + } + } + Some(View { + parts: vec![(pos, size)], + kind, + }) + } + fn get(&self, view: &View, slot: usize) -> Option<&ItemStack> { + let (pos, i) = view.locate(slot)?; + self.world + .block_entities + .get(&pos)? + .slots() + .get(i)? + .as_ref() + } + fn is_empty(&self, view: &View) -> bool { + (0..view.len()).all(|i| self.get(view, i).is_none()) + } + /// `Container.canPlaceItem` (+ `canPlaceItemThroughFace` for furnaces). + fn can_place(&self, view: &View, slot: usize, stack: &ItemStack) -> bool { + if view.kind != Kind::Furnace { + return true; + } + match slot { + 2 => false, + 1 => { + let fuel = self + .items + .get(&stack.item) + .is_some_and(|i| i.fuel.is_some()); + let current_bucket = self + .get(view, 1) + .is_some_and(|s| &*s.item == "minecraft:bucket"); + fuel || (&*stack.item == "minecraft:bucket" && !current_bucket) + } + _ => true, + } + } + /// `canTakeItemThroughFace` (only furnaces restrict it). + fn can_take(&self, view: &View, slot: usize, stack: &ItemStack, face: Direction) -> bool { + view.kind != Kind::Furnace + || face != Direction::Down + || slot != 1 + || matches!(&*stack.item, "minecraft:water_bucket" | "minecraft:bucket") + } + /// `HopperBlockEntity.isFullContainer`. + fn is_full(&self, view: &View, face: Direction) -> bool { + view.slots_for_face(Some(face)).into_iter().all(|i| { + self.get(view, i) + .is_some_and(|s| s.count >= self.max_stack(s)) + }) + } + /// `AbstractContainerMenu.getRedstoneSignalFromContainer`. + fn signal(&self, view: &View) -> i32 { + let mut total = 0.0f32; + for i in 0..view.len() { + if let Some(s) = self.get(view, i) { + total += s.count as f32 / self.max_stack(s).min(64) as f32; + } + } + total /= view.len().max(1) as f32; + // Mth.lerpDiscrete(total, 0, 15) + (total * 14.0).floor() as i32 + i32::from(total > 0.0) + } +} + +/// Comparator input from a container block entity (0 when there is none). +pub(super) fn container_signal( + world: &World, + behaviours: &Behaviours, + items: &Items, + registry: &'static horizon_world::registry::BlockRegistry, + pos: BlockPos, +) -> i32 { + let c = Containers { + world, + behaviours, + items, + registry, + }; + c.view((pos.x, pos.y, pos.z), true) + .map_or(0, |v| c.signal(&v)) +} + +impl Game<'_> { + fn containers(&self) -> Containers<'_> { + Containers { + world: &self.world, + behaviours: &self.res.behaviours, + items: &self.res.items, + registry: self.res.assets.registry, + } + } + fn slot_mut_at(&mut self, view: &View, slot: usize) -> Option<&mut Option> { + let (pos, i) = view.locate(slot)?; + self.world + .block_entities + .get_mut(&pos)? + .slots_mut() + .get_mut(i) + } + /// `BlockEntity.setChanged` for every block entity of a container. + fn view_changed(&mut self, view: &View) { + for &(pos, _) in &view.parts { + self.container_changed(pos); + } + } + /// `BlockEntity.setChanged` at `pos`: comparators re-read the container. + pub(super) fn container_changed(&mut self, pos: Pos) { + self.world.modified.insert((pos.0 >> 4, pos.2 >> 4)); + self.with_level(|b, level, ticks| { + b.container_changed(level, ticks, BlockPos::new(pos.0, pos.1, pos.2)) + }); + } + /// `HopperBlockEntity.tryMoveInItem`. + fn try_move_in_item( + &mut self, + from_hopper: Option, + view: &View, + mut stack: ItemStack, + slot: usize, + ) -> Option { + let c = self.containers(); + if !c.can_place(view, slot, &stack) { + return Some(stack); + } + let was_empty = c.is_empty(view); + let max = c.max_stack(&stack); + let mut success = false; + let target = self.slot_mut_at(view, slot)?; + match target { + None => { + *target = Some(stack.clone()); + stack.count = 0; + success = true; + } + Some(current) + if current.item == stack.item + && current.damage == stack.damage + && current.count <= max => + { + let space = max.saturating_sub(current.count); + let count = stack.count.min(space); + stack.count -= count; + current.count += count; + success = count > 0; + } + Some(_) => {} + } + if success { + if was_empty && view.kind == Kind::Hopper { + let dest = view.parts[0].0; + let from_ticked = from_hopper.and_then(|p| self.hoppers.get(&p).map(|h| h.ticked)); + let state = self.hoppers.entry(dest).or_default(); + if state.cooldown <= 8 { + let skip = i32::from(from_ticked.is_some_and(|t| state.ticked >= t)); + state.cooldown = 8 - skip; + } + } + self.view_changed(view); + } + (stack.count > 0).then_some(stack) + } + /// `HopperBlockEntity.addItem(from, container, stack, direction)`; the remainder. + fn add_item( + &mut self, + from_hopper: Option, + view: &View, + stack: ItemStack, + face: Option, + ) -> Option { + let slots = if view.kind == Kind::Furnace && face.is_some() { + view.slots_for_face(face) + } else { + (0..view.len()).collect() + }; + let mut rest = Some(stack); + for slot in slots { + let Some(stack) = rest.take() else { break }; + rest = self.try_move_in_item(from_hopper, view, stack, slot); + } + rest + } + /// Remove one item from a slot (`removeItem(slot, 1)`). + fn take_one(&mut self, view: &View, slot: usize) -> Option { + let target = self.slot_mut_at(view, slot)?; + let current = target.as_mut()?; + let one = ItemStack { + count: 1, + ..current.clone() + }; + current.count -= 1; + if current.count == 0 { + *target = None; + } + Some(one) + } + /// Undo `take_one` after a failed move. + fn put_back(&mut self, view: &View, slot: usize, one: ItemStack) { + if let Some(target) = self.slot_mut_at(view, slot) { + match target { + Some(current) => current.count += one.count, + None => *target = Some(one), + } + } + } + /// Every hopper's `pushItemsTick`, in a stable position order. + pub(super) fn tick_hoppers(&mut self) -> Result<()> { + let hopper = self + .res + .assets + .registry + .default_state("minecraft:hopper") + .map(|s| self.res.facts.get(s).name.clone()); + let Some(hopper) = hopper else { return Ok(()) }; + let mut positions: Vec = self + .world + .block_entities + .keys() + .copied() + .filter(|p| self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == hopper) + .collect(); + positions.sort_unstable(); + self.hoppers + .retain(|p, _| positions.binary_search(p).is_ok()); + let time = self.world.game_time; + for pos in positions { + let state = self.hoppers.entry(pos).or_default(); + state.cooldown -= 1; + state.ticked = time; + if state.cooldown <= 0 { + state.cooldown = 0; + self.hopper_try_move_items(pos); + } + } + Ok(()) + } + /// `HopperBlockEntity.tryMoveItems` with `suckInItems`. + fn hopper_try_move_items(&mut self, pos: Pos) { + let state = self.world.block(pos.0, pos.1, pos.2); + let c = self.containers(); + let enabled = c.prop(state, "enabled") != Some("false"); + let Some(view) = c.view(pos, false) else { + return; + }; + if self.hoppers.get(&pos).is_some_and(|h| h.cooldown > 0) || !enabled { + return; + } + let mut changed = false; + if !c.is_empty(&view) { + changed = self.hopper_eject(pos, &view); + } + let c = self.containers(); + let full = + (0..view.len()).all(|i| c.get(&view, i).is_some_and(|s| s.count == c.max_stack(s))); + if !full { + changed |= self.hopper_suck(pos, &view); + } + if changed { + self.hoppers.entry(pos).or_default().cooldown = 8; + self.container_changed(pos); + } + } + /// `HopperBlockEntity.ejectItems`. + fn hopper_eject(&mut self, pos: Pos, hopper: &View) -> bool { + let state = self.world.block(pos.0, pos.1, pos.2); + let c = self.containers(); + let Some(facing) = c.prop(state, "facing").and_then(dir_from_name) else { + return false; + }; + let Some(target) = c.view(offset(pos, facing), false) else { + return false; + }; + let face = facing.opposite(); + if c.is_full(&target, face) { + return false; + } + for slot in 0..hopper.len() { + let Some(one) = self.take_one(hopper, slot) else { + continue; + }; + match self.add_item(Some(pos), &target, one, Some(face)) { + None => { + self.view_changed(&target); + return true; + } + Some(rest) => self.put_back(hopper, slot, rest), + } + } + false + } + /// `HopperBlockEntity.suckInItems`: from the container above, or item entities. + fn hopper_suck(&mut self, pos: Pos, hopper: &View) -> bool { + let above = (pos.0, pos.1 + 1, pos.2); + let c = self.containers(); + if let Some(source) = c.view(above, false) { + let source_hopper = (source.kind == Kind::Hopper).then_some(above); + for slot in source.slots_for_face(Some(Direction::Down)) { + let c = self.containers(); + let Some(stack) = c.get(&source, slot) else { + continue; + }; + if !c.can_take(&source, slot, stack, Direction::Down) { + continue; + } + let Some(one) = self.take_one(&source, slot) else { + continue; + }; + match self.add_item(source_hopper, hopper, one, None) { + None => { + self.view_changed(&source); + return true; + } + Some(rest) => self.put_back(&source, slot, rest), + } + } + return false; + } + let above_state = self.world.block(above.0, above.1, above.2); + let blocked = self.res.facts.get(above_state).full_collision + && !self + .res + .behaviours + .tag("minecraft:does_not_block_hoppers") + .is_some_and(|t| t.contains(self.res.behaviours.block(above_state))); + if blocked { + return false; + } + // Hopper.SUCK_AABB: the hopper bowl and the block above. + let (min, max) = ( + [ + f64::from(pos.0), + f64::from(pos.1) + 11.0 / 16.0, + f64::from(pos.2), + ], + [ + f64::from(pos.0) + 1.0, + f64::from(pos.1) + 2.0, + f64::from(pos.2) + 1.0, + ], + ); + let mut i = 0; + while i < self.dropped.len() { + let b = self.dropped[i].bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + let inside = lo.x < max[0] + && hi.x > min[0] + && lo.y < max[1] + && hi.y > min[1] + && lo.z < max[2] + && hi.z > min[2]; + if inside { + let stack = self.dropped[i].stack.clone(); + match self.add_item(None, hopper, stack, None) { + None => { + self.dropped.remove(i); + return true; + } + Some(rest) => self.dropped[i].stack = rest, + } + } + i += 1; + } + false + } + + // ---- dispensers and droppers ---- + + /// `DispenserBlock.dispenseFrom` / `DropperBlock.dispenseFrom`. + pub(super) fn dispense_from(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> { + let key = (pos.x, pos.y, pos.z); + let name = self.res.facts.get(state).name.clone(); + let dropper = &*name == "minecraft:dropper"; + if !dropper && &*name != "minecraft:dispenser" { + return Ok(()); + } + let Some(view) = self.containers().view(key, false) else { + return Ok(()); + }; + // DispenserBlockEntity.getRandomSlot + let mut slot = None; + let mut odds = 1; + for i in 0..view.len() { + if self.containers().get(&view, i).is_some() { + if self.world.random.next_int_bound(odds).unwrap_or(1) == 0 { + slot = Some(i); + } + odds += 1; + } + } + let center = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 0.5, + f64::from(pos.z) + 0.5, + ]; + let Some(slot) = slot else { + self.audio + .play("minecraft:block.dispenser.fail", Some(center), 1.0, 1.2); + return Ok(()); + }; + let Some(facing) = self + .containers() + .prop(state, "facing") + .and_then(dir_from_name) + else { + return Ok(()); + }; + let Some(stack) = self.containers().get(&view, slot).cloned() else { + return Ok(()); + }; + let target = offset(key, facing); + let remaining = if dropper { + match self.containers().view(target, false) { + None => self.default_dispense(key, facing, stack), + Some(into) => { + let one = ItemStack { + count: 1, + ..stack.clone() + }; + if self + .add_item(None, &into, one, Some(facing.opposite())) + .is_none() + { + self.view_changed(&into); + Some(ItemStack { + count: stack.count - 1, + ..stack + }) + .filter(|s| s.count > 0) + } else { + Some(stack) + } + } + } + } else { + self.dispense_behaviour(key, facing, stack)? + }; + if let Some(entry) = self.slot_mut_at(&view, slot) { + *entry = remaining; + } + self.container_changed(key); + Ok(()) + } + /// `DefaultDispenseItemBehavior.dispense`: drop one item, click and smoke. + fn default_dispense( + &mut self, + pos: Pos, + facing: Direction, + mut stack: ItemStack, + ) -> Option { + let one = ItemStack { + count: 1, + ..stack.clone() + }; + stack.count -= 1; + self.spawn_dispensed(pos, facing, one, 6); + self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); + (stack.count > 0).then_some(stack) + } + fn dispenser_sound(&mut self, pos: Pos, sound: &str, pitch: f32) { + let center = [ + f64::from(pos.0) + 0.5, + f64::from(pos.1) + 0.5, + f64::from(pos.2) + 0.5, + ]; + self.audio.play(sound, Some(center), 1.0, pitch); + } + /// `DefaultDispenseItemBehavior.spawnItem` at `DispenserBlock.getDispensePosition`. + fn spawn_dispensed(&mut self, pos: Pos, facing: Direction, stack: ItemStack, accuracy: i32) { + let s = step(facing); + let mut at = [ + f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]), + f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]), + f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]), + ]; + at[1] -= if s[1] != 0 { 0.125 } else { 0.156_25 }; + let r = &mut self.world.random; + // new ItemEntity(level, x, y, z, stack): its default motion draws first. + let _ = (r.next_double(), r.next_double()); + let pow = r.next_double() * 0.1 + 0.2; + let spread = 0.017_227_5 * f64::from(accuracy); + let v = [ + r.triangle(f64::from(s[0]) * pow, spread), + r.triangle(0.2, spread), + r.triangle(f64::from(s[2]) * pow, spread), + ]; + self.spawn_item(stack, at, v, 0); + } + /// `DefaultDispenseItemBehavior.consumeWithRemainder`. + fn consume_with_remainder( + &mut self, + pos: Pos, + facing: Direction, + mut stack: ItemStack, + remainder: ItemStack, + ) -> Option { + stack.count -= 1; + if stack.count == 0 { + return Some(remainder); + } + // DispenserBlockEntity.insertItem, then drop what does not fit. + let mut rest = remainder; + if let Some(view) = self.containers().view(pos, false) { + let max = self.containers().max_stack(&rest); + for i in 0..view.len() { + let Some(entry) = self.slot_mut_at(&view, i) else { + continue; + }; + match entry { + None => { + let n = rest.count.min(max); + *entry = Some(ItemStack { + count: n, + ..rest.clone() + }); + rest.count -= n; + } + Some(e) if e.item == rest.item && e.damage == rest.damage => { + let n = rest.count.min(max.saturating_sub(e.count)); + e.count += n; + rest.count -= n; + } + Some(_) => {} + } + if rest.count == 0 { + break; + } + } + } + if rest.count > 0 { + self.spawn_dispensed(pos, facing, rest, 6); + self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); + } + Some(stack) + } + /// `DispenserBlock.getDispenseMethod(..).dispense(source, stack)`. + fn dispense_behaviour( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result> { + let target = offset(pos, facing); + let target_pos = BlockPos::new(target.0, target.1, target.2); + let item = stack.item.to_string(); + let result = match item.as_str() { + "minecraft:bone_meal" => { + let grown = self.with_level(|b, level, ticks| { + b.grow_crop(level, ticks, target_pos) + || b.grow_water_plant(level, ticks, target_pos, None) + }); + self.process_level_events()?; + if grown { + self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); + self.audio.play( + "minecraft:item.bone_meal.use", + Some([ + f64::from(target.0) + 0.5, + f64::from(target.1) + 0.5, + f64::from(target.2) + 0.5, + ]), + 1.0, + 1.0, + ); + Some(ItemStack { + count: stack.count - 1, + ..stack + }) + .filter(|s| s.count > 0) + } else { + self.dispenser_sound(pos, "minecraft:block.dispenser.fail", 1.2); + Some(stack) + } + } + "minecraft:tnt" => { + self.spawn_primed_tnt(target_pos, false); + self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); + Some(ItemStack { + count: stack.count - 1, + ..stack + }) + .filter(|s| s.count > 0) + } + "minecraft:flint_and_steel" => { + let target_state = self.world.block(target.0, target.1, target.2); + let target_name = self.res.facts.get(target_state).name.clone(); + let fire = self.res.assets.registry.default_state("minecraft:fire"); + let success = if self.res.facts.is_air(target_state) + && let Some(fire) = fire + && self + .with_level(|b, level, ticks| b.can_survive(level, ticks, target_pos, fire)) + { + self.level_set([target.0, target.1, target.2], fire)?; + true + } else if &*target_name == "minecraft:tnt" { + self.spawn_primed_tnt(target_pos, false); + self.with_level(|b, level, ticks| { + b.remove_block(level, ticks, target_pos, false) + }); + self.process_level_events()?; + true + } else if self.containers().prop(target_state, "lit") == Some("false") + && (target_name.contains("campfire") || target_name.contains("candle")) + && self.containers().prop(target_state, "waterlogged") != Some("true") + { + let lit = self + .res + .assets + .registry + .state(target_state) + .cloned() + .and_then(|mut s| { + s.properties.insert("lit".into(), "true".into()); + self.res.assets.registry.resolve(&s).ok() + }); + if let Some(lit) = lit { + self.level_set([target.0, target.1, target.2], lit)?; + } + true + } else { + false + }; + self.dispenser_sound( + pos, + if success { + "minecraft:block.dispenser.dispense" + } else { + "minecraft:block.dispenser.fail" + }, + if success { 1.0 } else { 1.2 }, + ); + let mut stack = stack; + if success { + stack.damage += 1; + let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); + if max > 0 && stack.damage >= max { + return Ok(None); + } + } + Some(stack) + } + "minecraft:water_bucket" | "minecraft:lava_bucket" => { + let fluid = if item == "minecraft:water_bucket" { + "minecraft:water" + } else { + "minecraft:lava" + }; + let target_state = self.world.block(target.0, target.1, target.2); + let f = self.res.facts.get(target_state).clone(); + let waterloggable = item == "minecraft:water_bucket" + && self.containers().prop(target_state, "waterlogged") == Some("false"); + if waterloggable { + let wet = self + .res + .assets + .registry + .state(target_state) + .cloned() + .and_then(|mut s| { + s.properties.insert("waterlogged".into(), "true".into()); + self.res.assets.registry.resolve(&s).ok() + }); + if let Some(wet) = wet { + self.level_set([target.0, target.1, target.2], wet)?; + } + self.consume_with_remainder( + pos, + facing, + stack, + ItemStack { + item: "minecraft:bucket".into(), + count: 1, + damage: 0, + }, + ) + } else if (self.res.facts.is_air(target_state) || f.replaceable) + && !(f.fluid_level == 8 && !f.fluid_falling && &*f.name == fluid) + && let Some(source) = self.res.assets.registry.default_state(fluid) + { + self.level_set([target.0, target.1, target.2], source)?; + let sound = if fluid == "minecraft:water" { + "minecraft:item.bucket.empty" + } else { + "minecraft:item.bucket.empty_lava" + }; + self.audio.play( + sound, + Some([ + f64::from(target.0) + 0.5, + f64::from(target.1) + 0.5, + f64::from(target.2) + 0.5, + ]), + 1.0, + 1.0, + ); + self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); + self.consume_with_remainder( + pos, + facing, + stack, + ItemStack { + item: "minecraft:bucket".into(), + count: 1, + damage: 0, + }, + ) + } else { + self.default_dispense(pos, facing, stack) + } + } + "minecraft:bucket" => { + let target_state = self.world.block(target.0, target.1, target.2); + let f = self.res.facts.get(target_state).clone(); + let picked = if f.waterlogged + && self.containers().prop(target_state, "waterlogged") == Some("true") + { + let dry = self + .res + .assets + .registry + .state(target_state) + .cloned() + .and_then(|mut s| { + s.properties.insert("waterlogged".into(), "false".into()); + self.res.assets.registry.resolve(&s).ok() + }); + if let Some(dry) = dry { + self.level_set([target.0, target.1, target.2], dry)?; + } + Some("minecraft:water_bucket") + } else if f.fluid_level == 8 + && !f.fluid_falling + && matches!(&*f.name, "minecraft:water" | "minecraft:lava") + { + self.level_set([target.0, target.1, target.2], self.world.air)?; + Some(if &*f.name == "minecraft:water" { + "minecraft:water_bucket" + } else { + "minecraft:lava_bucket" + }) + } else if &*f.name == "minecraft:powder_snow" { + self.level_set([target.0, target.1, target.2], self.world.air)?; + Some("minecraft:powder_snow_bucket") + } else { + None + }; + match picked { + Some(filled) => { + self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); + self.consume_with_remainder( + pos, + facing, + stack, + ItemStack { + item: filled.into(), + count: 1, + damage: 0, + }, + ) + } + None => self.default_dispense(pos, facing, stack), + } + } + "minecraft:arrow" | "minecraft:spectral_arrow" | "minecraft:tipped_arrow" => { + // ProjectileDispenseBehavior: power 1.1, uncertainty 6, from 0.7 ahead and 0.1 up. + let s = step(facing); + let at = Vec3::new( + f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]), + f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]) + 0.1, + f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]), + ); + let spread = 0.017_227_5 * 6.0; + let v = ENTITY_RANDOM.with(|r| { + let r = &mut *r.borrow_mut(); + [ + (f64::from(s[0]) + r.triangle(0.0, spread)) * 1.1, + (f64::from(s[1]) + r.triangle(0.0, spread)) * 1.1, + (f64::from(s[2]) + r.triangle(0.0, spread)) * 1.1, + ] + }); + self.arrows.push(Arrow { + from_player: true, + critical: false, + position: at, + previous: at, + velocity: Vec3::new(v[0], v[1], v[2]), + stuck: false, + age: 0, + base_damage: 2.0, + }); + self.dispenser_sound(pos, "minecraft:block.dispenser.launch", 1.2); + Some(ItemStack { + count: stack.count - 1, + ..stack + }) + .filter(|s| s.count > 0) + } + _ => self.default_dispense(pos, facing, stack), + }; + Ok(result) + } +} + +// ---- hopper, dispenser and dropper screens ---- + +/// Which machine screen the open container uses. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Screen { + Hopper, + Dispenser, + Dropper, +} + +impl Game<'_> { + fn machine_screen(&self) -> Option { + let key = self.container?; + let state = self.world.block(key.0, key.1, key.2); + match &*self.res.facts.get(state).name { + "minecraft:hopper" => Some(Screen::Hopper), + "minecraft:dispenser" => Some(Screen::Dispenser), + "minecraft:dropper" => Some(Screen::Dropper), + _ => None, + } + } + /// `imageHeight` of the open screen (HopperScreen is 133 tall). + pub(super) fn screen_height(&self) -> f32 { + if self.machine_screen() == Some(Screen::Hopper) { + 133.0 + } else { + 166.0 + } + } + /// HopperMenu / DispenserMenu slot layouts; None for other screens. + pub(super) fn machine_slot_position(&self, i: usize) -> Option<(f32, f32)> { + let screen = self.machine_screen()?; + let inventory_y = if screen == Screen::Hopper { 51.0 } else { 84.0 }; + Some(match i { + 0..9 => (8.0 + i as f32 * 18.0, inventory_y + 58.0), + 9..36 => ( + 8.0 + ((i - 9) % 9) as f32 * 18.0, + inventory_y + ((i - 9) / 9) as f32 * 18.0, + ), + 300..500 if screen == Screen::Hopper => (44.0 + (i - 300) as f32 * 18.0, 20.0), + 300..500 => ( + 62.0 + ((i - 300) % 3) as f32 * 18.0, + 17.0 + ((i - 300) / 3) as f32 * 18.0, + ), + _ => return None, + }) + } + /// HopperScreen / DispenserScreen background and labels; false for other containers. + pub(super) fn draw_machine_screen( + &self, + batch: &mut horizon_client::hud::HudBatch, + ox: f32, + oy: f32, + ) -> bool { + let Some(screen) = self.machine_screen() else { + return false; + }; + let atlas = &self.res.atlas; + let (texture, height, title) = match screen { + Screen::Hopper => ("gui/container/hopper", 133.0, "Item Hopper"), + Screen::Dispenser => ("gui/container/dispenser", 166.0, "Dispenser"), + Screen::Dropper => ("gui/container/dispenser", 166.0, "Dropper"), + }; + if let Some(mut r) = atlas.sprites.get(texture).copied() { + let dv = (r.v1 - r.v0) / r.h as f32; + let du = (r.u1 - r.u0) / r.w as f32; + r.u1 = r.u0 + 176.0 * du; + r.v1 = r.v0 + height * dv; + batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX); + } + let grey = horizon_client::hud::rgba(64, 64, 64, 255); + let title_x = if screen == Screen::Hopper { + 8.0 + } else { + (176.0 - horizon_client::hud::HudBatch::text_width(atlas, title)) / 2.0 + }; + batch.text(atlas, title, ox + title_x, oy + 6.0, grey, false); + batch.text( + atlas, + "Inventory", + ox + 8.0, + oy + height - 94.0, + grey, + false, + ); + true + } +} diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 6997be4f8..165320b2f 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -125,7 +125,7 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: let pos = (int("x")?, int("y")?, int("z")?); let mut entity = BlockEntity::for_block(&id)?; match &mut entity { - BlockEntity::Chest(items) => *items = decode_items(tag.get("Items"), 27), + BlockEntity::Chest(items) => *items = decode_items(tag.get("Items"), items.len()), BlockEntity::Furnace(f) => { let items = decode_items(tag.get("Items"), 3); f.items = [items[0].clone(), items[1].clone(), items[2].clone()]; @@ -209,7 +209,15 @@ pub fn encode(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes) -> Named ("InhabitedTime", Tag::Long(0)), ("isLightOn", Tag::Byte(0)), ("sections", Tag::List(sections)), - ("block_entities", Tag::List(chunk.block_entities.iter().map(|(p, e)| encode_block_entity(*p, e)).collect())), + ("block_entities", Tag::List(chunk.block_entities.iter().map(|(p, e)| { + // The block's own entity id (barrels, droppers, trapped chests). + let mut tag = encode_block_entity(*p, e); + let state = chunk.block(p.0 & 15, p.1, p.2 & 15); + if let (Tag::Compound(entries), Some(id)) = (&mut tag, registry.state(state).and_then(|s| crate::containers::BlockEntity::id_for_block(&s.name))) { + entries.insert("id".into(), string(id)); + } + tag + }).collect())), ]), } } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 45b6ebaaf..ee7e1aa61 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -113,6 +113,7 @@ mod query; mod rails; mod redstone; mod shapes; +mod signals; mod speleothem; mod survive; mod tick; diff --git a/crates/horizon-world/src/level/signals.rs b/crates/horizon-world/src/level/signals.rs new file mode 100644 index 000000000..6f02ff549 --- /dev/null +++ b/crates/horizon-world/src/level/signals.rs @@ -0,0 +1,21 @@ +//! Output-signal notifications for block entities the caller owns. +use super::{Behaviours, LevelAccess, Ticks}; +use horizon_core::position::BlockPos; + +impl Behaviours { + /// `BlockEntity.setChanged`: a container at `pos` changed its contents, so + /// comparators reading it (`Level.updateNeighbourForOutputSignal`) update. + pub fn container_changed( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + let state = level.block_state(pos); + if !self.is_air(state) { + let block = self.block(state); + self.sim(level, ticks) + .update_neighbour_for_output_signal(pos, block); + } + } +} From 5b1936d5d528ffb78bc56098d6af8ba534462873 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:43:25 +0200 Subject: [PATCH 5/8] Form snow and ice and fill cauldrons in rain from biome temperatures Answer ServerLevel.tickPrecipitation (Biome.shouldFreeze, shouldSnow, getPrecipitationAt) and Level.isRainingAt from the worldgen bundle's biome temperatures, so snow accumulates, water freezes, cauldrons fill, farmland stays moist and fire is extinguished in rain. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 6 + .../horizon-world/src/level/growth_tests.rs | 30 +++- crates/horizon-world/src/level/mod.rs | 1 + crates/horizon-world/src/level/weather.rs | 132 ++++++++++++++++++ crates/horizon-world/src/worldgen/live.rs | 17 +++ 5 files changed, 183 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-world/src/level/weather.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e88f91635..1b9052ae0 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -208,6 +208,12 @@ struct GameLevel<'w> { registry: &'static horizon_world::registry::BlockRegistry, } impl LevelAccess for GameLevel<'_> { + fn precipitation(&self, pos: BlockPos) -> Option { + self.behaviours.precipitation_info(self, pos) + } + fn is_raining_at(&self, pos: BlockPos) -> bool { + self.behaviours.is_raining_at(self, pos) + } fn block_entity_analog_signal(&self, pos: BlockPos, _state: BlockStateId, _direction: Direction) -> i32 { machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos) } diff --git a/crates/horizon-world/src/level/growth_tests.rs b/crates/horizon-world/src/level/growth_tests.rs index 2d120335c..de46103b8 100644 --- a/crates/horizon-world/src/level/growth_tests.rs +++ b/crates/horizon-world/src/level/growth_tests.rs @@ -70,9 +70,6 @@ impl LevelAccess for Level { fn game_time(&self) -> i64 { 0 } - fn block_light(&self, _pos: BlockPos) -> i32 { - 15 - } fn emit(&mut self, event: LevelEvent) { self.events.push(event); } @@ -340,3 +337,30 @@ fn tall_flowers_and_seagrass() { } ))); } + +#[test] +fn snowy_biomes_freeze_and_snow() { + let Some(f) = fixture() else { return }; + let mut w = World::new(f, 1); + w.level.biome = "minecraft:snowy_plains"; + w.floor("grass_block", 2); + let water = w.id("water", &[]); + w.put(BlockPos::new(1, 63, 0), water); + let b = &f.behaviours; + let grass = b + .precipitation_info(&w.level, BlockPos::new(0, 70, 0)) + .unwrap(); + assert_eq!(grass.top, BlockPos::new(0, 64, 0)); + assert!(grass.snows_at_top && !grass.freezes_below); + assert_eq!(grass.kind, PrecipitationKind::Snow); + let pond = b + .precipitation_info(&w.level, BlockPos::new(1, 70, 0)) + .unwrap(); + assert!(pond.freezes_below, "a water source at the edge freezes"); + w.level.biome = "minecraft:plains"; + let rain = b + .precipitation_info(&w.level, BlockPos::new(0, 70, 0)) + .unwrap(); + assert!(!rain.snows_at_top && !rain.freezes_below); + assert_eq!(rain.kind, PrecipitationKind::Rain); +} diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index ee7e1aa61..b111b392d 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -118,6 +118,7 @@ mod speleothem; mod survive; mod tick; mod update; +mod weather; #[cfg(test)] mod growth_tests; diff --git a/crates/horizon-world/src/level/weather.rs b/crates/horizon-world/src/level/weather.rs new file mode 100644 index 000000000..845548ce1 --- /dev/null +++ b/crates/horizon-world/src/level/weather.rs @@ -0,0 +1,132 @@ +//! Biome weather queries for a live level: `ServerLevel.tickPrecipitation`'s +//! inputs (`Biome.shouldFreeze`, `shouldSnow`, `getPrecipitationAt`) and +//! `Level.isRainingAt`, from the biome temperatures of the worldgen bundle. +use super::{Behaviours, Dimension, LevelAccess, Precipitation, PrecipitationKind}; +use crate::{ + fluid::FluidKind, + worldgen::biome_temperature::{BiomeTemperatureSettings, Precipitation as BiomePrecipitation}, +}; +use horizon_core::{geometry::Direction, position::BlockPos}; + +fn sea_level(level: &L) -> i32 { + match level.dimension() { + Dimension::Nether => 32, + Dimension::End => 0, + Dimension::Overworld => 63, + } +} + +impl Behaviours { + fn biome_settings( + &self, + level: &L, + pos: BlockPos, + ) -> Option { + let features = self.live_features()?; + let biome = features.biome_id(level.biome_name(pos)?)?; + features.biome_temperature(biome) + } + /// `Biome.getPrecipitationAt(pos, seaLevel)`. + fn precipitation_kind( + settings: BiomeTemperatureSettings, + pos: BlockPos, + sea: i32, + ) -> BiomePrecipitation { + if !settings.has_precipitation { + BiomePrecipitation::None + } else if settings.height_adjusted(pos, sea) < 0.15 { + BiomePrecipitation::Snow + } else { + BiomePrecipitation::Rain + } + } + /// `getHeightmapPos(MOTION_BLOCKING, pos)`. + fn motion_blocking_top(&self, level: &L, pos: BlockPos) -> BlockPos { + let blocks = self.tag("minecraft:blocks_motion_in_heightmap"); + for y in (level.min_y()..level.max_y()).rev() { + let state = level.block_state(BlockPos::new(pos.x, y, pos.z)); + let fluid = self.fluid(state).kind() != FluidKind::Empty; + if fluid || blocks.is_some_and(|t| t.contains(self.block(state))) { + return BlockPos::new(pos.x, y + 1, pos.z); + } + } + BlockPos::new(pos.x, level.min_y(), pos.z) + } + /// Answers for one `ServerLevel.tickPrecipitation` at the column of `pos`; + /// None without live features or a biome. + pub fn precipitation_info( + &self, + level: &L, + pos: BlockPos, + ) -> Option { + let top = self.motion_blocking_top(level, pos); + let below = BlockPos::new(top.x, top.y - 1, top.z); + let settings = self.biome_settings(level, top)?; + let sea = sea_level(level); + let inside = |p: BlockPos| p.y >= level.min_y() && p.y < level.max_y(); + // Biome.shouldFreeze(level, below, true) + let freezes_below = settings.height_adjusted(below, sea) < 0.15 + && inside(below) + && level.block_light(below) < 10 + && { + let state = level.block_state(below); + self.block(state) == self.named.water && self.fluid(state).is_source() + } + && [ + Direction::West, + Direction::East, + Direction::North, + Direction::South, + ] + .into_iter() + .any(|d| { + let n = super::update::rel(below, d); + !self.is_water_fluid(self.fluid(level.block_state(n)).kind()) + }); + // Biome.shouldSnow(level, top) + let snows_at_top = Self::precipitation_kind(settings, top, sea) == BiomePrecipitation::Snow + && inside(top) + && level.block_light(top) < 10 + && { + let state = level.block_state(top); + (self.is_air(state) || self.block(state) == self.named.snow) + && self.snow_survives(level, top) + }; + let kind = match Self::precipitation_kind(settings, below, sea) { + BiomePrecipitation::None => PrecipitationKind::None, + BiomePrecipitation::Rain => PrecipitationKind::Rain, + BiomePrecipitation::Snow => PrecipitationKind::Snow, + }; + Some(Precipitation { + top, + freezes_below, + snows_at_top, + kind, + }) + } + /// `SnowLayerBlock.canSurvive` for a default snow layer at `pos`. + fn snow_survives(&self, level: &L, pos: BlockPos) -> bool { + let below = level.block_state(BlockPos::new(pos.x, pos.y - 1, pos.z)); + let block = self.block(below); + if self.tags.cannot_support_snow_layer.contains(block) { + return false; + } + if self.tags.support_override_snow_layer.contains(block) { + return true; + } + self.collision_face_full(below, Direction::Up) + || (block == self.named.snow && self.table.int(below, self.props.layers) == 8) + } + /// `Level.isRainingAt(pos)`. + pub fn is_raining_at(&self, level: &L, pos: BlockPos) -> bool { + if !level.is_raining() || level.sky_light(pos) < 15 { + return false; + } + if self.motion_blocking_top(level, pos).y > pos.y { + return false; + } + self.biome_settings(level, pos).is_some_and(|s| { + Self::precipitation_kind(s, pos, sea_level(level)) == BiomePrecipitation::Rain + }) + } +} diff --git a/crates/horizon-world/src/worldgen/live.rs b/crates/horizon-world/src/worldgen/live.rs index 7460d1450..c8cbcca0c 100644 --- a/crates/horizon-world/src/worldgen/live.rs +++ b/crates/horizon-world/src/worldgen/live.rs @@ -34,6 +34,8 @@ pub struct LiveFeatures { placed: Cache, /// `BiomeGenerationSettings.getBoneMealFeatures` per biome, in vanilla order. bone_meal: Vec>, + /// Temperature settings per biome (`Biome.getTemperature`). + temperatures: Vec, } fn resource(message: impl Into) -> GeneratorError { @@ -193,7 +195,15 @@ impl LiveFeatures { } bone_meal.push(list); } + let temperatures = (0..data.biome_names().len()) + .map(|i| { + super::biome_temperature::BiomeTemperatureSettings::from_json( + data.biome_json(BiomeId(i as u32)), + ) + }) + .collect::, _>>()?; Ok(Some(Self { + temperatures, data: data.clone(), catalog, bindings, @@ -296,6 +306,13 @@ impl LiveFeatures { } } } + /// Temperature settings of a biome. + pub fn biome_temperature( + &self, + biome: BiomeId, + ) -> Option { + self.temperatures.get(biome.0 as usize).copied() + } /// Whether the named biome is in a biome tag (`minecraft:...`). pub fn biome_in_tag(&self, biome: &str, tag: &str) -> bool { self.data From 1ee753254d2e563003bb392a94fac8a3436f0293 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:47:50 +0200 Subject: [PATCH 6/8] Tick eyeblossoms, potted eyeblossoms, turtle eggs and dried ghasts Eyeblossoms follow the day timeline's eyeblossom_open attribute (waking neighbours in vanilla scan order), turtle eggs crack and hatch on sand with the timeline hatch chance, and dried ghasts hydrate while waterlogged. Adds LevelAccess::day_time. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 3 + .../horizon-world/src/level/growth_tests.rs | 50 ++++ crates/horizon-world/src/level/mod.rs | 6 + crates/horizon-world/src/level/states.rs | 4 + crates/horizon-world/src/level/tick.rs | 6 + crates/horizon-world/src/level/timeline.rs | 216 ++++++++++++++++++ 6 files changed, 285 insertions(+) create mode 100644 crates/horizon-world/src/level/timeline.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1b9052ae0..989123384 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -224,6 +224,9 @@ impl LevelAccess for GameLevel<'_> { fn world_seed(&self) -> i64 { self.seed } + fn day_time(&self) -> i64 { + self.world.day_time + } fn block_state(&self, pos: BlockPos) -> BlockStateId { self.world.block(pos.x, pos.y, pos.z) } diff --git a/crates/horizon-world/src/level/growth_tests.rs b/crates/horizon-world/src/level/growth_tests.rs index de46103b8..16a78fbff 100644 --- a/crates/horizon-world/src/level/growth_tests.rs +++ b/crates/horizon-world/src/level/growth_tests.rs @@ -53,8 +53,12 @@ struct Level { random: LegacyRandom, events: Vec, biome: &'static str, + day: i64, } impl LevelAccess for Level { + fn day_time(&self) -> i64 { + self.day + } fn block_state(&self, pos: BlockPos) -> BlockStateId { self.blocks.get(&pos).copied().unwrap_or(self.air) } @@ -98,6 +102,7 @@ impl World { random: LegacyRandom::new(seed), events: Vec::new(), biome: "minecraft:plains", + day: 6000, }, f, ticks, @@ -364,3 +369,48 @@ fn snowy_biomes_freeze_and_snow() { assert!(!rain.snows_at_top && !rain.freezes_below); assert_eq!(rain.kind, PrecipitationKind::Rain); } + +#[test] +fn eyeblossoms_open_at_night_and_wake_neighbours() { + let Some(f) = fixture() else { return }; + let mut w = World::new(f, 2); + w.floor("grass_block", 4); + let closed = w.id("closed_eyeblossom", &[]); + w.put(BlockPos::new(0, 64, 0), closed); + w.put(BlockPos::new(2, 64, 1), closed); + f.behaviours + .random_tick(&mut w.level, &mut w.ticks, BlockPos::new(0, 64, 0)); + assert_eq!( + w.name(BlockPos::new(0, 64, 0)), + "minecraft:closed_eyeblossom", + "closed by day" + ); + w.level.day = 13000; + f.behaviours + .random_tick(&mut w.level, &mut w.ticks, BlockPos::new(0, 64, 0)); + assert_eq!(w.name(BlockPos::new(0, 64, 0)), "minecraft:open_eyeblossom"); + let block = f.behaviours.block(closed); + assert!( + w.ticks.has_block_tick(BlockPos::new(2, 64, 1), block), + "neighbour scheduled" + ); + assert!(w.level.events.iter().any(|e| matches!(e, LevelEvent::Sound { sound, .. } if &**sound == "minecraft:block.eyeblossom.open_long"))); +} +#[test] +fn turtle_eggs_crack_at_dawn_on_sand() { + let Some(f) = fixture() else { return }; + let mut w = World::new(f, 3); + w.floor("sand", 1); + let egg = w.id("turtle_egg", &[]); + let pos = BlockPos::new(0, 64, 0); + w.put(pos, egg); + w.level.day = 21500; + f.behaviours.random_tick(&mut w.level, &mut w.ticks, pos); + assert_eq!( + w.level.block_state(pos), + w.id("turtle_egg", &[("hatch", "1")]) + ); + f.behaviours.random_tick(&mut w.level, &mut w.ticks, pos); + f.behaviours.random_tick(&mut w.level, &mut w.ticks, pos); + assert_eq!(w.name(pos), "minecraft:air", "hatched"); +} diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index b111b392d..1a066cafc 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -117,6 +117,7 @@ mod signals; mod speleothem; mod survive; mod tick; +mod timeline; mod update; mod weather; @@ -353,6 +354,11 @@ pub trait LevelAccess { fn world_seed(&self) -> i64 { 0 } + /// `Level.getDayTime` (the overworld clock driving the day timeline's + /// environment attributes, e.g. eyeblossoms opening at night). + fn day_time(&self) -> i64 { + 6000 + } } /// Raw brightness as `Level.getRawBrightness(pos, skyDarken)`. diff --git a/crates/horizon-world/src/level/states.rs b/crates/horizon-world/src/level/states.rs index abe6c08cf..c7fe012dc 100644 --- a/crates/horizon-world/src/level/states.rs +++ b/crates/horizon-world/src/level/states.rs @@ -208,6 +208,10 @@ impl StateTable { pub fn key(&mut self, name: &str) -> PropKey { self.key_or_insert(name) } + /// An existing property key, without interning a new one. + pub fn key_of(&self, name: &str) -> Option { + self.keys.get(name).copied() + } pub fn state_count(&self) -> usize { self.state_block.len() } diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 548ba97da..3fd318027 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -140,6 +140,8 @@ impl Sim<'_, L> { } } Class::Observer => self.observer_tick(pos, state), + Class::Eyeblossom => self.eyeblossom_tick(state, pos, false), + Class::DriedGhast => self.dried_ghast_tick(state, pos), Class::RedstoneLamp => self.lamp_tick(pos, state), Class::RedstoneTorch => self.torch_tick(pos, state), Class::Scaffolding => self.scaffolding_tick(pos, state), @@ -329,6 +331,10 @@ impl Sim<'_, L> { } } Class::Vine => self.vine_random_tick(state, pos), + Class::Eyeblossom => self.eyeblossom_tick(state, pos, true), + Class::FlowerPot => self.potted_eyeblossom_tick(state, pos), + Class::TurtleEgg => self.turtle_egg_tick(state, pos), + Class::DriedGhast => self.dried_ghast_random_tick(state, pos), Class::WeatheringCopperFull => self.copper_change_over_time(state, pos), _ => continue, } diff --git a/crates/horizon-world/src/level/timeline.rs b/crates/horizon-world/src/level/timeline.rs new file mode 100644 index 000000000..75616590b --- /dev/null +++ b/crates/horizon-world/src/level/timeline.rs @@ -0,0 +1,216 @@ +//! Blocks driven by the overworld day timeline's environment attributes +//! (`gameplay/eyeblossom_open`, `gameplay/turtle_egg_hatch_chance`) and the +//! dried ghast's hydration ticks. +use super::{Dimension, LevelAccess, LevelEvent, Sim, update::below}; +use crate::registry::BlockStateId; +use horizon_core::{position::BlockPos, random::RandomSource}; +use std::sync::Arc; + +/// `BlockScanUtils.findBlocks` order: sections by x, z, y; blocks by y, z, x. +pub(crate) fn box_scan_order(min: BlockPos, max: BlockPos) -> Vec { + let mut out = Vec::new(); + for sx in (min.x >> 4)..=(max.x >> 4) { + for sz in (min.z >> 4)..=(max.z >> 4) { + for sy in (min.y >> 4)..=(max.y >> 4) { + for y in (sy * 16).max(min.y)..=(sy * 16 + 15).min(max.y) { + for z in (sz * 16).max(min.z)..=(sz * 16 + 15).min(max.z) { + for x in (sx * 16).max(min.x)..=(sx * 16 + 15).min(max.x) { + out.push(BlockPos::new(x, y, z)); + } + } + } + } + } + } + out +} + +impl Sim<'_, L> { + fn day_ticks(&self) -> Option { + (self.level.dimension() == Dimension::Overworld) + .then(|| self.level.day_time().rem_euclid(24000)) + } + /// `EnvironmentAttributes.EYEBLOSSOM_OPEN` (day timeline: open from 12600 + /// to 23400); None (TriState.DEFAULT) outside the overworld. + fn eyeblossom_open(&self) -> Option { + self.day_ticks().map(|t| (12600..23401).contains(&t)) + } + /// `EnvironmentAttributes.TURTLE_EGG_HATCH_CHANCE`: 1.0 around dawn + /// (21062..21905), otherwise the 0.002 default. + fn turtle_hatch_chance(&self) -> f32 { + match self.day_ticks() { + Some(t) if (21062..21905).contains(&t) => 1.0, + _ => 0.002, + } + } + fn named_state(&self, name: &str) -> Option { + self.b + .table + .block_by_name(name) + .map(|b| self.b.default_of(b)) + } + fn play(&mut self, pos: BlockPos, sound: &str, volume: f32, pitch: f32) { + self.emit(LevelEvent::Sound { + pos, + sound: Arc::from(sound), + volume, + pitch, + }); + } + /// `EyeblossomBlock.Type.spawnTransformParticle`: four random draws. + fn eyeblossom_particle_draws(&mut self) { + for _ in 0..4 { + self.random().next_double(); + } + } + /// `EyeblossomBlock.tryChangingState`; `long` picks the random-tick sound. + pub(crate) fn eyeblossom_tick(&mut self, state: BlockStateId, pos: BlockPos, long: bool) { + let b = self.b; + let open = b.table.name(state) == "minecraft:open_eyeblossom"; + let Some(should_be_open) = self.eyeblossom_open() else { + return; + }; + if should_be_open == open { + return; + } + let new_name = if open { + "minecraft:closed_eyeblossom" + } else { + "minecraft:open_eyeblossom" + }; + let Some(next) = self.named_state(new_name) else { + return; + }; + self.set_block_and_update(pos, next); + self.game_event(pos, "minecraft:block_change"); + self.eyeblossom_particle_draws(); + let min = pos.offset(-3, -2, -3); + let max = pos.offset(3, 2, 3); + let block = b.block(state); + for near in box_scan_order(min, max) { + if self.state(near) != state { + continue; + } + let (dx, dy, dz) = (near.x - pos.x, near.y - pos.y, near.z - pos.z); + let distance = f64::from(dx * dx + dy * dy + dz * dz).sqrt(); + let (lo, hi) = ((distance * 5.0) as i32, (distance * 10.0) as i32); + let delay = self + .random() + .next_int_between_inclusive(lo, hi) + .unwrap_or(lo); + self.schedule_tick(near, block, delay); + } + let sound = match (!open, long) { + (true, true) => "minecraft:block.eyeblossom.open_long", + (true, false) => "minecraft:block.eyeblossom.open", + (false, true) => "minecraft:block.eyeblossom.close_long", + (false, false) => "minecraft:block.eyeblossom.close", + }; + self.play(pos, sound, 1.0, 1.0); + } + /// `FlowerPotBlock.randomTick` for potted eyeblossoms. + pub(crate) fn potted_eyeblossom_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let name = self.b.table.name(state); + let open = match name { + "minecraft:potted_open_eyeblossom" => true, + "minecraft:potted_closed_eyeblossom" => false, + _ => return, + }; + let Some(should_be_open) = self.eyeblossom_open() else { + return; + }; + if open == should_be_open { + return; + } + let other = if open { + "minecraft:potted_closed_eyeblossom" + } else { + "minecraft:potted_open_eyeblossom" + }; + let Some(next) = self.named_state(other) else { + return; + }; + self.set_block_and_update(pos, next); + self.eyeblossom_particle_draws(); + let sound = if open { + "minecraft:block.eyeblossom.close_long" + } else { + "minecraft:block.eyeblossom.open_long" + }; + self.play(pos, sound, 1.0, 1.0); + } + /// `TurtleEggBlock.randomTick`: crack, then hatch on sand. + pub(crate) fn turtle_egg_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let chance = self.turtle_hatch_chance(); + if !(chance > 0.0 && self.random().next_float() < chance) { + return; + } + if !b + .tag("minecraft:sand") + .is_some_and(|t| b.in_set(self.state(below(pos)), t)) + { + return; + } + let hatch = b.table.int(state, b.props.hatch); + let pitch = 0.9 + self.random().next_float() * 0.2; + if hatch < 2 { + self.play(pos, "minecraft:entity.turtle.egg_crack", 0.7, pitch); + self.set_block(pos, b.table.set_int(state, b.props.hatch, hatch + 1), 2); + self.game_event(pos, "minecraft:block_change"); + } else { + self.play(pos, "minecraft:entity.turtle.egg_hatch", 0.7, pitch); + self.remove_block(pos, false); + self.game_event(pos, "minecraft:block_destroy"); + for _ in 0..b.table.int(state, b.props.eggs) { + self.level_event(2001, pos, state.0 as i32); + } + // Baby turtles are entities the caller spawns (one per egg). + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "hatch_turtles", + }); + } + } + /// `DriedGhastBlock.tick`: hydrate while waterlogged, dry out otherwise. + pub(crate) fn dried_ghast_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let Some(key) = b.table.key_of("hydration") else { + return; + }; + let hydration = b.table.int(state, key); + if b.table.bool(state, b.props.waterlogged) { + if hydration < 3 { + self.play(pos, "minecraft:block.dried_ghast.transition", 1.0, 1.0); + self.set_block(pos, b.table.set_int(state, key, hydration + 1), 2); + self.game_event(pos, "minecraft:block_change"); + } else { + self.remove_block(pos, false); + // The happy ghastling is an entity the caller spawns. + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "spawn_ghastling", + }); + } + } else if hydration > 0 { + self.set_block(pos, b.table.set_int(state, key, hydration - 1), 2); + self.game_event(pos, "minecraft:block_change"); + } + } + /// `DriedGhastBlock.randomTick`: keep a 5000-tick hydration tick scheduled. + pub(crate) fn dried_ghast_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let hydration = b + .table + .key_of("hydration") + .map_or(0, |k| b.table.int(state, k)); + let block = b.block(state); + if (b.table.bool(state, b.props.waterlogged) || hydration > 0) + && !self.ticks.has_block_tick(pos, block) + { + self.schedule_tick(pos, block, 5000); + } + } +} From 68ffc31a0ec34d3b79e8f93f6a7c448c86354b2e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:49:45 +0200 Subject: [PATCH 7/8] Run neighbour and shape updates after landing writes (farmland trampling) Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 7 +++++++ crates/horizon-world/src/level/signals.rs | 24 +++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 989123384..490a8a896 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1386,6 +1386,13 @@ impl Game<'_> { }; self.audio.play(name, Some(feet), volume, pitch); } + MotionEvent::Fall(horizon_client::landing::FallEvent::Write { position, flags, .. }) => { + // Landing rules (farmland trampling, turtle eggs) wrote the block raw. + self.with_level(|b, level, ticks| b.notify_written(level, ticks, position, flags as i32)); + } + MotionEvent::Fall(horizon_client::landing::FallEvent::Destroy { position, .. }) => { + self.with_level(|b, level, ticks| b.notify_written(level, ticks, position, level_flags::UPDATE_ALL)); + } MotionEvent::Fall(horizon_client::landing::FallEvent::Damage { .. }) => { self.audio.play("minecraft:entity.player.hurt", Some(feet), 1.0, 1.0); } diff --git a/crates/horizon-world/src/level/signals.rs b/crates/horizon-world/src/level/signals.rs index 6f02ff549..95b7130d7 100644 --- a/crates/horizon-world/src/level/signals.rs +++ b/crates/horizon-world/src/level/signals.rs @@ -19,3 +19,27 @@ impl Behaviours { } } } + +impl Behaviours { + /// The update half of `Level.setBlock` for a state the caller already + /// wrote to storage (entity landing rules write blocks directly): + /// neighbour updates, then neighbour shape updates, per `flags`. + pub fn notify_written( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + flags: i32, + ) { + use super::flags as f; + let state = level.block_state(pos); + let mut sim = self.sim(level, ticks); + if flags & f::UPDATE_NEIGHBORS != 0 { + sim.update_neighbors_at(pos, self.block(state)); + } + if flags & f::UPDATE_KNOWN_SHAPE == 0 { + let neighbour_flags = flags & !(f::UPDATE_NEIGHBORS | f::UPDATE_SUPPRESS_DROPS); + sim.update_neighbour_shapes(state, pos, neighbour_flags, f::UPDATE_LIMIT - 1); + } + } +} From 445a3ec4f28f940eedf9cd9121013b07e21d373c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 21:40:00 +0200 Subject: [PATCH 8/8] WIP snapshot: unfinished blocks parity work (paused mid-task, may not build) Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/explosion.rs | 2 +- crates/horizon-client/src/game/tnt.rs | 2 +- crates/horizon-world/src/level/bonemeal.rs | 14 +- crates/horizon-world/src/level/growth.rs | 5 +- docs/parity/blocks.md | 166 ++++++++++++++++++++ 5 files changed, 178 insertions(+), 11 deletions(-) create mode 100644 docs/parity/blocks.md diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index eb70a4478..e178b1d83 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -372,7 +372,7 @@ impl Game<'_> { let is_tnt = &*name == "minecraft:tnt"; if !is_tnt { let drops = self.res.items.block_drops( - &self.res.assets.registry, + self.res.assets.registry, state, None, &mut self.world.random, diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 1eacb125a..ce19e97f1 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -206,7 +206,7 @@ impl Game<'_> { (t.position.y + 0.5).floor() as i32, t.position.z.floor() as i32, ); - let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; + let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); let v = |x: f32, y: f32, z: f32| o + glam::Vec3::new(x - 0.5, y - 0.5, z - 0.5) * scale; let faces = [ ( diff --git a/crates/horizon-world/src/level/bonemeal.rs b/crates/horizon-world/src/level/bonemeal.rs index a59a1c7e1..cf930109a 100644 --- a/crates/horizon-world/src/level/bonemeal.rs +++ b/crates/horizon-world/src/level/bonemeal.rs @@ -445,24 +445,22 @@ impl Sim<'_, L> { } Kind::BambooSapling => self.bamboo_sapling_grow(pos), Kind::Bamboo => { - let mut height_above = self.bamboo_height_above(pos); + let height_above = self.bamboo_height_above(pos); let height_below = self.bamboo_height_below(pos); - let mut total = height_above + height_below + 1; + let total = height_above + height_below + 1; let count = 1 + self.next_int(2); - for _ in 0..count { - let top = pos.offset(0, height_above, 0); + for i in 0..count { + let top = pos.offset(0, height_above + i, 0); let top_state = self.state(top); let growth = above(top); - if total >= 16 + if total + i >= 16 || b.table.int(top_state, p.stage) == 1 || !self.is_empty_block(growth) || !self.is_inside_build_height(growth.y) { return; } - self.bamboo_grow(top_state, top, total); - height_above += 1; - total += 1; + self.bamboo_grow(top_state, top, total + i); } } Kind::Cocoa => { diff --git a/crates/horizon-world/src/level/growth.rs b/crates/horizon-world/src/level/growth.rs index bfc1d4482..d4f3a971b 100644 --- a/crates/horizon-world/src/level/growth.rs +++ b/crates/horizon-world/src/level/growth.rs @@ -23,6 +23,9 @@ impl Behaviours { } } +/// The four (state, position) pairs of a 2x2 sapling square. +type Saplings = [(BlockStateId, BlockPos); 4]; + /// `TreeGrower` (vanilla's registered growers, by name). pub(crate) struct TreeGrower { pub name: &'static str, @@ -206,7 +209,7 @@ impl Sim<'_, L> { &self, state: BlockStateId, pos: BlockPos, - ) -> Option<(i32, i32, [(BlockStateId, BlockPos); 4])> { + ) -> Option<(i32, i32, Saplings)> { let block = self.b.block(state); for dx in [0, -1] { for dz in [0, -1] { diff --git a/docs/parity/blocks.md b/docs/parity/blocks.md new file mode 100644 index 000000000..b9e88d06f --- /dev/null +++ b/docs/parity/blocks.md @@ -0,0 +1,166 @@ +# Block behaviours and ticking: parity status + +Area: random and scheduled block ticks, growth, bone meal, TNT and +explosions, hoppers, dispensers and droppers, comparators reading +containers, weather-driven blocks. The library code lives in +`crates/horizon-world/src/level/`. The client glue lives in +`crates/horizon-client/src/game/` (`growth.rs`, `tnt.rs`, `explosion.rs`, +`machines.rs`, `blockctl.rs`). + +## Implemented (ported from the 26.3 sources) + +- **Growth through live feature placement.** `worldgen/live.rs` decodes + configured and placed features by name from the worldgen bundle. It shares + the generator's `GeneratorData`. `level/feature_world.rs` runs features on + the live level as a `FeatureWorld` and `PlacementContext`, and writes + blocks through `Behaviours::set_block` with the feature's flags. Tree + placement also calls `updateShapeAtEdge`. +- **`TreeGrower.growTree`** (`level/growth.rs`) covers every vanilla grower: + oak and its bee variants (with the flower check), spruce, birch, jungle, + acacia, cherry, mangrove, azalea and poplar. It also covers the 2×2 forms: + dark oak, pale oak, mega spruce and pine, and mega jungle. It keeps the + random draw order: mega feature, then flowers, then feature. Saplings are + removed with flags 818 and restored with flags 260 when the tree does not + fit. Saplings, propagules and azaleas grow both on random ticks and with + bone meal. +- **Bone meal** (`level/bonemeal.rs`) ports `BoneMealItem.useOn`, + `growCrop` and `growWaterPlant`, including coral from bone meal in warm + ocean biomes. It also ports every vanilla `BonemealableBlock`: + - saplings, propagules, mushrooms, fungi and azaleas + - grass (with the biome's `getBoneMealFeatures`), nylium, netherrack and + moss + - rooted dirt, mangrove leaves, crops (including beetroot and torchflower + increments) and stems + - pitcher, bamboo and bamboo sapling, cocoa and sweet berries + - tall grass and fern, tall flowers, bush and firefly bush, flower beds + - kelp, twisting and weeping vines, cave vines (head and body), seagrass + and sea pickles + - big and small dripleaf, glow lichen (`MultifaceSpreader`), hanging moss + and pale moss carpet + - short and tall dry grass, and shelf mushroom + + Level event 1505 plays the bone meal sound. +- **Fixes to existing ticks.** Torchflower crops now mature into + torchflowers. Kelp grows into any water block, as in vanilla. +- **Primed TNT** (`game/tnt.rs`): + - It has an 80-tick fuse, gravity 0.04, 0.98 drag and the 0.7/−0.5 ground + bounce. + - It explodes with power 4 at `y + 0.06125`. + - It renders with the `TntRenderer` swell and a white flash every 5 ticks + (entity overlay 4 in `entity.wgsl`). + - TNT is primed by redstone, fire, flint and steel or fire charges + (`TntBlock.useItemOn`), and by players breaking unstable TNT. + - Explosions prime TNT with a random short fuse (chain reactions). + - Dispensers prime TNT too. +- **`ServerExplosion`** (`game/explosion.rs`): + - It marches 1352 rays through a Java `HashSet` + (`java_hash_map`), so iteration and the `Util.shuffle` draws match + vanilla. + - Each block costs `max(block, fluid)` resistance. + - Damage and knockback scale with exposure for the player, mobs, items + and TNT. Creative players take no damage. + - TNT explosions drop every block. Mob explosions use drop decay. + - Drops merge in stacks of up to 16. Container contents spill. +- **Hoppers** (`game/machines.rs`): + - They push and pull through `HopperBlockEntity.tryMoveItems`. + - The 8-tick cooldown applies, with the transfer cooldown hand-off between + hoppers. + - They insert into furnace faces (`WorldlyContainer` slots, fuel and + bucket rules) and into double chests (right half first). + - They respect `does_not_block_hoppers` and pick up item entities from the + suck box. + - The `enabled` property stops them. +- **Dispensers and droppers.** They use `getRandomSlot` and the drop + position and velocity from `DefaultDispenseItemBehavior.spawnItem`. The + dispense behaviours are: + - bone meal + - TNT + - flint and steel (fire, TNT, campfires and candles) + - water and lava buckets (including waterlogging) + - empty buckets (fluids, waterlogged blocks and powder snow) + - arrows (power 1.1, uncertainty 6) + + Droppers insert into containers. Clicks and failure sounds play. +- **Comparators reading containers.** `GameLevel` answers + `block_entity_analog_signal` with + `AbstractContainerMenu.getRedstoneSignalFromContainer`. Chests blocked by + a conductor read 0. Double chests are combined. Container changes from + hoppers, dispensers and the player call `container_changed`, which runs + `updateNeighbourForOutputSignal`. +- **Weather** (`level/weather.rs`) uses biome temperatures from the worldgen + bundle, with the height adjustment and frozen noise. They feed + `ServerLevel.tickPrecipitation`: ice formation, snow accumulation, and + cauldrons filling with water or powder snow. They also feed + `Level.isRainingAt`, which drives farmland moisture and fire going out in + rain. +- **Day-timeline blocks** (`level/timeline.rs`): + - Eyeblossoms open and close, and potted eyeblossoms follow. Neighbours are + scheduled in the `BlockScanUtils` scan order. + - Turtle eggs crack and hatch on sand, using the dawn hatch chance. + - Dried ghasts hydrate while waterlogged. +- **Landing writes.** Farmland trampling and turtle eggs crushed by landing + now run neighbour and shape updates, so crops on trampled farmland pop. +- **Smaller fixes.** + - Hopper, dispenser and dropper block entities save with their own ids. + Barrels and trapped chests do too. + - Their screens use the vanilla hopper and dispenser layouts. + - `GameLevel::max_y` is exclusive, as `LevelAccess` documents. + +## Verification + +- Unit tests in `crates/horizon-world/src/level/growth_tests.rs` cover: + - every sapling kind, including the 2×2 trees + - azalea and mangrove growth + - random-tick stage advance followed by growth + - grass bone meal with flowers + - huge mushrooms and crimson fungi + - crop ages, torchflowers, ferns and tall flowers + - snow, ice and rain answers + - eyeblossoms and turtle eggs + + They need the feature block exports in `worldgen/blocks` + (`block-properties.nbt`). The shared `.local` bundle lacks those files, so + run the tests with `HORIZON_RESOURCES` pointing at a complete prepared + bundle. Without one, the tests skip. +- Client tests cover the Java `Vec3i` hash and compare order and the + explosion stack merging. +- In the game on the virtual screen, driven by `horizon-ctl`: + - Bone meal on oak, birch, cherry, 2×2 dark oak, spruce and jungle + saplings grew all of them. + - Flint and steel on a TNT cluster: the TNT flashed white and chain + exploded, leaving a crater with drops. + - A redstone block primed TNT. + - A chest drained through a hopper chain into a chest at 2.5 items/s. The + comparator lit a lamp. + - A dispenser bone-mealed a sapling into a tree. A dropper ejected an item. + - Landing on farmland turned it to dirt and popped the wheat. + - The hopper screen shows the vanilla layout. + + New `horizon-ctl` commands drive these checks: `setblock`, `fill`, + `getblock` and `container`. + +## Known gaps + +- **Random draws.** + - Features placed from block behaviour draw from a copy of the level + random. Their `next_world_*` draws and any draws in neighbour updates + during placement do not reach the real stream. + - Client sections that hold any non-air block get random ticks, not only + sections with randomly ticking states. This advances the + `getBlockRandomPos` generator more often than vanilla does. +- **Explosion details.** Exposure uses full-collision blocks only. + `getEntities` order is approximate. Experience orbs, falling blocks and + arrows are not pushed. +- **Missing entities.** + - Dispensers have no behaviour for fire charges, other projectiles, + armour, shulker boxes, boats, minecarts or spawn eggs. Fire charges and + most other items drop instead; projectiles, boats, minecarts and spawn + eggs are not entities in Horizon. + - Turtle hatchlings and happy ghastlings are reported as `BlockEvent`s and + not spawned. + - Hoppers do not see minecart containers. Item entities do not trigger the + hopper's `entityInside`; suction covers the same box on the hopper tick. +- **Not implemented.** The sculk vibration system (sensors, shriekers, + catalyst spread) and creaking hearts. Lightning (`tickThunder`). + Particles for bone meal, explosions and TNT smoke. +- **Not saved.** Primed TNT and hopper cooldowns (`TransferCooldown`).