Merge remote-tracking branch 'origin/fix/lan-player-arrows-hit-players' into integ/b5-lan-rest

# Conflicts:
#	tools/lan_e2e.py
This commit is contained in:
Ludovic Marie
2026-10-22 06:17:27 +02:00
5 changed files with 187 additions and 9 deletions
+3
View File
@@ -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<u32>,
/// 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<u32>,
+24 -2
View File
@@ -1415,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
@@ -1653,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)));
}
@@ -1712,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.
+101 -1
View File
@@ -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<Victim> {
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 {
+19 -3
View File
@@ -3336,6 +3336,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 +3361,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))
+40 -3
View File
@@ -21,6 +21,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
- 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;
@@ -124,7 +127,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', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', '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', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth']
class Game:
@@ -620,7 +623,8 @@ 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
@@ -656,6 +660,39 @@ def check_kills(host, guest, out):
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):
@@ -2002,7 +2039,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name
'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, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills}
'time': check_time, 'growth': check_growth, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows}
def run(ctl, out, resources, checks):