ghast-entity 0.5.3

Entity tracking for the ghast Minecraft Java Edition client library: zero-allocation parsing of 1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3 entity packets, vanilla-exact positions, O(1) lookup
Documentation
//! Modern entity tracking: 26.1 (protocol 775) as `v26_1`, 26.2 (protocol 776) as `v26_2`,
//! 26.3 (protocol 777) as `v26_3`.
//!
//! The modules are the same source compiled over their version's protocol and data modules:
//! entity type ids, sizes and the slot codec are that version's; the behaviour below is the
//! same in all three clients (26.2 and 26.3 replay their own golden dumps,
//! `tests/golden/26.2/` and `tests/golden/26.3/`).
//!
//! The modern client no longer keeps a separate "server position": an entity *is* at
//! `Entity.position()`, and what a position packet does depends on the type
//! (`ghast_data::modern::EntityTypeData::interpolation`, from the jar):
//!
//! - **Interpolated** types (living entities, boats, minecarts, experience orbs, fishing bobbers)
//!   get a target; [`Tracker::tick`] moves them a third of the remaining way per tick
//!   (`InterpolationHandler`: `Mth.lerp` / `Mth.rotLerp` in doubles, the target follows position
//!   changes made between steps unless the moved box would collide, see [`Tracker::tick_with`]).
//!   Head rotations of living entities are lerped over 3 ticks the same way.
//! - **Other** types (items, projectiles, end crystals, ...) move at once.
//!
//! Packet coordinates: spawns and `entity_position_sync` set the `VecDeltaCodec` base (doubles);
//! a relative move decodes `round(base * 4096) + delta` per non-zero axis, divided by 4096
//! (`Math.round`, half up; an axis with delta 0 keeps the base exactly). `teleport_entity` does
//! not touch the base; its relative axes are relative to the interpolation target. Syncs farther
//! than 64 blocks, and syncs of entities in chunks the client has not loaded, snap. Spawn
//! rotations follow `recreateFromPacket` (living: `absSnapTo` with x / z clamped to ±3e7).
//!
//! **Position at pick time.** Vanilla's `Minecraft.tick` runs the crosshair pick *before*
//! `ClientLevel.tickEntities`, after the tick's packets: apply this tick's packets, pick with
//! [`Entity::position`] / [`Entity::bounding_box`], then call [`Tracker::tick`]. Proven against
//! the real client by `tests/golden/26.1/entity_tracking.jsonl.gz` (oracle `EntityTrackDump`).
//!
//! Not modelled here: the client-side physics of projectiles, items, orbs, TNT and falling
//! blocks between packets (they move on their own in vanilla; a caller that runs it writes the
//! result back with [`Tracker::client_simulated`], as ghast-client does with
//! `Interests::ENTITY_PHYSICS`), passenger positions (vanilla places
//! riders on their vehicle every tick), vehicles the bot controls other than boats (they ignore
//! position packets in vanilla), and the client-side decay of velocities: [`Entity::velocity`] is
//! the last velocity the server sent (a relative teleport adds to it without `ROTATE_DELTA`).
//!
//! Every packet is parsed by hand from the body; movement packets touch no allocator, and with
//! [`Config::metadata`] off metadata is walked without allocating (the size keys, sleeping
//! position and item counts are always applied).
//!
//! Layout: this file holds the packet id lists, [`Tracker`] and the per-entity accessors;
//! `methods.rs` the tracker's methods and packet dispatch, `motion.rs` movement,
//! interpolation and the entity tick, `spawn.rs` spawn / move / sync / teleport packets,
//! `metadata.rs` metadata, attributes and the player list.

mod metadata;
mod methods;
mod motion;
mod spawn;
#[cfg(test)]
mod tests;

use metadata::*;
use motion::*;
use spawn::*;

// Row items (the per-version module this source is compiled in) the topic files name as
// `super::...`.
use super::{ERA, PATHS, proto};

use std::ops::Deref;

use super::data::entities::{self as data, EntityTypeData, type_flags};
use super::proto::play::clientbound::{Login, Respawn, id};
use super::read_stack;
use crate::modern_state::st;
use bytes::Bytes;
use ghast_protocol::nbt::AnonNbt;
use ghast_protocol::types::LpVec3;
use ghast_protocol::types::slot::v775::ItemStack;
use ghast_protocol::{Decode, DecodeError, RawPacket, Reader};

use crate::Applied;
use crate::common::{IdMask, R, angle, for_each_varint, own_str, skip_string};
use crate::common::{remove_effect, set_effect};
use crate::entity::{Effect, Entity, EntityClass, EntityType, Item, MetaValue};
use crate::store::{Config, Entities, Event, Fast, PlayerInfo};

/// Spawn, movement, destroy, riding, pickup, status, metadata, attribute packets, chunk loads
/// (only their coordinates are read: an entity in an unloaded chunk does not tick), plus `login`
/// / `respawn`.
pub const CORE_IDS: &[i32] = &[
    id::LOGIN,
    id::RESPAWN,
    id::SPAWN_ENTITY,
    id::ENTITY_VELOCITY,
    id::ENTITY_DESTROY,
    id::REL_ENTITY_MOVE,
    id::ENTITY_LOOK,
    id::ENTITY_MOVE_LOOK,
    id::SYNC_ENTITY_POSITION,
    id::ENTITY_TELEPORT,
    id::ENTITY_HEAD_ROTATION,
    id::ENTITY_STATUS,
    id::DAMAGE_EVENT,
    id::ATTACH_ENTITY,
    id::SET_PASSENGERS,
    id::COLLECT,
    id::ENTITY_METADATA,
    id::ENTITY_UPDATE_ATTRIBUTES,
    id::MAP_CHUNK,
    id::UNLOAD_CHUNK,
];
/// `entity_metadata` (always in [`CORE_IDS`]: poses, baby flags, sizes, sleeping positions and
/// item counts change boxes and positions).
pub const METADATA_IDS: &[i32] = &[id::ENTITY_METADATA];
/// `entity_equipment`.
pub const EQUIPMENT_IDS: &[i32] = &[id::ENTITY_EQUIPMENT];
/// `entity_effect`, `remove_entity_effect`.
pub const EFFECT_IDS: &[i32] = &[id::ENTITY_EFFECT, id::REMOVE_ENTITY_EFFECT];
/// `player_info` (update), `player_remove`. Player spawns need the tab list: vanilla skips a
/// player spawn whose profile is not in it (with [`Config::player_list`] off every spawn is kept).
pub const PLAYER_LIST_IDS: &[i32] = &[id::PLAYER_INFO, id::PLAYER_REMOVE];

/// Index of the fox flags byte (`Fox.DATA_FLAGS_ID`; 0x20 = sleeping).
const FOX_FLAGS: u8 = 19;

/// Registry id of `minecraft:scale` in this version (checked against the jar by the oracle test).
pub const SCALE_ATTRIBUTE: i32 = super::SCALE_ATTRIBUTE_ID;

/// Metadata indices shared by every entity / living entity (the same in 26.1 and 26.2).
pub mod meta {
    /// Entity flags byte (0x01 on fire, 0x02 crouching, 0x08 sprinting, 0x10 swimming,
    /// 0x20 invisible, 0x40 glowing, 0x80 fall flying).
    pub const FLAGS: u8 = 0;
    /// Air (VarInt).
    pub const AIR: u8 = 1;
    /// Custom name (optional component).
    pub const CUSTOM_NAME: u8 = 2;
    /// No gravity.
    pub const NO_GRAVITY: u8 = 5;
    /// Pose.
    pub const POSE: u8 = 6;
    /// Living: hand states.
    pub const LIVING_FLAGS: u8 = 8;
    /// Living: health (float).
    pub const HEALTH: u8 = 9;
    /// Living: sleeping position (optional block position; setting it moves the entity onto
    /// the bed: `x + 0.5, y + 0.6875, z + 0.5`).
    pub const SLEEPING_POS: u8 = 14;
    /// Item entity: the stack.
    pub const ITEM: u8 = 8;
}

/// The bot's entity view on a modern (26.1 – 26.3) connection. Dereferences to the shared [`Entities`].
#[derive(Clone, Debug)]
pub struct Tracker {
    store: Entities,
    dimension: String,
    wanted: IdMask,
    /// Loaded chunk columns (`x & 0xffffffff | z << 32`).
    chunks: Fast<u64, ()>,
    /// Ids held in vanilla's tick list by a spawn the entity lookup refused (duplicate UUID): the
    /// tick list is keyed by id, so `isTickingEntity` says yes for any entity with that id until
    /// a real one with it starts ticking.
    ghosts: Fast<i32, ()>,
    /// The client's tick list (`EntityTickList`, a linked map by id): each member's insertion
    /// number. Re-adding an id that is still a member keeps its place.
    order: Fast<i32, u32>,
    next_seq: u32,
    /// `order`'s capacity after its last insert (see `store::after_insert`).
    order_cap: usize,
    /// Entities [`Tracker::tick_early`] already ticked this client tick (the next
    /// [`Tracker::tick_with`] skips them once).
    early: Vec<i32>,
    /// Tick list membership may have changed in a way only a full re-check finds (passengers
    /// changed vehicles): re-checked at the start of the next tick.
    order_dirty: bool,
}

impl Deref for Tracker {
    type Target = Entities;
    fn deref(&self) -> &Entities {
        &self.store
    }
}

/// The packet coordinates of a 26.1 entity (`VecDeltaCodec` base: the last spawn, relative move
/// or position sync; teleports do not change it).
#[must_use]
pub fn server_position(e: &Entity) -> [f64; 3] {
    base(e)
}

/// The interpolation target and its `(yRot, xRot)` while an interpolation is active.
#[must_use]
pub fn interpolation_target(e: &Entity) -> Option<([f64; 3], [f32; 2])> {
    (e.m.steps > 0).then_some((e.m.target, e.m.target_rot))
}

/// The type facts from ghast-data.
#[must_use]
pub fn entity_type(e: &Entity) -> Option<&'static EntityTypeData> {
    e.m.td
}

/// Pick radius (`getPickRadius`, 0 for every 26.1 type).
#[must_use]
pub fn pick_radius(e: &Entity) -> f32 {
    e.m.td
        .and_then(|t| t.size)
        .map_or(0.0, |s| s.targeting_margin)
}

/// `yBodyRot` of mobs with the default body control and armor stands (exact); other entities
/// keep their spawn value (players turn their body from movement, not modelled).
#[must_use]
pub fn body_yaw(e: &Entity) -> f32 {
    e.m.body_yaw
}

/// The pose id (`Pose`: 0 standing, 2 sleeping, 3 swimming, 5 crouching, 10 sitting, ...).
#[must_use]
pub fn pose(e: &Entity) -> u8 {
    e.m.pose
}

/// The `minecraft:scale` value the client uses for the entity's size.
#[must_use]
pub fn scale(e: &Entity) -> f32 {
    e.m.scale
}

/// Stack size of an item entity (0 before its stack arrived).
#[must_use]
pub fn item_count(e: &Entity) -> i32 {
    e.m.item_count
}

/// The stack of an item entity (always kept for item entities).
#[must_use]
pub fn item_stack(e: &Entity) -> Option<&ItemStack> {
    match e.meta.get(meta::ITEM)? {
        MetaValue::Stack(s) if e.ty == EntityType::Registry(data::ITEM) => s.as_ref(),
        _ => None,
    }
}

/// 26.1 health of a living entity (with [`Config::metadata`]).
#[must_use]
pub fn health(e: &Entity) -> Option<f32> {
    e.metadata().float(meta::HEALTH)
}

/// Vanilla `LivingEntity.isAlive` as far as the packets tell (removed entities are not
/// tracked): `false` once the server sent a health that is not above 0 (NaN included), `true`
/// for other entities and before any health arrived. Kept with and without [`Config::metadata`].
#[must_use]
pub fn alive(e: &Entity) -> bool {
    if !living(e) {
        return true;
    }
    match health(e) {
        Some(h) => h > 0.0,
        None => !e.m.flag(st::DEAD),
    }
}

/// 26.1 entity flags byte (0 when unknown).
#[must_use]
pub fn flags(e: &Entity) -> u8 {
    e.metadata().byte(meta::FLAGS).unwrap_or(0) as u8
}

/// 26.1 custom name (raw network NBT text component).
#[must_use]
pub fn custom_name(e: &Entity) -> Option<&Bytes> {
    match e.metadata().get(meta::CUSTOM_NAME)? {
        MetaValue::OptComponent(Some(b)) => Some(b),
        _ => None,
    }
}

/// Static type information from ghast-data.
#[must_use]
pub fn info(t: EntityType) -> Option<&'static ghast_data::EntityInfo> {
    match t {
        EntityType::Registry(id) => super::data::entity(id),
        EntityType::Player => super::data::entity(data::PLAYER),
        _ => None,
    }
}

pub(crate) fn class(e: &Entity) -> EntityClass {
    match e.ty {
        EntityType::Player => EntityClass::Player,
        EntityType::Registry(data::ITEM) => EntityClass::Item,
        EntityType::Registry(data::EXPERIENCE_ORB) => EntityClass::ExperienceOrb,
        EntityType::Registry(data::PAINTING) => EntityClass::Painting,
        _ if e.living => EntityClass::Mob,
        _ => EntityClass::Object,
    }
}

pub(crate) fn vanilla_size(e: &Entity) -> Option<&'static ghast_data::VanillaEntitySize> {
    e.m.td.and_then(|t| t.size)
}

/// The client's cached dimensions (`Entity.dimensions`).
pub(crate) fn dimensions(e: &Entity) -> Option<ghast_data::EntityDimensions> {
    e.m.dims()
}

/// `getDimensions(getPose())`: variant (baby flag, slime size, armor stand flags), pose, scale.
fn compute_dims(e: &Entity) -> Option<ghast_data::EntityDimensions> {
    let t = e.m.td?;
    let m = &e.m;
    let (variant, slime) = if t.size_meta.is_some() {
        ("default", Some(m.slime_size))
    } else if t.flags_meta.is_some() {
        let f = m.stand_flags;
        let v = match (f & 0x01 != 0, f & 0x10 != 0) {
            (true, true) => "small_marker",
            (false, true) => "marker",
            (true, false) => "small",
            _ => "default",
        };
        (v, None)
    } else if t.baby_meta.is_some() && m.flag(st::BABY) {
        ("baby", None)
    } else {
        ("default", None)
    };
    let d = t.dimensions(variant, slime, i32::from(m.pose))?;
    if t.is_living() && m.pose != 2 {
        let fixed = t.flags & type_flags::FIXED != 0
            || variant.ends_with("marker")
            || t.fixed_poses & (1 << m.pose) != 0;
        return Some(EntityTypeData::scaled(d, m.scale, fixed));
    }
    Some(d)
}