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/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 218d9e85c..f67a7960a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1393,7 +1393,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 @@ -1631,14 +1632,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))); } @@ -1690,6 +1707,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. 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/tools/lan_e2e.py b/tools/lan_e2e.py index 0b40e55e4..699de83f8 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -20,6 +20,7 @@ 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; +- 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; @@ -111,7 +112,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', '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: @@ -613,6 +614,39 @@ def check_pvp(host, guest, out): return hits +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): @@ -1712,7 +1746,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth} + 'time': check_time, 'growth': check_growth, 'arrows': check_arrows} def run(ctl, out, resources, checks):