diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 64120b353..bf882b86a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -109,6 +109,7 @@ mod raids; mod recipe_book; mod remote; mod remote_objects; +mod remote_projectiles; mod render_control; mod render_tick; mod respawn_anchor; diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 58733bf45..6827d49c9 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -760,6 +760,8 @@ impl Game<'_> { status["physical_keys"] = json!(physical_keys); // Boats, minecarts, armor stands, item frames and paintings. status["objects"] = json!(self.objects_status()); + // Primed TNT, falling blocks, projectiles, tridents and end crystals. + status["projectiles"] = json!(self.projectiles_status()); status } } diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index a7e071c52..7b5e08f42 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -35,6 +35,29 @@ pub(super) struct Rocket { pub(super) item: ItemStack, } impl Rocket { + /// A rocket a server sent (`handleAddEntity`): placed and moved by it. + pub(super) fn remote(id: u32, position: Vec3, velocity: Vec3) -> Self { + let item = ItemStack::new("minecraft:firework_rocket", 1); + let (_, explosions) = fireworks_of(&item); + Self { + id, + position, + previous: position, + velocity, + life: 0, + lifetime: i32::MAX, + explosions, + attached: false, + angled: false, + item, + } + } + /// One tick of a server's client: the previous position, then `step`. + pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) { + self.previous = self.position; + self.life += 1; + self.position = step(self.position); + } /// Position and motion (the dispenser parity fixture). pub(super) fn motion(&self) -> (Vec3, Vec3) { (self.position, self.velocity) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 0edf4ade7..b9f0e5df5 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -246,6 +246,7 @@ impl Game<'_> { self.spawn = None; self.mobs.clear(); self.clear_remote_objects(); + self.clear_remote_projectiles(); self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); @@ -365,6 +366,7 @@ impl Game<'_> { self.player = None; self.mobs.clear(); self.clear_remote_objects(); + self.clear_remote_projectiles(); self.dropped.clear(); self.particles.clear(); self.pickups.clear(); @@ -611,6 +613,7 @@ impl Game<'_> { self.world.weather = weather; self.mobs.clear(); self.clear_remote_objects(); + self.clear_remote_projectiles(); self.dropped.clear(); self.particles.clear(); self.pickups.clear(); @@ -997,12 +1000,14 @@ impl Game<'_> { m.on_ground = on_ground; } self.turn_remote_object(id, rotation.map(|(yaw, _)| yaw), on_ground); + self.turn_remote_projectile(id, rotation); } fn remove_entity(&mut self, id: i32) { self.mobs.retain(|m| m.id != id as u32); self.orbs.retain(|o| o.id != id as u32); self.dropped.retain(|d| d.id != id as u32); self.remove_remote_object(id as u32); + self.remove_remote_projectile(id as u32); if let Some(r) = self.remote.as_mut() { r.entities.remove(&id); r.lerps.remove(&id); @@ -1266,7 +1271,16 @@ impl Game<'_> { } } self.spawn_entity(p.id, &kind, p.position, rotation); - self.spawn_remote_object(p.id, &kind, p.position, rotation[0], p.data); + if !self.spawn_remote_object(p.id, &kind, p.position, rotation[0], p.data) { + self.spawn_remote_projectile( + p.id, + &kind, + p.position, + (rotation[0], rotation[1]), + p.velocity, + p.data, + ); + } } C::RemoveEntities(p) => { for id in p.ids { @@ -1376,6 +1390,7 @@ impl Game<'_> { } } self.remote_object_data(p.id, &p.values); + self.remote_projectile_data(p.id, &p.values); } // ClientPacketListener.handleSetEquipment: what a mob or another // player holds and wears (EquipmentSlot ordinals). @@ -2545,8 +2560,9 @@ impl Game<'_> { } head_lerps.retain(|_, (_, steps)| *steps > 0); if running { - // Boats, minecarts and armor stands interpolate like mobs. - self.tick_remote_objects(|id, at| match lerps.get_mut(&(id as i32)) { + // Boats, minecarts, armor stands, projectiles and the rest + // interpolate like mobs. + let mut step = |id: u32, at: Vec3| match lerps.get_mut(&(id as i32)) { Some(l) if l.steps > 0 => { let n = f64::from(l.steps); l.steps -= 1; @@ -2557,7 +2573,9 @@ impl Game<'_> { ) } _ => at, - }); + }; + self.tick_remote_objects(&mut step); + self.tick_remote_projectiles(&mut step); } lerps.retain(|_, l| l.steps > 0); if let Some(r) = self.remote.as_mut() { diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs new file mode 100644 index 000000000..23cbb1913 --- /dev/null +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -0,0 +1,229 @@ +//! Primed TNT, falling blocks, projectiles, tridents, firework rockets and +//! end crystals on a server's client (`ClientPacketListener.handleAddEntity` +//! and `handleSetEntityData`): the server simulates them, the client draws +//! them where it says and interpolates their moves. +use super::{FallingBlock, Game}; +use horizon_client::projectiles::{Projectile, ProjectileKind}; +use horizon_core::{geometry::Vec3, position::BlockPos}; +use horizon_protocol::entity_data::Value; +use horizon_world::registry::BlockStateId; + +/// The projectile a type id names, as Horizon models it. +fn projectile_kind(kind: &str) -> Option { + Some(match kind { + "minecraft:arrow" | "minecraft:spectral_arrow" => ProjectileKind::Arrow { + base_damage: 2.0, + critical: false, + effect: None, + }, + "minecraft:snowball" => ProjectileKind::Snowball, + "minecraft:egg" => ProjectileKind::Egg, + "minecraft:ender_pearl" => ProjectileKind::EnderPearl, + "minecraft:small_fireball" => ProjectileKind::SmallFireball, + "minecraft:fireball" => ProjectileKind::LargeFireball { power: 1 }, + "minecraft:llama_spit" => ProjectileKind::LlamaSpit, + "minecraft:wind_charge" => ProjectileKind::WindCharge, + "minecraft:breeze_wind_charge" => ProjectileKind::BreezeWindCharge, + "minecraft:wither_skull" => ProjectileKind::WitherSkull { dangerous: false }, + _ => return None, + }) +} + +impl Game<'_> { + /// `handleAddEntity` for these types; false when `kind` isn't one. + pub(super) fn spawn_remote_projectile( + &mut self, + id: i32, + kind: &str, + position: [f64; 3], + rotation: (f32, f32), + velocity: [f64; 3], + data: i32, + ) -> bool { + let id = id as u32; + let at = Vec3::new(position[0], position[1], position[2]); + let velocity = Vec3::new(velocity[0], velocity[1], velocity[2]); + let (yaw, pitch) = rotation; + self.remove_remote_projectile(id); + match kind { + "minecraft:tnt" => self.tnts.push(super::tnt::PrimedTnt { + id, + position: at, + previous: at, + velocity, + fuse: 80, + on_ground: false, + }), + // FallingBlockEntity.recreateFromPacket: the block state is the data. + "minecraft:falling_block" => self.falling.push(FallingBlock { + id, + state: BlockStateId(data.max(0) as u32), + start_pos: BlockPos::default(), + position: at, + previous: at, + velocity, + age: 0, + no_gravity: false, + drop_item: false, + fall_distance: 0.0, + damage: Default::default(), + saved: None, + }), + "minecraft:trident" => { + let mut t = super::trident::ThrownTrident::remote(id, at, yaw, pitch); + t.velocity = velocity; + self.tridents.push(t); + } + "minecraft:firework_rocket" => { + self.rockets + .push(super::fireworks::Rocket::remote(id, at, velocity)); + } + "minecraft:end_crystal" => self.crystals.push(super::dragon::Crystal { + id, + position: at, + show_bottom: true, + time: 0, + beam: None, + invulnerable: false, + }), + _ => { + let Some(k) = projectile_kind(kind) else { + return false; + }; + let mut p = Projectile::new(k, at, None); + p.id = id; + p.velocity = velocity; + p.yaw = yaw; + p.pitch = pitch; + self.creatures.projectiles.push(p); + } + } + true + } + + /// `handleSetEntityData` for these types: what changes how they look. + pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { + let id = id as u32; + for (index, _, value) in values { + if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id) { + // PrimedTnt.DATA_FUSE_ID. + if let (8, Value::Int(fuse)) = (index, value) { + t.fuse = *fuse; + } + } else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id) { + // FallingBlockEntity.DATA_START_POS (the model's seed). + if let (8, Value::Pos(p)) = (index, value) { + f.start_pos = BlockPos::new(p[0], p[1], p[2]); + } + } else if let Some(c) = self.crystals.iter_mut().find(|c| c.id == id) { + // EndCrystal.DATA_BEAM_TARGET and DATA_SHOW_BOTTOM. + match (index, value) { + (8, Value::OptPos(beam)) => c.beam = *beam, + (9, Value::Bool(show)) => c.show_bottom = *show, + _ => {} + } + } else if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| p.id == id) { + match (&mut p.kind, index, value) { + // AbstractArrow.ID_FLAGS (critical) and IN_GROUND. + (ProjectileKind::Arrow { critical, .. }, 8, Value::Byte(flags)) => { + *critical = flags & 1 != 0; + } + (ProjectileKind::Arrow { .. }, 10, Value::Bool(in_ground)) => { + p.stuck = *in_ground; + } + // WitherSkull.DATA_DANGEROUS. + (ProjectileKind::WitherSkull { dangerous }, 8, Value::Bool(d)) => { + *dangerous = *d; + } + _ => {} + } + } + } + } + + /// A move's rotation for a projectile or trident. + pub(super) fn turn_remote_projectile(&mut self, id: i32, rotation: Option<(f32, f32)>) { + let (id, Some((yaw, pitch))) = (id as u32, rotation) else { + return; + }; + if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| p.id == id) { + p.yaw = yaw; + p.pitch = pitch; + } else if let Some(t) = self.tridents.iter_mut().find(|t| t.id == id) { + t.yaw = yaw; + t.pitch = pitch; + } + } + + /// One tick of interpolation, as `tick_remote_objects`. + pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + for t in &mut self.tnts { + t.previous = t.position; + t.position = step(t.id, t.position); + } + for f in &mut self.falling { + f.previous = f.position; + f.age += 1; + f.position = step(f.id, f.position); + } + for p in &mut self.creatures.projectiles { + p.previous = p.position; + p.age += 1; + p.position = step(p.id, p.position); + } + for t in &mut self.tridents { + let id = t.id; + t.remote_step(|at| step(id, at)); + } + for r in &mut self.rockets { + let id = r.id; + r.remote_step(|at| step(id, at)); + } + for c in &mut self.crystals { + c.time += 1; + c.position = step(c.id, c.position); + } + } + + pub(super) fn remove_remote_projectile(&mut self, id: u32) { + self.tnts.retain(|t| t.id != id); + self.falling.retain(|f| f.id != id); + self.creatures.projectiles.retain(|p| p.id != id); + self.tridents.retain(|t| t.id != id); + self.rockets.retain(|r| r.id != id); + self.crystals.retain(|c| c.id != id); + } + + /// Every one a server sent (a new connection, level or dimension). + pub(super) fn clear_remote_projectiles(&mut self) { + self.tnts.clear(); + self.falling.clear(); + self.creatures.projectiles.clear(); + self.tridents.clear(); + self.rockets.clear(); + self.crystals.clear(); + } + + /// Their kind and place, for `status`. + pub(super) fn projectiles_status(&self) -> Vec { + use serde_json::json; + let at = |p: Vec3| [p.x, p.y, p.z]; + let mut out = Vec::new(); + for t in &self.tnts { + out.push(json!({"id": t.id, "kind": "minecraft:tnt", "position": at(t.position), "fuse": t.fuse})); + } + for f in &self.falling { + out.push(json!({"id": f.id, "kind": "minecraft:falling_block", "position": at(f.position), "state": f.state.0})); + } + for c in &self.crystals { + out.push(json!({"id": c.id, "kind": "minecraft:end_crystal", "position": at(c.position), "show_bottom": c.show_bottom})); + } + for t in &self.tridents { + out.push(json!({"id": t.id, "kind": "minecraft:trident", "position": at(t.position)})); + } + for p in &self.creatures.projectiles { + out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position)})); + } + out + } +} diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index 2077cfada..ecfea890f 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -31,6 +31,32 @@ pub(super) struct ThrownTrident { returning: u32, creative_only: bool, } +impl ThrownTrident { + /// A trident a server sent (`handleAddEntity`): placed and moved by it. + pub(super) fn remote(id: u32, position: Vec3, yaw: f32, pitch: f32) -> Self { + Self { + id, + stack: ItemStack::new("minecraft:trident", 1), + position, + previous: position, + velocity: Vec3::ZERO, + yaw, + pitch, + in_ground: false, + in_ground_time: 0, + dealt_damage: false, + loyalty: 0, + no_physics: false, + returning: 0, + creative_only: false, + } + } + /// One tick of a server's client: the previous position, then `step`. + pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) { + self.previous = self.position; + self.position = step(self.position); + } +} const HALF: f64 = 0.25; fn bounds(p: Vec3) -> Aabb { Aabb::new( diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 01375c79a..80f4a03c8 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -44,6 +44,8 @@ address. The script then checks, from both sides, what a guest's game used to ge guest their points (not the host). - objects: boats, minecarts, armor stands, item frames and paintings the host summons reach the 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. Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -77,7 +79,7 @@ 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', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'effects', 'portals', - 'objects'] + 'objects', 'projectiles'] class Game: @@ -1047,10 +1049,10 @@ def check_xp(host, guest, out): return {'seen': seen, 'guest': xp, 'host': host_xp} -def objects_near(game, centre): +def objects_near(game, centre, key='objects'): """`status`'s objects within 8 blocks of centre, without their ids (each side numbers its own).""" out = [] - for o in game('status')['objects']: + for o in game('status')[key]: if all(abs(o['position'][i] - centre[i]) <= 8 for i in (0, 2)): o = dict(o) o.pop('id') @@ -1100,6 +1102,35 @@ def check_objects(host, guest, out): return f'{len(theirs)} objects identical' +def check_projectiles(host, guest, out): + x, y, z = (int(v // 1) for v in pos_of(host)) + commands = [ + f'summon minecraft:tnt {x + 4.5} {y} {z + 4.5} {{fuse:2000s}}', + f'summon minecraft:end_crystal {x - 4.5} {y} {z + 4.5} {{ShowBottom:0b}}', + f'summon minecraft:tnt {x + 2.5} {y + 5} {z - 3.5} {{fuse:2000s}}', + f'summon minecraft:arrow {x - 2.5} {y + 4} {z - 2.5} {{Motion:[0.2d,0d,0d]}}', + f'summon minecraft:falling_block {x - 0.5} {y + 6} {z - 4.5} {{BlockState:{{Name:"minecraft:sand"}}}}', + ] + try: + for command in commands: + host('command', command=command) + host.wait(80) + guest.raw('look-at', x, y, z) + guest.wait(5) + guest.shot(out, 'projectiles') + mine = objects_near(host, (x, y, z), 'projectiles') + theirs = objects_near(guest, (x, y, z), 'projectiles') + finally: + host('command', command=f'kill @e[type=!minecraft:player,x={x - 8},y={y - 2},z={z - 8},dx=16,dy=10,dz=16]') + host('command', command=f'setblock {x - 1} {y} {z - 5} minecraft:air') + assert len(mine) == len(commands) - 1, f'the host has {len(mine)}: {mine}' + # The fuse counts down every tick: the guest's, read a moment later, may be a tick or two behind. + fuses = [(m.pop('fuse', 0), t.pop('fuse', 0)) for m, t in zip(mine, theirs)] + assert theirs == mine, f'the guest sees {theirs}\nthe host has {mine}' + assert all(abs(a - b) <= 2 for a, b in fuses), f'fuses (host, guest): {fuses}' + return f'{len(theirs)} identical, fuses (host, guest) {fuses}' + + 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, @@ -1107,7 +1138,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, 'effects': check_effects, 'portals': check_portals, 'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, - 'xp': check_xp, 'objects': check_objects} + 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles} def run(ctl, out, resources, checks):