From 0bc19687aa29e714f03df078b425261329b40688 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:14:48 +0200 Subject: [PATCH] LAN: guests see mobs flash when hit The host told guests of a hurt mob with EntityEvent 2, which 26.3's clients read as a kinetic hit, not a hurt. It now sends ClientboundDamageEventPacket (ServerLevel.broadcastDamageEvent) with the damage type and the attacker, and the guest's client restarts the hurt flash and jolts the walk animation (LivingEntity.handleDamageEvent). lan_e2e.py hurt: a pig the guest hits and one the host hits flash on both sides. Part of #848 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/agent.rs | 2 +- crates/horizon-client/src/game/creatures.rs | 2 +- crates/horizon-client/src/game/lan.rs | 26 ++++++++++++- crates/horizon-client/src/game/remote.rs | 9 +++++ crates/horizon-client/src/lan/containers.rs | 27 +++++++++++++ crates/horizon-protocol/src/packets/play.rs | 20 ++++++++++ tools/lan_e2e.py | 43 +++++++++++++++++++-- 7 files changed, 121 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index b11fdd552..5a7894ea2 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -579,7 +579,7 @@ impl Game<'_> { push( [m.position.x, m.position.y, m.position.z], m.kind.id.as_ref(), - json!({ "id": m.id, "kind": "mob", "health": m.health, "baby": m.is_baby() }), + json!({ "id": m.id, "kind": "mob", "health": m.health, "baby": m.is_baby(), "hurt_time": m.hurt_time }), ); } for item in &self.dropped { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 3ef399e62..9f657b816 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3016,7 +3016,7 @@ impl Game<'_> { } /// Mob.getBaseExperienceReward /// The damage type id of a Horizon damage kind. -fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { +pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { use horizon_client::mobs::DamageKind as K; match kind { K::PlayerAttack => "minecraft:player_attack", diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index d35bf787a..eaf4672c0 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1068,8 +1068,30 @@ impl Game<'_> { .and_then(|s| s.get(&m.id)) .copied(); let at = [m.position.x, m.position.y, m.position.z]; - if m.hurt_time > old.map_or(0, |o| o.0) && !dead { - host.hub.entity_event(m.id as i32, 2, at); + // LivingEntity.hurtServer: a hurt that restarted the hurt time. + if m.hurt_time > old.map_or(0, |o| o.0) + && !dead + && let Some((source, _)) = m.last_damage + { + use horizon_client::mobs::{DamageKind as K, Who}; + let player = source.attacker == Some(Who::Player); + let kind = super::creatures::damage_type(source.kind, player); + // The player a mob sees is the guest acting, else the host. + let cause = source.attacker.map(|who| match who { + Who::Player => host + .mob_players + .get(&m.id) + .and_then(|conn| host.hub.guest(*conn)) + .map_or(host.host_entity, |g| g.entity_id), + Who::Mob(id) => id as i32, + }); + // A projectile is the direct entity of its hit: not tracked here. + let melee = matches!( + source.kind, + K::PlayerAttack | K::MaceSmash | K::MobAttack | K::Sting | K::SonicBoom + ); + let direct = cause.filter(|_| melee); + host.hub.damage_event(m.id as i32, kind, cause, direct, at); } if dead && !old.is_some_and(|o| o.1) { host.hub.entity_event(m.id as i32, 3, at); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 680360c93..b144b55dd 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1572,6 +1572,15 @@ impl Game<'_> { pl.velocity = Vec3::new(p.velocity[0], p.velocity[1], p.velocity[2]); } } + // ClientPacketListener.handleDamageEvent: LivingEntity.handleDamageEvent + // jolts the walk animation and restarts the hurt flash. Its hurt + // sound comes as a sound from Horizon's host, which plays it itself. + C::DamageEvent(p) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.limb_speed = 1.5; + m.hurt_time = 10; + } + } C::HurtAnimation(p) => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { m.hurt_time = 10; diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 3ecd58b80..9f8607bb9 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -109,6 +109,33 @@ impl Hub { ); } + /// `ServerLevel.broadcastDamageEvent`: the clients around show the hurt + /// entity's flash and hear its hurt sound. + pub fn damage_event( + &self, + id: i32, + kind: &str, + cause: Option, + direct: Option, + at: [f64; 3], + ) { + let Some(source_type) = self.sync.id("minecraft:damage_type", kind) else { + return; + }; + self.broadcast_near( + at, + 128.0, + &C::DamageEvent(play::DamageEvent { + id, + source_type, + cause, + direct, + position: None, + }), + None, + ); + } + pub fn swing(&self, id: i32, hand: i32, at: [f64; 3], except: Option) { self.broadcast_near( at, diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 895db9755..349f41ddd 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -244,6 +244,18 @@ packet!(EntityPositionSync { id: i32 => VarInt, path: PositionPath => PositionPa packet!(ForgetLevelChunk { pos: [i32; 2] => ChunkPos }); packet!(GameEvent { event: u8 => UByte, param: f32 => Float }); packet!(HurtAnimation { id: i32 => VarInt, yaw: f32 => Float }); +packet!( + /// ClientboundDamageEventPacket: the hurt entity, the damage type's + /// registry id, the causing and the direct entity (none: -1 on the wire's + /// id + 1) and the source's position. + DamageEvent { + id: i32 => VarInt, + source_type: i32 => VarInt, + cause: Option => OptVarInt, + direct: Option => OptVarInt, + position: Option<[f64; 3]> => Opt, + } +); packet!(LevelChunkWithLight { x: i32 => Int, z: i32 => Int, chunk: ChunkData => ChunkData, light: LightData => LightData }); packet!(LevelEvent { kind: i32 => Int, pos: [i32; 3] => Pos, data: i32 => Int, global: bool => Bool }); packet!(LightUpdate { x: i32 => VarInt, z: i32 => VarInt, light: LightData => LightData }); @@ -1388,6 +1400,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { GameEvent(GameEvent) = GAME_EVENT, GameRuleValues(GameRuleValues) = GAME_RULE_VALUES, HurtAnimation(HurtAnimation) = HURT_ANIMATION, + DamageEvent(DamageEvent) = DAMAGE_EVENT, KeepAlive(KeepAlive) = KEEP_ALIVE, InitializeBorder(InitializeBorder) = INITIALIZE_BORDER, LevelChunkWithLight(LevelChunkWithLight) = LEVEL_CHUNK_WITH_LIGHT, @@ -2110,6 +2123,13 @@ mod tests { id: 2, slots: vec![(0, None), (5, Some(Stack::new(1, 1)))], }), + Clientbound::DamageEvent(DamageEvent { + id: 7, + source_type: 31, + cause: Some(0), + direct: None, + position: Some([1.5, -2.0, 3.25]), + }), Clientbound::SetHealth(SetHealth { health: 17.5, food: 18, diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 4d13b1c22..85a4f9e36 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -19,6 +19,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - hazards: a guest in survival gets hungry sprint-jumping and is hurt by lava, a block at the eyes, drowning and the void (then respawns); - pvp: the guest and the host hit each other with a sword; with the pvp game rule off, nothing; +- hurt: a pig the guest hits, and one the host hits, flashes red on the other side too (the + server's damage event) (#848); - containers: the guest's ender chest holds the guest's items, not the host's, and a double chest opens as 9x6 with the right half first; - feedback: the guest's command feedback names the guest and shows the numbers; @@ -84,7 +86,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'titles', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'objects', 'projectiles', 'light', 'effects', 'portals', 'distance'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'containers', 'feedback', 'titles', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'objects', 'projectiles', 'light', 'effects', 'portals', 'distance'] class Game: @@ -575,6 +577,33 @@ def check_pvp(host, guest, out): return hits +def check_hurt(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='clear @s') + face_each_other(host, guest) + hx, hy, hz = pos_of(host) + # Between the two, within both players' reach; bare hands leave it alive. + host('command', command=f'summon minecraft:pig {hx + 1.5:.2f} {hy:.2f} {hz + 0.8:.2f} {{NoAI:1b}}') + host.wait(30) + + def pig(game): + return game.raw('entities', 6, 'pig')['entities'][0] + seen = {} + for name, attacker, watcher in (('guest hits', guest, host), ('host hits', host, guest)): + attacker.wait(30) # a full attack charge + attacker.raw('attack', pig(attacker)['id']) + seen[name] = {'attacker': pig(attacker)['hurt_time'], 'watcher': pig(watcher)['hurt_time']} + attacker.shot(out, 'hurt-' + name.replace(' ', '-')) + watcher.shot(out, 'hurt-' + name.replace(' ', '-') + '-seen') + attacker.wait(20) + host('command', command='kill @e[type=minecraft:pig]') + # LivingEntity.hurtTime: 10 when hurt, one less each tick; the reads come a few ticks later. + for name, sides in seen.items(): + assert all(t > 0 for t in sides.values()), f'{name}: the pig\'s hurt flash {seen}' + return seen + + def container_items(game): """The open container's stacks by slot (Horizon's container slots are 300 and up) and its size.""" slots = [s for s in game('screen').get('slots', []) if s.get('slot', 0) >= 300] @@ -1100,7 +1129,13 @@ def check_xp(host, guest, out): g('command', command='gamemode survival') g('command', command='xp set @s 0 levels') g('command', command='xp set @s 0 points') + # Out of the orbs' way wherever an earlier check left the host (ExperienceOrb follows the + # nearest player who isn't a spectator). + host('command', command='gamemode spectator') guest.wait(10) + # `xp set` leaves Player.totalExperience (the score): experience from earlier checks stays in it. + total = guest('state')['player']['xp']['total'] + host_total = host('state')['player']['xp']['total'] x, y, z = pos_of(guest) # Three orbs of 7 points 4 blocks east of the guest (out of reach, within the 8 blocks orbs # follow from): they fly to the guest. @@ -1116,8 +1151,8 @@ def check_xp(host, guest, out): detail = {'seen': seen, 'guest': xp, 'host': host_xp, 'left': left} # ExperienceOrb.scanForMerges: orbs of one value side by side can merge into one. assert 1 <= seen <= 3, f'the guest saw {seen} orbs: {detail}' - assert xp['total'] == 21 and xp['level'] == 2, f'the guest\'s experience after three 7-point orbs: {detail}' - assert host_xp['total'] == 0, f'the host took the orbs: {detail}' + assert xp['total'] - total == 21 and xp['level'] == 2, f'the guest\'s experience after three 7-point orbs: {detail}' + assert host_xp['total'] == host_total, f'the host took the orbs: {detail}' assert left == 0, f'orbs left on the guest\'s screen: {detail}' return {'seen': seen, 'guest': xp, 'host': host_xp} @@ -1271,7 +1306,7 @@ def check_light(host, guest, out): CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, - 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, + 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'hurt': check_hurt, 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'commands': check_commands, 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls,