a71d148ca5
A player who joins over the network, which is now single player's own player on its server thread, had no status effects: what they drank, ate or were given went to the host, and their client never heard of any. - Each guest has their own effects. `as_guest` trades them, and what their body was given for them (attribute modifiers, armor protection, enchantment modifiers), with the host's while the guest acts. - They tick on the server with the guest's body (LivingEntity.baseTick's tickEffects), spectators included. - The client is told as vanilla's ServerPlayer does: every effect when placed (PlayerList.sendActivePlayerEffects), then added (blended), updated, refreshed every 600 ticks left, and removed. An effect that only counted down is not sent again. - The client keeps its own effects from those packets (LivingEntity.forceAddEffect), counts them down (tickClient), and its predicted movement, HUD icons and night vision follow them. A respawn starts without effects on both sides. - Guests save and load them in their player file. Saving also stops writing effects that have run out: the loaded player compound kept the old `active_effects`, and they came back on reopen. Potions in flight now tick on a server without a local player too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
338 lines
11 KiB
Rust
338 lines
11 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::{HashSet, 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,
|
|
/// 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,
|
|
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,
|
|
/// 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 client finished loading terrain (ServerboundPlayerLoadedPacket).
|
|
pub loaded: bool,
|
|
// Chunks.
|
|
pub center: Option<(i32, i32)>,
|
|
pub sent_chunks: HashSet<(i32, i32)>,
|
|
pub chunk_queue: Vec<(i32, i32)>,
|
|
pub unacknowledged: u32,
|
|
pub chunks_per_tick: f32,
|
|
pub chunk_credit: 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,
|
|
pub sent_health: Option<(f32, i32, f32)>,
|
|
pub sent_xp: Option<(f32, i32, 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 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>,
|
|
}
|
|
|
|
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,
|
|
placed_at: 0,
|
|
center_sent: None,
|
|
left_reason: String::new(),
|
|
uuid: j.uuid,
|
|
name: j.name,
|
|
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,
|
|
awaiting_teleport: None,
|
|
teleport_counter: 0,
|
|
loaded: false,
|
|
center: None,
|
|
sent_chunks: HashSet::new(),
|
|
chunk_queue: Vec::new(),
|
|
unacknowledged: 0,
|
|
chunks_per_tick: 9.0,
|
|
chunk_credit: 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,
|
|
sent_selected: 0,
|
|
inbox: VecDeque::new(),
|
|
joined_tick: 0,
|
|
ticks: 0,
|
|
moves: Vec::new(),
|
|
moves_from_ground: false,
|
|
dead: false,
|
|
placed: false,
|
|
menu: None,
|
|
next_window: 0,
|
|
drag: None,
|
|
saved: None,
|
|
}
|
|
}
|
|
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)
|
|
}
|