From 89cbe03ebe1a6d54f4a494fcc0402f1768cdc710 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: everyone sees players' arm swings The host ignored ServerboundPunchPacket, so a guest mining or hitting swung only on its own screen; only the first swing a guest's use ever started went out, the host's own swings never did, the host drew no swing on guests' bodies and a guest's client ignored ClientboundSwingAnimationPacket. The host now swings the guest's hand on a punch (handlePunch), sends each tick's guest swings to the players around and the host's own to the guests, and swings and ticks the guests' bodies it draws. A use the server ran that swung goes back to the guest too: Horizon's client does not run uses itself, so it never predicted that swing (the hoe). The guest's client swings itself or the other entity on the packet. lan_e2e.py swings: mining swings seen from each side, and the guest's own hoe swing. Part of #848 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/agent.rs | 2 + crates/horizon-client/src/game/lan.rs | 8 ++ crates/horizon-client/src/game/lan_actions.rs | 93 ++++++++++++++++--- crates/horizon-client/src/game/remote.rs | 19 ++++ crates/horizon-client/src/mobs/ai.rs | 2 +- tools/lan_e2e.py | 60 +++++++++++- 6 files changed, 167 insertions(+), 17 deletions(-) diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index b11fdd552..71992ec3f 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -477,6 +477,8 @@ impl Game<'_> { "sleeping": self.sleeping, // The item in use: its slot and for how many ticks. "using": self.using.map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })), + // The arm swings started (LivingEntity.swing). + "swings": self.swings_started, "time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) }, "weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering }, "paused": self.pause, diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index d35bf787a..491767836 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -42,6 +42,8 @@ pub(super) struct LanHost { pub hub: Hub, pub settings: LanSettings, pub host_entity: i32, + /// The host's swings the guests were told of (`Game::swings_started`). + pub host_swings: u32, pub host_uuid: u128, /// The host's profile name (the account's, or the offline name). pub host_name: String, @@ -395,6 +397,8 @@ impl Game<'_> { [&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet] .map(|s| s.as_deref()) }), + // The host draws this guest's arm swinging. + "model_swinging": h.models.get(&g.conn).map(|m| m.ai.swinging), })).collect::>(), }), _ => json!({ "open": false }), @@ -509,6 +513,7 @@ impl Game<'_> { hub, settings: LanSettings { port, ..settings }, host_entity, + host_swings: self.swings_started, host_uuid, host_name: self.options.player_name(), models: HashMap::new(), @@ -1158,6 +1163,9 @@ impl Game<'_> { .each_ref() .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; + // LivingEntity.updateSwingTime: the arm swing lan_swings started. + m.anim.attack_anim_o = m.anim.attack_anim; + horizon_client::mobs::ai::tick_swing(m); } } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ced435d8d..e161517dd 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -10,6 +10,7 @@ use horizon_client::{ command::vanilla, containers::BlockEntity, entities::Experience, + first_person::{Hand, SwingAnimation}, items::ItemStack, lan::{ guest::SPECTATOR, @@ -43,8 +44,9 @@ pub(super) struct GuestPlay { /// its progress since `dig_start` is complete (ServerPlayerGameMode.hasDelayedDestroy). delayed: Option<([i32; 3], u64)>, last_progress: i32, - /// Hand movements the client announced and the host animated. - swung: bool, + /// Swings the guest's actions started this tick, for the players around + /// (`LivingEntity.swing` sends ClientboundSwingAnimationPacket). + swings: u32, /// The trading screen the guest has open. pub(super) merchant: Option, /// The inventory menu and the crafting table the guest crafts in. @@ -202,7 +204,11 @@ impl Game<'_> { self.lan_acting_name = Some(g.name.clone()); self.lan_acting_uuid = Some(g.uuid); + // The guest's swings are theirs: the host's own count stays the host's. + let swings = self.swings_started; let result = f(self); + play.swings += self.swings_started.wrapping_sub(swings); + self.swings_started = swings; for packet in std::mem::take(&mut self.guest_packets) { host.hub.send_to(conn, &packet); } @@ -542,6 +548,16 @@ impl Game<'_> { } } } + // ServerGamePacketListenerImpl.handlePunch: the main hand swings + // with the held item's attack animation (mining, attacking, a + // click on nothing), seen by the players around, and the attack + // strength starts again. + S::Punch(_) => { + self.as_guest(host, conn, |g| { + g.swing_hand(Hand::Main, SwingAnimation::DEFAULT); + g.reset_attack_strength(); + }); + } S::UseItemOn(p) => { host.hub.ack(conn, p.sequence); if spectator { @@ -557,11 +573,14 @@ impl Game<'_> { f64::from(p.pos[2]) + f64::from(p.cursor[2]), ], }; - self.as_guest(host, conn, |g| { + let swung = self.as_guest(host, conn, |g| { g.forced_hit = Some(hit); + let swings = g.swings_started; let _ = g.use_item(); g.forced_hit = None; + g.swings_started != swings }); + self.lan_swing_back(host, conn, swung); // The client predicted a result: correct it with what really is. for pos in [ p.pos, @@ -579,20 +598,26 @@ impl Game<'_> { } // handleUseItem: the client's rotation, then the item alone. What it // looked at a moment ago (a block, a mob) is UseItemOn's or Interact's. - self.as_guest(host, conn, |g| { + let swung = self.as_guest(host, conn, |g| { (g.yaw, g.pitch) = (p.yaw, p.pitch); g.lan_item_only = true; + let swings = g.swings_started; let _ = g.use_item(); g.lan_item_only = false; + g.swings_started != swings }); + self.lan_swing_back(host, conn, swung); } S::Attack(p) => self.guest_attack(host, conn, p.id), S::Interact(p) => { if let Some((position, eye)) = self.look_at_entity(host, gi, p.id) { let _ = (position, eye); - self.as_guest(host, conn, |g| { + let swung = self.as_guest(host, conn, |g| { + let swings = g.swings_started; let _ = g.use_item(); + g.swings_started != swings }); + self.lan_swing_back(host, conn, swung); } } S::SetCreativeModeSlot(p) => { @@ -1619,23 +1644,63 @@ impl Game<'_> { } } - /// Guests' arm swings for everyone else. + /// A use the server ran swung the guest's hand: their own client is told + /// too (`swing(hand, true)` for a SwingSource.SERVER result). Horizon's + /// client does not run uses itself, so it does not predict the swing; a + /// client that did (a block placed) is still in the first half of its + /// swing and ignores it (`SwingState.startIfAble`). + fn lan_swing_back(&mut self, host: &mut LanHost, conn: u32, swung: Option) { + if swung != Some(true) { + return; + } + let (Some(g), Some(play)) = (host.hub.guest(conn), host.play.get(&conn)) else { + return; + }; + if let Some(c) = play.swing.current { + host.hub + .send_to(conn, &swing_packet(g.entity_id, c.hand, c.animation)); + } + } + + /// The tick's arm swings for the players around (the guests' to everyone + /// else, the host's to the guests), and `LivingEntity.updateSwingTime` + /// for the guests' bodies here. pub(super) fn lan_swings(&mut self, host: &mut LanHost) { let conns: Vec = host.play.keys().copied().collect(); for conn in conns { let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else { continue; }; - if !host.hub.here(g) { - continue; - } - let (id, at) = (g.entity_id, g.position); + let (id, at, here) = (g.entity_id, g.position, host.hub.here(g)); let play = host.play.get_mut(&conn).expect("play"); - let swinging = play.swing.swinging() && play.swing.ticks == 0; - if swinging && !play.swung { - host.hub.swing(id, 0, at, Some(conn)); + let swung = std::mem::take(&mut play.swings) > 0; + if let (true, true, Some(c)) = (swung, here, play.swing.current) { + let packet = swing_packet(id, c.hand, c.animation); + host.hub.broadcast_near(at, 128.0, &packet, Some(conn)); + if let Some(m) = host.models.get_mut(&conn) { + m.swing(); + } + } + play.swing.tick(); + } + if self.swings_started != host.host_swings { + host.host_swings = self.swings_started; + if let (Some(p), Some(c)) = (self.player.as_ref(), self.swing.current) { + let at = [p.position.x, p.position.y, p.position.z]; + let packet = swing_packet(host.host_entity, c.hand, c.animation); + host.hub.broadcast_near(at, 128.0, &packet, None); } - play.swung = swinging; } } } + +/// ClientboundSwingAnimationPacket: the hand and the animation (its type and +/// base duration; each client applies the swinger's haste and fatigue). +fn swing_packet(id: i32, hand: Hand, animation: SwingAnimation) -> C { + C::SwingAnimation(play::SwingAnimation { + id, + hand: i32::from(hand == Hand::Off), + kind: i32::from(animation.kind), + duration: animation.duration, + }) +} diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 680360c93..e5bc9b6b4 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1599,6 +1599,21 @@ impl Game<'_> { } } C::Animate(p) => self.remote_animate(p.id, p.action), + // ClientPacketListener.handleSwingAnimation: the entity swings + // (LivingEntity.swing, which a swing in its first half ignores). + C::SwingAnimation(p) => { + use horizon_client::first_person::Hand; + let hand = if p.hand == 1 { Hand::Off } else { Hand::Main }; + let animation = horizon_client::first_person::SwingAnimation { + kind: p.kind.clamp(0, 255) as u8, + duration: p.duration, + }; + if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + self.swing_hand(hand, animation); + } else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.swing(); + } + } C::UpdateMobEffect(p) => self.remote_effect(&p), C::RemoveMobEffect(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) @@ -2621,6 +2636,9 @@ impl Game<'_> { if !m.alive() { m.death_time += 1; } + // LivingEntity.updateSwingTime. + m.anim.attack_anim_o = m.anim.attack_anim; + horizon_client::mobs::ai::tick_swing(m); // Entity.commonTick: LinearInterpolationHandler.interpolate. if let Some(l) = lerps.get_mut(&(m.id as i32)) && l.steps > 0 @@ -3728,6 +3746,7 @@ impl Game<'_> { let armor = [&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref()); serde_json::json!({ "id": m.id, + "swinging": m.ai.swinging, "armor": armor, "main_hand": e.main_hand.as_deref(), "off_hand": e.off_hand.as_deref(), diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index f74a3c7d1..475bd7611 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -429,7 +429,7 @@ pub fn tick( true } /// LivingEntity.updateSwingTime (6-tick swing duration). -fn tick_swing(m: &mut Mob) { +pub fn tick_swing(m: &mut Mob) { if m.ai.swinging { m.ai.swing_time += 1; if m.ai.swing_time >= 6 { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 4d13b1c22..e0a696c23 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -49,6 +49,8 @@ address. The script then checks, from both sides, what a guest's game used to ge guest as the host has them (kind, place, rotation, what they hold or wear, the variant). - projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where the host has them; a falling block lands on both sides. +- swings: each side sees the other's arm swing while it mines a block, and the guest sees its own + swing when its hoe tills dirt (the server's use) (#848). - light: the guest's light matches the host's: around a torch placed near it, under a roof and once a block of the roof is removed under the sky, and in the last chunk it tracks next to glowstone in a chunk it doesn't (only the server's light updates bring that one). @@ -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', 'containers', 'feedback', 'titles', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'objects', 'projectiles', 'light', 'swings', 'effects', 'portals', 'distance'] class Game: @@ -1095,6 +1097,60 @@ def check_eat(host, guest, out): return detail +def watch_mining(miner, pos, seen): + """Mine the block at `pos` (by hand, for seconds) and sample `seen()` meanwhile.""" + dig = threading.Thread(target=miner.raw, args=('break', *pos)) + dig.start() + samples = [] + for _ in range(8): + time.sleep(0.25) + samples.append(seen()) + dig.join() + return samples + + +def check_swings(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 = (int(v // 1) for v in pos_of(host)) + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + # Stone by hand takes 7.5 seconds: ServerboundPunchPacket every tick keeps the arm swinging. + guest('command', command=f'setblock {gx} {gy} {gz + 1} minecraft:stone') + host('command', command=f'setblock {hx} {hy} {hz + 1} minecraft:stone') + host.wait(10) + def swinging(game): + # On its server thread the host's window is a client of its server too. + if game is host and not SERVER_THREAD: + return lan_guest(host).get('model_swinging') + return any(e.get('swinging') for e in remote(game).get('player_equipment', [])) + # Most samples: a swing restarts only past its first half (SwingState.startIfAble), so a sample can + # fall between two. + host_sees = watch_mining(guest, (gx, gy, gz + 1), lambda: swinging(host)) + guest_sees = watch_mining(host, (hx, hy, hz + 1), lambda: swinging(guest)) + # A hoe on dirt: the server tills it and swings the guest's hand, on the guest's screen too. + # Where the guest stands now (an earlier check can leave it on a ledge it then drops from). + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + soil = (gx, gy - 1, gz + 1) + guest('command', command=f'setblock {soil[0]} {soil[1]} {soil[2]} minecraft:dirt') + # HoeItem.useOn tills only under air. + guest('command', command=f'setblock {soil[0]} {soil[1] + 1} {soil[2]} minecraft:air') + guest('command', command='give @s minecraft:wooden_hoe') + guest.wait(10) + guest.raw('select', 'minecraft:wooden_hoe') + before = guest('state')['swings'] + guest.raw('interact', *soil) + guest.wait(10) + hoe = {'swings': guest('state')['swings'] - before, 'soil': host.raw('block', *soil)['block']} + guest('command', command=f'setblock {soil[0]} {soil[1]} {soil[2]} minecraft:stone') + detail = {'host_sees_guest': host_sees, 'guest_sees_host': guest_sees, 'hoe': hoe} + assert sum(map(bool, host_sees)) >= 4, f'the host does not see the guest mine: {detail}' + assert sum(map(bool, guest_sees)) >= 4, f'the guest does not see the host mine: {detail}' + assert hoe == {'swings': 1, 'soil': 'minecraft:farmland'}, f'the guest\'s hoe: {detail}' + return detail + + def check_xp(host, guest, out): for g in (host, guest): g('command', command='gamemode survival') @@ -1278,7 +1334,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'effects': check_effects, 'portals': check_portals, 'distance': check_distance, 'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, - 'light': check_light} + 'light': check_light, 'swings': check_swings} def run(ctl, out, resources, checks):