From c7073db8b5b54fd8f03d40dd7e03c8bc1e23d07f Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:47:49 -0400 Subject: [PATCH] Apply falling anvil impact damage and wear --- crates/horizon-client/src/entity_nbt.rs | 45 +++- crates/horizon-client/src/falling_block.rs | 192 ++++++++++++++++++ crates/horizon-client/src/game.rs | 55 +++-- crates/horizon-client/src/game/creatures.rs | 1 + .../horizon-client/src/game/falling_damage.rs | 123 +++++++++++ crates/horizon-client/src/game/persist.rs | 21 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/mobs.rs | 7 + 8 files changed, 394 insertions(+), 51 deletions(-) create mode 100644 crates/horizon-client/src/falling_block.rs create mode 100644 crates/horizon-client/src/game/falling_damage.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 4e1220d91..adeb1da25 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -1046,12 +1046,15 @@ pub fn arrow_from_nbt( } /// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities. +#[allow(clippy::too_many_arguments)] pub fn falling_block_to_nbt( state: Tag, position: Vec3, motion: Vec3, time: i32, drop_item: bool, + damage: crate::falling_block::Damage, + fall_distance: f64, uuid: [i32; 4], ) -> Tag { let base = Base { @@ -1061,29 +1064,27 @@ pub fn falling_block_to_nbt( motion, rotation: [0.0, 0.0], on_ground: false, - fall_distance: 0.0, + fall_distance, }; let mut tag = base.tag(None); for (key, value) in [ ("BlockState", state), ("Time", Tag::Int(time)), ("DropItem", Tag::Byte(i8::from(drop_item))), - ("HurtEntities", Tag::Byte(0)), - ("CancelDrop", Tag::Byte(0)), - ("FallHurtAmount", Tag::Float(0)), - ("FallHurtMax", Tag::Int(40)), ] { put(&mut tag, key, value); } + damage.save(&mut tag); tag } -/// (block state tag, position, motion, time) -pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32)> { +/// (block state tag, position, motion, time, fall distance) +pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32, f64)> { Some(( tag.get("BlockState")?.clone(), position(tag)?, motion(tag), number(tag.get("Time")).unwrap_or(0) as i32, + float(tag.get("fall_distance")).unwrap_or(0.0), )) } @@ -1493,6 +1494,36 @@ mod tests { use super::*; use crate::items::ItemStack; + #[test] + fn falling_block_round_trip_keeps_impact_distance_and_settings() { + let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]); + let position = Vec3::new(3.5, 100.0, -7.5); + let velocity = Vec3::new(0.0, -1.25, 0.0); + let damage = crate::falling_block::Damage { + cancel_drop: true, + ..crate::falling_block::Damage::anvil() + }; + let tag = falling_block_to_nbt( + state.clone(), + position, + velocity, + 30, + false, + damage, + 19.75, + [1, 2, 3, 4], + ); + let (loaded_state, pos, motion, age, distance) = falling_block_from_nbt(&tag).unwrap(); + assert_eq!(loaded_state, state); + assert_eq!( + (pos, motion, age, distance), + (position, velocity, 30, 19.75) + ); + assert_eq!(falling_block_flags(&tag), (false, false)); + assert_eq!(crate::falling_block::Damage::from_nbt(&tag, true), damage); + assert_eq!(uuid(&tag), Some([1, 2, 3, 4])); + } + #[test] fn item_entities_round_trip() { let e = ItemEntity { diff --git a/crates/horizon-client/src/falling_block.rs b/crates/horizon-client/src/falling_block.rs new file mode 100644 index 000000000..86c6ebd6f --- /dev/null +++ b/crates/horizon-client/src/falling_block.rs @@ -0,0 +1,192 @@ +//! FallingBlockEntity's impact damage, anvil wear and saved impact settings. +use crate::{ + mobs::{Damage as MobDamage, DamageKind, Mob}, + save::{float, number, put}, +}; +use horizon_core::geometry::{Aabb, Vec3}; +use horizon_world::{chunk::BlockState, nbt::Tag}; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Damage { + pub hurt_entities: bool, + pub cancel_drop: bool, + pub per_distance: f32, + pub max: i32, +} +impl Default for Damage { + fn default() -> Self { + Self { + hurt_entities: false, + cancel_drop: false, + per_distance: 0.0, + max: 40, + } + } +} +impl Damage { + pub fn anvil() -> Self { + Self { + hurt_entities: true, + per_distance: 2.0, + ..Self::default() + } + } + pub fn from_nbt(tag: &Tag, anvil: bool) -> Self { + Self { + hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0), + cancel_drop: number(tag.get("CancelDrop")).is_some_and(|v| v != 0), + per_distance: float(tag.get("FallHurtAmount")).unwrap_or(0.0) as f32, + max: number(tag.get("FallHurtMax")).unwrap_or(40) as i32, + } + } + pub fn save(self, tag: &mut Tag) { + for (key, value) in [ + ("HurtEntities", Tag::Byte(i8::from(self.hurt_entities))), + ("CancelDrop", Tag::Byte(i8::from(self.cancel_drop))), + ("FallHurtAmount", Tag::Float(self.per_distance.to_bits())), + ("FallHurtMax", Tag::Int(self.max)), + ] { + put(tag, key, value); + } + } + pub fn impact(self, fall_distance: f64) -> Option { + if !self.hurt_entities { + return None; + } + let steps = (fall_distance - 1.0).ceil() as i32; + if steps < 0 { + return None; + } + let amount = ((steps as f32 * self.per_distance).floor() as i32).min(self.max) as f32; + Some(Impact { + amount, + wear_chance: if amount > 0.0 { + 0.05 + steps as f32 * 0.05 + } else { + 0.0 + }, + }) + } +} + +#[derive(Clone, Copy, Debug)] +pub struct Impact { + pub amount: f32, + pub wear_chance: f32, +} + +/// AnvilBlock.damage: advance wear without changing facing; false means broken. +pub fn wear_anvil(state: &mut BlockState) -> bool { + state.name = match state.name.as_str() { + "minecraft:anvil" => "minecraft:chipped_anvil", + "minecraft:chipped_anvil" => "minecraft:damaged_anvil", + _ => return false, + } + .into(); + true +} + +pub fn bounds(position: Vec3) -> Aabb { + let size = f64::from(0.98_f32); + Aabb::new( + Vec3::new(position.x - size / 2.0, position.y, position.z - size / 2.0), + Vec3::new( + position.x + size / 2.0, + position.y + size, + position.z + size / 2.0, + ), + ) +} +pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) { + if amount <= 0.0 { + return; + } + let bounds = bounds(position); + let source = MobDamage { + kind: DamageKind::FallingBlock, + attacker: None, + from: Some([position.x, position.y, position.z]), + }; + for mob in mobs + .iter_mut() + .filter(|m| m.alive() && bounds.intersects(m.bounds())) + { + mob.damage(amount, source); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() { + let damage = Damage::anvil(); + assert!(Damage::default().impact(50.0).is_none()); + assert!(damage.impact(0.0).is_none()); + let short = damage.impact(1.0).unwrap(); + assert_eq!((short.amount, short.wear_chance), (0.0, 0.0)); + assert_eq!(damage.impact(1.01).unwrap().amount, 2.0); + assert_eq!(damage.impact(5.0).unwrap().amount, 8.0); + assert_eq!(damage.impact(100.0).unwrap().amount, 40.0); + assert!(damage.impact(21.0).unwrap().wear_chance > 1.0); + } + #[test] + fn damage_settings_round_trip_and_keep_vanilla_load_defaults() { + let empty = Tag::Compound(Default::default()); + assert_eq!(Damage::from_nbt(&empty, false), Damage::default()); + let loaded_anvil = Damage::from_nbt(&empty, true); + assert!(loaded_anvil.hurt_entities); + assert_eq!(loaded_anvil.per_distance, 0.0); + let damage = Damage { + hurt_entities: true, + cancel_drop: true, + per_distance: 3.5, + max: 17, + }; + let mut tag = empty; + damage.save(&mut tag); + assert_eq!(Damage::from_nbt(&tag, false), damage); + } + #[test] + fn anvil_wears_twice_then_breaks_preserving_facing() { + for facing in ["north", "south", "east", "west"] { + let mut state = BlockState { + name: "minecraft:anvil".into(), + properties: [("facing".into(), facing.into())].into(), + }; + for name in ["minecraft:chipped_anvil", "minecraft:damaged_anvil"] { + assert!(wear_anvil(&mut state)); + assert_eq!(state.name, name); + assert_eq!(state.properties["facing"], facing); + } + assert!(!wear_anvil(&mut state)); + } + } + #[test] + #[ignore = "requires prepared entity models/data in HORIZON_TEST_RESOURCES"] + fn impact_hurts_only_living_intersecting_noninvulnerable_mobs() { + use crate::mobs::{Mob, MobTypes}; + use std::{path::Path, sync::Arc}; + let root = std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"); + let types = MobTypes::load(Path::new(&root)).unwrap(); + let cow = Arc::new(types.types["minecraft:cow"].clone()); + let mut mobs = vec![ + Mob::new(1, cow.clone(), Vec3::ZERO, 0.0), + Mob::new(2, cow.clone(), Vec3::new(3.0, 0.0, 0.0), 0.0), + Mob::new(3, cow.clone(), Vec3::ZERO, 0.0), + Mob::new(4, cow, Vec3::ZERO, 0.0), + ]; + mobs[2].invulnerable_flag = true; + mobs[3].extra.head = Some("minecraft:carved_pumpkin".into()); + let initial = mobs.iter().map(|m| m.health).collect::>(); + hurt_mobs( + &mut mobs, + Vec3::ZERO, + Damage::anvil().impact(5.0).unwrap().amount, + ); + assert_eq!(mobs[0].health, initial[0] - 8.0); + assert_eq!(mobs[1].health, initial[1]); + assert_eq!(mobs[2].health, initial[2]); + assert_eq!(mobs[3].health, initial[3] - 6.0); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7072abeb5..4c039204b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -41,6 +41,7 @@ mod entity_culling; mod events; mod explosion; mod extras; +mod falling_damage; mod fangs; mod fireworks; mod fishing; @@ -642,6 +643,7 @@ struct FallingBlock { drop_item: bool, /// `Entity.fallDistance` (powder snow holds a block that fell far at 0.9). fall_distance: f64, + damage: horizon_client::falling_block::Damage, /// The UUID and compound it was loaded with, kept while it moves. saved: Option>, } @@ -1900,6 +1902,7 @@ impl Game<'_> { 1009 => Some(("minecraft:block.fire.extinguish", 0.5)), 1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)), 1030 => Some(("minecraft:block.anvil.use", 1.0)), + 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), 1505 => Some(("minecraft:item.bone_meal.use", 1.0)), _ => None, @@ -1952,6 +1955,11 @@ impl Game<'_> { no_gravity: false, drop_item: true, fall_distance: 0.0, + damage: if self.res.facts.get(state).name.ends_with("anvil") { + horizon_client::falling_block::Damage::anvil() + } else { + Default::default() + }, saved: None, }); } @@ -2207,14 +2215,19 @@ impl Game<'_> { return false; } if solid { - landed.push(( - f.state, - [ - next.x.floor() as i32, - next.y.floor() as i32 + i32::from(!sunk), - next.z.floor() as i32, - ], - )); + let pos = [ + next.x.floor() as i32, + next.y.floor() as i32 + i32::from(!sunk), + next.z.floor() as i32, + ]; + let landing_y = if sunk { + next.y.floor() + f64::from(0.9_f32) + } else { + f64::from(pos[1]) + }; + f.fall_distance += (f.position.y - landing_y).max(0.0); + f.position = Vec3::new(next.x, landing_y, next.z); + landed.push((f.clone(), pos)); return false; } if next.y < f.position.y { @@ -2248,30 +2261,8 @@ impl Game<'_> { self.spawn_item(stack, [at.x, at.y, at.z], v, 10); } } - for (state, pos) in landed { - let landing = self.with_level(|b, level, ticks| { - b.falling_block_landed( - level, - ticks, - BlockPos::new(pos[0], pos[1], pos[2]), - state, - false, - ) - }); - if matches!(landing, Landing::Broken) { - let item = self.res.facts.get(state).item.clone(); - if &*item != "minecraft:air" { - self.pop_resource( - pos, - ItemStack { - item, - count: 1, - damage: 0, - extra: None, - }, - ); - } - } + for (block, pos) in landed { + self.finish_falling_block(block, pos); } self.process_level_events() } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index e454264d8..262ff11c2 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2980,6 +2980,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static K::Explosion if player => "minecraft:player_explosion", K::Explosion => "minecraft:explosion", K::Fall => "minecraft:fall", + K::FallingBlock => "minecraft:falling_block", K::OnFire => "minecraft:on_fire", K::InFire => "minecraft:in_fire", K::Lava => "minecraft:lava", diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs new file mode 100644 index 000000000..313ddbaac --- /dev/null +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -0,0 +1,123 @@ +//! Landing impacts for falling blocks, before their placement/drop decision. +use super::{FallingBlock, Game, Landing}; +use horizon_client::{falling_block, items::ItemStack}; +use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource}; +use horizon_world::level::LevelEvent; + +impl Game<'_> { + pub(super) fn finish_falling_block(&mut self, mut block: FallingBlock, pos: [i32; 3]) { + let anvil = self.res.facts.get(block.state).name.ends_with("anvil"); + if let Some(impact) = block.damage.impact(block.fall_distance) { + if impact.amount > 0.0 { + falling_block::hurt_mobs(&mut self.mobs, block.position, impact.amount); + let kind = if anvil { + "minecraft:falling_anvil" + } else { + "minecraft:falling_block" + }; + self.falling_hurt_player(block.position, impact.amount, kind); + if let Some(mut host) = self.lan.take() { + let bounds = falling_block::bounds(block.position); + let conns = host + .hub + .guests + .iter() + .filter(|g| { + g.placed + && g.loaded + && !g.dead + && !g.creative() + && !g.spectator() + && bounds.intersects(super::lan_mobs::guest_bounds(g)) + }) + .map(|g| g.conn) + .collect::>(); + for conn in conns { + self.guest_hit_by(&mut host, conn, |g| { + g.falling_hurt_player(block.position, impact.amount, kind) + }); + } + self.lan = Some(host); + } + } + if anvil + && impact.wear_chance > 0.0 + && self.world.random.next_float() < impact.wear_chance + && let Some(mut state) = self.res.assets.registry.state(block.state).cloned() + { + if falling_block::wear_anvil(&mut state) { + block.state = self + .res + .assets + .registry + .resolve(&state) + .unwrap_or(block.state); + } else { + block.damage.cancel_drop = true; + } + } + } + if block.damage.cancel_drop { + if anvil { + self.level_events.push(LevelEvent::LevelEvent { + id: 1029, + pos: BlockPos::new(pos[0], pos[1], pos[2]), + data: 0, + }); + } + return; + } + let landing = self.with_level(|b, level, ticks| { + b.falling_block_landed( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + block.state, + false, + ) + }); + if matches!(landing, Landing::Broken) + && block.drop_item + && self.ui.rules.bool("entity_drops") + { + let item = self.res.facts.get(block.state).item.clone(); + if &*item != "minecraft:air" { + self.pop_resource( + pos, + ItemStack { + item, + count: 1, + damage: 0, + extra: None, + }, + ); + } + } + } + fn falling_hurt_player(&mut self, position: Vec3, amount: f32, kind: &str) { + if self.creative || self.spectator() { + return; + } + if self.player.as_ref().is_none_or(|p| { + p.health.dead_or_dying() || !falling_block::bounds(position).intersects(p.bounds()) + }) { + return; + } + let amount = if self.armor[0].is_some() { + amount * 0.75 + } else { + amount + }; + let hurt = if let Some(p) = self.player.as_mut() + && let Some(id) = self.motion.health.damage.id(kind) + { + p.hurt(&self.motion.health, self.world.health_rules, id, amount) + .unwrap_or(false) + } else { + false + }; + if hurt { + self.hurt_armor(amount); + } + } +} diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 054f2c2fc..29549bb02 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -49,16 +49,7 @@ fn with_raw(modelled: Tag, raw: Option<&Tag>) -> Tag { // Defaults Horizon invents for fields it does not simulate give way to the save. let invented = matches!( k.to_string_lossy().as_str(), - "Fire" - | "Air" - | "Invulnerable" - | "PortalCooldown" - | "HasBeenShot" - // FallingBlockEntity fields Horizon does not simulate. - | "HurtEntities" - | "CancelDrop" - | "FallHurtAmount" - | "FallHurtMax" + "Fire" | "Air" | "Invulnerable" | "PortalCooldown" | "HasBeenShot" ); if !(invented && out.contains_key(k)) { out.insert(k.clone(), v.clone()); @@ -199,7 +190,7 @@ impl Game<'_> { } } "minecraft:falling_block" => { - if let Some((state, position, velocity, age)) = + if let Some((state, position, velocity, age, fall_distance)) = entity_nbt::falling_block_from_nbt(&tag) && let Some(state) = self.state_from_nbt(&state) { @@ -214,7 +205,11 @@ impl Game<'_> { age, no_gravity, drop_item, - fall_distance: 0.0, + fall_distance, + damage: horizon_client::falling_block::Damage::from_nbt( + &tag, + self.res.facts.get(state).name.ends_with("anvil"), + ), saved: uuid.map(|u| Box::new((u, tag.clone()))), }); } @@ -620,6 +615,8 @@ impl Game<'_> { f.velocity, f.age, f.drop_item, + f.damage, + f.fall_distance, uuid, ); out.entry(chunk_of(f.position)) diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index b56891996..092a782e4 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -59,6 +59,7 @@ pub mod entity_nbt; pub mod environment; pub mod extras; pub mod extras_hud; +pub mod falling_block; pub mod fast_hash; pub mod fastutil_order; pub mod fire_render; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a98cbb897..8697f66f0 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -507,6 +507,7 @@ pub enum DamageKind { Fireball, Explosion, Fall, + FallingBlock, OnFire, InFire, Lava, @@ -1610,6 +1611,12 @@ impl Mob { return false; } let mut amount = amount; + if source.kind == DamageKind::FallingBlock + && !species::body_slot(self.species()) + && self.extra.head.is_some() + { + amount *= 0.75; + } let (worn, worn_toughness) = self.worn_armor(); if !source.bypasses_armor() && self.kind.armor + worn > 0.0 { // CombatRules.getDamageAfterAbsorb