Files
horizon-airdef/crates/horizon-client/src/lan/guest.rs
T
Ludovic Marie 76e659c74b LAN: players see each other use items (eating, bows, shields)
Neither side sent LivingEntity.DATA_LIVING_ENTITY_FLAGS for players, so
no one saw another player eat, draw a bow or raise a shield. The host now
sends the item in use and its hand for itself and every guest (always:
the trackers send only the entries that changed, and stopping is a change
back to 0), and draws its guests' bodies using their items. A guest's
client starts and stops the other players' item use from the flags and
drops their eating crumbs at their mouth (Consumable.onConsumeTick); the
eating sounds already come from the server.

lan_e2e.py eating: the host and the guest each see the other eat bread,
and stop.

Part of #803

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 16:41:06 +02:00

418 lines
15 KiB
Rust

//! A remote player: connection, position, chunk and entity views, and the
//! player state (inventory, health, game mode) that the host's gameplay code
//! operates on when it acts for them.
use super::{Joined, PlayerSender, entity::Tracker};
use crate::{items::ItemStack, motion::PlayerMotion};
use horizon_protocol::{
item::Stack,
packets::{configuration::ClientInformation, play},
};
use std::{
collections::VecDeque,
sync::{Arc, atomic::AtomicI32},
};
/// GameType ids.
pub const SURVIVAL: i32 = 0;
pub const CREATIVE: i32 = 1;
pub const ADVENTURE: i32 = 2;
pub const SPECTATOR: i32 = 3;
/// An effect as last sent in ClientboundUpdateMobEffectPacket.
#[derive(Clone, Debug, PartialEq)]
pub struct SentEffect {
pub id: &'static str,
pub amplifier: i32,
pub flags: i8,
pub duration: i32,
pub tick_count: i32,
}
pub struct Guest {
pub conn: u32,
/// The client's address (IP bans, `list`).
pub address: std::net::SocketAddr,
/// The hub tick of the player's last action (ServerPlayer.lastActionTime),
/// for player-idle-timeout.
pub last_action_tick: u64,
/// The next ClientboundPlayerChatPacket.globalIndex for this connection.
pub chat_index: i32,
/// Secure chat (ServerGamePacketListenerImpl): the player's message
/// chain, keyed once it sends a chat session; the messages its
/// acknowledgements cover; the signatures its client caches.
pub chain: horizon_protocol::secure_chat::Chain,
pub last_seen: horizon_protocol::secure_chat::LastSeenValidator,
pub signatures: horizon_protocol::secure_chat::SignatureCache,
/// The hub tick the player was placed on: chunks go out from the tick
/// after next, behind the first doTick's packets, as vanilla's do.
pub placed_at: u64,
/// The chunk cache centre placeNewPlayer already sent.
pub center_sent: Option<(i32, i32)>,
/// Why the connection closed (the console's "lost connection").
pub left_reason: String,
pub uuid: u128,
pub name: String,
/// The profile's properties, for the player list (skins).
pub properties: Vec<horizon_protocol::packets::login::Property>,
pub entity_id: i32,
pub sender: PlayerSender,
pub latency: Arc<AtomicI32>,
pub info: ClientInformation,
pub brand: String,
/// The chunk radius this client is sent.
pub view_distance: i32,
pub position: [f64; 3],
pub previous_position: [f64; 3],
pub yaw: f32,
pub pitch: f32,
pub head_yaw: f32,
pub on_ground: bool,
pub game_mode: i32,
/// The permission level (0 none, 2 game masters, 4 owners).
pub permission: u8,
pub sneaking: bool,
pub sprinting: bool,
pub fall_flying: bool,
pub flying: bool,
pub sleeping: bool,
/// `LivingEntity.DATA_LIVING_ENTITY_FLAGS`: 1 while using an item, 2 if
/// it is in the off hand.
pub living_flags: i8,
/// The bed (its head) the player sleeps in (`LivingEntity.getSleepingPos`),
/// `Player.sleepCounter`, and the bed last told to the player itself.
pub bed: Option<[i32; 3]>,
pub sleep_timer: u32,
pub sent_bed: Option<[i32; 3]>,
/// Where the player respawns (a bed's spot; `ServerPlayer.respawnConfig`),
/// None for the world spawn.
pub spawn: Option<[f64; 3]>,
/// Pending ClientboundPlayerPositionPacket id; movement is ignored until
/// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient).
pub awaiting_teleport: Option<(i32, [f64; 3])>,
pub teleport_counter: i32,
/// The hub tick the pending teleport was (re)sent on (awaitingTeleportTime).
pub teleport_tick: u64,
/// Where the player was when this tick's packets began (firstGoodX/Y/Z),
/// for the moved-too-quickly check.
pub first_good: [f64; 3],
/// Position moves received in all and by the start of this tick
/// (receivedMovePacketCount, knownMovePacketCount).
pub received_moves: i32,
pub known_moves: i32,
/// A position move arrived since the client's last ClientTickEnd
/// (receivedPositionThisTick): a second one is a protocol error.
pub position_this_tick: bool,
/// The client finished loading terrain (ServerboundPlayerLoadedPacket).
pub loaded: bool,
// Chunks.
pub center: Option<(i32, i32)>,
pub sent_chunks: crate::fast_hash::FxHashSet<(i32, i32)>,
pub chunk_queue: Vec<(i32, i32)>,
/// PlayerChunkSender: batches sent but not yet acknowledged, how many
/// may be (1 until the client's first acknowledgement, then 10), the
/// rate the client asks for and the chunks the next batch may hold.
pub unacknowledged: u32,
pub max_unacknowledged: u32,
pub chunks_per_tick: f32,
pub batch_quota: f32,
// Entities.
pub tracker: Tracker,
// Player state the gameplay code reads and writes.
pub motion: Option<Box<PlayerMotion>>,
/// The 36 inventory slots (hotbar first), armor (head..feet) and off hand.
pub inventory: Vec<Option<ItemStack>>,
pub armor: [Option<ItemStack>; 4],
pub offhand: Option<ItemStack>,
pub selected: usize,
pub carried: Option<ItemStack>,
/// The inventory menu's crafting grid (2x2) and its result
/// (`InventoryMenu.craftSlots`, `resultSlots`), which the game computes.
pub craft_grid: [Option<ItemStack>; 4],
pub craft_result: Option<ItemStack>,
/// The ender chest inventory (`PlayerEnderChestContainer`, 27 slots).
pub ender_items: Vec<Option<ItemStack>>,
pub health: f32,
pub food: i32,
pub saturation: f32,
pub xp_level: i32,
pub xp_progress: f32,
pub xp_total: i32,
/// Active status effects (`LivingEntity.activeEffects`).
pub effects: crate::effects::PlayerEffects,
/// What the client was told of each effect: id, amplifier, flags, and
/// the duration and `effects.tick_count` at the time, so a duration that
/// only counted down is not sent again (`ServerPlayer.onEffectUpdated`).
pub sent_effects: Vec<SentEffect>,
/// What the client believes the inventory menu holds (for change detection).
pub menu_sent: Vec<Option<ItemStack>>,
pub menu_state: i32,
/// `lastSentHealth`, `lastSentFood` and `lastFoodSaturationZero`.
pub sent_health: Option<(f32, i32, bool)>,
pub sent_xp: Option<(f32, i32, i32)>,
/// Where the player last died (Player.lastDeathLocation), sent with the respawn.
pub last_death: Option<[i32; 3]>,
/// The last action sequence to acknowledge at the next tick (-1: none).
pub ack_up_to: std::cell::Cell<i32>,
pub sent_selected: usize,
pub inbox: VecDeque<play::Serverbound>,
pub joined_tick: u64,
pub ticks: u64,
/// The moves accepted since the game last looked (movement, on ground),
/// for ServerPlayer.doCheckFallDamage.
pub moves: Vec<([f64; 3], bool)>,
/// Whether the guest was on the ground before the first of `moves`.
pub moves_from_ground: bool,
pub dead: bool,
/// The join packets were sent (PlayerList.placeNewPlayer ran).
pub placed: bool,
/// The level the player is in (`ServerPlayer.level().dimension()`): the
/// hub's level passes only reach the players in theirs.
pub dimension: String,
/// The open block container, if any.
pub menu: Option<super::menu::Menu>,
pub next_window: i32,
/// An unfinished drag in the inventory menu.
pub drag: Option<(u8, Vec<usize>)>,
/// The compound this player was loaded from, for fields Horizon does not model.
pub saved: Option<horizon_world::nbt::Tag>,
/// `ServerPlayer.recipeBook`.
pub recipe_book: crate::recipe_book::Settings,
/// `PlayerAdvancements`: the criteria obtained, whether they came from
/// the player's file, the advancements the client was last told it may
/// see (empty before the first packet), and those whose progress
/// changed since (`progressChanged`).
pub advancements: crate::advancements::Progress,
pub advancements_loaded: bool,
pub advancements_visible: Vec<bool>,
pub advancements_changed: std::collections::BTreeSet<usize>,
/// Recipes unlocked since the client was last told
/// (`ServerRecipeBook.addRecipes` sends them).
pub recipes_unlocked: Vec<String>,
}
impl Guest {
pub fn new(j: Joined, entity_id: i32, position: [f64; 3], view_distance: i32) -> Self {
Self {
conn: j.conn,
address: j.address,
last_action_tick: 0,
chat_index: 0,
chain: Default::default(),
last_seen: Default::default(),
signatures: Default::default(),
placed_at: 0,
center_sent: None,
left_reason: String::new(),
uuid: j.uuid,
name: j.name,
properties: j.properties,
entity_id,
sender: j.sender,
latency: j.latency,
view_distance: (i32::from(j.info.view_distance)).clamp(2, view_distance),
info: j.info,
brand: j.brand,
position,
previous_position: position,
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: false,
game_mode: SURVIVAL,
permission: 0,
sneaking: false,
sprinting: false,
fall_flying: false,
flying: false,
sleeping: false,
living_flags: 0,
bed: None,
sleep_timer: 0,
sent_bed: None,
spawn: None,
awaiting_teleport: None,
teleport_counter: 0,
teleport_tick: 0,
first_good: position,
received_moves: 0,
known_moves: 0,
position_this_tick: false,
loaded: false,
center: None,
sent_chunks: Default::default(),
chunk_queue: Vec::new(),
unacknowledged: 0,
max_unacknowledged: 1,
chunks_per_tick: 9.0,
batch_quota: 0.0,
tracker: Tracker::default(),
motion: None,
inventory: vec![None; 36],
armor: [None, None, None, None],
offhand: None,
selected: 0,
carried: None,
craft_grid: Default::default(),
craft_result: None,
ender_items: vec![None; 27],
health: 20.0,
food: 20,
saturation: 5.0,
xp_level: 0,
xp_progress: 0.0,
xp_total: 0,
effects: Default::default(),
sent_effects: Vec::new(),
menu_sent: vec![None; 46],
menu_state: 0,
sent_health: None,
sent_xp: None,
last_death: None,
ack_up_to: std::cell::Cell::new(-1),
sent_selected: 0,
inbox: VecDeque::new(),
joined_tick: 0,
ticks: 0,
moves: Vec::new(),
moves_from_ground: false,
dead: false,
placed: false,
dimension: "minecraft:overworld".into(),
menu: None,
next_window: 0,
drag: None,
saved: None,
recipe_book: Default::default(),
advancements: Default::default(),
advancements_loaded: false,
advancements_visible: Vec::new(),
advancements_changed: Default::default(),
recipes_unlocked: Vec::new(),
}
}
pub fn send(&self, packet: &play::Clientbound) {
self.sender.send(packet.encode());
}
pub fn send_all(&self, packets: &[play::Clientbound]) {
for p in packets {
self.send(p);
}
}
pub fn chunk(&self) -> (i32, i32) {
(
(self.position[0].floor() as i32) >> 4,
(self.position[2].floor() as i32) >> 4,
)
}
pub fn creative(&self) -> bool {
self.game_mode == CREATIVE
}
pub fn spectator(&self) -> bool {
self.game_mode == SPECTATOR
}
/// PlayerAbilities flags (invulnerable, flying, may fly, instabuild).
pub fn ability_flags(&self) -> i8 {
let mut f = 0;
if self.creative() || self.spectator() {
f |= 1;
}
if self.flying || self.spectator() {
f |= 2;
}
if self.creative() || self.spectator() {
f |= 4;
}
if self.creative() {
f |= 8;
}
f
}
pub fn eye_height(&self) -> f64 {
if self.sneaking { 1.27 } else { 1.62 }
}
/// The inventory menu's 46 slots (ServerPlayer.inventoryMenu): 0 crafting
/// result, 1..=4 crafting grid, 5..=8 armor, 9..=35 main, 36..=44 hotbar,
/// 45 off hand.
pub fn menu_slot(&self, slot: usize) -> Option<ItemStack> {
match slot {
0 => self.craft_result.clone(),
1..=4 => self.craft_grid[slot - 1].clone(),
5..=8 => self.armor[slot - 5].clone(),
9..=35 => self.inventory.get(slot).cloned().flatten(),
36..=44 => self.inventory.get(slot - 36).cloned().flatten(),
45 => self.offhand.clone(),
_ => None,
}
}
pub fn set_menu_slot(&mut self, slot: usize, item: Option<ItemStack>) {
match slot {
0 => self.craft_result = item,
1..=4 => self.craft_grid[slot - 1] = item,
5..=8 => self.armor[slot - 5] = item,
9..=35 => self.inventory[slot] = item,
36..=44 => self.inventory[slot - 36] = item,
45 => self.offhand = item,
_ => {}
}
}
}
/// The off hand slot is conventionally 40 in saves and 45 in the menu.
pub fn stack_to_network(
item_id: impl Fn(&str) -> i32,
enchantment_id: impl Fn(&str) -> Option<i32>,
s: &Option<ItemStack>,
) -> Option<Stack> {
let s = s.as_ref()?;
let mut stack = Stack::new(item_id(&s.item), s.count as i32);
if s.damage > 0 {
stack.added.push((
horizon_protocol::item::component::DAMAGE,
horizon_protocol::item::Component::Int(s.damage as i32),
));
}
let enchantments: Vec<(i32, i32)> = s
.enchantments()
.iter()
.filter_map(|(e, level)| Some((enchantment_id(e)?, *level as i32)))
.collect();
if !enchantments.is_empty() {
stack.added.push((
horizon_protocol::item::component::ENCHANTMENTS,
horizon_protocol::item::Component::Enchantments(enchantments),
));
}
let stored: Vec<(i32, i32)> = s
.stored_enchantments()
.iter()
.filter_map(|(e, level)| Some((enchantment_id(e)?, *level as i32)))
.collect();
if !stored.is_empty() {
stack.added.push((
horizon_protocol::item::component::STORED_ENCHANTMENTS,
horizon_protocol::item::Component::Enchantments(stored),
));
}
if let Some(d) = s.data() {
if let Some(rgb) = d.dyed_color {
stack.added.push((
horizon_protocol::item::component::DYED_COLOR,
horizon_protocol::item::Component::Int(rgb),
));
}
if let Some(id) = d.map_id {
stack.added.push((
horizon_protocol::item::component::MAP_ID,
horizon_protocol::item::Component::Int(id),
));
}
}
if let Some(name) = s.custom_name() {
stack.added.push((
horizon_protocol::item::component::CUSTOM_NAME,
horizon_protocol::item::Component::Text(horizon_protocol::text::literal(name)),
));
}
Some(stack)
}