diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 14de6efc7..f101f53cd 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -158,6 +158,9 @@ pub struct Audio { /// Positional sounds played since the last drain, kept while the world /// is open to the network so guests hear them too. pub capture: Option>, + /// How many times each positional sound played (the control socket's `status`), + /// with or without an audio device. + pub heard: std::collections::BTreeMap, } fn decode(path: &Path) -> Option<(Vec, u32)> { use symphonia::core::{ @@ -591,6 +594,7 @@ impl Audio { random: LegacyRandom::new(crate::sound_engine::unique_seed()), source_override: None, capture: None, + heard: Default::default(), } } #[cfg(not(feature = "audio"))] @@ -733,6 +737,9 @@ impl Audio { if let (Some(capture), Some(at)) = (self.capture.as_mut(), at) { capture.push((event.to_owned(), at, volume, pitch)); } + if at.is_some() { + *self.heard.entry(event.to_owned()).or_default() += 1; + } self.sync_volumes(); let event = crate::sound_events::normalize(event); let source = self diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e3e409263..f2505c23b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -34,6 +34,7 @@ mod crossbow; mod debug_keys; mod decorated_pot; mod dedicated; +mod deflect; mod dispense_fixture; mod dispenser; mod dragon; @@ -1236,7 +1237,9 @@ struct Game<'a> { /// swap just before an attack keeps them, with the new item's enchantments /// (attribute swapping). attack_item: Option>, - last_hurt_by_player: HashSet, + /// Mobs a player hurt (`LivingEntity.lastHurtByPlayer`), with the guest + /// it was by connection (None: the host). + last_hurt_by_player: HashMap>, /// Mobs whose death (`LivingEntity.die`) has been handled. died: HashSet, /// Client-ticked block-entity animation state (`game/block_entity_anims.rs`). @@ -6830,6 +6833,10 @@ impl Game<'_> { self.break_painting(i, true); return true; } + // A ghast's fireball or a wind charge in front: turned back. + if self.attack_redirectable() { + return true; + } let hand_damage = 1.0 + self .held() @@ -6938,7 +6945,8 @@ impl Game<'_> { (actual * 0.5) as u32, ); } - self.last_hurt_by_player.insert(self.mobs[index].id); + self.last_hurt_by_player + .insert(self.mobs[index].id, self.lan_acting); let sound = if crit { "minecraft:entity.player.attack.crit" } else if scale > 0.9 { @@ -11324,7 +11332,7 @@ impl<'a> Game<'a> { raiding: Default::default(), attack_ticks: 100, attack_item: None, - last_hurt_by_player: HashSet::new(), + last_hurt_by_player: HashMap::new(), died: HashSet::new(), be_anims: { let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index da3851d9a..70ae082aa 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -25,6 +25,9 @@ pub(super) struct CombatTracker { pub(super) last_hurt_mob: Option<(u32, i64)>, /// The mob whose projectile is hitting the player now. pub(super) projectile_owner: Option, + /// The projectile hitting the player now is another player's that + /// `ServerPlayer.canHarmPlayer` refuses (the `pvp` rule, an ally). + pub(super) refuse_player_hit: bool, /// The mob exploding now (`ServerExplosion.source`): its team's friendly /// fire decides whom the blast may hurt. pub(super) explosion_source: Option, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 6c69904ac..d79f69d3c 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -912,6 +912,7 @@ impl Game<'_> { status["pending_uploads"] = self.pending_uploads.len().into(); status["destroying"] = json!(destroying); status["physical_keys"] = json!(physical_keys); + status["heard"] = json!(self.audio.heard); // Boats, minecarts, armor stands, item frames and paintings. status["objects"] = json!(self.objects_status()); // Primed TNT, falling blocks, projectiles, tridents and end crystals. diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index ceb5f2920..78efc708d 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -623,7 +623,8 @@ impl Game<'_> { } /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { - let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0; + let killer = self.last_hurt_by_player.remove(&m.id); + let by_player = killer.is_some() || m.ai.last_hurt_by_player > 0; let mut dying = m.clone(); // LivingEntity.die: the death is heard, and a sculk catalyst nearby // takes the experience (before the loot is dropped). @@ -637,11 +638,22 @@ impl Game<'_> { } }); if by_player { - self.stats.add("killed", &m.kind.id, 1); - self.stats.custom("mob_kills", 1); - self.score_player_killed(super::commands::Target::Mob(m.id)); - let view = self.mob_entity(m); - self.trigger_entity("minecraft:player_killed_entity", "entity", &view); + // A guest's kill is theirs: their statistics, scores and + // advancements (LivingEntity.die credits lastHurtByPlayer). + let guest = killer.flatten().filter(|_| self.lan_acting.is_none()); + let credited = guest.is_some_and(|conn| { + let Some(mut host) = self.lan.take() else { + return false; + }; + let done = self + .as_guest(&mut host, conn, |g| g.credit_kill(m)) + .is_some(); + self.lan = Some(host); + done + }); + if !credited { + self.credit_kill(m); + } } self.score_entity_removed(m.id); self.raider_died(m, by_player); @@ -676,6 +688,15 @@ impl Game<'_> { } } } + /// The killer's side of a mob's death: `ServerPlayer.awardKillScore`'s + /// statistics and scores, and the `player_killed_entity` trigger. + fn credit_kill(&mut self, m: &Mob) { + self.stats.add("killed", &m.kind.id, 1); + self.stats.custom("mob_kills", 1); + self.score_player_killed(super::commands::Target::Mob(m.id)); + let view = self.mob_entity(m); + self.trigger_entity("minecraft:player_killed_entity", "entity", &view); + } /// `dropAllDeathLoot` through `mobs::drops`: the entity loot table from the /// world's random sequence, equipment by drop chance, species extras and /// the experience orbs, spawned in order. @@ -1394,7 +1415,8 @@ impl Game<'_> { from: [f64; 3], damage_type: &str, ) -> bool { - if self.creative { + // ServerPlayer.canHarmPlayer refused another player's projectile. + if self.creative || self.combat.refuse_player_hit { return false; } let projectile = self @@ -1632,14 +1654,30 @@ impl Game<'_> { w: &w, targets: targets_guests, }; + let guest_entities = self.lan_guest_entities(); projectiles.retain_mut(|p| { let mob_shot = !matches!(p.owner, Some(Who::Player)); - let (keep, hit) = match (p.arrow.is_some(), mob_shot) { + // A player's arrows, snowballs and eggs meet every player; a + // guest's flies from that guest (Projectile.getOwner), not + // from the host, until it has left them. + let pvp = !mob_shot && super::lan_pvp::meets_players(&p.kind); + let shooter = p + .guest + .filter(|_| pvp) + .and_then(|c| guest_entities.iter().find(|(g, _)| *g == c)) + .map(|&(_, id)| Who::Mob(id)); + if shooter.is_some() { + p.owner = shooter; + } + let (keep, hit) = match (p.arrow.is_some(), mob_shot || pvp) { (true, false) => horizon_client::arrows::tick(p, &scene, &arrow_targets), (true, true) => horizon_client::arrows::tick(p, &scene, &arrow_targets_guests), (false, false) => p.tick(&pw), (false, true) => p.tick(&pw_guests), }; + if shooter.is_some() { + p.owner = Some(Who::Player); + } if let Some(a) = p.arrow.as_mut() { arrow_events.extend(a.events.drain(..).map(|e| (p.position, e))); } @@ -1691,6 +1729,11 @@ impl Game<'_> { } self.creatures.projectiles.append(&mut projectiles); for (p, hit) in hits { + // A player's arrow on another player lands as the victim's hurt. + if let Some(victim) = self.projectile_pvp_victim(&p, hit) { + self.projectile_hits_player(&p, hit, victim)?; + continue; + } // A guest's projectile lands as theirs: a pearl takes them, what // it hurts answers to them. One hitting the host (`Who::Player` // here) stays the host's hit. @@ -1974,7 +2017,7 @@ impl Game<'_> { .find(|m| m.id == id) .is_some_and(|m| m.damage(amount, source)); if p.owner == Some(Who::Player) { - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } hurt } @@ -2099,15 +2142,21 @@ impl Game<'_> { } }, Hit::Block { pos, face, .. } => { + // SmallFireball.onHitBlock: a mob's only with mobGriefing; + // BaseFireBlock.getState placed with updates (the fire + // ticks, ages and goes out where it can't stay). let fire = [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]]; - if self - .res - .facts() - .is_air(self.world.block(fire[0], fire[1], fire[2])) - && let Some(state) = - self.pack.assets.registry.default_state("minecraft:fire") + let mob = matches!(p.owner, Some(Who::Mob(_))); + if (!mob || self.ui.rules.bool("mob_griefing")) + && self + .res + .facts() + .is_air(self.world.block(fire[0], fire[1], fire[2])) { - self.world.set(fire[0], fire[1], fire[2], state)?; + let at = BlockPos::new(fire[0], fire[1], fire[2]); + let state = + self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, at)); + self.level_set(fire, state)?; } } Hit::None => {} diff --git a/crates/horizon-client/src/game/deflect.rs b/crates/horizon-client/src/game/deflect.rs new file mode 100644 index 000000000..a08de87b3 --- /dev/null +++ b/crates/horizon-client/src/game/deflect.rs @@ -0,0 +1,155 @@ +//! A player's blow at a ghast's fireball or a wind charge +//! (`#minecraft:redirectable_projectile`): `Player.attack` turns it with +//! `ProjectileDeflection.AIM_DEFLECT` instead of hurting anything. It flies on +//! along the player's view and is the player's now (`Projectile.deflect` +//! sets the owner), so a ghast it meets dies of it (`Ghast.isReflectedFireball`). +use super::{Game, ray_box, view_vector}; +use horizon_client::{ + mobs::Who, + projectiles::{Projectile, ProjectileKind}, +}; +use horizon_core::geometry::{Aabb, Vec3}; + +/// `AbstractHurtingProjectile.getPickRadius`: the crosshair finds it a block +/// round its box. +const PICK_RADIUS: f64 = 1.0; + +/// `#minecraft:redirectable_projectile`: a ghast's fireball and both wind charges. +pub(super) fn redirectable(p: &Projectile) -> bool { + !p.stuck + && matches!( + p.kind, + ProjectileKind::LargeFireball { .. } + | ProjectileKind::WindCharge + | ProjectileKind::BreezeWindCharge + ) +} + +/// Its box for the crosshair: the entity's (a fireball 1 x 1, a wind charge +/// 0.3125, from its feet up) grown by the pick radius. +fn pick_box(p: &Projectile) -> Aabb { + let size = match p.kind { + ProjectileKind::LargeFireball { .. } => 1.0, + _ => 0.3125, + }; + let half = size / 2.0 + PICK_RADIUS; + Aabb::new( + Vec3::new( + p.position.x - half, + p.position.y - PICK_RADIUS, + p.position.z - half, + ), + Vec3::new( + p.position.x + half, + p.position.y + size + PICK_RADIUS, + p.position.z + half, + ), + ) +} + +impl Game<'_> { + /// The redirectable projectile under the crosshair within the attack + /// reach, and how far along the view it is. + pub(super) fn redirectable_hit(&self) -> Option<(usize, f64)> { + let eye = self.eye_position()?; + let dir = view_vector(self.yaw, self.pitch); + let reach: f64 = if self.creative { 5.0 } else { 3.0 }; + self.creatures + .projectiles + .iter() + .enumerate() + .filter(|(_, p)| redirectable(p)) + .filter_map(|(i, p)| ray_box(eye, dir, reach, pick_box(p)).map(|t| (i, t))) + .min_by(|a, b| a.1.total_cmp(&b.1)) + } + + /// `Player.attack` on a redirectable projectile nearer than any mob or + /// block in view: `AIM_DEFLECT` (its movement the unit view vector), the + /// player its owner, its acceleration power back to 0.1 + /// (`onDeflection` by an attack), and the no-damage sound. True when a + /// projectile was turned. + pub(super) fn attack_redirectable(&mut self) -> bool { + let Some((i, t)) = self.redirectable_hit() else { + return false; + }; + if self.mob_hit().is_some_and(|(_, d)| d < t) { + return false; + } + if let (Some(hit), Some(eye)) = (self.pick(), self.eye_position()) { + let d = (0..3) + .map(|a| (hit.point[a] - eye[a]).powi(2)) + .sum::() + .sqrt(); + if d < t { + return false; + } + } + self.deflect(i); + true + } + + /// `Player.canInteractWithEntity(box, 3.0)` as the server checks an + /// attack packet: the projectile's box within the reach plus 3 of the eyes. + pub(super) fn within_interaction_range(&self, i: usize) -> bool { + let (Some(eye), Some(p)) = (self.eye_position(), self.creatures.projectiles.get(i)) else { + return false; + }; + let b = pick_box(p); + let (lo, hi) = (b.min_position(), b.max_position()); + let (lo, hi) = ( + [lo.x + PICK_RADIUS, lo.y + PICK_RADIUS, lo.z + PICK_RADIUS], + [hi.x - PICK_RADIUS, hi.y - PICK_RADIUS, hi.z - PICK_RADIUS], + ); + let d2: f64 = (0..3) + .map(|a| (eye[a] - eye[a].clamp(lo[a], hi[a])).powi(2)) + .sum(); + let range = if self.creative { 5.0 } else { 3.0 } + 3.0; + d2 < range * range + } + + /// `Projectile.deflect(AIM_DEFLECT, player, player, true)`. + pub(super) fn deflect(&mut self, i: usize) { + let dir = view_vector(self.yaw, self.pitch); + let guest = self.lan_acting; + let p = &mut self.creatures.projectiles[i]; + p.velocity = Vec3::new(dir[0], dir[1], dir[2]); + p.yaw = dir[0].atan2(dir[2]).to_degrees() as f32; + p.pitch = dir[1].atan2(dir[0].hypot(dir[2])).to_degrees() as f32; + p.owner = Some(Who::Player); + // On a server, the guest who struck it (their projectile now). + p.guest = guest; + // Not into the one who turned it on its way out. + p.left_owner = false; + self.reset_attack_strength(); + self.swing_arm(); + let from = self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]); + self.audio + .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_ghast_fireballs_and_wind_charges_are_redirectable() { + let at = Vec3::new(0.0, 64.0, 0.0); + let large = Projectile::fireball( + ProjectileKind::LargeFireball { power: 1 }, + at, + None, + [1.0, 0.0, 0.0], + ); + let small = Projectile::fireball(ProjectileKind::SmallFireball, at, None, [1.0, 0.0, 0.0]); + assert!(redirectable(&large)); + assert!(!redirectable(&small)); + // The pick box: a block round the fireball's 1 x 1 box. + let b = pick_box(&large); + assert_eq!(b.min_position().x, -1.5); + assert_eq!(b.max_position().y, 66.0); + } +} diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 55babd9af..5cf67f586 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -226,6 +226,102 @@ impl Game<'_> { } /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT); /// the player takes `damage_type`. + /// `ServerExplosion.hurtEntities` for the player: damage scaled by + /// distance and exposure, through a raised shield (`hurtServer` blocks + /// explosions like any attack from where the blast is), then the push + /// (less with explosion knockback resistance; none for spectators or a + /// creative player flying). + pub(super) fn explosion_hurt_player( + &mut self, + center: [f64; 3], + radius: f32, + damage_type: &str, + exploding: Option, + ) { + let diameter = f64::from(radius * 2.0); + // Blast protection: `EXPLOSION_KNOCKBACK_RESISTANCE` (0.15 per level and + // piece, so two Blast Protection IV pieces cancel it). + let resistance = self + .player + .as_mut() + .and_then(|p| p.attribute("minecraft:explosion_knockback_resistance").ok()) + .unwrap_or(0.0); + let Some(p) = self.player.as_ref() else { + return; + }; + let feet = [p.position.x, p.position.y, p.position.z]; + let dist = ((feet[0] - center[0]).powi(2) + + (feet[1] - center[1]).powi(2) + + (feet[2] - center[2]).powi(2)) + .sqrt() + / diameter; + if dist > 1.0 || p.health.dead_or_dying() { + return; + } + let w = f64::from(p.dimensions.width) / 2.0; + let h = f64::from(p.dimensions.height); + let eye = [ + feet[0], + feet[1] + f64::from(p.dimensions.eye_height), + feet[2], + ]; + let exposure = self.seen_percent( + center, + [feet[0] - w, feet[1], feet[2] - w], + [feet[0] + w, feet[1] + h, feet[2] + w], + ); + let pow = (1.0 - dist) * f64::from(exposure); + let amount = ((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32; + let d = [eye[0] - center[0], eye[1] - center[1], eye[2] - center[2]]; + let l = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + let dir = if l < 1.0e-4 { + [0.0; 3] + } else { + [d[0] / l, d[1] / l, d[2] / l] + }; + let power = pow * (1.0 - resistance); + // `source.doTeamsAllowDamage(entity)`. + let hurtable = exploding.is_none_or(|id| { + horizon_client::scoreboard::teams_allow_damage(self.mob_team(id), self.player_team()) + }); + let blocking = self.player_blocking(Some(center), damage_type, false); + let raised = blocking.is_some(); + let (creative, spectator) = (self.creative, self.spectator()); + let flying = self.player.as_ref().is_some_and(|p| p.flying); + let mut outcome = horizon_client::health::BlockOutcome::default(); + if let Some(p) = self.player.as_mut() + && let Some(id) = self.motion.health.damage.id(damage_type) + { + // Creative players are invulnerable to explosions. + if !creative + && !spectator + && hurtable + && let Ok(o) = p.hurt_blocking( + &self.motion.health, + self.world.health_rules, + id, + amount, + blocking, + ) + { + outcome = o; + } + if !spectator && !(creative && flying) { + p.velocity = Vec3::new( + p.velocity.x + dir[0] * power, + p.velocity.y + dir[1] * power, + p.velocity.z + dir[2] * power, + ); + } + } + if outcome.hurt && !creative { + self.hurt_armor(amount); + } + if raised { + self.after_block(outcome, amount, None, false); + } + } + fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32, damage_type: &str) { if radius < 1.0e-5 { return; @@ -261,57 +357,23 @@ impl Game<'_> { horizon_client::scoreboard::teams_allow_damage(g.mob_team(id), victim) }) }; - let player_hurtable = teams_allow(self, self.player_team()); - // Player. - if let Some(p) = self.player.as_ref() { - let feet = [p.position.x, p.position.y, p.position.z]; - let dist = distance(feet) / diameter; - if dist <= 1.0 && !p.health.dead_or_dying() { - let w = f64::from(p.dimensions.width) / 2.0; - let h = f64::from(p.dimensions.height); - let eye = [ - feet[0], - feet[1] + f64::from(p.dimensions.eye_height), - feet[2], - ]; - let exposure = self.seen_percent( - center, - [feet[0] - w, feet[1], feet[2] - w], - [feet[0] + w, feet[1] + h, feet[2] + w], - ); - let amount = damage(dist, exposure); - let dir = direction(eye); - let mut hurt = false; - let creative = self.creative; - if let Some(p) = self.player.as_mut() - && let Some(id) = self.motion.health.damage.id(damage_type) - { - // Creative players are invulnerable to explosions. - if !creative && player_hurtable { - hurt = p - .hurt(&self.motion.health, self.world.health_rules, id, amount) - .unwrap_or(false); - } - // Blast protection: `EXPLOSION_KNOCKBACK_RESISTANCE` (0.15 per - // level and piece, so two Blast Protection IV pieces cancel it). - let resistance = p - .attribute("minecraft:explosion_knockback_resistance") - .unwrap_or(0.0); - let power = (1.0 - dist) * f64::from(exposure) * (1.0 - resistance); - // `hitPlayers` skips creative players who are flying: the - // client gets no knockback in the explode packet. - if !(creative && p.flying) { - p.velocity = Vec3::new( - p.velocity.x + dir[0] * power, - p.velocity.y + dir[1] * power, - p.velocity.z + dir[2] * power, - ); - } - } - if hurt && !self.creative { - self.hurt_armor(amount); - } + // The player, then every other player in the level (LAN guests), + // each swapped in as the player. + self.explosion_hurt_player(center, radius, damage_type, exploding); + if let Some(mut host) = self.lan.take() { + let guests: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| g.conn) + .collect(); + for conn in guests { + self.guest_hit_by(&mut host, conn, |g| { + g.explosion_hurt_player(center, radius, damage_type, exploding); + }); } + self.lan = Some(host); } // Mobs. let mut mobs = std::mem::take(&mut self.mobs); diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index 84cea5a5c..a7218ff3c 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -156,6 +156,7 @@ impl Game<'_> { || before(self.dragon_hit().map(|h| h.1)) || before(self.mob_hit().map(|h| h.1)) || before(self.guest_hit().map(|h| h.1)) + || before(self.redirectable_hit().map(|h| h.1)) } /// `LocalPlayer.isHandsBusy`: paddling a boat. fn hands_busy(&self) -> bool { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 1c38f9542..b261e8ad2 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -64,6 +64,12 @@ pub(super) struct GuestPlay { xp_delay: u32, /// What last killed the guest outright (`/kill`): the death message's key. death_cause: Option, + /// The equipment modifiers on the guest's attributes (`apply_equipment`) + /// and the armour and main hand they were put on for: the hub's player + /// is a `ServerPlayer` too, whose worn armour counts + /// (`LivingEntity.collectEquipmentChanges`). + modifiers: Vec<(String, String)>, + equipped: Option>>, } /// A guest's command waiting for the hub (`LanHost::commands`). @@ -130,6 +136,8 @@ pub(super) struct GuestSwap { swings: u32, /// How many projectiles there were: those added since are the guest's. projectiles: usize, + /// The host's equipment modifiers. + modifiers: Vec<(String, String)>, } impl GuestPlay { @@ -193,7 +201,8 @@ impl Game<'_> { return None; } let i = host.hub.guests.iter().position(|g| g.conn == conn)?; - if host.hub.guests[i].motion.is_none() { + let fresh = host.hub.guests[i].motion.is_none(); + if fresh { let p = Vec3::new( host.hub.guests[i].position[0], host.hub.guests[i].position[1], @@ -207,6 +216,10 @@ impl Game<'_> { } } let mut play = host.play.remove(&conn).unwrap_or_default(); + if fresh { + // A new body (joined, respawned, changed level): nothing on it yet. + play.equipped = None; + } let g = &mut host.hub.guests[i]; // The guest's body. let Some(mut motion) = g.motion.take() else { @@ -310,6 +323,17 @@ impl Game<'_> { let packets = std::mem::take(&mut self.guest_packets); let swings = self.swings_started; let projectiles = self.creatures.projectiles.len(); + let modifiers = std::mem::replace( + &mut self.applied_modifiers, + std::mem::take(&mut play.modifiers), + ); + // Its worn armour on its attributes, when it changed. + let mut equipped: Vec> = self.armor.to_vec(); + equipped.push(self.inventory.get(self.selected).cloned().flatten()); + if play.equipped.as_ref() != Some(&equipped) { + self.apply_equipment(); + play.equipped = Some(equipped); + } Some(GuestSwap { conn, i, @@ -355,6 +379,7 @@ impl Game<'_> { packets, swings, projectiles, + modifiers, }) } @@ -406,7 +431,9 @@ impl Game<'_> { packets, swings, projectiles, + modifiers, } = swap; + play.modifiers = std::mem::replace(&mut self.applied_modifiers, modifiers); // What the guest shot is theirs (Projectile.setOwner). for p in self.creatures.projectiles.iter_mut().skip(projectiles) { if p.owner == Some(horizon_client::mobs::Who::Player) && p.guest.is_none() { @@ -805,6 +832,8 @@ impl Game<'_> { ], }; let hand = if p.hand == 1 { Hand::Off } else { Hand::Main }; + let logged = self.world.block_log.as_ref().map_or(0, Vec::len); + let heard = self.audio.capture.as_ref().map_or(0, Vec::len); let swung = self.as_guest(host, conn, |g| { g.forced_hit = Some(hit); g.guest_use = Some(GuestUse::OnBlock(hand)); @@ -815,6 +844,7 @@ impl Game<'_> { g.swings_started != swings }); self.lan_swing_back(host, conn, swung); + self.guest_use_sounds(host, conn, logged, heard); // The client predicted a result: correct it with what really is. for pos in [ p.pos, @@ -1127,6 +1157,22 @@ impl Game<'_> { } return; } + // A ghast's fireball or a wind charge: turned along the guest's own + // view (ServerGamePacketListenerImpl.handleInteract, then + // Player.attack's AIM_DEFLECT). + if let Some(i) = self + .creatures + .projectiles + .iter() + .position(|p| p.id != 0 && p.id as i32 == id && super::deflect::redirectable(p)) + { + self.as_guest(host, conn, |g| { + if g.within_interaction_range(i) { + g.deflect(i); + } + }); + return; + } let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch); if self.look_at_entity(host, gi, id).is_none() { return; @@ -1962,6 +2008,33 @@ impl Game<'_> { } } + /// `level.playSound(player, ...)` of a guest's use it predicted (`remote::hand_operated` + /// blocks only, as the guest decides): the others hear it now, the guest already did. + fn guest_use_sounds(&mut self, host: &mut LanHost, conn: u32, logged: usize, heard: usize) { + let changed: Vec<(i32, i32, i32)> = self + .world + .block_log + .as_ref() + .map_or(&[][..], |log| log.get(logged..).unwrap_or(&[])) + .to_vec(); + let facts = self.res.facts(); + if changed.is_empty() + || !changed.iter().all(|&(x, y, z)| { + super::remote::hand_operated(&facts.get(self.world.block(x, y, z)).name) + }) + { + return; + } + let Some(capture) = self.audio.capture.as_mut() else { + return; + }; + let sounds: Vec<_> = capture.drain(heard.min(capture.len())..).collect(); + for (name, at, volume, pitch) in sounds { + let source = horizon_client::settings::sound_source(&name) as i32; + host.hub.sound(&name, at, volume, pitch, source, Some(conn)); + } + } + /// Positional sounds and level events of the tick, for the guests. pub(super) fn lan_broadcast_effects(&mut self, host: &mut LanHost) { let sounds = self.audio.capture.take().unwrap_or_default(); diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index a7347ab2a..d2c643088 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -3,9 +3,26 @@ //! is worked out as the attacker (weapon, attack strength, critical hit, //! enchantments, a mace's smash) and lands on the victim like any player //! attack (blocking, armour, knockback), when the `pvp` game rule allows it -//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`). +//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`). A player's arrow on +//! another player lands the same way. use super::{Game, lan::LanHost, lan_mobs::guest_bounds, ray_box, view_vector}; +use horizon_client::{ + Result, + mobs::Who, + projectiles::{Hit, Projectile, ProjectileKind}, +}; + +/// The player projectiles that meet other players: arrows (their hurt), and +/// snowballs and eggs, which break on them (`Player.hurtServer` takes no 0 +/// damage). Pearls, potions and wind charges fly past players as before. +pub(super) fn meets_players(kind: &ProjectileKind) -> bool { + matches!( + kind, + ProjectileKind::Arrow { .. } | ProjectileKind::Snowball | ProjectileKind::Egg + ) +} + /// Who a player's attack lands on. #[derive(Clone, Copy)] pub(super) enum Victim { @@ -105,6 +122,89 @@ impl Game<'_> { }) } + /// The guests by connection, with their entity ids. + pub(super) fn lan_guest_entities(&self) -> Vec<(u32, u32)> { + self.lan.as_ref().map_or_else(Vec::new, |host| { + host.hub + .guests + .iter() + .map(|g| (g.conn, g.entity_id as u32)) + .collect() + }) + } + + /// The player a player's projectile hit, when it hit one: the host for a + /// guest's shot, or a guest. + pub(super) fn projectile_pvp_victim(&self, p: &Projectile, hit: Hit) -> Option { + if p.owner != Some(Who::Player) || !meets_players(&p.kind) { + return None; + } + let Hit::Entity { who, .. } = hit else { + return None; + }; + match who { + Who::Player => p.guest.map(|_| Victim::Host), + Who::Mob(id) => self + .lan + .as_ref()? + .hub + .guests + .iter() + .find(|g| g.entity_id as u32 == id) + .map(|g| Victim::Guest(g.conn)), + } + } + + /// A player's projectile on a player: the hit runs as the victim, whose + /// hurt refuses it when the `pvp` game rule or their teams forbid it + /// (`ServerPlayer.canHarmPlayer`; `AbstractArrow.onHitEntity` then turns + /// the arrow back). + pub(super) fn projectile_hits_player( + &mut self, + p: &Projectile, + hit: Hit, + victim: Victim, + ) -> Result<()> { + let Hit::Entity { at, .. } = hit else { + return Ok(()); + }; + let Some(mut host) = self.lan.take() else { + return self.projectile_hit(p, hit); + }; + let team_of = |game: &Self, name: &str| game.score.board.players_team(name).cloned(); + let attacker = match p.guest { + Some(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)), + None => self.player_team().cloned(), + }; + let target = match victim { + Victim::Host => self.player_team().cloned(), + Victim::Guest(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)), + }; + let refused = !(self.ui.rules.bool("pvp") + && horizon_client::scoreboard::teams_allow_damage(target.as_ref(), attacker.as_ref())); + let on_player = Hit::Entity { + who: Who::Player, + at, + }; + let result = match victim { + Victim::Host => { + self.lan = Some(host); + self.combat.refuse_player_hit = refused; + let r = self.projectile_hit(p, on_player); + self.combat.refuse_player_hit = false; + return r; + } + Victim::Guest(conn) => self.guest_hit_by(&mut host, conn, |g| { + g.combat.refuse_player_hit = refused; + let r = g.projectile_hit(p, on_player); + g.combat.refuse_player_hit = false; + r + }), + }; + self.lan = Some(host); + result.unwrap_or(Ok(())) + } + /// The hit landing on the victim with its extra knockback, then the /// attacker's attack sound. Whether the victim was hurt. pub(super) fn pvp_land(&mut self, host: &mut LanHost, victim: Victim, s: &Strike) -> bool { diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index 9df5311aa..6280959d8 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -6,7 +6,7 @@ use horizon_client::{ items::ItemStack, mobs::{Species, Who, piglin::ADMIRE}, }; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { fn piglin_loved(&self, item: &str) -> bool { @@ -132,12 +132,29 @@ impl Game<'_> { } else { vec![ItemStack::new(&item, 1)] }; - // BehaviorUtils.throwItem toward the nearest visible player, else nearby. - let target = self + // BehaviorUtils.throwItem toward the nearest visible player + // (NEAREST_VISIBLE_PLAYER: within 16, alive, no spectators; the + // guests count as much as the host), else nearby. + let at = m.position; + let host = self .player .as_ref() - .filter(|p| p.position.distance_squared(m.position) < 256.0) - .map(|p| [p.position.x, p.position.y + 1.0, p.position.z]); + .filter(|p| !p.health.dead_or_dying() && !self.spectator()) + .map(|p| [p.position.x, p.position.y, p.position.z]); + let guests = self.lan.iter().flat_map(|h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g) && g.loaded && !g.dead && !g.spectator()) + .map(|g| g.position) + }); + let d = |p: &[f64; 3]| at.distance_squared(Vec3::new(p[0], p[1], p[2])); + let target = host + .into_iter() + .chain(guests) + .filter(|p| d(p) < 256.0) + .min_by(|a, b| d(a).total_cmp(&d(b))) + .map(|p| [p[0], p[1] + 1.0, p[2]]); for stack in items { let to = target.unwrap_or_else(|| { let r = &mut self.world.random; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 17c6e0299..5b8072d7f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3244,7 +3244,11 @@ impl Game<'_> { .and_then(|h| self.res.items().get(&h.item)) .is_some_and(|i| i.block.is_some()); if let Some(hit) = self.pick() { - let reacts = hand == Hand::Main && self.remote_block_reacts(&hit, held.as_ref()); + let (reacts, changes) = if hand == Hand::Main { + self.remote_block_reacts(&hit, held.as_ref()) + } else { + (false, DryUse::default()) + }; let seq = self.next_sequence(); let cursor = [ (hit.point[0] - f64::from(hit.pos[0])) as f32, @@ -3270,6 +3274,9 @@ impl Game<'_> { r.use_target = Some(hit.pos); r.placing = Some((target, ticks)); } + if reacts { + self.predict_use(&changes, seq); + } if held_block { self.with_hand(hand, Game::swing_arm); return true; @@ -3279,15 +3286,61 @@ impl Game<'_> { false } + /// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the + /// use changed on this client's level at once, each kept as predicted + /// under the use's sequence until the server acknowledges it (a use the + /// server refused goes back). Only the blocks a hand opens or flips: a + /// wooden or copper door, trapdoor or fence gate, a lever or a button; + /// whatever else the use changes waits for the server. + fn predict_use(&mut self, (changes, sounds): &DryUse, seq: i32) { + let facts = self.res.facts(); + let predicted = |state: BlockStateId| hand_operated(&facts.get(state).name); + if changes.is_empty() + || !changes + .iter() + .all(|(p, s)| predicted(*s) && predicted(self.world.block(p.x, p.y, p.z))) + { + return; + } + for &(p, state) in changes { + let pos = [p.x, p.y, p.z]; + let before = self.world.block(p.x, p.y, p.z); + // BlockStatePredictionHandler.retainKnownServerState. + if let Some(r) = self.remote.as_mut() { + r.predictions + .entry(pos) + .and_modify(|e| e.0 = seq) + .or_insert((seq, before.0 as i32)); + } + self.set_block(pos, state.0 as i32); + } + // `level.playSound(player, ...)`: the clicker hears it from its own use; the + // server sends it to the others only. + for (pos, sound, volume, pitch) in sounds { + let at = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 0.5, + f64::from(pos.z) + 0.5, + ]; + let name = if sound.contains(':') { + sound.to_string() + } else { + format!("minecraft:{sound}") + }; + self.audio.play(&name, Some(at), *volume, *pitch); + } + } + /// Whether the block hit takes a main-hand right click with `held` /// (`BlockState.useItemOn`, then `useWithoutItem`): a door, a button, a - /// container. Vanilla's client runs it on its own level first; this runs - /// it on a copy that keeps no change. - fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> bool { + /// container, and the blocks it changed. Vanilla's client runs it on its + /// own level first; this runs it on a copy, and `predict_use` keeps the + /// changes it predicts. + fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> (bool, DryUse) { // Player.isSecondaryUseActive with something in either hand. let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some(); if self.keys.contains(&KeyCode::ShiftLeft) && hands_full { - return false; + return (false, DryUse::default()); } use horizon_core::geometry::Direction; let face = match hit.face { @@ -3302,8 +3355,10 @@ impl Game<'_> { world: &self.world, changed: HashMap::new(), random: horizon_core::random::LegacyRandom::new(0), + sounds: Vec::new(), }; - self.res + let reacts = self + .res .behaviours() .use_item_on( &mut level, @@ -3314,7 +3369,8 @@ impl Game<'_> { self.use_context(), held.map(|s| &*s.item), ) - .consumes_action() + .consumes_action(); + (reacts, (level.changed.into_iter().collect(), level.sounds)) } /// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether @@ -3336,6 +3392,16 @@ impl Game<'_> { // MultiPlayerGameMode.useItem runs the use here too: food starts // being eaten (Consumable.startConsuming). self.with_hand(hand, |g| g.start_eating(&info)); + // BowItem.use: startUsingItem here too (with an arrow, or in creative), so that letting + // go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and the server shoots. + if &*held.item == "minecraft:bow" { + self.with_hand(hand, |g| { + if g.using.is_none() && (g.creative || g.projectile_slot("minecraft:bow").is_some()) + { + g.using = Some((g.held_slot(), 0)); + } + }); + } item_has_use(&info) } @@ -3351,14 +3417,20 @@ impl Game<'_> { } self.remote_use_item(Hand::Off); } - /// `LivingEntity.updatingUsingItem` for a consumable on a server client: the - /// eating animation and its crumbs. The server eats it and sends the - /// stack, the hunger and the sounds. + /// `LivingEntity.updatingUsingItem` on a server client: a drawn bow, and a + /// consumable's eating animation and its crumbs. The server eats it and + /// sends the stack, the hunger and the sounds. fn remote_tick_using(&mut self) { let Some((slot, ticks)) = self.using else { return; }; let stack = self.stack_in(slot).cloned(); + // A drawn bow: held until the button lets go (or another slot is picked). + if stack.as_ref().is_some_and(|s| &*s.item == "minecraft:bow") { + self.using = (slot == self.selected || slot == super::shield::OFFHAND_SLOT) + .then_some((slot, ticks + 1)); + return; + } let consumable = stack .as_ref() .and_then(|s| self.res.items().get(&s.item)) @@ -3468,7 +3540,18 @@ impl Game<'_> { return true; } let mut instant = false; - if let Some((i, distance)) = self.mob_hit() + // A ghast's fireball or a wind charge nearer than any mob: the + // server turns it (game/deflect.rs). + if let Some((i, distance)) = self.redirectable_hit() + && self.mob_hit().is_none_or(|(_, d)| distance <= d) + && self.before_block(distance) + && self.creatures.projectiles[i].id != 0 + { + self.send(S::Attack(play::Attack { + id: self.creatures.projectiles[i].id as i32, + })); + self.reset_attack_strength(); + } else if let Some((i, distance)) = self.mob_hit() && self.before_block(distance) { self.send(S::Attack(play::Attack { @@ -4216,9 +4299,45 @@ struct DryLevel<'w> { world: &'w horizon_client::world::World, changed: HashMap, random: horizon_core::random::LegacyRandom, + /// The sounds the use plays (a door's creak). + sounds: Vec, +} + +type DrySound = ( + horizon_core::position::BlockPos, + std::sync::Arc, + f32, + f32, +); +/// What a use on the dry level changed, and the sounds it played. +type DryUse = ( + Vec<(horizon_core::position::BlockPos, BlockStateId)>, + Vec, +); + +/// The blocks a guest's hand flips that its use predicts (and hears at once): a wooden or +/// copper door, trapdoor or fence gate, a lever or a button. An iron door or trapdoor has +/// no hand use. +pub(super) fn hand_operated(name: &str) -> bool { + let name = name.trim_start_matches("minecraft:"); + ((name.ends_with("_door") || name.ends_with("_trapdoor")) && !name.starts_with("iron_")) + || name.ends_with("_fence_gate") + || name.ends_with("_button") + || name == "lever" } impl horizon_world::level::LevelAccess for DryLevel<'_> { + fn emit(&mut self, event: horizon_world::level::LevelEvent) { + if let horizon_world::level::LevelEvent::Sound { + pos, + sound, + volume, + pitch, + } = event + { + self.sounds.push((pos, sound, volume, pitch)); + } + } fn block_state(&self, pos: horizon_core::position::BlockPos) -> BlockStateId { self.changed .get(&pos) diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 890e571b8..d71cd5431 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -665,7 +665,7 @@ impl Game<'_> { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { m.damage(amount, horizon_client::mobs::Damage::player(at)); } - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } "set" => { let n = |i: usize| words[i].parse::().unwrap_or(0); diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 355b5b877..72e6ee0e8 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -131,7 +131,7 @@ impl Game<'_> { m.damage(1.0, source); } if p.owner == Some(Who::Player) { - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index c8155984c..28bcadeed 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1623,13 +1623,18 @@ impl Mob { if !self.alive() || self.removed || self.invulnerable_flag { return false; } - if source.is_fire() && (self.kind.flags.fire_immune) { + // Ghast.isReflectedFireball: a fireball a player turned back is + // no fire to it, and kills it (Ghast.hurtServer: 1000 damage). + let reflected = &*self.kind.id == "minecraft:ghast" + && source.kind == DamageKind::Fireball + && source.attacker == Some(Who::Player); + if source.is_fire() && (self.kind.flags.fire_immune) && !reflected { return false; } if !ai::accepts_damage(self, &source, amount) { return false; } - let mut amount = amount; + let mut amount = if reflected { 1000.0 } else { amount }; if source.kind == DamageKind::FallingBlock && !species::body_slot(self.species()) && self.extra.head.is_some() diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0b40e55e4..4a149ba03 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -20,6 +20,10 @@ address. The script then checks, from both sides, what a guest's game used to ge drowning and the void (then respawns); - pvp: the guest and the host hit each other with a sword; with the pvp game rule off, or on one team without friendly fire, nothing; +- kills: a pig the guest kills counts in the guest's killed statistic, not the host's (#484); + + +- arrows: the guest and the host shoot each other with a bow; with the pvp game rule off, nothing (#484); - respawn: a player killed is drawn dead by the other side, and alive again once it respawns (the respawned player is a new entity to the others); the host dies, and on the server thread the guest too; @@ -52,6 +56,9 @@ address. The script then checks, from both sides, what a guest's game used to ge its crafting grid and gathers a stack with a double click; the server has each. - sleep: at night the guest lies down in its own bed (not the host); alone it stays night, it gets up with Escape, and once the host sleeps too the night ends and both wake. +- predict: with the host frozen, the oak door the guest opens opens on the guest's screen at once (its + prediction) and creaks there at once, stays open once the server answers, and each side hears + it once; an iron door stays shut (#869). - push: a cow standing in the guest pushes it just clear of the cow (the guest's own client pushes it, as in vanilla), not ever faster across the ground. - eat: holding right click with bread, the guest's own screen plays the eating (the item in use @@ -64,6 +71,17 @@ 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. +- fireball: a fire charge a dispenser shoots onto stone lights a fire both sides see, and the fire + goes out on its own within a minute (it ticks: FireBlock.tick on a floor that doesn't burn) + + +- blast: primed TNT going off beside a guest in survival hurts the guest and pushes it away + (ServerExplosion.hurtEntities takes every player); facing it behind a raised shield, the + guest takes nothing. + + +- worn: iron armour the guest puts on in its inventory protects it: a 10-damage blow takes 6 + (armour 15, LivingEntity.getDamageAfterArmorAbsorb), and the full 10 without it. - plates: a stone pressure plate the guest steps on is pressed on both sides, and comes up once 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 @@ -91,6 +109,7 @@ macOS both games render offscreen. Games started here have no audio (HORIZON_NO_ """ import argparse import json +import math import os import re import shutil @@ -111,7 +130,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', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -607,12 +626,76 @@ def check_pvp(host, guest, out): host('command', command='team remove parity_allies') assert hits['guest hits host'][1] < hits['guest hits host'][0], f'the guest did not hurt the host: {hits}' assert hits['host hits guest'][1] < hits['host hits guest'][0], f'the host did not hurt the guest: {hits}' - assert hits['pvp off'][1] == hits['pvp off'][0], f'pvp off still hurts: {hits}' + # Natural regeneration may heal the victim meanwhile. + assert hits['pvp off'][1] >= hits['pvp off'][0], f'pvp off still hurts: {hits}' for name in ('guest hits teammate', 'host hits teammate'): assert hits[name][1] == hits[name][0], f'friendly fire off still hurts ({name}): {hits}' return hits +def check_kills(host, guest, out): + # A mob the guest kills is the guest's kill (#484): LivingEntity.die credits lastHurtByPlayer, so the + # killed statistic (and its scoreboard criterion) counts for the guest, not the host. + host('command', command='scoreboard objectives add parity_kills minecraft.killed:minecraft.pig') + for g in (host, guest): + g('command', command='gamemode survival') + guest('command', command='item replace entity @s weapon.mainhand with minecraft:iron_sword') + face_each_other(host, guest) + hx, hy, hz = pos_of(host) + try: + # Between the two, in front of the guest, with one health left. + host('command', command=f'summon minecraft:pig {hx + 1.5:.2f} {hy:.2f} {hz:.2f} {{NoAI:1b,Health:1.0f}}') + guest.wait(30) + guest.raw('look-at', f'{hx + 1.5:.2f}', f'{hy + 0.5:.2f}', f'{hz:.2f}') + guest.wait(10) + guest.raw('attack') + guest.wait(20) + host('command', command=f'scoreboard players get {GUEST_NAME} parity_kills') + host('command', command=f'scoreboard players get {host.player} parity_kills') + host.wait(10) + chat = host.raw('messages', 10)['chat'] + guest.shot(out, 'kills') + finally: + host('command', command='kill @e[type=minecraft:pig]') + host('command', command='scoreboard objectives remove parity_kills') + assert any(f'{GUEST_NAME} has 1 [parity_kills]' in line for line in chat), f"the guest's kill is not theirs: {chat}" + assert not any(f'{host.player} has 1 [parity_kills]' in line for line in chat), f"the host got the guest's kill: {chat}" + return chat + + +def check_arrows(host, guest, out): + # A player's arrow on another player (#484): AbstractArrow.onHitEntity, refused by + # ServerPlayer.canHarmPlayer with the pvp game rule off (the arrow turns back). + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='clear @s') + g('command', command='item replace entity @s weapon.mainhand with minecraft:bow') + g('command', command='give @s minecraft:arrow 16') + hits = {} + try: + for name, rule, shooter in (('guest shoots host', 'true', guest), ('host shoots guest', 'true', host), + ('pvp off', 'false', guest)): + host('command', command=f'gamerule pvp {rule}') + for g in (host, guest): + g('command', command='effect give @s minecraft:instant_health 1 5') + face_each_other(host, guest) + shooter.wait(20) + victim = (lambda: host('state')['player']['health']) if shooter is guest else (lambda: remote(guest)['health']) + before = victim() + shooter.raw('use-item', '--hold', 1.3) # a full draw (BowItem: 20 ticks) + shooter.wait(20) + hits[name] = (before, victim()) + shooter.shot(out, 'arrows-' + name.replace(' ', '-')) + finally: + host('command', command='gamerule pvp true') + for g in (host, guest): + g('command', command='clear @s') + assert hits['guest shoots host'][1] < hits['guest shoots host'][0], f"the guest's arrow did not hurt the host: {hits}" + assert hits['host shoots guest'][1] < hits['host shoots guest'][0], f"the host's arrow did not hurt the guest: {hits}" + assert hits['pvp off'][1] >= hits['pvp off'][0], f'pvp off, an arrow still hurts: {hits}' + return hits + + def dead_players(game, want, ticks=60): """The other players `game`'s client draws dead, once that is `want` (empty or not) or after `ticks`.""" for _ in range(ticks // 5): @@ -1255,6 +1338,50 @@ def check_sleep(host, guest, out): assert lying['host'] and lying['guest'], f'a sleeping player is drawn standing: {detail}' assert not lying['after'], f'a player up again is still drawn lying: {detail}' return detail +def check_predict(host, guest, out): + # MultiPlayerGameMode.useItemOn under startPrediction (#869): the guest's door opens on its own screen + # at once, with the host (the server) frozen, and the server's answer later agrees; an iron door + # (no hand use) stays shut on both sides. + guest('command', command='gamemode survival') + guest('command', command='clear @s') + x, y, z = (int(v // 1) for v in pos_of(guest)) + wood, iron = (x - 1, y, z + 2), (x + 1, y, z + 2) + for (bx, by, bz), kind in ((wood, 'oak_door'), (iron, 'iron_door')): + for half, dy in (('lower', 0), ('upper', 1)): + host('command', command=f'setblock {bx} {by + dy} {bz} minecraft:{kind}[facing=north,hinge=right,half={half}]') + guest.wait(20) + state = lambda game, at: game.raw('block', *at)['state'] + seen = {} + creaks = lambda game: sum(n for s, n in game('status')['heard'].items() if 'door' in s) + heard = {'guest': creaks(guest), 'host': creaks(host)} + os.kill(host.pid, signal.SIGSTOP) + try: + guest.raw('interact', *wood) + seen['guest_frozen'] = (state(guest, wood), state(guest, (wood[0], wood[1] + 1, wood[2]))) + # level.playSound(player, ...): the clicker hears its own door at once. + seen['guest_heard_frozen'] = creaks(guest) - heard['guest'] + guest.raw('interact', *iron) + seen['guest_iron_frozen'] = state(guest, iron) + finally: + os.kill(host.pid, signal.SIGCONT) + guest.wait(20) + seen['guest_after'] = state(guest, wood) + seen['host_after'] = state(host, wood) + seen['iron_after'] = (state(guest, iron), state(host, iron)) + # ... and not a second time from the server; the host hears it once. + seen['heard_after'] = {'guest': creaks(guest) - heard['guest'], 'host': creaks(host) - heard['host']} + guest.shot(out, 'predict') + for (bx, by, bz) in (wood, iron): + host('command', command=f'fill {bx} {by} {bz} {bx} {by + 1} {bz} minecraft:air') + assert all('open=true' in s for s in seen['guest_frozen']), f'the door waited for the server: {seen}' + assert 'open=true' in seen['guest_after'] and 'open=true' in seen['host_after'], f'the door did not stay open: {seen}' + assert 'open=false' in seen['guest_iron_frozen'], f'the guest opened an iron door by hand: {seen}' + assert all('open=false' in s for s in seen['iron_after']), f'an iron door opened: {seen}' + assert seen['guest_heard_frozen'] == 1 and seen['heard_after'] == {'guest': 1, 'host': 1}, \ + f'the door is not heard once on each side: {seen}' + return seen + + def check_push(host, guest, out): guest('command', command='gamemode survival') x, y, z = (int(v // 1) + 0.5 for v in pos_of(guest)) @@ -1584,6 +1711,56 @@ def check_projectiles(host, guest, out): return f'{len(theirs)} identical, fuses (host, guest) {fuses}' +def check_blast(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + host('command', command='gamemode creative') + x, y, z = (int(v // 1) for v in pos_of(host)) + gx, gz = x + 6, z + floor = f'fill {gx - 6} {y - 1} {gz - 4} {gx + 6} {y - 1} {gz + 4} minecraft:bedrock' + detail = {} + try: + for shielded in (False, True): + if remote(guest)['health'] <= 0: + guest.raw('respawn') + guest.wait(40) + host('command', command=floor) + host('command', command=f'fill {gx - 6} {y} {gz - 4} {gx + 6} {y + 3} {gz + 4} minecraft:air') + guest('command', command=f'tp @s {gx + 0.5} {y} {gz + 0.5}') + guest('command', command='effect give @s minecraft:instant_health 1 5') + guest.wait(30) + hold = None + if shielded: + guest('command', command='item replace entity @s weapon.offhand with minecraft:shield') + guest.wait(5) + guest.raw('look-at', gx + 5.5, y + 0.5, gz + 0.5) + hold = threading.Thread(target=guest.raw, args=('use-item', '--hold', 2.5)) + hold.start() + time.sleep(0.5) + before = remote(guest)['health'] + at = pos_of(guest) + # Five blocks off: a blast that hurts without killing (about 14 at full exposure). + host('command', command=f'summon minecraft:tnt {gx + 5.5} {y} {gz + 0.5} {{fuse:10s}}') + # The guest's own controller is busy holding the shield up: the host waits. + host.wait(14) + after = remote(guest)['health'] + moved = pos_of(guest) + if hold: + hold.join() + guest.shot(out, f'blast-{"shield" if shielded else "open"}') + detail['shield' if shielded else 'open'] = { + 'before': before, 'after': after, 'pushed': round(at[0] - moved[0], 2)} + finally: + host('command', command='gamemode survival') + guest('command', command='clear @s') + host('command', command=floor) + open_, shield = detail['open'], detail['shield'] + assert open_['after'] < open_['before'], f'the blast never hurt the guest: {detail}' + assert open_['pushed'] > 0, f'the blast never pushed the guest away: {detail}' + assert shield['after'] >= shield['before'], f'the shield did not stop the blast: {detail}' + return detail + + def light_differences(host, guest, lo, hi): """Positions of the box loaded on both sides, and those whose sky or block light differ.""" h, g = host.raw('light', *lo, *hi), guest.raw('light', *lo, *hi) @@ -1697,6 +1874,203 @@ def check_light(host, guest, out): return results +def check_fireball(host, guest, out): + x, y, z = (int(v // 1) for v in pos_of(host)) + fx, fz = x + 4, z + # A stone floor, a dispenser facing down three blocks over it, a fire charge in it, powered. + host('command', command=f'fill {fx - 2} {y - 1} {fz - 2} {fx + 2} {y - 1} {fz + 2} minecraft:stone') + host('command', command=f'fill {fx - 2} {y} {fz - 2} {fx + 2} {y + 4} {fz + 2} minecraft:air') + host('command', command=f'setblock {fx} {y + 3} {fz} minecraft:dispenser[facing=down]') + host('command', command=f'item replace block {fx} {y + 3} {fz} container.0 with minecraft:fire_charge') + seen, gone = {}, None + try: + host('command', command=f'setblock {fx} {y + 4} {fz} minecraft:redstone_block') + host.wait(10) + seen = {'host': host.raw('block', fx, y, fz).get('block'), + 'guest': guest.raw('block', fx, y, fz).get('block')} + # FireBlock.tick every 30-39 ticks ages it by one a third of the time; past age 3 it goes. + for waited in range(40, 1240, 40): + host.wait(40) + if host.raw('block', fx, y, fz).get('block') == 'minecraft:air': + gone = waited + break + guest.wait(5) + seen['guest_after'] = guest.raw('block', fx, y, fz).get('block') + finally: + host('command', command=f'fill {fx - 2} {y} {fz - 2} {fx + 2} {y + 4} {fz + 2} minecraft:air') + assert seen.get('host') == 'minecraft:fire' and seen.get('guest') == 'minecraft:fire', \ + f'no fire where the fire charge landed: {seen}' + assert gone is not None, f'the fire on stone never went out (1200 ticks): {seen}' + assert seen['guest_after'] == 'minecraft:air', f'the guest still sees the fire: {seen}' + return {'out_after_ticks': gone, **seen} + + +def check_deflect(host, guest, out): + """The host punches a ghast's fireball back: it flies along the host's view and kills the ghast + (Player.attack: AIM_DEFLECT on #redirectable_projectile; Ghast.isReflectedFireball). The ghast is caged + (a window toward the host); the game runs at 4 ticks a second, and once the fireball is within 4.5 blocks + the host looks at the ghast and clicks.""" + if SERVER_THREAD: + # The fireball's position and the host's hurts are read from the host's own level. + return 'skipped (in-frame only)' + x, y, z = (int(v // 1) for v in pos_of(host)) + guest('command', command='gamemode creative') + host('command', command='gamemode survival') + host('command', command='difficulty normal') + gx, gz = x, z + 30 + gy = y + 20 + host('command', command=f'fill {gx - 3} {gy - 1} {gz - 3} {gx + 24} {gy - 1} {gz + 3} minecraft:glass') + host('command', command=f'fill {gx - 3} {gy} {gz - 3} {gx + 24} {gy + 8} {gz + 3} minecraft:air') + host('command', command=f'tp @s {gx + 0.5} {gy} {gz + 0.5} -90 0') + host.wait(20) + host.raw('hurtlog') + # The ghast in a glass cage it can't drift out of, a 3 x 3 window toward the host. + host('command', command=f'fill {gx + 13} {gy} {gz - 3} {gx + 19} {gy + 6} {gz + 3} minecraft:glass hollow') + host('command', command=f'fill {gx + 13} {gy + 2} {gz - 1} {gx + 13} {gy + 4} {gz + 1} minecraft:air') + host('command', command=f'summon minecraft:ghast {gx + 16.5} {gy + 1} {gz + 0.5}') + eye = (gx + 0.5, gy + 1.62, gz + 0.5) + host('command', command='tick rate 4') + turned, near, ghast, hurt = None, None, None, [] + try: + deadline = time.monotonic() + 120 + while time.monotonic() < deadline: + balls = [q for q in host.raw('status')['projectiles'] if q['kind'] == 'LargeFireball'] + near = min((math.dist(q['position'], eye) for q in balls), default=None) + if near is not None and near < 4.5: + g = [m['pos'] for m in host.raw('mobs', 60).get('near', []) if m['kind'].endswith('ghast')][0] + host.raw('look-at', f'{g[0]:.2f}', f'{g[1] + 2:.2f}', f'{g[2]:.2f}') + host.raw('mouse', 'left', 'down') + host.raw('mouse', 'left', 'up') + turned = near + break + host('command', command='tick rate 20') + host.wait(60) + ghast = [m for m in host.raw('mobs', 60).get('near', []) if m['kind'].endswith('ghast') and m['health'] > 0] + hurt = [h for pl in host.raw('hurtlog')['players'] if pl['name'] == 'host' for h in pl['hurts'] + if 'fireball' in h['source'] or 'explosion' in h['source']] + finally: + host('command', command='tick rate 20') + host('command', command='kill @e[type=minecraft:ghast]') + host('command', command=f'fill {gx - 3} {gy - 1} {gz - 3} {gx + 24} {gy + 8} {gz + 3} minecraft:air') + guest('command', command='gamemode survival') + assert turned is not None, f'no fireball came within 4.5 blocks (nearest {near})' + assert not hurt, f'the host was hit: {hurt}' + assert not ghast, f'the ghast lived: the fireball was not turned back ({ghast})' + return {'struck_at': round(turned, 2)} + + +def check_barter(host, guest, out): + """The guest, in gold boots, drops a gold ingot to a piglin: the piglin stays calm, takes it, and throws its + barter toward the nearest player, the guest (PiglinAi.throwItemsTowardPlayer: NEAREST_VISIBLE_PLAYER), who + picks it up. The host is nearby on the other side, so a barter thrown at the host misses the guest. A glass + corridor (the hollow box) keeps the piglin between them.""" + x, y, z = (int(v // 1) for v in pos_of(host)) + cz = z + 4 + host('command', command='gamemode creative') + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='effect give @s minecraft:instant_health 1 5') + host('command', command=f'fill {x + 1} {y - 1} {cz - 1} {x + 8} {y + 2} {cz + 1} minecraft:glass hollow') + host('command', command=f'fill {x + 2} {y - 1} {cz} {x + 7} {y - 1} {cz} minecraft:stone') + host('command', command=f'tp @s {x - 0.5} {y} {cz + 0.5} -90 0') + guest('command', command=f'tp @s {x + 7.3} {y} {cz + 0.5} 90 30') + guest('command', command='item replace entity @s armor.feet with minecraft:golden_boots') + guest('command', command='give @s minecraft:gold_ingot 1') + host('command', command=f'summon minecraft:piglin {x + 4.5} {y} {cz + 0.5} {{IsImmuneToZombification:1b}}') + guest.wait(20) + before = remote(guest)['health'] + kept = dict(guest('inventory')['counts']) + try: + guest.raw('select', 'minecraft:gold_ingot') + guest.raw('key', 'q', 'tap') + bought, trace = {}, [] + for _ in range(20): + guest.wait(20) + trace.append([(e['type'].split(':')[-1], round(e['pos'][0] - x, 1), round(e['pos'][2] - cz, 1)) + for e in host.raw('entities', 24)['entities'] if e['type'] in ('minecraft:item', 'minecraft:piglin')]) + counts = guest('inventory')['counts'] + bought = {k: n - kept.get(k, 0) for k, n in counts.items() + if k not in ('minecraft:gold_ingot', 'minecraft:golden_boots') and n > kept.get(k, 0)} + if bought: + guest.wait(40) + break + counts = guest('inventory')['counts'] + bought = {k: n - kept.get(k, 0) for k, n in counts.items() + if k not in ('minecraft:gold_ingot', 'minecraft:golden_boots') and n > kept.get(k, 0)} + piglins = [m for m in host.raw('mobs', 20).get('near', []) if m['kind'].split(':')[-1] == 'piglin'] + health = remote(guest)['health'] + finally: + host('command', command=f'kill @e[type=minecraft:piglin,x={x},y={y - 2},z={cz - 2},dx=10,dy=6,dz=4]') + # What lies on the floor, on the host's side of the piglin's start and on the guest's. + floor = [host('command', command=f'kill @e[type=minecraft:item,x={x0},y={y - 2},z={cz - 3},dx={dx},dy=6,dz=6]') + ['chat'][0] for x0, dx in ((x - 2, 6.5), (x + 4.5, 6))] + host('command', command=f'fill {x + 1} {y - 1} {cz - 1} {x + 8} {y + 2} {cz + 1} minecraft:air') + host('command', command=f'fill {x - 8} {y - 1} {z - 8} {x + 8} {y - 1} {z + 8} minecraft:stone') + guest('command', command='clear @s') + host('command', command='gamemode survival') + assert piglins, 'the piglin is gone' + assert health >= before, f'the piglin hurt the guest in gold boots: {before} -> {health}' + assert bought, f'no barter reached the guest (on the floor, host side then guest side: {floor}; items and the piglin, every second: {trace})' + return {'bought': bought, 'floor': floor} + + +def check_worn(host, guest, out): + pieces = ['iron_helmet', 'iron_chestplate', 'iron_leggings', 'iron_boots'] + guest('command', command='gamemode survival') + taken = {} + try: + for worn in (False, True): + guest('command', command='clear @s') + if remote(guest)['health'] <= 0: + guest.raw('respawn') + guest.wait(40) + if worn: + for piece in pieces: + guest('command', command=f'give @s minecraft:{piece}') + guest.wait(10) + # Shift-clicked from the hotbar onto the body in the inventory menu (the hub moves them). + guest.raw('key', 'e', 'tap') + guest.raw('wait-for', 'screen', 'inventory') + for piece in pieces: + guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{piece}'), 'shift') + guest.wait(2) + guest.raw('key', 'esc', 'tap') + guest.wait(5) + guest('command', command='effect give @s minecraft:instant_health 1 5') + guest.wait(30) + before = remote(guest)['health'] + if not SERVER_THREAD: + host.raw('hurtlog') + # A mob's blow (no attacker: no difficulty scaling); armour counts against it. + guest('command', command='damage @s 10 minecraft:mob_attack') + if SERVER_THREAD: + # The server's hurt log isn't on a control socket here: the health the guest is + # sent, read as soon as it drops (natural regeneration heals it again after). + health = before + for _ in range(40): + guest.wait(1) + health = remote(guest)['health'] + if health < before: + break + taken['worn' if worn else 'bare'] = [round(before - health, 2)] + continue + guest.wait(10) + log = [h for p in host.raw('hurtlog')['players'] if p['name'] == GUEST_NAME for h in p['hurts']] + taken['worn' if worn else 'bare'] = [(h['amount'], h['armor'], round(h['taken'], 2)) for h in log] + finally: + guest('command', command='clear @s') + guest('command', command='effect give @s minecraft:instant_health 1 5') + if SERVER_THREAD: + # Natural regeneration may heal up to a point before the health arrives. + assert len(taken['bare']) == 1 and 9.0 <= taken['bare'][0] <= 10.0, f'10 damage on no armour: {taken}' + assert len(taken['worn']) == 1 and 5.0 <= taken['worn'][0] <= 6.0, \ + f'10 damage through iron armour (15) should take 6: {taken}' + return taken + assert taken['bare'] == [(10.0, 0.0, 10.0)], f'10 damage on no armour: {taken}' + assert taken['worn'] == [(10.0, 15.0, 6.0)], f'10 damage through iron armour (15) should take 6: {taken}' + return taken + + 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, @@ -1709,10 +2083,10 @@ 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, 'distance': check_distance, 'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'eating': check_eating, - 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, + 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth} + 'time': check_time, 'growth': check_growth, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict} def run(ctl, out, resources, checks): @@ -1721,7 +2095,7 @@ def run(ctl, out, resources, checks): host.d.env['HORIZON_SERVER_THREAD'] = '1' results = {} try: - host('launch', wait=False, offscreen=sys.platform == 'darwin') + host.pid = host('launch', wait=False, offscreen=sys.platform == 'darwin')['pid'] # Guests' commands need the world's Allow Commands as well as the LAN's (#372): a creative # world has them; everyone plays in survival. host.raw('open', 'Lan', 5, 'creative')