Skip to main content

ghast_entity/
entity.rs

1//! Tracked entity state.
2
3use bytes::Bytes;
4use uuid::Uuid;
5
6/// What kind of entity this is, in the id space of the packet that spawned it.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum EntityType {
10    /// A player (`named_entity_spawn`).
11    Player,
12    /// 1.8 – 1.12 mob id (`spawn_entity_living`; the entity registry id), e.g. 54 = zombie. See
13    /// `ghast_data::v1_8::entity(EntityKind::Mob, id)` / `ghast_data::v1_12::entity(..)`.
14    LegacyMob(u8),
15    /// 1.8 – 1.12 object type (`spawn_entity`), e.g. 2 = item, 1 = boat. See
16    /// `ghast_data::v1_8::entity(EntityKind::Object, id)` / `ghast_data::v1_12::entity(..)`.
17    LegacyObject(u8),
18    /// 1.8 – 1.12 experience orb (`spawn_entity_experience_orb`; orb value in [`Entity::data`]).
19    ExperienceOrb,
20    /// 1.8 – 1.12 painting (`spawn_entity_painting`).
21    Painting,
22    /// 1.13+ entity registry id (1.16.5: every spawn packet except players), see
23    /// `ghast_data::v1_16_5::entity`.
24    Registry(u16),
25}
26
27/// Version-independent classification of an entity.
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29#[non_exhaustive]
30pub enum EntityClass {
31    /// A player.
32    Player,
33    /// A dropped item (stack: [`Entity::item`]).
34    Item,
35    /// An experience orb (value: [`Entity::data`]).
36    ExperienceOrb,
37    /// A living non-player entity (spawned with the mob-spawn packet).
38    Mob,
39    /// Any other spawned object (boats, minecarts, arrows, falling blocks, armor stands in 1.8, ...).
40    Object,
41    /// Paintings.
42    Painting,
43}
44
45/// An item stack (equipment, item entities, metadata).
46///
47/// `damage` is the 1.8 damage/metadata value (always 0 in 1.13+, where damage lives in NBT).
48/// `nbt` is a private copy of the raw NBT bytes (never a view into a packet buffer).
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct Item {
51    /// Item id.
52    pub id: i32,
53    /// Stack size.
54    pub count: i8,
55    /// 1.8 damage / metadata.
56    pub damage: i16,
57    /// Raw NBT (`None` = no tag).
58    pub nbt: Option<Bytes>,
59}
60
61/// An active status effect as the server reported it.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct Effect {
64    /// Effect id (1 = speed, 8 = jump boost, ...).
65    pub id: u8,
66    /// Amplifier (level - 1).
67    pub amplifier: i8,
68    /// Duration in ticks at the time of the packet (not counted down here).
69    pub duration: i32,
70    /// 1.8: bit 0 = hide particles. 1.12: bit 0 ambient, bit 1 show particles. 1.16: bit 0 ambient,
71    /// bit 1 show particles, bit 2 show icon.
72    pub flags: u8,
73}
74
75/// One entity metadata value (union of the 1.8, 1.12.2 and 1.16.5 serializer types; variants
76/// marked 1.16 also occur in 1.12 where 1.12 has that serializer).
77#[derive(Clone, Debug, PartialEq)]
78#[non_exhaustive]
79pub enum MetaValue {
80    /// Byte.
81    Byte(i8),
82    /// 1.8 short.
83    Short(i16),
84    /// 1.8 int.
85    Int(i32),
86    /// 1.16 VarInt.
87    VarInt(i32),
88    /// Float.
89    Float(f32),
90    /// String (1.8) / string (1.16).
91    String(Box<str>),
92    /// 1.16 chat component (raw JSON).
93    Chat(Box<str>),
94    /// 1.16 optional chat component (raw JSON).
95    OptChat(Option<Box<str>>),
96    /// Item stack (`None` = empty).
97    Item(Option<Item>),
98    /// 1.16 boolean.
99    Bool(bool),
100    /// Rotation (three floats).
101    Rotation([f32; 3]),
102    /// Block position.
103    BlockPos([i32; 3]),
104    /// 1.16 optional block position.
105    OptBlockPos(Option<[i32; 3]>),
106    /// 1.16 direction.
107    Direction(i32),
108    /// 1.16 optional UUID.
109    OptUuid(Option<Uuid>),
110    /// 1.16 optional block state (0 = none).
111    BlockState(i32),
112    /// 1.16 NBT (raw copy).
113    Nbt(Bytes),
114    /// 1.16 particle (only the particle type id is kept).
115    Particle(i32),
116    /// 1.16 villager data (type, profession, level).
117    VillagerData([i32; 3]),
118    /// 1.16 optional VarInt (0 = none, else value + 1).
119    OptVarInt(i32),
120    /// 1.16 / 26.1 pose.
121    Pose(i32),
122    /// 26.1 long (VarLong).
123    Long(i64),
124    /// 26.1 text component (the raw network NBT, copied).
125    Component(Bytes),
126    /// 26.1 optional text component (raw network NBT).
127    OptComponent(Option<Bytes>),
128    /// 26.1 item stack (`None` = empty; component patch copied out of the packet).
129    #[cfg(any(feature = "v26_1", feature = "v26_2"))]
130    Stack(Option<ghast_protocol::types::slot::v775::ItemStack>),
131    /// 26.1 registry or enum value: `(serializer id, value)` (cat / cow / wolf / frog / pig /
132    /// chicken / zombie nautilus variants and sound variants, sniffer / armadillo / copper golem
133    /// states, humanoid arm).
134    Enum(u8, i32),
135    /// 26.1 vector (three floats).
136    Vector3([f32; 3]),
137    /// 26.1 quaternion (four floats).
138    Quaternion([f32; 4]),
139    /// 26.1 value kept as its raw wire bytes, copied: `(serializer id, bytes)` (optional block
140    /// state, particle, particle list, optional global position, painting variant, resolvable
141    /// profile).
142    Raw(u8, Bytes),
143}
144
145/// The metadata of one entity: `(index, value)` pairs, at most one per index, in arrival order.
146///
147/// Scalar updates overwrite in place (no allocation).
148#[derive(Clone, Debug, Default, PartialEq)]
149pub struct Metadata {
150    entries: Vec<(u8, MetaValue)>,
151}
152
153impl Metadata {
154    /// The value at `index`.
155    #[must_use]
156    pub fn get(&self, index: u8) -> Option<&MetaValue> {
157        self.entries
158            .iter()
159            .find(|(i, _)| *i == index)
160            .map(|(_, v)| v)
161    }
162
163    /// Sets the value at `index`.
164    pub fn set(&mut self, index: u8, value: MetaValue) {
165        match self.entries.iter_mut().find(|(i, _)| *i == index) {
166            Some(slot) => slot.1 = value,
167            None => self.entries.push((index, value)),
168        }
169    }
170
171    /// All entries.
172    pub fn iter(&self) -> impl Iterator<Item = (u8, &MetaValue)> {
173        self.entries.iter().map(|(i, v)| (*i, v))
174    }
175
176    /// Number of entries.
177    #[must_use]
178    pub fn len(&self) -> usize {
179        self.entries.len()
180    }
181
182    /// `true` when nothing has been received.
183    #[must_use]
184    pub fn is_empty(&self) -> bool {
185        self.entries.is_empty()
186    }
187
188    /// Byte at `index` (`Byte` values only).
189    #[must_use]
190    pub fn byte(&self, index: u8) -> Option<i8> {
191        match self.get(index)? {
192            MetaValue::Byte(b) => Some(*b),
193            _ => None,
194        }
195    }
196
197    /// Float at `index`.
198    #[must_use]
199    pub fn float(&self, index: u8) -> Option<f32> {
200        match self.get(index)? {
201            MetaValue::Float(f) => Some(*f),
202            _ => None,
203        }
204    }
205
206    /// Item at `index` (`Some(None)` = an empty stack was sent).
207    #[must_use]
208    pub fn item(&self, index: u8) -> Option<Option<&Item>> {
209        match self.get(index)? {
210            MetaValue::Item(i) => Some(i.as_ref()),
211            _ => None,
212        }
213    }
214
215    pub(crate) fn clear(&mut self) {
216        self.entries.clear();
217    }
218
219    pub(crate) fn entries_mut(&mut self) -> impl Iterator<Item = &mut (u8, MetaValue)> {
220        self.entries.iter_mut()
221    }
222}
223
224/// The protocol family an entity was tracked with (selects metadata indices and size rules).
225#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
226pub(crate) enum Era {
227    /// 1.8.x.
228    #[default]
229    V1_8,
230    /// 1.9 – 1.12 (implemented: 1.12.2).
231    V1_12,
232    /// 1.16.5.
233    V1_16,
234    /// 26.1.
235    V26,
236    /// 26.2 (the same modern state as 26.1, with 26.2's ids and sizes).
237    V26_2,
238}
239
240/// 1.16 registry ids used by [`Entity::class`].
241const ITEM_1_16: u16 = 37;
242const XP_ORB_1_16: u16 = 24;
243const PAINTING_1_16: u16 = 55;
244
245/// Number of equipment slots kept (1.16: main hand, off hand, feet, legs, chest, head;
246/// 1.8: held, boots, leggings, chestplate, helmet in slots 0..=4).
247pub const EQUIPMENT_SLOTS: usize = 6;
248
249/// A tracked entity, as the vanilla client knows it from the server's packets.
250#[derive(Clone, Debug)]
251pub struct Entity {
252    pub(crate) id: i32,
253    pub(crate) uuid: Uuid,
254    pub(crate) ty: EntityType,
255    pub(crate) living: bool,
256    /// The tracker's protocol family.
257    pub(crate) era: Era,
258    /// Vanilla size table entry (resolved at spawn).
259    pub(crate) sizer: Option<&'static ghast_data::VanillaEntitySize>,
260    pub(crate) pos: [f64; 3],
261    /// Per version: 1.8 the server position in 1/32 blocks (`serverPos`, i32 values); 1.9 – 1.12
262    /// the tracked position in 1/4096 blocks (`lfloor(x * 4096)`, plus moves); 26.1 the
263    /// `VecDeltaCodec` base (`f64` bits).
264    pub(crate) traced: [i64; 3],
265    pub(crate) yaw: f32,
266    pub(crate) pitch: f32,
267    pub(crate) head_yaw: f32,
268    pub(crate) velocity: [f64; 3],
269    pub(crate) on_ground: bool,
270    pub(crate) data: i32,
271    pub(crate) vehicle: Option<i32>,
272    pub(crate) passengers: Vec<i32>,
273    pub(crate) leash_holder: Option<i32>,
274    pub(crate) meta: Metadata,
275    pub(crate) equipment: Option<Box<[Option<Item>; EQUIPMENT_SLOTS]>>,
276    pub(crate) effects: Vec<Effect>,
277    /// 26.1 client state (codec base, interpolation, size keys), boxed: one pointer for the
278    /// other versions.
279    #[cfg(any(feature = "v26_1", feature = "v26_2"))]
280    pub(crate) m: crate::modern_state::Ext,
281}
282
283impl Entity {
284    pub(crate) fn new(id: i32, ty: EntityType) -> Self {
285        Entity {
286            id,
287            uuid: Uuid::nil(),
288            ty,
289            living: matches!(ty, EntityType::Player | EntityType::LegacyMob(_)),
290            era: Era::V1_8,
291            sizer: None,
292            pos: [0.0; 3],
293            traced: [0; 3],
294            yaw: 0.0,
295            pitch: 0.0,
296            head_yaw: 0.0,
297            velocity: [0.0; 3],
298            on_ground: false,
299            data: 0,
300            vehicle: None,
301            passengers: Vec::new(),
302            leash_holder: None,
303            meta: Metadata::default(),
304            equipment: None,
305            effects: Vec::new(),
306            #[cfg(any(feature = "v26_1", feature = "v26_2"))]
307            m: crate::modern_state::Ext::default(),
308        }
309    }
310
311    /// Network entity id.
312    #[must_use]
313    pub fn id(&self) -> i32 {
314        self.id
315    }
316
317    /// UUID (nil for 1.8 entities other than players).
318    #[must_use]
319    pub fn uuid(&self) -> Uuid {
320        self.uuid
321    }
322
323    /// Type.
324    #[must_use]
325    pub fn entity_type(&self) -> EntityType {
326        self.ty
327    }
328
329    /// Version-independent class.
330    #[must_use]
331    pub fn class(&self) -> EntityClass {
332        #[cfg(feature = "v26_1")]
333        if self.era == Era::V26 {
334            return crate::v26_1::class(self);
335        }
336        #[cfg(feature = "v26_2")]
337        if self.era == Era::V26_2 {
338            return crate::v26_2::class(self);
339        }
340        match self.ty {
341            EntityType::Player => EntityClass::Player,
342            EntityType::LegacyObject(2) | EntityType::Registry(ITEM_1_16) => EntityClass::Item,
343            EntityType::ExperienceOrb | EntityType::Registry(XP_ORB_1_16) => {
344                EntityClass::ExperienceOrb
345            }
346            EntityType::Painting | EntityType::Registry(PAINTING_1_16) => EntityClass::Painting,
347            _ if self.living => EntityClass::Mob,
348            _ => EntityClass::Object,
349        }
350    }
351
352    /// The stack of an item entity (from metadata; `None` before the server sent it or when
353    /// metadata is not tracked; 1.16 always keeps it for item entities). Always `None` on 26.1,
354    /// whose stacks carry data components: see `v26_1::item_stack` / `v26_1::item_count`.
355    #[must_use]
356    pub fn item(&self) -> Option<&Item> {
357        if matches!(self.era, Era::V26 | Era::V26_2) {
358            return None;
359        }
360        let index = match self.ty {
361            EntityType::LegacyObject(2) if self.era == Era::V1_12 => 6,
362            EntityType::LegacyObject(2) => 10,
363            EntityType::Registry(ITEM_1_16) => 7,
364            _ => return None,
365        };
366        self.meta.item(index).flatten()
367    }
368
369    /// Vanilla client-side dimensions: the type's size from ghast-data (checked against the
370    /// oracle), with the variant the client applies from metadata (baby, slime size, wither
371    /// skeleton, elder guardian, small / marker armor stand, 1.16 player pose). `None` for
372    /// hanging entities (paintings, item frames, leash knots), whose box comes from facing.
373    ///
374    /// Variants vanilla applies on the entity's next client tick are applied immediately, and
375    /// the old-min-corner quirk after a resize is not modelled.
376    #[must_use]
377    pub fn dimensions(&self) -> Option<ghast_data::EntityDimensions> {
378        let vs = self.sizer?;
379        match self.era {
380            #[cfg(feature = "v1_8")]
381            Era::V1_8 => crate::v1_8::dimensions(self, vs),
382            #[cfg(feature = "v1_12")]
383            Era::V1_12 => crate::v1_12::dimensions(self, vs),
384            #[cfg(feature = "v1_16_5")]
385            Era::V1_16 => crate::v1_16_5::dimensions(self, vs),
386            #[cfg(feature = "v26_1")]
387            Era::V26 => {
388                let _ = vs;
389                crate::v26_1::dimensions(self)
390            }
391            #[cfg(feature = "v26_2")]
392            Era::V26_2 => {
393                let _ = vs;
394                crate::v26_2::dimensions(self)
395            }
396            // A tracker only stamps eras of versions compiled in.
397            #[allow(unreachable_patterns)]
398            _ => None,
399        }
400    }
401
402    /// How much the crosshair pick grows this entity's box (vanilla `getCollisionBorderSize` /
403    /// `getTargetingMargin`, from the type's size table: 0.1 for most 1.8 types, 0 since 1.9,
404    /// 1.0 for fireballs); 0 when the type has no size entry.
405    #[must_use]
406    pub fn targeting_margin(&self) -> f32 {
407        self.sizer.map_or(0.0, |s| s.targeting_margin)
408    }
409
410    /// `(width, height)` of [`Entity::dimensions`].
411    #[must_use]
412    pub fn size(&self) -> Option<(f32, f32)> {
413        self.dimensions().map(|d| (d.width, d.height))
414    }
415
416    /// Vanilla bounding box at the server position, `[min_x, min_y, min_z, max_x, max_y,
417    /// max_z]` (bit-exact `EntityDimensions::bounding_box`).
418    #[must_use]
419    pub fn bounding_box(&self) -> Option<[f64; 6]> {
420        let [x, y, z] = self.pos;
421        let b = self.dimensions()?.bounding_box(x, y, z);
422        Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
423    }
424
425    /// `true` for players.
426    #[must_use]
427    pub fn is_player(&self) -> bool {
428        self.ty == EntityType::Player
429    }
430
431    /// The **server position**: exactly the coordinates the vanilla client tracks from the
432    /// packets (1.8: `serverPos / 32.0`; 1.12: spawn / teleport coordinates, after a relative
433    /// move the tracked 1/4096 position; 1.16: the packet coordinates, rel moves applied in
434    /// 1/4096 fixed point). The rendered position interpolates towards this over 3 ticks in
435    /// vanilla; a bot does not need that.
436    ///
437    /// **26.1** is different: this is the entity's *current* position as the client holds it
438    /// (`Entity.position()`): position packets of interpolated entities (living entities, boats,
439    /// minecarts) set a target the entity reaches over 3 calls of `v26_1::Tracker::tick`, others
440    /// move at once. That is the position vanilla's crosshair pick reads at tick time (with
441    /// [`Entity::bounding_box`]); the packet coordinates are `v26_1::server_position`.
442    #[must_use]
443    pub fn position(&self) -> [f64; 3] {
444        self.pos
445    }
446
447    /// 1.8 only: the raw server position in 1/32 blocks (`[0; 3]` in 1.12 and 1.16).
448    #[must_use]
449    pub fn fixed_position(&self) -> [i32; 3] {
450        if self.era == Era::V1_8 {
451            self.traced.map(|t| t as i32)
452        } else {
453            [0; 3]
454        }
455    }
456
457    /// Body yaw in degrees as vanilla computes it from the angle byte (`b * 360 / 256f`).
458    #[must_use]
459    pub fn yaw(&self) -> f32 {
460        self.yaw
461    }
462
463    /// Pitch in degrees.
464    #[must_use]
465    pub fn pitch(&self) -> f32 {
466        self.pitch
467    }
468
469    /// Head yaw in degrees (from `entity_head_rotation`; mobs also at spawn).
470    #[must_use]
471    pub fn head_yaw(&self) -> f32 {
472        self.head_yaw
473    }
474
475    /// Last velocity the server sent (blocks per tick), from the spawn packet or
476    /// `entity_velocity`. Not integrated over time.
477    #[must_use]
478    pub fn velocity(&self) -> [f64; 3] {
479        self.velocity
480    }
481
482    /// On-ground flag of the last movement packet.
483    #[must_use]
484    pub fn on_ground(&self) -> bool {
485        self.on_ground
486    }
487
488    /// Spawn data: object data (1.8 objects / 1.16 `spawn_entity`), experience orb value,
489    /// painting direction.
490    #[must_use]
491    pub fn data(&self) -> i32 {
492        self.data
493    }
494
495    /// Entity this one rides.
496    #[must_use]
497    pub fn vehicle(&self) -> Option<i32> {
498        self.vehicle
499    }
500
501    /// Entities riding this one (1.8: at most one).
502    #[must_use]
503    pub fn passengers(&self) -> &[i32] {
504        &self.passengers
505    }
506
507    /// Entity holding this one's leash.
508    #[must_use]
509    pub fn leash_holder(&self) -> Option<i32> {
510        self.leash_holder
511    }
512
513    /// Metadata (empty unless metadata tracking is enabled).
514    #[must_use]
515    pub fn metadata(&self) -> &Metadata {
516        &self.meta
517    }
518
519    /// Equipment slot (see [`EQUIPMENT_SLOTS`]); `None` if never sent or empty.
520    #[must_use]
521    pub fn equipment(&self, slot: usize) -> Option<&Item> {
522        self.equipment.as_ref()?.get(slot)?.as_ref()
523    }
524
525    /// Active effects as last reported.
526    #[must_use]
527    pub fn effects(&self) -> &[Effect] {
528        &self.effects
529    }
530
531    /// The effect with this id, if active.
532    #[must_use]
533    pub fn effect(&self, id: u8) -> Option<&Effect> {
534        self.effects.iter().find(|e| e.id == id)
535    }
536}