From c4d6b341724103a581cc41e461615c568fdd8c41 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:46:48 +0200 Subject: [PATCH] Other players' block cracks are drawn On a server or a world open to LAN, a player saw only their own crack. The server sent each new stage to the others (ClientboundBlockDestruction), but a client of a server ignored the packet, and the host of a LAN world neither drew its guests' cracks nor sent its own to them. Vanilla keeps the cracks per breaker (ClientLevel.destroyBlockProgress: a progress outside 0..9 removes it, 400 ticks without news drops it) and draws, within 32 blocks, the furthest one on each block (LevelExtractor.extractBlockDestroyAnimation). Horizon now does the same: a client of a server takes the packet, a LAN host records its guests' stages and sends its own (each new stage, then -1 when it stops), and every crack is drawn with its own stage. A guest's crack also goes when the block it digs is gone before its STOP_DESTROY_BLOCK (its own tick broke it), as ServerPlayerGameMode.tick clears it on air: the others kept its last stage for 400 ticks. Each crack vertex carries its stage sprite's atlas origin in its light bytes (the crumbling pass is unlit); the shader keeps the shared sprite size. lan_e2e `cracks`: each side watches the block the other mines and sees its crack grow; no crack is left once the blocks break. The screenshots from both sides show the cracks. Fixes #1096 Co-Authored-By: Claude Opus 5.5 --- .../examples/breaking_fixture.rs | 6 +- .../horizon-client/src/block_entity_render.rs | 15 +- crates/horizon-client/src/breaking.rs | 56 +++++-- crates/horizon-client/src/entity.wgsl | 6 +- crates/horizon-client/src/game.rs | 144 +++++++++++------- crates/horizon-client/src/game/control.rs | 7 + crates/horizon-client/src/game/lan.rs | 3 + crates/horizon-client/src/game/lan_actions.rs | 88 +++++++++-- crates/horizon-client/src/game/remote.rs | 4 + crates/horizon-client/src/gfx.rs | 6 +- tools/lan_e2e.py | 49 +++++- 11 files changed, 294 insertions(+), 90 deletions(-) diff --git a/crates/horizon-client/examples/breaking_fixture.rs b/crates/horizon-client/examples/breaking_fixture.rs index 2016fd613..da696b88e 100644 --- a/crates/horizon-client/examples/breaking_fixture.rs +++ b/crates/horizon-client/examples/breaking_fixture.rs @@ -14,6 +14,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, path::Path, }; +/// The stage sprite origin the cracks carry (the oracle compares the geometry and UVs only). +const STAGE: [f32; 2] = [0.25, 0.5]; fn main() -> Result<(), Box> { let args: Vec<_> = std::env::args().collect(); let root = Path::new(&args[1]); @@ -47,7 +49,7 @@ fn main() -> Result<(), Box> { .iter() .any(|(_, m)| m.faces.iter().any(|f| f.translucent)); for (_, m) in models { - breaking::geometry(m, origin, translucent, &mut vertices); + breaking::geometry(m, origin, translucent, STAGE, &mut vertices); } } let quads: Vec<_> = vertices @@ -58,7 +60,7 @@ fn main() -> Result<(), Box> { q.iter() .map(|v| { assert_eq!(v.color, 0xffff_ffff); - assert_eq!(v.light, 240 | (240 << 8)); + assert_eq!(v.light, breaking::stage_light(STAGE)); assert_eq!(v.layer, if translucent { 12 } else { 11 }); [v.pos[0], v.pos[1], v.pos[2], v.uv[0], v.uv[1]] }) diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index db6bf7b79..21376d698 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -939,7 +939,14 @@ impl BlockEntityRenderer { !matches!(self.kind(state), Kind::None) } /// ChestRenderer and BannerRenderer submit their animated models for crumbling. - pub fn render_breaking(&self, scene: &Scene, pos: [i32; 3], state: u32, out: &mut Vec) { + pub fn render_breaking( + &self, + scene: &Scene, + pos: [i32; 3], + state: u32, + stage: [f32; 2], + out: &mut Vec, + ) { if !matches!(self.kind(state), Kind::Banner { .. } | Kind::Chest { .. }) { return; } @@ -958,7 +965,7 @@ impl BlockEntityRenderer { false, out, ); - crate::breaking::entity_geometry(&mut out[start..], origin); + crate::breaking::entity_geometry(&mut out[start..], origin, stage); } /// `ChestRenderer.extractRenderState`'s openness for the chest of `state` /// at `pos`: `ChestBlock.combine` (`DoubleBlockCombiner.combineWithNeigbour`) @@ -1942,7 +1949,7 @@ mod tests { let mut base = Vec::new(); renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base); let mut cracks = Vec::new(); - renderer.render_breaking(&scene, [0; 3], state, &mut cracks); + renderer.render_breaking(&scene, [0; 3], state, [0.0; 2], &mut cracks); assert!(!cracks.is_empty()); assert_eq!( base.iter().map(|v| v.pos).collect::>(), @@ -1956,7 +1963,7 @@ mod tests { scene.lid = &|_| 1.0; } let mut animated = Vec::new(); - renderer.render_breaking(&scene, [0; 3], state, &mut animated); + renderer.render_breaking(&scene, [0; 3], state, [0.0; 2], &mut animated); assert!(cracks.iter().zip(&animated).any(|(a, b)| a.pos != b.pos)); scene.game_time = 0; scene.lid = &|_| 0.0; diff --git a/crates/horizon-client/src/breaking.rs b/crates/horizon-client/src/breaking.rs index c7ee19206..84eedae75 100644 --- a/crates/horizon-client/src/breaking.rs +++ b/crates/horizon-client/src/breaking.rs @@ -23,7 +23,21 @@ pub fn decal_uv([x, y, z]: [f32; 3], direction: Direction) -> [f32; 2] { [-p[0], -p[1]] } -pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: &mut Vec) { +/// The light bytes of a crack vertex: the pass is unlit, so they carry the origin of the +/// vertex's destroy stage sprite (each crack in `LevelRenderer.destroyingBlocks` has its own +/// stage; every stage sprite has the same size, `crumbling_sprite.zw`). +pub fn stage_light([u0, v0]: [f32; 2]) -> u32 { + let q = |x: f32| (x.clamp(0.0, 1.0) * 65535.0).round() as u32; + q(u0) | (q(v0) << 16) +} + +pub fn geometry( + model: &BakedModel, + origin: glam::Vec3, + translucent: bool, + stage: [f32; 2], + out: &mut Vec, +) { // Vanilla visits all six cull groups and then the unculled faces, even beside solid neighbours. for cull in Direction::ALL.map(Some).into_iter().chain([None]) { for face in model.faces.iter().filter(|face| face.quad.cull == cull) { @@ -33,7 +47,7 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: uv: decal_uv(pos, face.quad.facing), layer: if translucent { 12 } else { 11 }, color: 0xffff_ffff, - light: 240 | (240 << 8), + light: stage_light(stage), normal: [0; 4], }); } @@ -42,7 +56,7 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: } /// Project a block entity's transformed quads onto the same destroy-stage pass. -pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { +pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3, stage: [f32; 2]) { for quad in vertices.as_chunks_mut::<4>().0 { let positions = [0, 1, 2].map(|i| glam::Vec3::from(quad[i].pos)); let normal = (positions[1] - positions[0]).cross(positions[2] - positions[0]); @@ -65,7 +79,7 @@ pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { vertex.uv = decal_uv((glam::Vec3::from(vertex.pos) - origin).to_array(), facing); vertex.layer = 11; vertex.color = 0xffff_ffff; - vertex.light = 240 | (240 << 8); + vertex.light = stage_light(stage); } } } @@ -73,6 +87,24 @@ pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { #[cfg(test)] mod tests { use super::*; + + #[test] + fn stage_origin_survives_the_light_bytes() { + // entity.wgsl's `wrap`: the low and high 16 bits over 65535. + for origin in [[0.0, 0.0], [0.5, 0.25], [0.123_456, 0.987_654], [1.0, 1.0]] { + let light = stage_light(origin); + let back = [ + (light & 0xffff) as f32 / 65535.0, + (light >> 16) as f32 / 65535.0, + ]; + for k in 0..2 { + assert!( + (back[k] - origin[k]).abs() <= 0.5 / 65535.0, + "{origin:?} -> {back:?}" + ); + } + } + } use crate::models::catalog::BakedFace; use horizon_assets::{bake::ModelQuad, model::Material}; fn slab_top() -> BakedModel { @@ -109,7 +141,13 @@ mod tests { fn slab_overlay_follows_baked_top_not_unit_cube() { let model = slab_top(); let mut vertices = Vec::new(); - geometry(&model, glam::Vec3::new(2.0, 3.0, 4.0), false, &mut vertices); + geometry( + &model, + glam::Vec3::new(2.0, 3.0, 4.0), + false, + [0.0; 2], + &mut vertices, + ); assert_eq!(vertices.len(), 4); for (v, p) in vertices.iter().zip(model.faces[0].quad.positions) { assert_eq!(v.pos, [p[0] + 2.0, p[1] + 3.0, p[2] + 4.0]); @@ -120,14 +158,14 @@ mod tests { fn entity_overlay_uses_block_local_projected_uvs() { let origin = glam::Vec3::new(12.0, -3.0, 8.0); let mut expected = Vec::new(); - geometry(&slab_top(), origin, false, &mut expected); + geometry(&slab_top(), origin, false, [0.0; 2], &mut expected); let mut actual = expected.clone(); for vertex in &mut actual { vertex.uv = [0.0; 2]; vertex.layer = 0; vertex.color = 0; } - entity_geometry(&mut actual, origin); + entity_geometry(&mut actual, origin, [0.0; 2]); assert_eq!( bytemuck::cast_slice::<_, u8>(&actual), bytemuck::cast_slice::<_, u8>(&expected) @@ -143,7 +181,7 @@ mod tests { #[test] fn translucent_overlay_has_its_own_pass() { let mut vertices = Vec::new(); - geometry(&slab_top(), glam::Vec3::ZERO, true, &mut vertices); + geometry(&slab_top(), glam::Vec3::ZERO, true, [0.0; 2], &mut vertices); assert!(vertices.iter().all(|v| v.layer == 12)); } #[test] @@ -151,7 +189,7 @@ mod tests { let mut model = slab_top(); model.faces.clear(); let mut vertices = Vec::new(); - geometry(&model, glam::Vec3::ZERO, false, &mut vertices); + geometry(&model, glam::Vec3::ZERO, false, [0.0; 2], &mut vertices); assert!(vertices.is_empty()); } } diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index c6305c697..9ca871f47 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -71,7 +71,8 @@ fn entity_vertex(position: vec3, uv: vec2, let unlit = overlay == 2u || overlay == 4u || overlay == 6u || overlay == 9u || overlay == 10u || overlay == 11u || overlay == 12u; out.light_color = select(lm, vec4(1.0), unlit); - // Overlay 6 (beacon beams): the light bytes carry the sprite's v range. + // Overlay 6 (beacon beams): the light bytes carry the sprite's v range; 11 and 12 + // (cracks): the destroy stage sprite's origin. out.wrap = vec2(f32(light.x | (light.y << 8u)), f32(light.z | (light.w << 8u))) / 65535.0; // minecraft_mix_light: the vertex colour times the cardinal light only. var c = color; @@ -147,7 +148,8 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { var uv = in.uv; if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; } if in.overlay == 11u || in.overlay == 12u { - uv = globals.crumbling_sprite.xy + fract(in.uv) * globals.crumbling_sprite.zw; + // Each crack's stage sprite origin comes in its light bytes (breaking::stage_light). + uv = in.wrap + fract(in.uv) * globals.crumbling_sprite.zw; } var color = textureSample(atlas, atlas_sampler, uv) * select(in.back_color, in.color, front); if in.overlay == 9u || in.overlay == 10u { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 460899bff..40dedd8ed 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1136,6 +1136,9 @@ struct Game<'a> { potions: potions::PotionState, scratch_slot: Option, mining: Option, + /// The other players' cracks (`LevelRenderer.destroyingBlocks`): breaker id to the block, + /// the stage (0..=9) and the game time it last changed. + destroying: HashMap, destroy_delay: u32, use_delay: u32, creative: bool, @@ -6433,19 +6436,11 @@ impl Game<'_> { .block_entity_render() .render(&scene, visible, &mut out); } - if let Some(mining) = &self.mining - && mining.progress > 0.0 - && self.gui.atlas.sprites.contains_key(&format!( - "block/destroy_stage_{}", - ((mining.progress * 10.0) as u32).min(9) - )) - { - let state = self - .world - .block(mining.pos[0], mining.pos[1], mining.pos[2]); + for (pos, stage) in self.cracks(camera) { + let state = self.world.block(pos[0], pos[1], pos[2]); self.res .block_entity_render() - .render_breaking(&scene, mining.pos, state.0, &mut out); + .render_breaking(&scene, pos, state.0, stage, &mut out); } } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. @@ -6563,50 +6558,90 @@ impl Game<'_> { &|b| world.light(b[0], b[1], b[2]), &mut out, ); - let atlas = &self.gui.atlas; - // Breaking progress overlay (destroy_stage_0..9). - if let Some(m) = &self.mining - && m.progress > 0.0 - { - let stage = ((m.progress * 10.0) as u32).min(9); - if atlas - .sprites - .contains_key(&format!("block/destroy_stage_{stage}")) + // Breaking progress overlays (destroy_stage_0..9): ours and the other players'. + for (pos, stage) in self.cracks(camera) { + let o = (glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) + - camera) + .as_vec3(); + let state = self.world.block(pos[0], pos[1], pos[2]); + if self.res.facts().get(state).render_shape + == horizon_client::blocks::RenderShape::Model + && let Ok(models) = self + .pack + .render + .model_catalog + .collect(state, BlockPos::new(pos[0], pos[1], pos[2])) { - let o = (glam::DVec3::new( - f64::from(m.pos[0]), - f64::from(m.pos[1]), - f64::from(m.pos[2]), - ) - camera) - .as_vec3(); - let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]); - if self.res.facts().get(state).render_shape - == horizon_client::blocks::RenderShape::Model - && let Ok(models) = self - .pack - .render - .model_catalog - .collect(state, BlockPos::new(m.pos[0], m.pos[1], m.pos[2])) - { - let offset = self - .pack - .context - .tables - .offset(state, m.pos[0], m.pos[2]) - .unwrap_or([0.0; 3]); - let origin = o + glam::DVec3::from(offset).as_vec3(); - let translucent = models - .iter() - .any(|(_, model)| model.faces.iter().any(|f| f.translucent)); - for (_, model) in models { - horizon_client::breaking::geometry(model, origin, translucent, &mut out); - } + let offset = self + .pack + .context + .tables + .offset(state, pos[0], pos[2]) + .unwrap_or([0.0; 3]); + let origin = o + glam::DVec3::from(offset).as_vec3(); + let translucent = models + .iter() + .any(|(_, model)| model.faces.iter().any(|f| f.translucent)); + for (_, model) in models { + horizon_client::breaking::geometry(model, origin, translucent, stage, &mut out); } } } out } + /// `LevelRenderer.destroyBlockProgress`: a player's crack on a block (0..=9), or none + /// (any other progress). Cracks not updated for 400 ticks are dropped. + pub(crate) fn destroy_block_progress(&mut self, breaker: i32, pos: [i32; 3], progress: i32) { + let now = self.world.game_time; + self.destroying + .retain(|_, c| now.saturating_sub(c.2) <= 400); + if (0..10).contains(&progress) { + self.destroying.insert(breaker, (pos, progress as u8, now)); + } else { + self.destroying.remove(&breaker); + } + } + + /// The cracks to draw and their stage sprite's atlas origin: our own mining and the + /// other players' (`renderBlockDestroyAnimation`: within 32 blocks of the camera, the + /// furthest progress on each block). + fn cracks(&self, camera: glam::DVec3) -> Vec<([i32; 3], [f32; 2])> { + let mut stages: Vec<([i32; 3], u32)> = Vec::new(); + let mut add = |pos: [i32; 3], stage: u32| match stages.iter_mut().find(|c| c.0 == pos) { + Some(c) => c.1 = c.1.max(stage), + None => stages.push((pos, stage)), + }; + if let Some(m) = &self.mining + && m.progress > 0.0 + { + add(m.pos, ((m.progress * 10.0) as u32).min(9)); + } + let now = self.world.game_time; + for (pos, stage, at) in self.destroying.values() { + if now.saturating_sub(*at) <= 400 { + add(*pos, u32::from(*stage)); + } + } + stages + .into_iter() + .filter(|(pos, _)| { + let d = glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) + + 0.5 + - camera; + d.length_squared() <= 1024.0 + }) + .filter_map(|(pos, stage)| { + let r = self + .gui + .atlas + .sprites + .get(&format!("block/destroy_stage_{stage}"))?; + Some((pos, [r.u0, r.v0])) + }) + .collect() + } + fn sky_darken(&self) -> i32 { if self.dim == Dim::Nether { return 11; @@ -9599,14 +9634,10 @@ impl Game<'_> { game_time: self.world.game_time as f32, shader_game_time: ((self.world.game_time % 24000) as f32 + alpha as f32) / 24000.0, crumbling_sprite: self - .mining - .as_ref() - .and_then(|m| { - self.gui.atlas.sprites.get(&format!( - "block/destroy_stage_{}", - ((m.progress * 10.0) as u32).min(9) - )) - }) + .gui + .atlas + .sprites + .get("block/destroy_stage_0") .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]), end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| { self.gui @@ -11148,6 +11179,7 @@ impl<'a> Game<'a> { potions: Default::default(), scratch_slot: None, mining: None, + destroying: HashMap::new(), destroy_delay: 0, use_delay: 0, creative, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 5cdf46110..04b0cd53b 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -769,6 +769,12 @@ impl Game<'_> { "pending_observations": self.lod_observe.len(), "refined_samples": self.lod.as_ref().map_or(0, |lod| lod.refined_samples()), }); + // The other players' cracks this client draws (LevelRenderer.destroyingBlocks). + let destroying: Vec<_> = self + .destroying + .iter() + .map(|(id, (pos, stage, _))| json!({ "id": id, "pos": pos, "stage": stage })) + .collect(); let mut status = json!({ "screen": self.screen_name(), "debug": { @@ -832,6 +838,7 @@ impl Game<'_> { status["lod"]["target_tiles"] = target.into(); status["lod"]["sampled_target_tiles"] = sampled.into(); status["pending_uploads"] = self.pending_uploads.len().into(); + status["destroying"] = json!(destroying); status["physical_keys"] = json!(physical_keys); // Boats, minecarts, armor stands, item frames and paintings. status["objects"] = json!(self.objects_status()); diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 18325828d..b08eccfc3 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -44,6 +44,8 @@ pub(super) struct LanHost { pub host_entity: i32, /// The host's swings the guests were told of (`Game::swings_started`). pub host_swings: u32, + /// The host's crack the guests were told of: the block and its stage. + pub host_crack: Option<([i32; 3], i32)>, pub host_uuid: u128, /// The host's profile name (the account's, or the offline name). pub host_name: String, @@ -519,6 +521,7 @@ impl Game<'_> { settings: LanSettings { port, ..settings }, host_entity, host_swings: self.swings_started, + host_crack: None, host_uuid, host_name: self.options.player_name(), models: HashMap::new(), diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index af127f42a..ab89d2920 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -717,6 +717,7 @@ impl Game<'_> { conn, &C::BlockUpdate(play::BlockUpdate { pos: a.pos, state }), ); + self.destroy_block_progress(host.hub.guests[gi].entity_id, a.pos, -1); host.hub.broadcast_near( [ f64::from(a.pos[0]), @@ -1684,7 +1685,12 @@ impl Game<'_> { play.mining = None; let start = play.dig_start; let state = self.world.block(pos[0], pos[1], pos[2]); - if !dug || self.res.facts().is_air(state) { + if !dug { + return; + } + if self.res.facts().is_air(state) { + // Already broken (the guest's own tick dug it out): only the crack goes. + self.guest_crack_gone(host, conn, pos); return; } let progress = self @@ -1733,18 +1739,7 @@ impl Game<'_> { self.as_guest(host, conn, |g| { let _ = g.break_block(pos); }); - if let Some(g) = host.hub.guest(conn) { - host.hub.broadcast_near( - [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], - 64.0, - &C::BlockDestruction(play::BlockDestruction { - id: g.entity_id, - pos, - progress: 255, - }), - Some(conn), - ); - } + self.guest_crack_gone(host, conn, pos); } /// The crack animation other players see. @@ -1756,6 +1751,18 @@ impl Game<'_> { let Some((pos, _)) = play.digging else { return; }; + // ServerPlayerGameMode.tick: a block gone while it is dug (the guest's own tick broke + // it, or something else did) clears the crack. + if play.last_progress >= 0 + && self + .res + .facts() + .is_air(self.world.block(pos[0], pos[1], pos[2])) + { + play.last_progress = -1; + self.guest_crack_gone(host, conn, pos); + return; + } let progress = play .mining .as_ref() @@ -1763,6 +1770,8 @@ impl Game<'_> { let swinging = play.swing.swinging(); if progress != play.last_progress && progress >= 0 { play.last_progress = progress; + // The host player sees it too (on the server thread its window is a guest). + self.destroy_block_progress(host.hub.guests[gi].entity_id, pos, progress); host.hub.broadcast_near( [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], 64.0, @@ -1777,6 +1786,25 @@ impl Game<'_> { let _ = swinging; } + /// `level.destroyBlockProgress(id, pos, -1)` for a guest: its crack on `pos` is gone, for the + /// host and the other guests. + fn guest_crack_gone(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) { + let Some(id) = host.hub.guest(conn).map(|g| g.entity_id) else { + return; + }; + self.destroy_block_progress(id, pos, -1); + host.hub.broadcast_near( + [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], + 64.0, + &C::BlockDestruction(play::BlockDestruction { + id, + pos, + progress: 255, + }), + Some(conn), + ); + } + /// Dropped items touching a guest go into their inventory. fn guest_pickups(&mut self, host: &mut LanHost, gi: usize) { let (conn, mode, position, id) = { @@ -1981,6 +2009,7 @@ impl Game<'_> { } play.swing.tick(); } + self.lan_host_crack(host); 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) { @@ -1992,6 +2021,39 @@ impl Game<'_> { } } +impl Game<'_> { + /// The host player's crack, for the guests (`ServerLevel.destroyBlockProgress` from the + /// host's mining): each new stage, and -1 once it stops or breaks the block. + fn lan_host_crack(&mut self, host: &mut LanHost) { + let now = self + .mining + .as_ref() + .and_then(|m| (m.progress > 0.0).then(|| (m.pos, ((m.progress * 10.0) as i32).min(9)))); + if now == host.host_crack { + return; + } + let packet = |pos: [i32; 3], progress: u8| { + C::BlockDestruction(play::BlockDestruction { + id: host.host_entity, + pos, + progress, + }) + }; + let near = |pos: [i32; 3]| [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]; + if let Some((pos, _)) = host.host_crack + && now.is_none_or(|(p, _)| p != pos) + { + host.hub + .broadcast_near(near(pos), 64.0, &packet(pos, 255), None); + } + if let Some((pos, stage)) = now { + host.hub + .broadcast_near(near(pos), 64.0, &packet(pos, stage as u8), None); + } + host.host_crack = now; + } +} + /// 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 { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5bb3e172c..6dbe850b6 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1342,6 +1342,10 @@ impl Game<'_> { })); } C::BlockUpdate(p) => self.server_block(p.pos, p.state), + // ClientPacketListener.handleBlockDestruction: another player's crack. + C::BlockDestruction(p) => { + self.destroy_block_progress(p.id, p.pos, i32::from(p.progress)); + } C::SectionBlocksUpdate(p) => { let [sx, sy, sz] = p.section; for change in p.changes { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 5141b6089..246c09e0c 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -108,7 +108,8 @@ struct Globals { end_portal_sprites: [[f32; 4]; 2], /// x: vanilla's `GameTime` uniform; y: nether cardinal lighting, zw unused. time: [f32; 4], - /// Atlas rect of the current destroy stage (entity.wgsl). + /// Atlas rect of a destroy stage (entity.wgsl takes only its size: every stage's is the same, + /// and each crack carries its own stage's origin). crumbling_sprite: [f32; 4], /// Framebuffer size, selection stroke width, perspective layering scale. outline_params: [f32; 4], @@ -212,7 +213,8 @@ pub struct Frame<'a> { /// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png /// (`rendertype_end_portal`'s Sampler0 and Sampler1). pub end_portal_sprites: [[f32; 4]; 2], - /// Current destroy-stage sprite: projected UVs repeat inside this atlas rect. + /// A destroy-stage sprite: projected UVs repeat inside a rect of this size, from the + /// origin each crack vertex carries (`breaking::stage_light`). pub crumbling_sprite: [f32; 4], pub ticks: u64, /// The darkness effect on the lightmap: the brightness it takes off the diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 606321e99..266e804b3 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -68,6 +68,8 @@ address. The script then checks, from both sides, what a guest's game used to ge the guest steps off (#848). - 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). +- cracks: each side sees the other player's crack on the block they mine grow, and go once it breaks + (#1096). - time: the guest's clock is the host's: it stops with `/time pause`, and catches up with the server's game time after the guest's game stalls for a few seconds (#848). - growth: far from the host, the chunks around the guest tick (#890): water placed there flows @@ -109,7 +111,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', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -1346,6 +1348,49 @@ def check_swings(host, guest, out): return detail +def check_cracks(host, guest, out): + # Another player's crack (#1096): ServerLevel.destroyBlockProgress sends each new stage to the + # others (ClientboundBlockDestructionPacket), drawn by LevelRenderer from destroyingBlocks. + 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)) + 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) + shots = [] + + def cracks(game, pos, name): + stage = max((c['stage'] for c in game('status')['destroying'] if tuple(c['pos']) == pos), default=None) + if stage is not None and stage >= 2 and name not in shots: + shots.append(name) + game.shot(out, name) + return stage + + def watch(miner, watcher, pos, name): + # The watcher looks at the block the other mines. + watcher.raw('look-at', f'{pos[0] + 0.5:.2f}', f'{pos[1] + 0.5:.2f}', f'{pos[2] + 0.5:.2f}') + watcher.wait(5) + return watch_mining(miner, pos, lambda: cracks(watcher, pos, name)) + host_sees = watch(guest, host, (gx, gy, gz + 1), 'cracks-guest-mines') + face_each_other(host, guest) + guest_sees = watch(host, guest, (hx, hy, hz + 1), 'cracks-host-mines') + host.wait(10) + # The breaker's -1 (ServerLevel.destroyBlockProgress once the block is broken) clears each crack. + gone = {name: [(c['pos'], game.raw('block', *c['pos'])['block']) for c in game('status')['destroying']] + for name, game in (('host', host), ('guest', guest))} + detail = {'host_sees_guest': host_sees, 'guest_sees_host': guest_sees, 'after': gone} + stages = lambda s: [x for x in s if x is not None] + assert len(stages(host_sees)) >= 3 and stages(host_sees) == sorted(stages(host_sees)), \ + f'the host does not see the guest\'s crack grow: {detail}' + assert len(stages(guest_sees)) >= 3 and stages(guest_sees) == sorted(stages(guest_sees)), \ + f'the guest does not see the host\'s crack grow: {detail}' + assert not any(gone.values()), f'a crack stays after the block broke: {detail}' + return detail + + def check_eating(host, guest, out): for g in (host, guest): g('command', command='gamemode survival') @@ -1655,7 +1700,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'eating': check_eating, 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, - 'swings': check_swings, + 'swings': check_swings, 'cracks': check_cracks, 'time': check_time, 'growth': check_growth}